Example usage for javax.servlet.http HttpSession getServletContext

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

Introduction

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

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns the ServletContext to which this session belongs.

Usage

From source file:jp.terasoluna.fw.service.thin.BLogicMapper.java

/**
 * T?[ubgReLXgwv?peBL?[l?B//w  ww. j av a  2  s  .  com
 *
 * @param propName v?peB
 * @param request HTTPNGXg
 * @param response HTTPX|X
 * @return v?peBl
 */
@Override
public Object getValueFromApplication(String propName, HttpServletRequest request,
        HttpServletResponse response) {

    if (propName == null || "".equals(propName)) {
        log.error("illegal argument:propName = [" + propName + "]");
        throw new IllegalArgumentException();
    }

    // T?[ubgReLXg
    HttpSession session = request.getSession(true);
    ServletContext context = session.getServletContext();
    // ZbVl
    Object value = context.getAttribute(propName);

    if (log.isDebugEnabled()) {
        if (value == null) {
            log.debug("ServletContext's attribute is null:key =[" + propName + "]");
        }
    }
    return value;
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.RDFSLabelGenerator.java

private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
    //Here, retrieve model from 
    OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
    if (editConfiguration.isDataPropertyUpdate()) {
        editConfiguration.prepareForDataPropUpdate(model, vreq.getWebappDaoFactory().getDataPropertyDao());
    }//from  w ww .  ja  v a  2 s.  c om
}

From source file:com.crimelab.service.FirearmsServiceImpl.java

@Override
public Workbook createFirearmsCases(HttpSession session, String month) {
    Workbook wb = null;//from w w  w  . j av a2 s. co m

    try {
        InputStream inp = session.getServletContext()
                .getResourceAsStream("/WEB-INF/templates/FirearmsCases.xls");
        wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        CellStyle cs1 = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();
        CellStyle bl = wb.createCellStyle();
        CellStyle br = wb.createCellStyle();
        CellStyle bt = wb.createCellStyle();
        CellStyle bb = wb.createCellStyle();
        cs1.setWrapText(true);
        cs2.setAlignment(ALIGN_CENTER);
        bt.setBorderTop(BORDER_THIN);
        bb.setBorderBottom(BORDER_THIN);
        bl.setBorderLeft(BORDER_THIN);
        br.setBorderRight(BORDER_THIN);

        Row intro1 = sheet.createRow(9);
        Cell in1 = intro1.createCell(0);
        in1.setCellValue("Period Covered:");
        in1.setCellStyle(cs1);
        in1.setCellStyle(cs2);

        Row intro2 = sheet.createRow(10);
        Cell in2 = intro2.createCell(0);
        in1.setCellValue(month.split("-")[0]);
        in1.setCellStyle(cs1);
        in1.setCellStyle(cs2);

        int ctr = 12; //initial
        Row row = sheet.createRow(ctr);
        month = month.split("-")[1];

        //JOptionPane.showMessageDialog(null, firearmsDAO.getAllFirearms(month));
        for (Firearms firearms : firearmsDAO.getAllFirearms(month)) {
            //JOptionPane.showMessageDialog(null, firearms.getReportNo());
            Cell cell0 = row.createCell(0);
            cell0.setCellValue(firearms.getReportNo());
            cell0.setCellStyle(bt);
            cell0.setCellStyle(bb);
            cell0.setCellStyle(bl);
            cell0.setCellStyle(br);

            Cell cell1 = row.createCell(1);//.setCellValue(firearms.getReportNo());
            cell1.setCellValue(firearms.getExaminerName());
            cell1.setCellStyle(bt);
            cell1.setCellStyle(bb);
            cell1.setCellStyle(bl);
            cell1.setCellStyle(br);

            Cell cell2 = row.createCell(2);//.setCellValue(firearms.getRequestingParty());
            cell2.setCellValue(firearms.getCaseType());
            cell2.setCellStyle(bt);
            cell2.setCellStyle(bb);
            cell2.setCellStyle(bl);
            cell2.setCellStyle(br);

            Cell cell3 = row.createCell(3);//.setCellValue(firearms.getDescriptionOfEvidence());
            cell3.setCellValue(firearms.getVictim());
            cell2.setCellStyle(bt);
            cell2.setCellStyle(bb);
            cell3.setCellStyle(bl);
            cell3.setCellStyle(br);

            Cell cell4 = row.createCell(4);//.setCellValue(firearms.getSpecimenWeight());
            cell4.setCellValue(firearms.getSuspect());
            cell4.setCellStyle(bt);
            cell4.setCellStyle(bb);
            cell4.setCellStyle(bl);
            cell4.setCellStyle(br);

            Cell cell5 = row.createCell(5);//.setCellValue(firearms.getCustody());
            cell5.setCellValue(firearms.getTimeDateIncident());
            cell5.setCellStyle(bt);
            cell5.setCellStyle(bb);
            cell5.setCellStyle(bl);
            cell5.setCellStyle(br);

            Cell cell6 = row.createCell(6);//.setCellValue(firearms.getSuspects());
            cell6.setCellValue(firearms.getPlaceOfIncident());
            cell6.setCellStyle(bt);
            cell6.setCellStyle(bb);
            cell6.setCellStyle(bl);
            cell6.setCellStyle(br);

            Cell cell7 = row.createCell(7);//.setCellValue(firearms.getTypeOfOperation());
            cell7.setCellValue(firearms.getRequestingParty());
            cell7.setCellStyle(bt);
            cell7.setCellStyle(bb);
            cell7.setCellStyle(bl);
            cell7.setCellStyle(br);

            Cell cell8 = row.createCell(8);//.setCellValue(firearms.getPlaceOfOperation());
            cell8.setCellValue(firearms.getInvestigator());
            cell8.setCellStyle(bt);
            cell8.setCellStyle(bb);
            cell8.setCellStyle(bl);
            cell8.setCellStyle(br);

            Cell cell9 = row.createCell(9);//.setCellValue(firearms.getPlaceOfOperation());
            cell9.setCellValue(firearms.getCaseStatus());
            cell9.setCellStyle(bt);
            cell9.setCellStyle(bb);
            cell9.setCellStyle(bl);
            cell9.setCellStyle(br);

            row = sheet.createRow(ctr += 1);

            return wb;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return wb;
}

From source file:com.liangc.hq.base.service.permissions.BaseSessionInitializationStrategy.java

public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) throws SessionAuthenticationException {
    final boolean debug = log.isDebugEnabled();

    if (debug)//from w  w  w  .j  ava  2 s  . com
        log.debug("Initializing UI session parameters...");
    boolean updateRoles = false;
    String username = authentication.getName();

    //If this is an organization authentication (ldap\kerberos) we will add a 'org\' prefix to the
    //user name so we will know it's an organization user
    if (null != authentication.getDetails()
            && (authentication.getDetails() instanceof HQAuthenticationDetails)) {
        HQAuthenticationDetails authDetails = (HQAuthenticationDetails) authentication.getDetails();
        if (authDetails.isUsingExternalAuth()) {
            username = HQConstants.ORG_AUTH_PREFIX + username;
            //If this is a Ldap user we will update his roles
            if (null != authentication.getPrincipal()
                    && authentication.getPrincipal().getClass().getName().contains("Ldap")) {
                updateRoles = true;
            }
        }
    }
    try {
        // The following is logic taken from the old HQ Authentication Filter
        int sessionId = sessionManager.put(authzSubjectManager.findSubjectByName(username));
        HttpSession session = request.getSession();
        ServletContext ctx = session.getServletContext();

        // look up the subject record
        AuthzSubject subj = authzBoss.getCurrentSubject(sessionId);
        boolean needsRegistration = false;

        if (subj == null || updateRoles) {
            try {
                AuthzSubject overlord = authzSubjectManager.getOverlordPojo();
                if (null == subj) {
                    needsRegistration = true;
                    subj = authzSubjectManager.createSubject(overlord, username, true,
                            HQConstants.ApplicationName, "", "", "", "", "", "", false);
                }
                //For LDAP users we first want to remove all the existing 'LDAP' roles and then add the current roles he belongs to.
                //We are doing that because for LDAP users we do an automatic mapping of the roles according to the group the
                //user belongs to, and if the user has been removed or added from some group we want this to be reflected in his roles.
                if (updateRoles) {
                    Collection<RoleValue> roles = roleManager.getRoles(subj, PageControl.PAGE_ALL);
                    for (RoleValue role : roles) {
                        String roleName = role.getName().toLowerCase();
                        if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) {
                            roleManager.removeSubjects(authzSubjectManager.getOverlordPojo(), role.getId(),
                                    new Integer[] { subj.getId() });
                        }
                    }
                }
                //every user has ROLE_HQ_USER.  If other roles assigned, automatically assign them to new user
                if (authentication.getAuthorities().size() > 1) {
                    Collection<Role> roles = roleManager.getAllRoles();
                    for (GrantedAuthority authority : authentication.getAuthorities()) {
                        if (authority.getAuthority().equals("ROLE_HQ_USER")) {
                            continue;
                        }
                        for (Role role : roles) {
                            String roleName = role.getName().toLowerCase();
                            String ldapRoleName = "";
                            if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) {
                                ldapRoleName = roleName.substring(roleName.indexOf(HQConstants.ORG_AUTH_PREFIX)
                                        + HQConstants.ORG_AUTH_PREFIX.length()).trim();
                            }
                            if ((("ROLE_" + role.getName()).equalsIgnoreCase(authority.getAuthority()))
                                    || (("ROLE_" + ldapRoleName).equalsIgnoreCase(authority.getAuthority()))) {
                                roleManager.addSubjects(authzSubjectManager.getOverlordPojo(), role.getId(),
                                        new Integer[] { subj.getId() });
                            }
                        }
                    }
                }
            } catch (ApplicationException e) {
                throw new SessionAuthenticationException("Unable to add user to authorization system");
            }

            sessionId = sessionManager.put(subj);
        } else {
            needsRegistration = subj.getEmailAddress() == null || subj.getEmailAddress().length() == 0;
        }

        userAuditFactory.loginAudit(subj);
        AuthzSubjectValue subject = subj.getAuthzSubjectValue();

        // figure out if the user has a principal
        boolean hasPrincipal = authBoss.isUser(sessionId, subject.getName());
        ConfigResponse preferences = needsRegistration ? new ConfigResponse()
                : getUserPreferences(ctx, sessionId, subject.getId(), authzBoss);
        WebUser webUser = new WebUser(subject, sessionId, preferences, hasPrincipal);

        // Add WebUser to Session
        session.setAttribute(Constants.WEBUSER_SES_ATTR, webUser);

        if (debug)
            log.debug("WebUser object created and stashed in the session");

        // TODO - We should use Spring Security for handling user
        // permissions...
        Map<String, Boolean> userOperationsMap = new HashMap<String, Boolean>();

        if (webUser.getPreferences().getKeys().size() > 0) {
            userOperationsMap = loadUserPermissions(webUser.getSessionId(), authzBoss);
        }

        session.setAttribute(Constants.USER_OPERATIONS_ATTR, userOperationsMap);

        if (debug)
            log.debug("Stashing user operations in the session");

        if (debug && needsRegistration) {
            log.debug("Authentic user but no HQ entity, must have authenticated outside of "
                    + "HQ...needs registration");
        }
    } catch (SessionException e) {
        if (debug) {
            log.debug("Authentication of user {" + username + "} failed due to an session error.");
        }

        throw new SessionAuthenticationException("login.error.application");
    } catch (PermissionException e) {
        if (debug) {
            log.debug("Authentication of user {" + username + "} failed due to an permissions error.");
        }

        throw new SessionAuthenticationException("login.error.application");
    }
}

From source file:org.forumj.web.servlet.post.SetAvatar.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    if (avatarsDir == null) {
        avatarsDir = session.getServletContext().getRealPath("img/" + avatarsContextDir);
    }//from   w w  w .  j  a  va 2s. co m
    StringBuffer buffer = new StringBuffer();
    try {
        ValidationErrors validationErrors = (ValidationErrors) request
                .getAttribute(ValidationErrors.class.getName());
        if (validationErrors.isHasErrors()) {
            List<ErrorCode> errors = validationErrors.getErrors();
            StringBuffer errCodes = new StringBuffer();
            for (ErrorCode errorCode : errors) {
                if (errCodes.length() == 0) {
                    errCodes.append("&errcode=");
                } else {
                    errCodes.append(",");
                }
                errCodes.append(errorCode.getErrorCode());
            }
            //TODO Magic integer!
            buffer.append(successPostOut("0", FJUrl.SETTINGS + "?id=9" + errCodes.toString()));
        } else {
            FileItem avatar = (FileItem) request.getAttribute("avatar");
            String sAvatarParameter = request.getParameter("s_avatar");
            boolean sAvatar = sAvatarParameter != null;
            IUser user = (IUser) session.getAttribute("user");
            if (user != null && !user.isBanned() && user.isLogined()) {
                String avatarUrl = createAvatar(user.getId(), avatar);
                user.setAvatar(avatarUrl);
                user.setAvatarApproved(true);
                user.setShowAvatar(sAvatar);
                UserService userService = FJServiceHolder.getUserService();
                userService.update(user);
                cache.remove("/" + avatarUrl);
                //                // TODO NLS!
                //                String text=" ? <a href='http://www.diletant.com.ua/forum/" + FJUrl.OK_AVATAR + "?qqnn=" + user.getId() + "'>" + user.getNick() + "</a>";
                //                String from = FJConfiguration.getConfig().getString("mail.from");
                //                String host = FJConfiguration.getConfig().getString("mail.smtp.host");
                //                String subject="Avatar changed";
                //                for (int toIndex = 0; toIndex < 1000; toIndex++) {
                //                    String to = FJConfiguration.getConfig().getString("mail.admin.address." + toIndex);
                //                    if (to != null){
                //                        FJEMail.sendMail(to, from, host, subject, text);
                //                    }else{
                //                        break;
                //                    }
                //
                //                }
                //TODO Magic integer!
                buffer.append(successPostOut("0", FJUrl.SETTINGS + "?id=9"));
            } else {
                //  ??
                buffer.append(unRegisteredPostOut());
            }
        }
    } catch (Throwable e) {
        buffer = new StringBuffer();
        buffer.append(errorOut(e));
        e.printStackTrace();
    }
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().write(buffer.toString());
}

From source file:org.beanfuse.security.monitor.SecurityFilter.java

/**
 * //ww  w .ja v  a 2 s  .c o m
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String resource = resourceExtractor.extract(httpRequest);
    request.setAttribute("resourceName", resource);
    HttpSession session = httpRequest.getSession(true);
    if (null == monitor) {
        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(session.getServletContext());
        monitor = (SecurityMonitor) wac.getBean("securityMonitor", SecurityMonitor.class);
    }
    // ??login??
    if (!freeResources.contains(resource) && !monitor.isPublicResource(resource)) {
        OnlineActivity info = monitor.getSessionController().getOnlineActivity(session.getId());
        if (info != null && null != httpRequest.getRemoteUser()
                && !info.getPrincipal().equals(httpRequest.getRemoteUser())) {
            info = null;
        }
        if (null == info) {
            Authentication auth = null;
            // remember me
            if (monitor.enableRememberMe()) {
                auth = monitor.getRememberMeService().autoLogin(httpRequest);
            }
            if (null == auth) {
                auth = new SsoAuthentication(httpRequest);
                auth.setDetails(monitor.getUserDetailsSource().buildDetails(httpRequest));
            }
            try {
                monitor.authenticate(auth);
            } catch (AuthenticationException e) {
                // URL
                session.setAttribute(PREVIOUS_URL,
                        httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, loginFailPath);
                return;
            }
        } else if (info.isExpired()) {
            monitor.logout(session);
            // URL
            session.setAttribute(PREVIOUS_URL,
                    httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
            redirectTo((HttpServletRequest) request, (HttpServletResponse) response, expiredPath);
            return;
        } else {
            info.refreshLastRequest();
            boolean pass = monitor.isAuthorized(info.getUserid(), resource);
            if (pass) {
                logger.debug("user {} access {} success", info.getPrincipal(), resource);
            } else {
                logger.info("user {} cannot access resource[{}]", info.getPrincipal(), resource);
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, noAuthorityPath);
                return;
            }
        }
    } else {
        logger.debug("free or public resource {} was accessed", resource);
    }
    chain.doFilter(request, response);
}

From source file:org.opentides.web.controller.ImageController.java

/**
 * Loads the default image /*from w ww. j  ava2 s .  c  o m*/
 * @param request
 * @return
 */
private final byte[] defaultImage(HttpServletRequest request) {
    if (StringUtil.isEmpty(defaultImageLocation))
        return ImageUtil.getDefaultImage();
    else {
        HttpSession session = request.getSession();
        ServletContext sc = session.getServletContext();
        InputStream is = sc.getResourceAsStream(defaultImageLocation);
        byte[] barray;

        try {
            barray = IOUtils.toByteArray(is);
        } catch (IOException e) {
            _log.error("Failed to load default image [" + defaultImageLocation + "].", e);
            return ImageUtil.getDefaultImage();
        }

        return barray;
    }
}

From source file:com.adito.core.CoreUtil.java

/**
 * Get message resources given the ID and the session. <code>null</code>
 * will be returned if no such resources exist.
 * //from  ww  w. j  a  va 2 s  .com
 * @param session session
 * @param key bundle key
 * @return resources
 */
public static MessageResources getMessageResources(HttpSession session, String key) {
    return getMessageResources(session.getServletContext(), key);
}

From source file:com.crimelab.service.ChemistryServiceImpl.java

@Override
public Workbook createMonthlyReport(HttpSession session, String month) {
    Workbook wb = null;//from  w ww .j a  va2  s .  c o m

    try {
        InputStream inp = session.getServletContext()
                .getResourceAsStream("/WEB-INF/templates/DrugMonthlyReport.xls");
        wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        CellStyle cs1 = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();
        CellStyle bl = wb.createCellStyle();
        CellStyle br = wb.createCellStyle();
        CellStyle bt = wb.createCellStyle();
        CellStyle bb = wb.createCellStyle();
        CellStyle stf = wb.createCellStyle();
        cs1.setWrapText(true);
        cs2.setAlignment(ALIGN_CENTER);
        bt.setBorderTop(BORDER_THIN);
        bb.setBorderBottom(BORDER_THIN);
        bl.setBorderLeft(BORDER_THIN);
        br.setBorderRight(BORDER_THIN);
        stf.setShrinkToFit(true);

        Row intro1 = sheet.createRow(7);
        Cell in1 = intro1.createCell(0);//.setCellValue("DRUG INVETORY COVERED PERIOD JANUARY-DECEMBER CY-" +month.split("-")[0]);
        in1.setCellValue("DRUG INVENTORY COVERED PERIOD JANUARY-DECEMBER CY-" + month.split("-")[0]);
        in1.setCellStyle(cs1);
        in1.setCellStyle(cs2);

        Row intro2 = sheet.createRow(9);
        Cell in2 = intro2.createCell(0);//.setCellValue("SUMMARY OF SEIZED/SURRENDERED/RECOVERED OF DRUG EVIDENCES FROM NEGATION OPERATIONS FROM LAW ENFORCEMENTS, PHARMACEUTICAL COMPANIES AND SIMILAR ESTABLISHMENTS FOR THE MONTH OF "+month);
        in2.setCellValue(
                "SUMMARY OF SEIZED/SURRENDERED/RECOVERED OF DRUG EVIDENCES FROM NEGATION OPERATIONS FROM LAW ENFORCEMENTS, PHARMACEUTICAL COMPANIES AND SIMILAR ESTABLISHMENTS FOR THE MONTH OF "
                        + month);
        in2.setCellStyle(cs1);
        in2.setCellStyle(cs2);
        in2.setCellStyle(stf);

        int ctr = 12; //initial
        Row row = sheet.createRow(ctr);
        month = month.split("-")[1];

        //System.out.println("GAC " + chemistryDAO.getAllChemistry(month).isEmpty());
        for (Chemistry chemistry : chemistryDAO.getAllChemistry(month)) {
            //System.out.println("Test " + chemistry.getTimeDateReceived());
            Cell cell0 = row.createCell(0);
            cell0.setCellValue(chemistry.getTimeDateReceived());
            cell0.setCellStyle(bt);
            cell0.setCellStyle(bb);
            cell0.setCellStyle(bl);
            cell0.setCellStyle(br);

            Cell cell1 = row.createCell(1);//.setCellValue(chemistry.getReportNo());
            cell1.setCellValue(chemistry.getReportNo());
            cell1.setCellStyle(bt);
            cell1.setCellStyle(bb);
            cell1.setCellStyle(bl);
            cell1.setCellStyle(br);

            Cell cell2 = row.createCell(2);//.setCellValue(chemistry.getRequestingParty());
            cell2.setCellValue(chemistry.getRequestingParty());
            cell2.setCellStyle(bt);
            cell2.setCellStyle(bb);
            cell2.setCellStyle(bl);
            cell2.setCellStyle(br);

            Cell cell3 = row.createCell(3);//.setCellValue(chemistry.getDescriptionOfEvidence());
            cell3.setCellValue(chemistry.getDescriptionOfEvidence());
            cell3.setCellStyle(bt);
            cell3.setCellStyle(bb);
            cell3.setCellStyle(bl);
            cell3.setCellStyle(br);

            Cell cell4 = row.createCell(4);//.setCellValue(chemistry.getSpecimenWeight());
            cell4.setCellValue(chemistry.getSpecimenWeight());
            cell4.setCellStyle(bt);
            cell4.setCellStyle(bb);
            cell4.setCellStyle(bl);
            cell4.setCellStyle(br);

            Cell cell5 = row.createCell(5);//.setCellValue(chemistry.getCustody());
            cell5.setCellValue(chemistry.getCustody());
            cell5.setCellStyle(bt);
            cell5.setCellStyle(bb);
            cell5.setCellStyle(bl);
            cell5.setCellStyle(br);

            Cell cell6 = row.createCell(6);//.setCellValue(chemistry.getSuspects());
            cell6.setCellValue(chemistry.getSuspects());
            cell6.setCellStyle(bt);
            cell6.setCellStyle(bb);
            cell6.setCellStyle(bl);
            cell6.setCellStyle(br);

            Cell cell7 = row.createCell(7);//.setCellValue(chemistry.getTypeOfOperation());
            cell7.setCellValue(chemistry.getTypeOfOperation());
            cell7.setCellStyle(bt);
            cell7.setCellStyle(bb);
            cell7.setCellStyle(bl);
            cell7.setCellStyle(br);

            Cell cell8 = row.createCell(8);//.setCellValue(chemistry.getPlaceOfOperation());
            cell8.setCellValue(chemistry.getPlaceOfOperation());
            cell8.setCellStyle(bt);
            cell8.setCellStyle(bb);
            cell8.setCellStyle(bl);
            cell8.setCellStyle(br);

            row = sheet.createRow(ctr += 1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return wb;
}

From source file:com.crimelab.service.GalleryServiceImpl.java

@Override
public XWPFDocument create(GalleryResults galleryResults, HttpSession session) {
    XWPFDocument document = null;/*from  w  w  w.j  ava2 s.c om*/

    //Insert into database
    galleryDAO.insertResults(galleryResults);

    try {
        //Retrieving Template
        InputStream inpDocx = session.getServletContext()
                .getResourceAsStream("/WEB-INF/templates/CompositeSketch.docx");
        document = new XWPFDocument(inpDocx);

        //Adding the picture
        XWPFParagraph pictureHolder = document.createParagraph();
        XWPFRun pictureRun = pictureHolder.createRun();

        FileInputStream getPhoto = new FileInputStream(galleryResults.getPhotoLocation());
        FileInputStream getImage = new FileInputStream(galleryResults.getPhotoLocation());
        ImageInputStream imageInput = ImageIO.createImageInputStream(getPhoto);
        BufferedImage bi = ImageIO.read(imageInput);
        int width = bi.getWidth() - 100;
        int height = bi.getHeight() - 100;

        pictureRun.addBreak();
        pictureRun.addPicture(getImage, XWPFDocument.PICTURE_TYPE_PNG, null, Units.toEMU(width),
                Units.toEMU(height));

        pictureHolder.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setBorderTop(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setBorderRight(Borders.BASIC_BLACK_DASHES);
        pictureHolder.setAlignment(ParagraphAlignment.CENTER);
        //            pictureRowHolder.getCell(0).setText("IMAGE PLACER");

        //Case number and Date            
        XWPFParagraph info = document.createParagraph();
        XWPFRun caseNoAndDate = info.createRun();
        caseNoAndDate.setText("Case Number: " + galleryResults.getCaseNo());
        caseNoAndDate.addTab();
        caseNoAndDate.addTab();
        caseNoAndDate.addTab();
        caseNoAndDate.addTab();
        caseNoAndDate.setText(galleryResults.getDate());
        caseNoAndDate.setFontSize(16);

        //Sketch Details
        XWPFParagraph caseDetails = document.createParagraph();
        XWPFRun detailsParagraph = caseDetails.createRun();
        detailsParagraph.setText("Offense/Incident: " + galleryResults.getOffenseIncident());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Name/AKA: " + galleryResults.getNameAKA());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Sex: " + galleryResults.getSex());
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.setText("Age: " + galleryResults.getAge());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Height: " + galleryResults.getHeight());
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.setText("Weight: " + galleryResults.getWeight());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Built: " + galleryResults.getBuilt());
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.addTab();
        detailsParagraph.setText("Complexion: " + galleryResults.getComplexion());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Other Information: " + galleryResults.getOtherInfo());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Described by: " + galleryResults.getDescribedBy());
        detailsParagraph.addBreak();
        detailsParagraph.setText("Requesting party: " + galleryResults.getRequestingParty());

        //Details Borders
        caseDetails.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        caseDetails.setBorderTop(Borders.BASIC_BLACK_DASHES);
        caseDetails.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        caseDetails.setBorderRight(Borders.BASIC_BLACK_DASHES);
        caseDetails.setAlignment(ParagraphAlignment.LEFT);

        //Reference Paragraph
        XWPFParagraph outsideDetails = document.createParagraph();
        XWPFRun outsideDetailsRun = outsideDetails.createRun();
        outsideDetailsRun.addBreak();
        outsideDetailsRun.setText("Note: For reference");
        outsideDetailsRun.addBreak();
        outsideDetailsRun.setText("The witness indicates that this image is: " + galleryResults.getRating());
        getPhoto.close();
        getImage.close();
        imageInput.close();
        document.getXWPFDocument();
    } catch (IOException | InvalidFormatException e) {
        e.printStackTrace();
    }
    return document;
}