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:com.tremolosecurity.scale.config.ScaleCommonConfig.java

@PostConstruct
public void init() {
    try {/*from  w ww. j  av a 2  s.  c  o  m*/
        ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();

        String logPath = null;

        try {
            logPath = InitialContext.doLookup("java:comp/env/scaleLog4jPath");
        } catch (NamingException ne) {
            try {
                logPath = InitialContext.doLookup("java:/env/scaleLog4jPath");
            } catch (NamingException ne2) {
                logPath = null;
            }
        }
        if (logPath == null) {
            Properties props = new Properties();
            props.put("log4j.rootLogger", "info,console");

            //props.put("log4j.appender.console","org.apache.log4j.RollingFileAppender");
            //props.put("log4j.appender.console.File","/home/mlb/myvd.log");
            props.put("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
            props.put("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
            props.put("log4j.appender.console.layout.ConversionPattern", "[%d][%t] %-5p %c{1} - %m%n");

            PropertyConfigurator.configure(props);
        } else {

            if (logPath.startsWith("WEB-INF/")) {
                org.apache.log4j.xml.DOMConfigurator.configure(context.getRealPath(logPath));
            } else {
                org.apache.log4j.xml.DOMConfigurator.configure(logPath);
            }

        }

        logger = Logger.getLogger(ScaleCommonConfig.class.getName());

        logger.info("Initializing Scale " + version);

        String configPath = null;

        try {
            configPath = InitialContext.doLookup("java:comp/env/scaleConfigPath");
        } catch (NamingException ne) {
            try {
                configPath = InitialContext.doLookup("java:/env/scaleConfigPath");
            } catch (NamingException ne2) {
                configPath = null;
            }

        }

        if (configPath == null) {
            configPath = "WEB-INF/scaleConfig.xml";
            logger.warn("No configuraiton path found - Loading configuration from '" + configPath + "'");
        } else {
            logger.info("Loading configuration from '" + configPath + "'");
        }

        InputStream in = null;

        if (configPath.startsWith("WEB-INF")) {

            in = new ByteArrayInputStream(ScaleCommonConfig
                    .includeEnvironmentVariables(context.getRealPath("/" + configPath)).getBytes("UTF-8"));

        } else {
            in = new ByteArrayInputStream(
                    ScaleCommonConfig.includeEnvironmentVariables(configPath).getBytes("UTF-8"));
        }

        JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.scale.config.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        Object obj = unmarshaller.unmarshal(in);

        JAXBElement<ScaleCommonConfigType> scaleConfig = (JAXBElement<ScaleCommonConfigType>) obj;

        this.scaleConfig = scaleConfig.getValue();

        String ksPath = this.scaleConfig.getServiceConfiguration().getKeyStorePath();
        String ksPass = this.scaleConfig.getServiceConfiguration().getKeyStorePassword();

        in = null;

        if (ksPath.startsWith("WEB-INF")) {
            in = context.getResourceAsStream("/" + ksPath);
        } else {
            in = new FileInputStream(ksPath);
        }

        this.tlsKeys = KeyStore.getInstance("JKS");
        this.tlsKeys.load(in, ksPass.toCharArray());

        this.sslctx = SSLContexts.custom().loadTrustMaterial(this.tlsKeys)
                .loadKeyMaterial(this.tlsKeys, ksPass.toCharArray()).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:PDF.Reportes.java

public void reportesPDF(HttpServletResponse response, int tr, ServletContext d, String usuario, String contra,
        String horario, int opc) {
    String reporteT = "";
    try {//w  ww . ja v  a 2s.c om

        Document reporte = new Document();
        Calendar cal = Calendar.getInstance();

        Paragraph intro = new Paragraph();
        intro.setAlignment(Element.ALIGN_CENTER);

        String linea = "/Imagenes/rallita.png";
        String absolute_url_linea = d.getRealPath(linea);

        Image linea_div = Image.getInstance(absolute_url_linea);

        Paragraph vacio = new Paragraph("  ", FontFactory.getFont("arial", 10));
        vacio.setAlignment(Element.ALIGN_CENTER);

        if (tr == 0) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(vacio);
            reporte.add(vacio);
            ArrayList<JFreeChart> graf = grafica(usuario, contra);
            if (graf == null) {

                intro = new Paragraph(
                        "Lo sentimos, por el momento an no existe informacin para este reporte.",
                        FontFactory.getFont("arial", 18));

                reporte.add(intro);
            } else {
                for (int i = 0; i < graf.size(); i++) {
                    BufferedImage bufferedImage = graf.get(i).createBufferedImage(500, 300);
                    Image chart = Image.getInstance(writer, bufferedImage, 1.0f);
                    reporte.add(vacio);
                    reporte.add(chart);
                }
            }
            reporteT = "Estadsticas de registros.";
        }
        if (tr == 1) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(linea_div);
            Paragraph creador = new Paragraph("Instituto Tecnolgico de Toluca\n" + "\n"
                    + "Centro de Cmputo\n" + "\n" + "Coordinacin de Desarrollo de Sistemas",
                    FontFactory.getFont("arial", 10));
            reporte.add(creador);
            reporte.add(linea_div);
            intro = new Paragraph("Sin alta en CENEVAL " + cal.get(Calendar.YEAR),
                    FontFactory.getFont("arial", 18));
            intro.setAlignment(Element.ALIGN_CENTER);
            reporte.add(intro);
            reporte.add(vacio);
            reporte.add(vacio);
            reporte.add(noaltaCen(usuario, contra));
            reporteT = "Sin alta en CENEVAL.";
        }
        if (tr == 2) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(linea_div);
            Paragraph creador = new Paragraph("Instituto Tecnolgico de Toluca\n" + "\n"
                    + "Centro de Cmputo\n" + "\n" + "Coordinacin de Desarrollo de Sistemas",
                    FontFactory.getFont("arial", 10));
            reporte.add(creador);
            reporte.add(linea_div);
            intro = new Paragraph("Estatus Prefichas " + cal.get(Calendar.YEAR),
                    FontFactory.getFont("arial", 18));
            intro.setAlignment(Element.ALIGN_CENTER);
            reporte.add(intro);
            reporte.add(vacio);
            reporte.add(vacio);

            reporte.add(statusfichas(usuario, contra));
            reporteT = "Estatus prefichas";
        }
        if (tr == 3) {
            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent event = new HeaderFooterPageEvent("header_pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            reporte.add(linea_div);
            Paragraph creador = new Paragraph("Instituto Tecnolgico de Toluca\n" + "\n"
                    + "Centro de Cmputo\n" + "\n" + "Coordinacin de Desarrollo de Sistemas",
                    FontFactory.getFont("arial", 10));
            reporte.add(creador);
            reporte.add(linea_div);
            intro = new Paragraph("Pre proceso concluido " + cal.get(Calendar.YEAR),
                    FontFactory.getFont("arial", 18));
            intro.setAlignment(Element.ALIGN_CENTER);
            reporte.add(intro);
            reporte.add(vacio);
            reporte.add(vacio);
            reporte.add(procesoCon(usuario, contra));
            reporteT = "Pre proceso concluido";
        }
        if (tr == 4) {

            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            ArrayList<PdfPTable> tables = firmasAspAula(usuario, contra, horario, opc);
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent2 event = new HeaderFooterPageEvent2("ficha-pdf.png");
            writer.setPageEvent(event);
            reporte.open();

            if (tables.size() != 1) {
                PdfPTable tableH = tables.get(tables.size() - 1);
                tableH.writeSelectedRows(0, -1, 10, 720, writer.getDirectContent());
            } else {
                reporte.add(tables.get(0));
            }
            reporte.add(vacio);

            reporte.add(vacio);
            reporte.add(vacio);
            for (int i = 0; i < tables.size(); i++) {

                if (i + 1 != tables.size()) {

                    reporte.add(tables.get(i));
                    if (i + 2 != tables.size()) {
                        reporte.newPage();
                    }
                }

            }

            reporteT = "Firmas Aspirantes_" + horario;

        }
        if (tr == 5) {

            PdfWriter writer = PdfWriter.getInstance(reporte, response.getOutputStream());
            ArrayList<PdfPTable> tables = tablaAspAula(usuario, contra, horario, opc);
            Rectangle rect = new Rectangle(30, 30, 550, 800);
            writer.setBoxSize("art", rect);
            HeaderFooterPageEvent2 event = new HeaderFooterPageEvent2("ficha-pdf.png");
            writer.setPageEvent(event);
            reporte.open();
            if (tables.size() != 1) {
                PdfPTable tableH = tables.get(tables.size() - 1);
                tableH.writeSelectedRows(0, -1, 10, 720, writer.getDirectContent());
            } else {
                reporte.add(tables.get(0));
            }

            reporte.add(vacio);

            reporte.add(vacio);
            reporte.add(vacio);
            for (int i = 0; i < tables.size(); i++) {

                if (i + 1 != tables.size()) {

                    reporte.add(tables.get(i));
                    if (i + 2 != tables.size()) {
                        reporte.newPage();
                    }
                }

            }

            reporteT = "Aspirantes por aula horario_" + horario;

        }

        reporte.addTitle("Reportes_" + reporteT);
        reporte.addSubject("Instituto Tecnolgico de Toluca");
        reporte.addKeywords("Instituto Tecnolgico de Toluca");
        reporte.addAuthor("Coordinacion de desarrollo de sistemas");
        reporte.addCreator("Centro de Cmputo ITT");

        //Asignamos el manejador de eventos al escritor.
        reporte.close();

    } catch (DocumentException | IOException ex) {
        Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

public String printListVaccinationReport(String type, String timeFrom, String timeTo, Commune commune,
        District district, List<RegionVaccinationReportData> statistics) {
    String path = "";
    String prefixFileName = "";
    if (commune != null)
        prefixFileName = commune.getDistrict().getProvince().getProvinceId()
                + commune.getDistrict().getDistrictId() + commune.getCommuneId();
    else//w  ww.  j av  a  2  s .c  o  m
        prefixFileName = district.getProvince().getProvinceId() + 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 + "_Report_" + currentTime;

    if (type.equalsIgnoreCase("pdf")) {
        JasperPrint reportPrint = createListVaccinationReportPrint(timeFrom, timeTo, commune, district,
                statistics);
        try {
            filePath += ".pdf";
            JasperExportManager.exportReportToPdfFile(reportPrint, filePath);
            path = "/reports/" + prefixFileName + "_Report_" + currentTime + ".pdf";
            log.debug("path to pdf report:" + path);
        } catch (Exception ex) {
            String connectMsg = "Could not create the report " + ex.getMessage() + " "
                    + ex.getLocalizedMessage();
            log.debug(connectMsg);
        }
    } else {
        filePath += ".xls";
        POIFSFileSystem fs;
        String regionName = "";
        String provinceName = "";
        String districtName = "";
        String communeName = "";
        String timeData = "";
        Short rId = 0;
        if (commune != null) {
            communeName = commune.getCommuneName();
            provinceName = commune.getDistrict().getProvince().getProvinceName();
            districtName = commune.getDistrict().getDistrictName();
            rId = commune.getDistrict().getProvince().getRegionId();
        } else if (district != null) {
            provinceName = district.getProvince().getProvinceName();
            districtName = district.getDistrictName();
            rId = district.getProvince().getRegionId();
        }
        if (rId == 1)
            regionName = "Mi?n Bc";
        else if (rId == 2)
            regionName = "Mi?n Trung";
        else
            regionName = "Mi?n Nam";
        if (timeFrom.equalsIgnoreCase(timeTo)) {
            timeData = timeTo;
        } else {
            timeData = timeFrom + " - " + timeTo;
        }
        try {
            fs = new POIFSFileSystem(new FileInputStream(reportDir + "/excel/TCMR_Report_Template.xls"));
            HSSFWorkbook wb = new HSSFWorkbook(fs, true);

            HSSFSheet s = wb.getSheetAt(0);

            HSSFRow r = null;
            HSSFCell c = null;

            r = s.getRow(4);
            c = r.getCell(1);
            c.setCellValue(c.getStringCellValue() + " " + regionName.toUpperCase());

            r = s.getRow(5);
            c = r.getCell(1);
            c.setCellValue(c.getStringCellValue() + " " + provinceName.toUpperCase());

            r = s.getRow(6);
            c = r.getCell(1);
            c.setCellValue(c.getStringCellValue() + " " + districtName.toUpperCase());

            r = s.getRow(7);
            c = r.getCell(1);
            c.setCellValue(c.getStringCellValue() + " " + communeName.toUpperCase());

            r = s.getRow(4);
            c = r.getCell(15);
            c.setCellValue(timeData);

            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);

            int rownum = 13;
            for (rownum = 13; rownum < statistics.size() + 11; rownum++) {
                if (rownum < statistics.size() + 10)
                    copyRow(wb, s, rownum, rownum + 1);
                r = s.getRow(rownum);
                r.setHeight((short) 270);
                c = r.getCell(1);
                c.setCellValue(rownum - 12);
                c = r.getCell(3);
                c.setCellValue(statistics.get(rownum - 13).getRegionName());
                c = r.getCell(6);
                c.setCellValue(statistics.get(rownum - 13).getChildrenUnder1() == null ? 0
                        : statistics.get(rownum - 13).getChildrenUnder1());
                c = r.getCell(8);
                c.setCellValue(statistics.get(rownum - 13).getBCG() + " ("
                        + statistics.get(rownum - 13).geteBCG() + ")");
                c = r.getCell(10);
                c.setCellValue(statistics.get(rownum - 13).getVGBL24() + " ("
                        + statistics.get(rownum - 13).geteVGBL24() + ")");
                c = r.getCell(11);
                c.setCellValue(statistics.get(rownum - 13).getVGBG24() + " ("
                        + statistics.get(rownum - 13).geteVGBG24() + ")");
                c = r.getCell(14);
                c.setCellValue(statistics.get(rownum - 13).getDPT_VGB_Hib1() + " ("
                        + statistics.get(rownum - 13).geteDPT_VGB_Hib1() + ")");
                c = r.getCell(16);
                c.setCellValue(statistics.get(rownum - 13).getDPT_VGB_Hib2() + " ("
                        + statistics.get(rownum - 13).geteDPT_VGB_Hib2() + ")");
                c = r.getCell(18);
                c.setCellValue(statistics.get(rownum - 13).getDPT_VGB_Hib3() + " ("
                        + statistics.get(rownum - 13).geteDPT_VGB_Hib3() + ")");
                c = r.getCell(19);
                c.setCellValue(statistics.get(rownum - 13).getOPV1() + " ("
                        + statistics.get(rownum - 13).geteOPV1() + ")");
                c = r.getCell(20);
                c.setCellValue(statistics.get(rownum - 13).getOPV2() + " ("
                        + statistics.get(rownum - 13).geteOPV2() + ")");
                c = r.getCell(21);
                c.setCellValue(statistics.get(rownum - 13).getOPV3() + " ("
                        + statistics.get(rownum - 13).geteOPV3() + ")");
                c = r.getCell(23);
                c.setCellValue(statistics.get(rownum - 13).getMeasles1() + " ("
                        + statistics.get(rownum - 13).geteMeasles1() + ")");
                c = r.getCell(25);
                c.setCellValue(statistics.get(rownum - 13).getAmountOfFinish());
                c = r.getCell(27);
                c.setCellValue(statistics.get(rownum - 13).getProtectedTetanusCases() == null ? 0
                        : statistics.get(rownum - 13).getProtectedTetanusCases());
                c = r.getCell(28);
                c.setCellValue(statistics.get(rownum - 13).getReactionNormalCases() == null ? 0
                        : statistics.get(rownum - 13).getReactionNormalCases());
                c = r.getCell(30);
                c.setCellValue(statistics.get(rownum - 13).getReactionSeriousCases() == null ? 0
                        : statistics.get(rownum - 13).getReactionSeriousCases());
            }
            if (statistics != null && statistics.size() > 0) {
                for (; rownum < statistics.size() + 13; rownum++) {
                    r = s.getRow(rownum);
                    c = r.getCell(6);
                    c.setCellValue(statistics.get(rownum - 13).getChildrenUnder1() == null ? 0
                            : statistics.get(rownum - 13).getChildrenUnder1());
                    c = r.getCell(8);
                    c.setCellValue(statistics.get(rownum - 13).getBCG() + "\n("
                            + statistics.get(rownum - 13).geteBCG() + ")");
                    c = r.getCell(10);
                    c.setCellValue(statistics.get(rownum - 13).getVGBL24() + "\n("
                            + statistics.get(rownum - 13).geteVGBL24() + ")");
                    c = r.getCell(11);
                    c.setCellValue(statistics.get(rownum - 13).getVGBG24() + "\n("
                            + statistics.get(rownum - 13).geteVGBG24() + ")");
                    c = r.getCell(14);
                    c.setCellValue(statistics.get(rownum - 13).getDPT_VGB_Hib1() + "\n("
                            + statistics.get(rownum - 13).geteDPT_VGB_Hib1() + ")");
                    c = r.getCell(16);
                    c.setCellValue(statistics.get(rownum - 13).getDPT_VGB_Hib2() + "\n("
                            + statistics.get(rownum - 13).geteDPT_VGB_Hib2() + ")");
                    c = r.getCell(18);
                    c.setCellValue(statistics.get(rownum - 13).getDPT_VGB_Hib3() + "\n("
                            + statistics.get(rownum - 13).geteDPT_VGB_Hib3() + ")");
                    c = r.getCell(19);
                    c.setCellValue(statistics.get(rownum - 13).getOPV1() + "\n("
                            + statistics.get(rownum - 13).geteOPV1() + ")");
                    c = r.getCell(20);
                    c.setCellValue(statistics.get(rownum - 13).getOPV2() + "\n("
                            + statistics.get(rownum - 13).geteOPV2() + ")");
                    c = r.getCell(21);
                    c.setCellValue(statistics.get(rownum - 13).getOPV3() + "\n("
                            + statistics.get(rownum - 13).geteOPV3() + ")");
                    c = r.getCell(23);
                    c.setCellValue(statistics.get(rownum - 13).getMeasles1() + "\n("
                            + statistics.get(rownum - 13).geteMeasles1() + ")");
                    c = r.getCell(25);
                    c.setCellValue(statistics.get(rownum - 13).getAmountOfFinish());
                    c = r.getCell(27);
                    c.setCellValue(statistics.get(rownum - 13).getProtectedTetanusCases() == null ? 0
                            : statistics.get(rownum - 13).getProtectedTetanusCases());
                    c = r.getCell(28);
                    c.setCellValue(statistics.get(rownum - 13).getReactionNormalCases() == null ? 0
                            : statistics.get(rownum - 13).getReactionNormalCases());
                    c = r.getCell(30);
                    c.setCellValue(statistics.get(rownum - 13).getReactionSeriousCases() == null ? 0
                            : statistics.get(rownum - 13).getReactionSeriousCases());
                    r.setHeight((short) 500);
                }
            } else {
                for (; rownum < 16; rownum++) {
                    r = s.getRow(rownum);
                    c = r.getCell(6);
                    c.setCellValue("");
                    c = r.getCell(8);
                    c.setCellValue("");
                    c = r.getCell(10);
                    c.setCellValue("");
                    c = r.getCell(11);
                    c.setCellValue("");
                    c = r.getCell(14);
                    c.setCellValue("");
                    c = r.getCell(16);
                    c.setCellValue("");
                    c = r.getCell(18);
                    c.setCellValue("");
                    c = r.getCell(19);
                    c.setCellValue("");
                    c = r.getCell(20);
                    c.setCellValue("");
                    c = r.getCell(21);
                    c.setCellValue("");
                    c = r.getCell(23);
                    c.setCellValue("");
                    c = r.getCell(25);
                    c.setCellValue("");
                    c = r.getCell(27);
                    c.setCellValue("");
                    c = r.getCell(28);
                    c.setCellValue("");
                    c = r.getCell(30);
                    c.setCellValue("");
                }
            }

            FileOutputStream fileOut = new FileOutputStream(filePath);
            wb.write(fileOut);
            fileOut.close();
            path = "/reports/" + prefixFileName + "_Report_" + currentTime + ".xls";
            log.debug("Excel: " + path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return path;
}

From source file:password.pwm.http.servlet.resource.ResourceFileServlet.java

static FileResource resolveRequestedFile(final ServletContext servletContext, final String resourcePathUri,
        final ResourceServletConfiguration resourceServletConfiguration) throws PwmUnrecoverableException {
    // URL-decode the file name (might contain spaces and on) and prepare file object.
    String filename = StringUtil.urlDecode(resourcePathUri);

    // parse out the session key...
    if (filename.contains(";")) {
        filename = filename.substring(0, filename.indexOf(";"));
    }// w  ww.j  a va 2 s  .co m

    if (!filename.startsWith(RESOURCE_PATH)) {
        LOGGER.warn("illegal url request to " + filename);
        throw new PwmUnrecoverableException(
                new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE, "illegal url request"));
    }

    {
        final FileResource resource = handleWebjarURIs(servletContext, resourcePathUri);
        if (resource != null) {
            return resource;
        }
    }

    {// check files system zip files.
        final Map<String, ZipFile> zipResources = resourceServletConfiguration.getZipResources();
        for (final String path : zipResources.keySet()) {
            if (filename.startsWith(path)) {
                final String zipSubPath = filename.substring(path.length() + 1, filename.length());
                final ZipFile zipFile = zipResources.get(path);
                final ZipEntry zipEntry = zipFile.getEntry(zipSubPath);
                if (zipEntry != null) {
                    return new ZipFileResource(zipFile, zipEntry);
                }
            }
            if (filename.startsWith(zipResources.get(path).getName())) {
                LOGGER.warn("illegal url request to " + filename + " zip resource");
                throw new PwmUnrecoverableException(
                        new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE, "illegal url request"));
            }
        }
    }

    // convert to file.
    final String filePath = servletContext.getRealPath(filename);
    final File file = new File(filePath);

    // figure top-most path allowed by request
    final String parentDirectoryPath = servletContext.getRealPath(RESOURCE_PATH);
    final File parentDirectory = new File(parentDirectoryPath);

    FileResource fileSystemResource = null;
    { //verify the requested page is a child of the servlet resource path.
        int recursions = 0;
        File recurseFile = file.getParentFile();
        while (recurseFile != null && recursions < 100) {
            if (parentDirectory.equals(recurseFile)) {
                fileSystemResource = new RealFileResource(file);
                break;
            }
            recurseFile = recurseFile.getParentFile();
            recursions++;
        }
    }

    if (fileSystemResource == null) {
        LOGGER.warn("attempt to access file outside of servlet path " + file.getAbsolutePath());
        throw new PwmUnrecoverableException(
                new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE, "illegal file path request"));
    }

    if (!fileSystemResource.exists()) { // check custom (configuration defined) zip file bundles
        final Map<String, FileResource> customResources = resourceServletConfiguration.getCustomFileBundle();
        for (final String customFileName : customResources.keySet()) {
            final String testName = RESOURCE_PATH + "/" + customFileName;
            if (testName.equals(resourcePathUri)) {
                return customResources.get(customFileName);
            }
        }
    }

    return fileSystemResource;
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {/*  w  ww .  j a v a2s  .c o  m*/

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadApplications(ServletContext servletContext) throws JAXBException, JSONException,
        InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException,
        SecurityException, InvocationTargetException, NoSuchMethodException, IOException,
        ParserConfigurationException, SAXException, TransformerFactoryConfigurationError, TransformerException,
        RapidLoadingException, XPathExpressionException {

    // get any existing applications
    Applications applications = (Applications) servletContext.getAttribute("applications");

    // check we got some
    if (applications != null) {
        // loop the application ids
        for (String appId : applications.getIds()) {
            // loop the versions
            for (String version : applications.getVersions(appId).keySet()) {
                // get the version
                Application application = applications.get(appId, version);
                // close it
                application.close(servletContext);
            }/*from  ww w  .j av  a 2  s. c  o  m*/
        }
    }

    // make a new set of applications
    applications = new Applications();

    File applicationFolderRoot = new File(servletContext.getRealPath("/WEB-INF/applications/"));

    for (File applicationFolder : applicationFolderRoot.listFiles()) {

        if (applicationFolder.isDirectory()) {

            // get the list of files in this folder - should be all version folders
            File[] applicationFolders = applicationFolder.listFiles();

            // assume we didn't need to version
            boolean versionCreated = false;

            // if we got some
            if (applicationFolders != null) {

                try {

                    // look for an application file in the root of the application folder
                    File applicationFile = new File(applicationFolder.getAbsoluteFile() + "/application.xml");

                    // set a version for this app (just in case it doesn't have one)
                    String version = "1";

                    // if it exists here, it's in the wrong (non-versioned) place!
                    if (applicationFile.exists()) {

                        // create a file for the new version folder
                        File versionFolder = new File(applicationFolder + "/" + version);
                        // keep appending the version if the folder already exists
                        while (versionFolder.exists()) {
                            // append .1 to the version 1, 1.1, 1.1.1, etc
                            version += ".1";
                            versionFolder = new File(applicationFolder + "/" + version);
                        }

                        // make the dir
                        versionFolder.mkdir();
                        _logger.info(versionFolder + " created");
                        // copy in all files and pages folder
                        for (File file : applicationFolders) {
                            // copy all files and the pages folder
                            if (!file.isDirectory() || (file.isDirectory() && "pages".equals(file.getName()))) {
                                // make a desintation file
                                File destFile = new File(versionFolder + "/" + file.getName());
                                // this is not a version folder itself, copy it to the new version folder
                                Files.copyFolder(file, destFile);
                                // delete the file or folder
                                Files.deleteRecurring(file);
                                // log
                                _logger.info(file + " moved to " + destFile);
                            }

                        }
                        // record that we created a version
                        versionCreated = true;

                    } // application.xml non-versioned check

                    try {

                        // get the version folders
                        File[] versionFolders = applicationFolder.listFiles();
                        // get a marshaller
                        Marshaller marshaller = RapidHttpServlet.getMarshaller();

                        // loop them
                        for (File versionFolder : versionFolders) {
                            // check is folder
                            if (versionFolder.isDirectory()) {
                                // look for an application file in the version folder
                                applicationFile = new File(versionFolder + "/application.xml");
                                // if it exists
                                if (applicationFile.exists()) {

                                    // placeholder for the application we're going to version up or just load
                                    Application application = null;

                                    // if we had to create a version for it
                                    if (versionCreated) {

                                        // load without resources
                                        application = Application.load(servletContext, applicationFile, false);

                                        // set the new version
                                        application.setVersion(version);

                                        // re-initialise it without resources (for the security adapter)
                                        application.initialise(servletContext, false);

                                        // marshal the updated application object to it's file
                                        FileOutputStream fos = new FileOutputStream(applicationFile);
                                        marshaller.marshal(application, fos);
                                        fos.close();

                                        // get a dir for the pages
                                        File pageDir = new File(versionFolder + "/pages");
                                        // check it exists
                                        if (pageDir.exists()) {
                                            // loop the pages files
                                            for (File pageFile : pageDir.listFiles()) {
                                                // read the contents of the file
                                                String pageContent = Strings.getString(pageFile);
                                                // replace all old file references
                                                pageContent = pageContent
                                                        .replace("/" + application.getId() + "/",
                                                                "/" + application.getId() + "/"
                                                                        + application.getVersion() + "/")
                                                        .replace("~?a=" + application.getId() + "&amp;",
                                                                "~?a=" + application.getId() + "&amp;"
                                                                        + application.getVersion() + "&amp;");
                                                // create a file writer
                                                FileWriter fs = new FileWriter(pageFile);
                                                // save the changes
                                                fs.write(pageContent);
                                                // close the writer
                                                fs.close();
                                                _logger.info(pageFile + " updated with new references");
                                            }
                                        }
                                        // make a dir for it's web resources
                                        File webDir = new File(application.getWebFolder(servletContext));
                                        webDir.mkdir();
                                        _logger.info(webDir + " created");
                                        // loop all the files in the parent
                                        for (File file : webDir.getParentFile().listFiles()) {
                                            // check not dir
                                            if (!file.isDirectory()) {
                                                // create a destination file for the new location
                                                File destFile = new File(webDir + "/" + file.getName());
                                                // copy it to the new destination
                                                Files.copyFile(file, destFile);
                                                // delete the file or folder
                                                file.delete();
                                                _logger.info(file + " moved to " + destFile);
                                            }

                                        }

                                    }

                                    // (re)load the application
                                    application = Application.load(servletContext, applicationFile);

                                    // put it in our collection
                                    applications.put(application);

                                }

                            } // folder check

                        } // version folder loop      

                    } catch (Exception ex) {

                        // log the exception
                        _logger.error(ex);

                    } // version load catch

                } catch (Exception ex) {

                    // log it
                    _logger.error("Error creating version folder for app " + applicationFolder, ex);

                } // version folder creation catch               

            } // application folders check

        } // application folder check

    } // application folder loop

    // store them in the context
    servletContext.setAttribute("applications", applications);

    _logger.info(applications.size() + " applications loaded");

    return applications.size();

}

From source file:org.xz.qstruts.views.velocity.VelocityManager.java

/**
 * load optional velocity properties using the following loading strategy
 * <ul>/* w w  w.j  a  v a 2s  . c o  m*/
 * <li>relative to the servlet context path</li>
 * <li>relative to the WEB-INF directory</li>
 * <li>on the classpath</li>
 * </ul>
 *
 * @param context the current ServletContext.  may <b>not</b> be null
 * @return the optional properties if struts.velocity.configfile was specified, an empty Properties file otherwise
 */
public Properties loadConfiguration(ServletContext context) {
    if (context == null) {
        String gripe = "Error attempting to create a loadConfiguration from a null ServletContext!";
        LOG.error(gripe);
        throw new IllegalArgumentException(gripe);
    }

    Properties properties = new Properties();

    // now apply our systemic defaults, then allow user to override
    applyDefaultConfiguration(context, properties);

    String defaultUserDirective = properties.getProperty("userdirective");
    properties.remove("userdirective");
    /**
     * if the user has specified an external velocity configuration file, we'll want to search for it in the
     * following order
     *
     * 1. relative to the context path
     * 2. relative to /WEB-INF
     * 3. in the class path
     */
    String configfile;

    if (customConfigFile != null) {
        configfile = customConfigFile;
    } else {
        configfile = "velocity.properties";
    }

    configfile = configfile.trim();

    InputStream in = null;
    String resourceLocation = null;

    try {
        if (context.getRealPath(configfile) != null) {
            // 1. relative to context path, i.e. /velocity.properties
            String filename = context.getRealPath(configfile);

            if (filename != null) {
                File file = new File(filename);

                if (file.isFile()) {
                    resourceLocation = file.getCanonicalPath() + " from file system";
                    in = new FileInputStream(file);
                }

                // 2. if nothing was found relative to the context path, search relative to the WEB-INF directory
                if (in == null) {
                    file = new File(context.getRealPath("/WEB-INF/" + configfile));

                    if (file.isFile()) {
                        resourceLocation = file.getCanonicalPath() + " from file system";
                        in = new FileInputStream(file);
                    }
                }
            }
        }

        // 3. finally, if there's no physical file, how about something in our classpath
        if (in == null) {
            in = VelocityManager.class.getClassLoader().getResourceAsStream(configfile);
            if (in != null) {
                resourceLocation = configfile + " from classloader";
            }
        }

        // if we've got something, load 'er up
        if (in != null) {
            LOG.info("Initializing velocity using " + resourceLocation);
            properties.load(in);
        }
    } catch (IOException e) {
        LOG.warn("Unable to load velocity configuration " + resourceLocation, e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }

    // overide with programmatically set properties
    if (this.velocityProperties != null) {
        Iterator keys = this.velocityProperties.keySet().iterator();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            properties.setProperty(key, this.velocityProperties.getProperty(key));
        }
    }

    String userdirective = properties.getProperty("userdirective");

    if ((userdirective == null) || userdirective.trim().equals("")) {
        userdirective = defaultUserDirective;
    } else {
        userdirective = userdirective.trim() + "," + defaultUserDirective;
    }

    properties.setProperty("userdirective", userdirective);

    // for debugging purposes, allows users to dump out the properties that have been configured
    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing Velocity with the following properties ...");

        for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            String value = properties.getProperty(key);

            if (LOG.isDebugEnabled()) {
                LOG.debug("    '" + key + "' = '" + value + "'");
            }
        }
    }

    return properties;
}

From source file:org.apache.struts2.views.velocity.VelocityManager.java

/**
 * load optional velocity properties using the following loading strategy
 * <ul>//from   w  w  w .j a  v a  2s .  c  om
 * <li>relative to the servlet context path</li>
 * <li>relative to the WEB-INF directory</li>
 * <li>on the classpath</li>
 * </ul>
 *
 * @param context the current ServletContext.  may <b>not</b> be null
 * @return the optional properties if struts.velocity.configfile was specified, an empty Properties file otherwise
 */
public Properties loadConfiguration(ServletContext context) {
    if (context == null) {
        String gripe = "Error attempting to create a loadConfiguration from a null ServletContext!";
        LOG.error(gripe);
        throw new IllegalArgumentException(gripe);
    }

    Properties properties = new Properties();

    // now apply our systemic defaults, then allow user to override
    applyDefaultConfiguration(context, properties);

    String defaultUserDirective = properties.getProperty("userdirective");

    /**
     * if the user has specified an external velocity configuration file, we'll want to search for it in the
     * following order
     *
     * 1. relative to the context path
     * 2. relative to /WEB-INF
     * 3. in the class path
     */
    String configfile;

    if (customConfigFile != null) {
        configfile = customConfigFile;
    } else {
        configfile = "velocity.properties";
    }

    configfile = configfile.trim();

    InputStream in = null;
    String resourceLocation = null;

    try {
        if (context.getRealPath(configfile) != null) {
            // 1. relative to context path, i.e. /velocity.properties
            String filename = context.getRealPath(configfile);

            if (filename != null) {
                File file = new File(filename);

                if (file.isFile()) {
                    resourceLocation = file.getCanonicalPath() + " from file system";
                    in = new FileInputStream(file);
                }

                // 2. if nothing was found relative to the context path, search relative to the WEB-INF directory
                if (in == null) {
                    file = new File(context.getRealPath("/WEB-INF/" + configfile));

                    if (file.isFile()) {
                        resourceLocation = file.getCanonicalPath() + " from file system";
                        in = new FileInputStream(file);
                    }
                }
            }
        }

        // 3. finally, if there's no physical file, how about something in our classpath
        if (in == null) {
            in = VelocityManager.class.getClassLoader().getResourceAsStream(configfile);
            if (in != null) {
                resourceLocation = configfile + " from classloader";
            }
        }

        // if we've got something, load 'er up
        if (in != null) {
            if (LOG.isInfoEnabled()) {
                LOG.info("Initializing velocity using " + resourceLocation);
            }
            properties.load(in);
        }
    } catch (IOException e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("Unable to load velocity configuration " + resourceLocation, e);
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }

    // overide with programmatically set properties
    if (this.velocityProperties != null) {
        Iterator keys = this.velocityProperties.keySet().iterator();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            properties.setProperty(key, this.velocityProperties.getProperty(key));
        }
    }

    String userdirective = properties.getProperty("userdirective");

    if ((userdirective == null) || userdirective.trim().equals("")) {
        userdirective = defaultUserDirective;
    } else {
        userdirective = userdirective.trim() + "," + defaultUserDirective;
    }

    properties.setProperty("userdirective", userdirective);

    // for debugging purposes, allows users to dump out the properties that have been configured
    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing Velocity with the following properties ...");

        for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            String value = properties.getProperty(key);

            if (LOG.isDebugEnabled()) {
                LOG.debug("    '" + key + "' = '" + value + "'");
            }
        }
    }

    return properties;
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private void initResources(FilterConfig config) {
    try {/* w ww. j  ava 2 s  .com*/
        if (CONFIG.getContent().getAssetsUrl() != null) {
            LOGGER.log(Level.INFO, "Using external assets, please provide the jsmart assets content at ["
                    + CONFIG.getContent().getAssetsUrl() + "]");
        }

        ServletContext context = config.getServletContext();
        Set<String> libs = context.getResourcePaths(LIB_FILE_PATH);

        if (libs == null || libs.isEmpty()) {
            LOGGER.log(Level.SEVERE, "Could not find the JSmart library JAR file. Empty [" + LIB_FILE_PATH
                    + "] resource folder.");
            return;
        }

        String libFilePath = null;
        for (String lib : libs) {
            Matcher matcher = JAR_FILE_PATTERN.matcher(lib);
            if (matcher.find()) {
                libFilePath = matcher.group();
                break;
            }
        }

        if (libFilePath == null) {
            LOGGER.log(Level.SEVERE,
                    "Could not find the JSmart library JAR file inside [" + LIB_FILE_PATH + "]");
            return;
        }

        Resources jsonResources = EXPRESSIONS.GSON.fromJson(convertResourceToString(FILTER_RESOURCES),
                Resources.class);

        File libFile = new File(context.getRealPath(libFilePath));
        Dir content = Vfs.fromURL(libFile.toURI().toURL());

        Iterator<Vfs.File> files = content.getFiles().iterator();
        while (files.hasNext()) {
            Vfs.File file = files.next();

            // Copy index.jsp and replace content to redirect to welcome-url case configured
            if (file.getRelativePath().startsWith(INDEX_JSP)) {
                if (CONFIG.getContent().getWelcomeUrl() != null) {
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(file.openInputStream(), writer);
                    String index = writer.toString().replace("{0}", CONFIG.getContent().getWelcomeUrl());
                    copyFileResource(new ByteArrayInputStream(index.getBytes(ENCODING)), file.getRelativePath(),
                            context);
                }
            }

            // Do not copy anything if assets-url was provided
            if (CONFIG.getContent().getAssetsUrl() != null) {
                continue;
            }

            // Copy js, css and font resources to specific location
            for (String resource : jsonResources.getResources()) {
                String resourcePath = resource.replace("*", "");

                if (file.getRelativePath().startsWith(resourcePath)) {
                    initDirResources(context.getRealPath(PATH_SEPARATOR), file.getRelativePath());
                    copyFileResource(file.openInputStream(), file.getRelativePath(), context);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:org.vfny.geoserver.config.web.tiles.definition.MultipleDefinitionsFactory.java

/**
 * Parse specified xml file and add definition to specified definitions set.
 * This method is used to load several description files in one instances list.
 * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return
 * passed definition set (can be <code>null</code>).
 * @param servletContext Current servlet context. Used to open file.
 * @param filename Name of file to parse.
 * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions
 * set is created on request./*from   ww  w. ja va 2  s.c  om*/
 * @return XmlDefinitionsSet The definitions set created or passed as parameter.
 * @throws DefinitionsFactoryException On errors parsing file.
 */
private XmlDefinitionsSet parseXmlFile(ServletContext servletContext, String filename,
        XmlDefinitionsSet xmlDefinitions) throws DefinitionsFactoryException {
    try {
        /*InputStream input = servletContext.getResourceAsStream(filename);*/
        InputStream input = null;
        Resource[] resources = WebApplicationContextUtils.getWebApplicationContext(servletContext)
                .getResources(filename);
        final int length = resources.length;

        for (int i = 0; i < length; i++) {
            try {
                input = resources[i].getURL().openStream(); /*getServletContext().getResource(path)*/
            } catch (IOException e) {
                //error loading from this resource.  Probably it doesn't exist.
                if (log.isDebugEnabled()) {
                    log.debug("", e);
                }

                return xmlDefinitions;
            }

            // Try to load using real path.
            // This allow to load config file under websphere 3.5.x
            // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002
            if (null == input) {
                try {
                    input = new java.io.FileInputStream(servletContext.getRealPath(filename));
                } catch (Exception e) {
                }
            }

            // If still nothing found, this mean no config file is associated
            if (input == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Can't open file '" + filename + "'");
                }

                return xmlDefinitions;
            }

            // Check if parser already exist.
            // Doesn't seem to work yet.
            //if( xmlParser == null )
            if (true) {
                xmlParser = new XmlParser();
                xmlParser.setValidating(isValidatingParser);
            }

            // Check if definition set already exist.
            if (xmlDefinitions == null) {
                xmlDefinitions = new XmlDefinitionsSet();
            }

            xmlParser.parse(input, xmlDefinitions);
        }
    } catch (SAXException ex) {
        if (log.isDebugEnabled()) {
            log.debug("Error while parsing file '" + filename + "'.");
            ex.printStackTrace();
        }

        throw new DefinitionsFactoryException("Error while parsing file '" + filename + "'. " + ex.getMessage(),
                ex);
    } catch (IOException ex) {
        /*throw new DefinitionsFactoryException*/
        if (log.isDebugEnabled()) {
            log.debug("IO Error while parsing file '" + filename + "'. " + ex.getMessage(), ex);
        }
    }

    return xmlDefinitions;
}