Example usage for javax.servlet ServletContext getRealPath

List of usage examples for javax.servlet ServletContext getRealPath

Introduction

In this page you can find the example usage for javax.servlet ServletContext getRealPath.

Prototype

public String getRealPath(String path);

Source Link

Document

Gets the real path corresponding to the given virtual path.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.ApplicationModelSetup.java

/**
 * All of the list views should now reside in files in DISPLAY_MODEL_LOAD_AT_STARTUP_DIR.
 * This will check for custom list view annotation statements in the displayModel, check
 * if they exist in the files in DISPLAY_MODEL_LOAD_AT_STARTUP_DIR, and write any that don't
 * exist there to a file in DISPLAY_MODEL_LOAD_AT_STARTUP_DIR.  After that the statements
 * will be removed from the displayDBModel.
 * //from   w  w  w.j a va  2s. com
 *   returns true if there were old list view statements in the DB, returns false
 *   if there were none.  displayLoadAlways should be reloaded from the file system
 *   if this returns true as this method may have changed the files.
 *   
 *   displayLoadAtStartup and displayModel may be modified.
 */
private void checkForOldListViews(ServletContext ctx, OntModel displayModel, Model displayLoadAtStartup) {
    // run construct for old custom list view statements from displayModel
    Model oldListViewModel = getOldListViewStatements(displayModel);
    if (log.isDebugEnabled()) {
        log.debug("Printing the old list view statements from the display model to System.out.");
        oldListViewModel.write(System.out, "N3-PP");
    }

    // find statements in old stmts that are not in loadedAtStartup and 
    // save them in a new file in DISPLAY_MODEL_LOAD_AT_STARTUP_DIR
    // so that in the future they will be in loadedAtStartup
    Model stmtsInOldAndFiles = displayLoadAtStartup.intersection(displayModel);
    Model unhandledOldListViewStmts = oldListViewModel.difference(stmtsInOldAndFiles);

    boolean saved = false;
    boolean neededSave = false;

    if (unhandledOldListViewStmts != null && !unhandledOldListViewStmts.isEmpty()) {
        log.debug("need to deal with old list view statements from the display model");
        neededSave = true;
        try {
            //create a file for the old statements in the loadAtStartup directory
            String newFileName = ctx.getRealPath(DISPLAY_MODEL_LOAD_AT_STARTUP_DIR + File.separator
                    + new DateTime().toString(ISODateTimeFormat.basicDateTime()) + ".n3");
            File file = new File(newFileName);
            file.createNewFile();

            log.info("Relocating " + unhandledOldListViewStmts.size()
                    + " custom list view statements from DB and saving to " + file.getAbsolutePath()
                    + File.separator + file.getName()
                    + ". These will be loaded from this file when the system starts up.");

            FileOutputStream fileOut = new FileOutputStream(file);
            unhandledOldListViewStmts.write(fileOut, "N3-PP");
            fileOut.close();
            saved = true;
        } catch (Throwable th) {
            log.warn("Could not save old list view statements.  Leaving them in the DB", th);
        }

        //need to reload displayLoadAlways because DISPLAY_MODEL_LOAD_AT_STARTUP_DIR may have changed
        displayLoadAtStartup.removeAll().add(readInDisplayModelLoadAtStartup(ctx));
    }

    if (oldListViewModel != null && !oldListViewModel.isEmpty()) {
        //At this point, there are old list view statements in the DB but they
        //should are all redundant with ones in DISPLAY_MODEL_LOAD_AT_STARTUP_DIR   
        if ((neededSave && saved) || (!neededSave)) {
            //if there was nothing to save, just remove the old stuff
            //if there was stuff to save, only remove if it was saved.
            log.debug("removing old statements from displayModel");
            displayModel.remove(oldListViewModel);
        }
    }

}

From source file:org.hil.children.service.impl.ChildrenManagerImpl.java

public String printListChildrenDue(String dueTime, Commune commune, List<ChildrenDuePrintVO> childrenDue) {
    String path = "";
    JasperPrint reportPrint = createListChildrenPrintVOReportPrint(childrenDue, dueTime, commune);
    String prefixFileName = commune.getDistrict().getProvince().getProvinceId()
            + commune.getDistrict().getDistrictId() + commune.getCommuneId();
    try {/*from w w  w.ja  v a2  s . c o m*/
        long currentTime = System.currentTimeMillis();

        GraniteContext gc = GraniteContext.getCurrentInstance();
        ServletContext sc = ((HttpGraniteContext) gc).getServletContext();

        String reportDir = sc.getRealPath(config.getBaseReportDir());

        String pdfPath = reportDir + "/" + prefixFileName + "_" + currentTime + ".pdf";
        log.debug("path to pdf report:" + pdfPath);
        JasperExportManager.exportReportToPdfFile(reportPrint, pdfPath);
        path = "/reports/" + prefixFileName + "_" + currentTime + ".pdf";
    } catch (Exception ex) {
        String connectMsg = "Could not create the report " + ex.getMessage() + " " + ex.getLocalizedMessage();
        log.debug(connectMsg);
    }
    return path;
}

From source file:org.hil.children.service.impl.ChildrenManagerImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public JasperPrint createListChildrenPrintVOReportPrint(List<ChildrenDuePrintVO> childrenDue, String dueTime,
        Commune commune) {//w ww . j  a v a 2 s  . co m

    JasperPrint childrenVOReportPrint = new JasperPrint();
    try {
        Map parameters = new HashMap();
        GraniteContext gc = GraniteContext.getCurrentInstance();
        ServletContext sc = ((HttpGraniteContext) gc).getServletContext();
        String reportDir = sc.getRealPath(config.getBaseReportDir());

        parameters.put("SUBREPORT_DIR", reportDir + "/jrxml/");

        String jasperPath = reportDir + "/jrxml/ListChildrenImmunization.jasper";
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath);
        JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(
                getListChildrenPrintVO(childrenDue, dueTime, commune));
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds);
        childrenVOReportPrint = jasperPrint;

    } catch (Exception ex) {
        String connectMsg = "Could not create the report " + ex.getMessage() + " " + ex.getLocalizedMessage();
        log.debug(connectMsg);
    }
    return childrenVOReportPrint;
}

From source file:org.hil.children.service.impl.ChildrenManagerImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public JasperPrint createListVaccinationReportPrint(String timeFrom, String timeTo, Commune commune,
        District district, List<RegionVaccinationReportData> statistics) {
    JasperPrint vaccinationReportPrint = new JasperPrint();
    try {//from  ww w  .  j av a  2 s . co m
        Map parameters = new HashMap();
        GraniteContext gc = GraniteContext.getCurrentInstance();
        ServletContext sc = ((HttpGraniteContext) gc).getServletContext();
        String reportDir = sc.getRealPath(config.getBaseReportDir());

        parameters.put("SUBREPORT_DIR", reportDir + "/jrxml/");

        String jasperPath = reportDir + "/jrxml/ImmunizationReport.jasper";
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath);

        JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(
                getListVaccinationReportPrintVO(timeFrom, timeTo, commune, district, statistics));
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds);
        vaccinationReportPrint = jasperPrint;

    } catch (Exception ex) {
        String connectMsg = "Could not create the report " + ex.getMessage() + " " + ex.getLocalizedMessage();
        log.debug(connectMsg);
    }
    return vaccinationReportPrint;
}

From source file:org.workcast.ssoficlient.service.LoginHandler.java

private File resolveFile(String fileName) {
    ServletContext sc = session.getServletContext();
    if (!fileName.startsWith("/")) {
        // This addresses a TomCat 8 bug where paths without a starting slash used to work
        // but getRealPath in TomCat 8 for a path without a slash  returns a null!
        fileName = "/" + fileName;
    }//from   ww w .j a va  2s  .  c  o m
    String wayPath = sc.getRealPath(fileName);
    File file = new File(wayPath);
    return file;
}

From source file:org.red5.server.tomcat.TomcatLoader.java

/**
 * Initialization.//ww  w .  j  a v a  2  s . c  o m
 */
public void init() {
    log.info("Loading tomcat context");

    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);

    // create one embedded (server) and use it everywhere
    embedded = new Embedded();
    embedded.createLoader(originalClassLoader);
    embedded.setCatalinaBase(serverRoot);
    embedded.setCatalinaHome(serverRoot);
    embedded.setName(serviceEngineName);
    log.trace("Classloader for embedded: {} TCL: {}", Embedded.class.getClassLoader(), originalClassLoader);

    engine = embedded.createEngine();
    engine.setDefaultHost(host.getName());
    engine.setName(serviceEngineName);

    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);

    // scan for additional webapp contexts

    // Root applications directory
    File appDirBase = new File(webappFolder);
    // Subdirs of root apps dir
    File[] dirs = appDirBase.listFiles(new DirectoryFilter());
    // Search for additional context files
    for (File dir : dirs) {
        String dirName = '/' + dir.getName();
        // check to see if the directory is already mapped
        if (null == host.findChild(dirName)) {
            String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
            log.debug("Webapp context directory (full path): {}", webappContextDir);
            Context ctx = null;
            if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
                log.trace("Adding ROOT context");
                ctx = addContext("/", webappContextDir);
            } else {
                log.trace("Adding context from directory scan: {}", dirName);
                ctx = addContext(dirName, webappContextDir);
            }
            log.trace("Context: {}", ctx);

            //see if the application requests php support
            String enablePhp = ctx.findParameter("enable-php");
            //if its null try to read directly
            if (enablePhp == null) {
                File webxml = new File(webappContextDir + "/WEB-INF/", "web.xml");
                if (webxml.exists() && webxml.canRead()) {
                    try {
                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                        Document doc = docBuilder.parse(webxml);
                        // normalize text representation
                        doc.getDocumentElement().normalize();
                        log.trace("Root element of the doc is {}", doc.getDocumentElement().getNodeName());
                        NodeList listOfElements = doc.getElementsByTagName("context-param");
                        int totalElements = listOfElements.getLength();
                        log.trace("Total no of elements: {}", totalElements);
                        for (int s = 0; s < totalElements; s++) {
                            Node fstNode = listOfElements.item(s);
                            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                                Element fstElmnt = (Element) fstNode;
                                NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("param-name");
                                Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                                NodeList fstNm = fstNmElmnt.getChildNodes();
                                String pName = (fstNm.item(0)).getNodeValue();
                                log.trace("Param name: {}", pName);
                                if ("enable-php".equals(pName)) {
                                    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("param-value");
                                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                                    NodeList lstNm = lstNmElmnt.getChildNodes();
                                    String pValue = (lstNm.item(0)).getNodeValue();
                                    log.trace("Param value: {}", pValue);
                                    enablePhp = pValue;
                                    //
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.warn("Error reading web.xml", e);
                    }
                }
                webxml = null;
            }
            log.debug("Enable php: {}", enablePhp);
            if ("true".equals(enablePhp)) {
                log.info("Adding PHP (Quercus) servlet for context: {}", ctx.getName());
                // add servlet wrapper
                StandardWrapper wrapper = (StandardWrapper) ctx.createWrapper();
                wrapper.setServletName("QuercusServlet");
                wrapper.setServletClass("com.caucho.quercus.servlet.QuercusServlet");
                log.debug("Wrapper: {}", wrapper);
                ctx.addChild(wrapper);
                // add servlet mappings
                ctx.addServletMapping("*.php", "QuercusServlet");
            }

            webappContextDir = null;
        }
    }
    appDirBase = null;
    dirs = null;

    // Dump context list
    if (log.isDebugEnabled()) {
        for (Container cont : host.findChildren()) {
            log.debug("Context child name: {}", cont.getName());
        }
    }

    // Set a realm
    if (realm == null) {
        realm = new MemoryRealm();
    }
    embedded.setRealm(realm);

    // use Tomcat jndi or not
    if (System.getProperty("catalina.useNaming") != null) {
        embedded.setUseNaming(Boolean.valueOf(System.getProperty("catalina.useNaming")));
    }

    // add the valves to the host
    for (Valve valve : valves) {
        log.debug("Adding host valve: {}", valve);
        ((StandardHost) host).addValve(valve);
    }

    // baseHost = embedded.createHost(hostName, appRoot);
    engine.addChild(host);

    // add any additional hosts
    if (hosts != null && !hosts.isEmpty()) {
        // grab current contexts from base host
        Container[] currentContexts = host.findChildren();
        log.info("Adding {} additional hosts", hosts.size());
        for (Host h : hosts) {
            log.debug("Host - name: {} appBase: {} info: {}",
                    new Object[] { h.getName(), h.getAppBase(), h.getInfo() });
            //add the contexts to each host
            for (Container cont : currentContexts) {
                Context c = (Context) cont;
                addContext(c.getPath(), c.getDocBase(), h);
            }
            //add the host to the engine
            engine.addChild(h);
        }
    }

    // Add new Engine to set of Engine for embedded server
    embedded.addEngine(engine);

    // set connection properties
    for (String key : connectionProperties.keySet()) {
        log.debug("Setting connection property: {} = {}", key, connectionProperties.get(key));
        if (connectors == null || connectors.isEmpty()) {
            connector.setProperty(key, connectionProperties.get(key));
        } else {
            for (Connector ctr : connectors) {
                ctr.setProperty(key, connectionProperties.get(key));
            }
        }
    }

    // set the bind address
    if (address == null) {
        //bind locally
        address = InetSocketAddress.createUnresolved("127.0.0.1", connector.getPort()).getAddress();
    }
    // apply the bind address
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof Http11Protocol) {
        ((Http11Protocol) handler).setAddress(address);
    } else if (handler instanceof Http11NioProtocol) {
        ((Http11NioProtocol) handler).setAddress(address);
    } else {
        log.warn("Unknown handler type: {}", handler.getClass().getName());
    }

    // Start server
    try {
        // Add new Connector to set of Connectors for embedded server,
        // associated with Engine
        if (connectors == null || connectors.isEmpty()) {
            embedded.addConnector(connector);
            log.trace("Connector oName: {}", connector.getObjectName());
        } else {
            for (Connector ctr : connectors) {
                embedded.addConnector(ctr);
                log.trace("Connector oName: {}", ctr.getObjectName());
            }
        }

        log.info("Starting Tomcat servlet engine");
        embedded.start();

        LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext));

        for (Container cont : host.findChildren()) {
            if (cont instanceof StandardContext) {
                StandardContext ctx = (StandardContext) cont;

                final ServletContext servletContext = ctx.getServletContext();
                log.debug("Context initialized: {}", servletContext.getContextPath());

                //set the hosts id
                servletContext.setAttribute("red5.host.id", getHostId());

                String prefix = servletContext.getRealPath("/");
                log.debug("Path: {}", prefix);

                try {
                    if (ctx.resourcesStart()) {
                        log.debug("Resources started");
                    }

                    log.debug("Context - available: {} privileged: {}, start time: {}, reloadable: {}",
                            new Object[] { ctx.getAvailable(), ctx.getPrivileged(), ctx.getStartTime(),
                                    ctx.getReloadable() });

                    Loader cldr = ctx.getLoader();
                    log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName());
                    if (cldr instanceof WebappLoader) {
                        log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath());
                    }
                    final ClassLoader webClassLoader = cldr.getClassLoader();
                    log.debug("Webapp classloader: {}", webClassLoader);

                    // get the (spring) config file path
                    final String contextConfigLocation = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                    ? defaultSpringConfigLocation
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                    log.debug("Spring context config location: {}", contextConfigLocation);

                    // get the (spring) parent context key
                    final String parentContextKey = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                    ? defaultParentContextKey
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                    log.debug("Spring parent context key: {}", parentContextKey);

                    //set current threads classloader to the webapp classloader
                    Thread.currentThread().setContextClassLoader(webClassLoader);

                    //create a thread to speed-up application loading
                    Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                        public void run() {
                            //set thread context classloader to web classloader
                            Thread.currentThread().setContextClassLoader(webClassLoader);
                            //get the web app's parent context
                            ApplicationContext parentContext = null;
                            if (applicationContext.containsBean(parentContextKey)) {
                                parentContext = (ApplicationContext) applicationContext
                                        .getBean(parentContextKey);
                            } else {
                                log.warn("Parent context was not found: {}", parentContextKey);
                            }
                            // create a spring web application context
                            final String contextClass = servletContext.getInitParameter(
                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                            ? XmlWebApplicationContext.class.getName()
                                            : servletContext.getInitParameter(
                                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                            //web app context (spring)
                            ConfigurableWebApplicationContext appctx = null;
                            try {
                                Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                                appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            } catch (Throwable e) {
                                throw new RuntimeException("Failed to load webapplication context class.", e);
                            }
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            //set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            //refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                        }
                    };
                    thread.setDaemon(true);
                    thread.start();

                } catch (Throwable t) {
                    log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                            t.getMessage());
                    t.printStackTrace();
                } finally {
                    //reset the classloader
                    Thread.currentThread().setContextClassLoader(originalClassLoader);
                }
            }
        }

        // if everything is ok at this point then call the rtmpt and rtmps
        // beans so they will init
        if (applicationContext.containsBean("red5.core")) {
            ApplicationContext core = (ApplicationContext) applicationContext.getBean("red5.core");
            if (core.containsBean("rtmpt.server")) {
                log.debug("Initializing RTMPT");
                core.getBean("rtmpt.server");
                log.debug("Finished initializing RTMPT");
            } else {
                log.info("Dedicated RTMPT server configuration was not specified");
            }
            if (core.containsBean("rtmps.server")) {
                log.debug("Initializing RTMPS");
                core.getBean("rtmps.server");
                log.debug("Finished initializing RTMPS");
            } else {
                log.info("Dedicated RTMPS server configuration was not specified");
            }
        } else {
            log.info("Core context was not found");
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading tomcat, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading tomcat", e);
        }
    } finally {
        registerJMX();
    }

}

From source file:org.bibalex.wamcp.storage.WAMCPIndexedStorage.java

 public void writeIndexFieldsToFile(ActionEvent ev) throws WAMCPException, WFSVNException,
      SVNException, XSAException {//ww w  .ja  v  a 2 s. c  om
      
   Properties ixedFieldsNameType = new Properties();
      
   for (String key : this.getAllFieldNames()) {
      String value = this.getSolrTypeForField(key);
         
      if (!key.startsWith("All")) { // catch all fields don't have an XPath
         
         Set<Entry<XSAInstance, String>> entriesToSearch;
         if (key.indexOf('_') == -1) {
            entriesToSearch = this.advSearchFieldsNames.entrySet();
         } else {
            entriesToSearch = this.ixedFieldsNames.entrySet();
         }
            
         for (Entry<XSAInstance, String> mapping : entriesToSearch) {
            if (key.equals(mapping.getValue())) {
                  
               String fieldXPathStr = mapping.getKey().getXPathToAllOccsInAllBaseShifts();
               value += "," + fieldXPathStr;
                  
               // A field can take values from more than one XPath break;
            }
         }
      }
         
      ixedFieldsNameType.setProperty(key, value);
   }
      
   try {
      File ixedFieldesNameTypeTempFile = new File(this.getUserDir().getCanonicalPath()
            + File.separator + "ixedFieldesNameType.properties");
      FileOutputStream ixedFieldesNameTypeTempStream = new FileOutputStream(
            ixedFieldesNameTypeTempFile);
         
      ixedFieldsNameType.store(ixedFieldesNameTypeTempStream, "");
         
      ixedFieldesNameTypeTempStream.flush();
      ixedFieldesNameTypeTempStream.close();
         
      String targetPathAbs = ixedFieldesNameTypeTempFile.getCanonicalPath();
      ServletContext sltCtx = (ServletContext) FacesContext.getCurrentInstance()
            .getExternalContext().getContext();
      String filePathAbs = sltCtx.getRealPath("");
         
      String filePathRel = targetPathAbs.substring(filePathAbs.length());
      filePathRel = filePathRel.replace('\\', '/');
      String fileURL = sltCtx.getContextPath() + filePathRel;
         
      this.setQuickMessage("Index fields file created: <a href='" + fileURL
            + "'>"
            + " Click to download! </a>");
   } catch (IOException e) {
      throw new WAMCPException(e);
   }
      
}

From source file:org.hil.children.service.impl.ChildrenManagerImpl.java

public String printListVaccinatedInLocationReport(String type, String timeFrom, String timeTo, Commune commune,
        District district, Vaccination vaccine, List<ChildrenVaccinatedInLocationVO> statistics) {

    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

    String path = "";
    String prefixFileName = "";
    if (commune != null)
        prefixFileName = district.getDistrictId() + "_" + commune.getCommuneId();
    else if (district != null)
        prefixFileName = district.getDistrictId();
    GraniteContext gc = GraniteContext.getCurrentInstance();
    ServletContext sc = ((HttpGraniteContext) gc).getServletContext();
    String reportDir = sc.getRealPath(config.getBaseReportDir());
    long currentTime = System.currentTimeMillis();
    String filePath = reportDir + "/" + prefixFileName + "_DanhSachTreDenTiem_" + vaccine.getName() + "_"
            + currentTime;//  w  ww  . ja  v a2s  .  c om

    POIFSFileSystem fs;
    try {
        filePath += ".xls";
        fs = new POIFSFileSystem(
                new FileInputStream(reportDir + "/excel/ListOfChildrenVaccinatedInLocation.xls"));
        HSSFWorkbook wb = new HSSFWorkbook(fs, true);

        HSSFSheet s = wb.getSheetAt(0);

        HSSFRow r = null;
        HSSFCell c = null;

        r = s.getRow(0);
        c = r.getCell(0);
        c.setCellValue("Danh sch tr n tim chng " + vaccine.getName()
                + " (bao gm c tr tim  bnh vin/phng khm)");

        r = s.getRow(1);
        c = r.getCell(1);
        c.setCellValue(district.getDistrictName());
        if (commune != null) {
            c = r.getCell(2);
            c.setCellValue("X");
            c = r.getCell(3);
            c.setCellValue(commune.getCommuneName());
            c = r.getCell(4);
            c.setCellValue("(" + timeFrom + " - " + timeTo + ")");
        } else {
            c = r.getCell(2);
            c.setCellValue("(" + timeFrom + " - " + timeTo + ")");
        }
        HSSFCellStyle cs = wb.createCellStyle();
        cs.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cs.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs.setBorderRight(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle cs1 = wb.createCellStyle();
        cs1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cs1.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle cs2 = wb.createCellStyle();
        cs2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cs2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        CreationHelper createHelper = wb.getCreationHelper();
        cs2.setDataFormat(createHelper.createDataFormat().getFormat("dd/MM/yyyy"));

        int rownum = 3;
        for (rownum = 3; rownum < statistics.size() + 3; rownum++) {
            r = s.createRow(rownum);

            c = r.createCell(0);
            c.setCellStyle(cs1);
            c.setCellValue(rownum - 2);

            c = r.createCell(1);
            c.setCellStyle(cs);
            c.setCellValue(statistics.get(rownum - 3).getCommuneName());

            c = r.createCell(2);
            c.setCellStyle(cs);
            c.setCellValue(statistics.get(rownum - 3).getVillageName());

            c = r.createCell(3);
            c.setCellStyle(cs);
            c.setCellValue(statistics.get(rownum - 3).getChildCode());

            c = r.createCell(4);
            c.setCellStyle(cs);
            c.setCellValue(statistics.get(rownum - 3).getFullName());

            c = r.createCell(5);
            c.setCellStyle(cs1);
            c.setCellValue(statistics.get(rownum - 3).getGender() == true ? "N" : "Nam");

            c = r.createCell(6);
            c.setCellStyle(cs2);
            c.setCellValue(statistics.get(rownum - 3).getDateOfBirth());

            c = r.createCell(7);
            c.setCellStyle(cs);
            c.setCellValue(statistics.get(rownum - 3).getMotherName());

            c = r.createCell(8);
            c.setCellStyle(cs2);
            c.setCellValue(statistics.get(rownum - 3).getDateOfImmunization());

            c = r.createCell(9);
            c.setCellStyle(cs);
            String vaccinatedLocation = "";
            if (statistics.get(rownum - 3).getOtherLocation() != null
                    && statistics.get(rownum - 3).getOtherLocation() >= 1
                    && statistics.get(rownum - 3).getOtherLocation() <= 4) {
                if (statistics.get(rownum - 3).getOtherLocation() == 1)
                    vaccinatedLocation = "Bnh vin TW";
                else if (statistics.get(rownum - 3).getOtherLocation() == 2)
                    vaccinatedLocation = "Bnh vin tnh";
                else if (statistics.get(rownum - 3).getOtherLocation() == 3)
                    vaccinatedLocation = "Bnh vin huyn";
                else if (statistics.get(rownum - 3).getOtherLocation() == 4)
                    vaccinatedLocation = "Phng khm/Bnh vin t nhn";
            } else
                vaccinatedLocation = statistics.get(rownum - 3).getVaccinatedCommune();
            c.setCellValue(vaccinatedLocation);
        }

        FileOutputStream fileOut = new FileOutputStream(filePath);
        wb.write(fileOut);
        fileOut.close();
        path = "/reports/" + prefixFileName + "_DanhSachTreDenTiem_" + vaccine.getName() + "_" + currentTime
                + ".xls";
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return path;
}

From source file:org.hil.children.service.impl.ChildrenManagerImpl.java

public String printListChildren(ChildrenSearchVO params) {
    List<ChildrenPrintVO> children = childrenDaoExt.searchChildrenForPrint(params);
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    String strDOBFrom = format.format(params.getDateOfBirthFrom());
    String strDOBTo = format.format(params.getDateOfBirthTo());
    String path = "";
    String prefixFileName = "";
    Commune commune = communeDao.get(params.getCommuneId());
    prefixFileName = commune.getDistrict().getProvince().getProvinceId() + commune.getDistrict().getDistrictId()
            + commune.getCommuneId();/*from   ww w .  j a  v a  2  s.c  om*/

    GraniteContext gc = GraniteContext.getCurrentInstance();
    ServletContext sc = ((HttpGraniteContext) gc).getServletContext();
    String reportDir = sc.getRealPath(config.getBaseReportDir());
    long currentTime = System.currentTimeMillis();
    String filePath = reportDir + "/" + prefixFileName + "_List_Children_Excel_" + currentTime;

    POIFSFileSystem fs;
    try {
        filePath += ".xls";
        fs = new POIFSFileSystem(new FileInputStream(reportDir + "/excel/ListOfChildrenInCommune.xls"));
        HSSFWorkbook wb = new HSSFWorkbook(fs, true);

        HSSFSheet s = wb.getSheetAt(0);

        HSSFRow r = null;
        HSSFCell c = null;

        r = s.getRow(0);
        c = r.getCell(1);
        c.setCellValue(commune.getCommuneName());

        c = r.getCell(2);
        c.setCellValue("(" + strDOBFrom + " - " + strDOBTo + ")");

        HSSFCellStyle cs = wb.createCellStyle();
        cs.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cs.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs.setBorderRight(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle cs1 = wb.createCellStyle();
        cs1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cs1.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle cs2 = wb.createCellStyle();
        cs2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cs2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        CreationHelper createHelper = wb.getCreationHelper();
        cs2.setDataFormat(createHelper.createDataFormat().getFormat("dd/MM/yyyy"));

        int rownum = 3;
        for (rownum = 3; rownum < children.size() + 3; rownum++) {
            r = s.createRow(rownum);

            c = r.createCell(0);
            c.setCellStyle(cs1);
            c.setCellValue(rownum - 2);

            c = r.createCell(1);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getFullName());

            c = r.createCell(2);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getDateOfBirth());

            c = r.createCell(3);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).isGender() == true ? "N" : "Nam");

            c = r.createCell(4);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getVillageName());

            c = r.createCell(5);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getMotherName());

            c = r.createCell(6);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getMotherBirthYear() != null
                    ? children.get(rownum - 3).getMotherBirthYear()
                    : 0);

            c = r.createCell(7);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getMotherMobile());

            c = r.createCell(8);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getFatherName());

            c = r.createCell(9);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getFatherBirthYear() != null
                    ? children.get(rownum - 3).getFatherBirthYear()
                    : 0);

            c = r.createCell(10);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getFatherMobile());

            c = r.createCell(11);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getCaretakerName());

            c = r.createCell(12);
            c.setCellStyle(cs);
            c.setCellValue(children.get(rownum - 3).getCaretakerMobile());

            c = r.createCell(13);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getVGB());

            c = r.createCell(14);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getBCG());

            c = r.createCell(15);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getDPT_VGB_Hib1());

            c = r.createCell(16);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getDPT_VGB_Hib2());

            c = r.createCell(17);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getDPT_VGB_Hib3());

            c = r.createCell(18);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getOPV1());

            c = r.createCell(19);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getOPV2());

            c = r.createCell(20);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getOPV3());

            c = r.createCell(21);
            c.setCellStyle(cs2);
            c.setCellValue(children.get(rownum - 3).getMeasles1());
        }

        FileOutputStream fileOut = new FileOutputStream(filePath);
        wb.write(fileOut);
        fileOut.close();
        path = "/reports/" + prefixFileName + "_List_Children_Excel_" + currentTime + ".xls";
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return path;
}

From source file:org.apache.jasper.compiler.JspRuntimeContext.java

/**
 * Create a JspRuntimeContext for a web application context.
 *
 * Loads in any previously generated dependencies from file.
 *
 * @param ServletContext for web application
 *//*from  w  w w.j av  a  2s . c  o m*/
public JspRuntimeContext(ServletContext context, Options options) {

    System.setErr(new SystemLogHandler(System.err));

    this.context = context;
    this.options = options;

    // Get the parent class loader
    parentClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    if (parentClassLoader == null) {
        parentClassLoader = (URLClassLoader) this.getClass().getClassLoader();
    }

    if (log.isDebugEnabled()) {
        if (parentClassLoader != null) {
            log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", parentClassLoader.toString()));
        } else {
            log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>"));
        }
    }

    initClassPath();

    if (context instanceof org.apache.jasper.servlet.JspCServletContext) {
        return;
    }

    if (System.getSecurityManager() != null) {
        initSecurity();
    }

    // If this web application context is running from a
    // directory, start the background compilation thread
    String appBase = context.getRealPath("/");
    if (!options.getDevelopment() && appBase != null && options.getReloading()) {
        if (appBase.endsWith(File.separator)) {
            appBase = appBase.substring(0, appBase.length() - 1);
        }
        String directory = appBase.substring(appBase.lastIndexOf(File.separator));
        threadName = threadName + "[" + directory + "]";
        threadStart();
    }
}