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:org.jbpm.designer.web.preprocessing.impl.JbpmPreprocessingUnit.java

public JbpmPreprocessingUnit(ServletContext servletContext, String designerPath, VFSService vfsService) {
    this.designer_path = designerPath.substring(0, designerPath.length() - 1);
    this.vfsService = vfsService;
    stencilPath = servletContext.getRealPath(designer_path + "/" + STENCILSET_PATH);
    origStencilFilePath = stencilPath + "/bpmn2.0jbpm/stencildata/" + "bpmn2.0jbpm.orig";
    stencilFilePath = stencilPath + "/bpmn2.0jbpm/" + "bpmn2.0jbpm.json";
    workitemSVGFilePath = stencilPath + "/bpmn2.0jbpm/view/activity/workitems/";
    origWorkitemSVGFile = workitemSVGFilePath + "workitem.orig";
    default_emailicon = servletContext.getRealPath(designer_path + "/defaults/defaultemailicon.gif");
    default_logicon = servletContext.getRealPath(designer_path + "/defaults/defaultlogicon.gif");
    default_servicenodeicon = servletContext
            .getRealPath(designer_path + "/defaults/defaultservicenodeicon.png");
    default_widconfigtemplate = servletContext.getRealPath(designer_path + "/defaults/WorkDefinitions.wid.st");
    themeInfo = servletContext.getRealPath(designer_path + "/defaults/themes.json");
    formWidgetsDir = servletContext.getRealPath(designer_path + "/defaults/formwidgets");
    customEditorsInfo = servletContext.getRealPath(designer_path + "/defaults/customeditors.json");
    patternsData = servletContext.getRealPath(designer_path + "/defaults/patterns.json");
    sampleBpmn2 = servletContext.getRealPath(designer_path + "/defaults/SampleProcess.bpmn2");
    includeDataObjects = Boolean.parseBoolean(
            System.getProperty(INCLUDE_DATA_OBJECT) == null ? "true" : System.getProperty(INCLUDE_DATA_OBJECT));
}

From source file:org.more.webui.components.upload.Upload.java

public void onEvent(Event event, UIComponent component, ViewContext viewContext) throws Throwable {
    Upload swfUpload = (Upload) component;
    HttpServletRequest httpRequest = viewContext.getHttpRequest();
    ServletContext servletContext = httpRequest.getSession(true).getServletContext();
    if (ServletFileUpload.isMultipartContent(httpRequest) == false)
        return;// ??multipart??
    try {/* w w  w .  ja  v  a  2  s.  c  om*/
        //1.
        DiskFileItemFactory factory = new DiskFileItemFactory();// DiskFileItemFactory??????List
        ServletFileUpload upload = new ServletFileUpload(factory);
        String charset = httpRequest.getCharacterEncoding();
        if (charset != null)
            upload.setHeaderEncoding(charset);
        factory.setSizeThreshold(swfUpload.getUploadSizeThreshold());
        File uploadTempDir = new File(servletContext.getRealPath(swfUpload.getUploadTempDir()));
        if (uploadTempDir.exists() == false)
            uploadTempDir.mkdirs();
        factory.setRepository(uploadTempDir);
        //2.?
        List<FileItem> itemList = upload.parseRequest(httpRequest);
        List<FileItem> finalList = new ArrayList<FileItem>();
        Map<String, String> finalParam = new HashMap<String, String>();
        for (FileItem item : itemList)
            if (item.isFormField() == false)
                finalList.add(item);
            else
                finalParam.put(new String(item.getFieldName().getBytes("iso-8859-1")),
                        new String(item.getString().getBytes("iso-8859-1")));
        //3.
        Object returnData = null;
        MethodExpression onBizActionExp = swfUpload.getOnBizActionExpression();
        if (onBizActionExp != null) {
            HashMap<String, Object> upObject = new HashMap<String, Object>();
            upObject.put("files", finalList);
            upObject.put("params", finalParam);
            HashMap<String, Object> upParam = new HashMap<String, Object>();
            upParam.put("up", upObject);
            returnData = onBizActionExp.execute(component, viewContext, upParam);
        }
        //4.??
        for (FileItem item : itemList)
            try {
                item.delete();
            } catch (Exception e) {
            }
        //5.
        viewContext.sendObject(returnData);
    } catch (Exception e) {
        viewContext.sendError(e);
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentUninstaller.java

@Override
public boolean uninstallComponent(Component component) throws ApsSystemException {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) _applicationContext)
            .getServletContext();//  www .j  a  v a 2  s  . c om
    ClassLoader cl = (ClassLoader) servletContext.getAttribute("componentInstallerClassLoader");
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    ClassPathXmlApplicationContext appCtx = null;
    if (ctxList != null) {
        for (ClassPathXmlApplicationContext ctx : ctxList) {
            if (component.getCode().equals(ctx.getDisplayName())) {
                appCtx = ctx;
            }
        }
    }
    String appRootPath = servletContext.getRealPath("/");
    String backupDirPath = appRootPath + "componentinstaller" + File.separator + component.getArtifactId()
            + "-backup";
    Map<File, File> resourcesMap = new HashMap<File, File>();
    try {
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            if (cl != null) {
                Thread.currentThread().setContextClassLoader(cl);
            }
            if (null == component || null == component.getUninstallerInfo()) {
                return false;
            }
            this.getDatabaseManager().createBackup();//backup database
            SystemInstallationReport report = super.extractReport();
            ComponentUninstallerInfo ui = component.getUninstallerInfo();
            //remove records from db
            String[] dataSourceNames = this.extractBeanNames(DataSource.class);
            for (int j = 0; j < dataSourceNames.length; j++) {
                String dataSourceName = dataSourceNames[j];
                Resource resource = (null != ui) ? ui.getSqlResources(dataSourceName) : null;
                String script = (null != resource) ? this.readFile(resource) : null;
                if (null != script && script.trim().length() > 0) {
                    DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
                    String[] queries = QueryExtractor.extractDeleteQueries(script);
                    TableDataUtils.executeQueries(dataSource, queries, true);
                }
            }
            this.executePostProcesses(ui.getPostProcesses());

            //drop tables
            Map<String, List<String>> tableMapping = component.getTableMapping();
            if (tableMapping != null) {
                for (int j = 0; j < dataSourceNames.length; j++) {
                    String dataSourceName = dataSourceNames[j];
                    List<String> tableClasses = tableMapping.get(dataSourceName);
                    if (null != tableClasses && tableClasses.size() > 0) {
                        List<String> newList = new ArrayList<String>();
                        newList.addAll(tableClasses);
                        Collections.reverse(newList);
                        DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
                        IDatabaseManager.DatabaseType type = this.getDatabaseManager()
                                .getDatabaseType(dataSource);
                        TableFactory tableFactory = new TableFactory(dataSourceName, dataSource, type);
                        tableFactory.dropTables(newList);
                    }
                }
            }

            //move resources (jar, files and folders) on temp folder  
            List<String> resourcesPaths = ui.getResourcesPaths();
            if (resourcesPaths != null) {
                for (String resourcePath : resourcesPaths) {
                    try {
                        String fullResourcePath = servletContext.getRealPath(resourcePath);
                        File resFile = new File(fullResourcePath);
                        String relResPath = FilenameUtils.getPath(resFile.getAbsolutePath());
                        File newResFile = new File(
                                backupDirPath + File.separator + relResPath + resFile.getName());
                        if (resFile.isDirectory()) {
                            FileUtils.copyDirectory(resFile, newResFile);
                            resourcesMap.put(resFile, newResFile);
                            FileUtils.deleteDirectory(resFile);
                        } else {
                            FileUtils.copyFile(resFile, newResFile);
                            resourcesMap.put(resFile, newResFile);
                            FileUtils.forceDelete(resFile);
                        }
                    } catch (Exception e) {
                    }
                }
            }

            //upgrade report
            ComponentInstallationReport cir = report.getComponentReport(component.getCode(), true);
            cir.getDataSourceReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
            cir.getDataReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
            this.saveReport(report);

            //remove plugin's xmlapplicationcontext if present
            if (appCtx != null) {
                appCtx.close();
                ctxList.remove(appCtx);
            }
            InitializerManager initializerManager = (InitializerManager) _applicationContext
                    .getBean("InitializerManager");
            initializerManager.reloadCurrentReport();
            ComponentManager componentManager = (ComponentManager) _applicationContext
                    .getBean("ComponentManager");
            componentManager.refresh();
        } catch (Exception e) {
            _logger.error("Unexpected error in component uninstallation process", e);
            throw new ApsSystemException("Unexpected error in component uninstallation process.", e);
        } finally {
            Thread.currentThread().setContextClassLoader(currentClassLoader);
            ApsWebApplicationUtils.executeSystemRefresh(servletContext);
        }
    } catch (Throwable t) {
        //restore files on temp folder
        try {
            for (Object object : resourcesMap.entrySet()) {
                File resFile = ((Map.Entry<File, File>) object).getKey();
                File newResFile = ((Map.Entry<File, File>) object).getValue();
                if (newResFile.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(newResFile, resFile.getParentFile());
                } else {
                    FileUtils.copyFile(newResFile, resFile.getParentFile());
                }
            }
        } catch (Exception e) {
        }
        _logger.error("Unexpected error in component uninstallation process", t);
        throw new ApsSystemException("Unexpected error in component uninstallation process.", t);
    } finally {
        //clean temp folder
    }
    return true;
}

From source file:info.magnolia.cms.servlets.PropertyInitializer.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *///from w ww .  ja v a2s  . c  om
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();

    String propertiesLocationString = context.getInitParameter(MAGNOLIA_INITIALIZATION_FILE);

    if (log.isDebugEnabled()) {
        log.debug("{} value in web.xml is :[{}]", MAGNOLIA_INITIALIZATION_FILE, propertiesLocationString); //$NON-NLS-1$
    }
    if (StringUtils.isEmpty(propertiesLocationString)) {
        propertiesLocationString = DEFAULT_INITIALIZATION_PARAMETER;
    }

    String[] propertiesLocation = StringUtils.split(propertiesLocationString, ',');

    String servername = null;

    try {
        servername = StringUtils.lowerCase(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        log.error(e.getMessage());
    }

    String rootPath = StringUtils.replace(context.getRealPath(StringUtils.EMPTY), "\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
    String webapp = StringUtils.substringAfterLast(rootPath, "/"); //$NON-NLS-1$

    File logs = new File(webapp + File.separator + "logs");
    File tmp = new File(webapp + File.separator + "tmp");
    if (!logs.exists()) {
        logs.mkdir();
        log.debug("Creating " + logs.getAbsoluteFile() + " folder");
    }

    if (!tmp.exists()) {
        tmp.mkdir();
        log.debug("Creating " + tmp.getAbsoluteFile() + " folder");
    }

    if (log.isDebugEnabled()) {
        log.debug("rootPath is {}, webapp is {}", rootPath, webapp); //$NON-NLS-1$ 
    }

    for (int j = 0; j < propertiesLocation.length; j++) {
        String location = StringUtils.trim(propertiesLocation[j]);
        location = StringUtils.replace(location, "${servername}", servername); //$NON-NLS-1$
        location = StringUtils.replace(location, "${webapp}", webapp); //$NON-NLS-1$

        File initFile = new File(rootPath, location);

        if (!initFile.exists() || initFile.isDirectory()) {
            if (log.isDebugEnabled()) {
                log.debug("Configuration file not found with path [{}]", //$NON-NLS-1$
                        initFile.getAbsolutePath());
            }
            continue;
        }

        InputStream fileStream;
        try {
            fileStream = new FileInputStream(initFile);
        } catch (FileNotFoundException e1) {
            log.debug("Configuration file not found with path [{}]", //$NON-NLS-1$
                    initFile.getAbsolutePath());
            return;
        }

        try {
            envProperties.load(fileStream);

            log.info("Loading configuration at {}", initFile.getAbsolutePath());//$NON-NLS-1$

            Log4jConfigurer.initLogging(context, envProperties);

            new ConfigLoader(context, envProperties);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fileStream);
        }
        return;

    }

    log.error(MessageFormat.format(
            "No configuration found using location list {0}. [servername] is [{1}], [webapp] is [{2}] and base path is [{3}]", //$NON-NLS-1$
            new Object[] { ArrayUtils.toString(propertiesLocation), servername, webapp, rootPath }));

}

From source file:org.jboss.bpm.report.BirtService.java

/**
 * Render a report based on render meta data.
 * this routine simply return the output filename.
 * in order to get to an absolute path you need to prepend the service output directory:<p>
 * <code>//from   w  w w  . jav a 2s  .c  o m
 *  BirtService.getIntegrationConfig().getOutputDir() + outputFileName;
 * </code>
 *
 * @param metaData render instruction like the template name
 * @return output filename
 */
public String view(RenderMetaData metaData, ServletContext servletContext, HttpServletRequest request) {
    if ((currentState == State.CREATED || currentState == State.STARTED) == false)
        throw new IllegalStateException("Cannot renderTask in state " + currentState);

    if (!reports.keySet().contains(metaData.getReportName()))
        throw new IllegalArgumentException("No such report template: " + metaData.getReportName());

    String outputFileName = null;

    log.debug("View " + metaData);

    IRenderTask renderTask = null;

    try {
        //Open a (cached) report design
        IReportDocument document = engine
                .openReportDocument(servletContext.getRealPath("/WEB-INF" + iConfig.getOutputDir()) + "/"
                        + metaData.getReportName() + ".rptdocument");

        //Create renderTask to run and renderTask the report,
        renderTask = engine.createRenderTask(document);

        //Set parent classloader for engine
        renderTask.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, metaData.getClassloader());
        renderTask.setParameterValues(metaData.getParameters());

        // ------------------

        IRenderOption options = new RenderOption();
        switch (metaData.getFormat()) {
        case HTML:
            options.setOutputFormat("html");
            outputFileName = extactReportName(metaData.getReportName()) + ".html";
            break;
        case PDF:
            options.setOutputFormat("pdf");
            outputFileName = extactReportName(metaData.getReportName()) + ".pdf";
            break;
        }
        options.setOutputFileName(
                servletContext.getRealPath("/WEB-INF" + iConfig.getOutputDir()) + "/" + outputFileName);

        // ------------------

        if (options.getOutputFormat().equalsIgnoreCase("html")) {
            HTMLRenderOption htmlOptions = new HTMLRenderOption(options);
            htmlOptions.setImageHandler(new HTMLServerImageHandler());
            htmlOptions.setImageDirectory(servletContext.getRealPath("/WEB-INF" + iConfig.getImageDirectory()));
            htmlOptions.setBaseImageURL(metaData.getImageBaseUrl());
            htmlOptions.setHtmlPagination(false);
            htmlOptions.setHtmlRtLFlag(false);
            htmlOptions.setLayoutPreference(HTMLRenderOption.LAYOUT_PREFERENCE_AUTO);
            htmlOptions.setSupportedImageFormats("PNG");
            //Setting this to true removes html and body tags
            htmlOptions.setEmbeddable(false);
            renderTask.setRenderOption(htmlOptions);
        } else if (options.getOutputFormat().equalsIgnoreCase("pdf")) {

            PDFRenderOption pdfOptions = new PDFRenderOption(options);
            pdfOptions.setOption(IPDFRenderOption.FIT_TO_PAGE, new Boolean(true));
            pdfOptions.setOption(IPDFRenderOption.PAGEBREAK_PAGINATION_ONLY, new Boolean(true));
            renderTask.setRenderOption(pdfOptions);
        }

        // ------------------
        if (renderTask.getRenderOption() == null)
            renderTask.setRenderOption(options);

        renderTask.render();

    } catch (EngineException e) {
        throw new RuntimeException("Failed to renderTask report: " + e.getMessage(), e);
    } finally {
        if (renderTask != null)
            renderTask.close();
    }

    return outputFileName;
}

From source file:com.orchestra.portale.controller.EditEventController.java

@RequestMapping(value = "/updateevent", method = RequestMethod.POST)
public ModelAndView updateEvent(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    CompletePOI poi = pm.getCompletePoiById(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }/*from www .j av a  2s  .  com*/
    }
    ModelAndView model = new ModelAndView("editedpoi");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));
    poi.setVisibility("1");
    poi.setAddress(params.get("address"));
    double lat = Double.parseDouble(params.get("latitude"));
    double longi = Double.parseDouble(params.get("longitude"));
    poi.setLocation(new double[] { lat, longi });
    poi.setStart_date(params.get("datai"));
    poi.setEnd_date(params.get("dataf"));
    poi.setShortDescription(params.get("shortd"));
    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1))) {
                img.setCredit(params.get("newcredit" + (i + 1)));
            }
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1))) {
                img.setCredit(params.get("credit" + (iximg + 1)));
            }
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //componente contatti
    ContactsComponent contacts_component = new ContactsComponent();
    //Recapiti telefonici
    i = 1;
    boolean contacts = false;
    if (params.containsKey("tel" + i)) {
        ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>();

        while (params.containsKey("tel" + i)) {
            PhoneContact phone = new PhoneContact();
            if (params.containsKey("tel" + i)) {
                phone.setLabel(params.get("desctel" + i));
            }
            phone.setNumber(params.get("tel" + i));
            phoneList.add(phone);
            i = i + 1;
        }
        contacts = true;
        contacts_component.setPhoneList(phoneList);
    }
    //Recapiti mail
    i = 1;
    if (params.containsKey("email" + i)) {
        ArrayList<EmailContact> emailList = new ArrayList<EmailContact>();

        while (params.containsKey("email" + i)) {
            EmailContact email = new EmailContact();
            if (params.containsKey("email" + i)) {
                email.setLabel(params.get("descemail" + i));
            }
            email.setEmail(params.get("email" + i));
            emailList.add(email);
            i = i + 1;
        }
        contacts = true;
        contacts_component.setEmailsList(emailList);
    }
    //Recapiti fax
    i = 1;
    if (params.containsKey("fax" + i)) {
        ArrayList<FaxContact> faxList = new ArrayList<FaxContact>();

        while (params.containsKey("fax" + i)) {
            FaxContact fax = new FaxContact();
            if (params.containsKey("fax" + i)) {
                fax.setLabel(params.get("descfax" + i));
            }
            fax.setFax(params.get("fax" + i));
            faxList.add(fax);
            i = i + 1;
        }
        contacts = true;
        contacts_component.setFaxList(faxList);
    }
    //Social predefiniti
    i = 1;
    if (params.containsKey("SN" + i)) {

        while (params.containsKey("SN" + i)) {
            if (params.get("SN" + i).equals("facebook")) {
                contacts = true;
                contacts_component.setFacebook(params.get("LSN" + i));
            }
            if (params.get("SN" + i).equals("twitter")) {
                contacts = true;
                contacts_component.setTwitter(params.get("LSN" + i));
            }
            if (params.get("SN" + i).equals("google")) {
                contacts = true;
                contacts_component.setGoogle(params.get("LSN" + i));
            }
            if (params.get("SN" + i).equals("skype")) {
                contacts = true;
                contacts_component.setSkype(params.get("LSN" + i));
            }
            i = i + 1;
        }
    }
    //Social personalizzati
    i = 1;
    if (params.containsKey("CSN" + i)) {
        ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>();

        while (params.containsKey("CSN" + i)) {
            GenericSocial social = new GenericSocial();
            contacts = true;
            social.setLabel(params.get("CSN" + i));
            social.setSocial(params.get("LCSN" + i));
            customsocial.add(social);
            i = i + 1;
        }
        contacts_component.setSocialList(customsocial);
    }
    if (contacts == true) {
        listComponent.add(contacts_component);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {
        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    //Orari
    i = 1;
    int k = 1;
    boolean ok = false;
    String gg = "";
    boolean[] aperto = new boolean[8];

    EventsDateComponent workingtime = new EventsDateComponent();
    if (params.containsKey("WD" + i + "start" + k + "H")) {
        ArrayList<EventsDates> workingdays = new ArrayList<EventsDates>();

        while (params.containsKey("WD" + i)) {
            ArrayList<EventsHours> Listwh = new ArrayList<EventsHours>();
            k = 1;
            while (params.containsKey("WD" + i + "start" + k + "H")) {
                EventsHours wh = new EventsHours();
                wh.setStart(params.get("WD" + i + "start" + k + "H") + ":"
                        + params.get("WD" + i + "start" + k + "M"));
                wh.setEnd(
                        params.get("WD" + i + "end" + k + "H") + ":" + params.get("WD" + i + "end" + k + "M"));
                Listwh.add(wh);
                k = k + 1;
            }
            EventsDates cwd = new EventsDates();
            cwd.setDate(params.get("WD" + i));
            cwd.setHours(Listwh);
            workingdays.add(cwd);
            i = i + 1;
        }

        workingtime.setDates(workingdays);
        listComponent.add(workingtime);
    }

    i = 1;
    if (params.containsKey("type" + i)) {

        PricesComponent pc = new PricesComponent();
        ArrayList<TicketPrice> tpList = new ArrayList<TicketPrice>();
        while (params.containsKey("type" + i)) {
            TicketPrice tp = new TicketPrice();
            tp.setType(params.get("type" + i));
            double dp = Double.parseDouble(params.get("price" + i));
            tp.setPrice(dp);
            tp.setType_description(params.get("typedesc" + i));
            tpList.add(tp);
            i = i + 1;
        }
        pc.setPrices(tpList);
        listComponent.add(pc);
    }

    i = 1;
    if (params.containsKey("SERV" + i)) {
        ArrayList<String> servList = new ArrayList<String>();
        while (params.containsKey("SERV" + i)) {
            servList.add(params.get("SERV" + i));
            i = i + 1;
        }
        ServicesComponent servicescomponent = new ServicesComponent();
        servicescomponent.setServicesList(servList);
        listComponent.add(servicescomponent);
    }
    poi.setComponents(listComponent);

    pm.savePoi(poi);

    CompletePOI poi2 = (CompletePOI) pm.findOneCompletePoiByName(poi.getName());

    // POI INGLESE 
    if (params.get("inglese").equals("true")) {
        addeng(params, poi2.getId(), coverimg, img_gallery);
    } else {
        EnCompletePOI enpoi = new EnCompletePOI();
        enpoi.setAddress(poi.getAddress());
        enpoi.setCategories(poi.getCategories());
        enpoi.setId(poi.getId());
        enpoi.setName(poi.getName());
        enpoi.setShortDescription(poi.getShortDescription());
        enpoi.setStart_date(poi.getStart_date());
        enpoi.setEnd_date(poi.getEnd_date());
        double enlat = Double.parseDouble(params.get("latitude"));
        double enlongi = Double.parseDouble(params.get("longitude"));
        poi.setLocation(new double[] { enlat, enlongi });
        enpoi.setComponents(listComponent);

        pm.saveEnPoi(enpoi);
    }
    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "poi" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE
    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }
    return model;
}

From source file:org.apache.struts2.spring.ClassReloadingXMLWebApplicationContext.java

public void setupReloading(String[] watchList, String acceptClasses, ServletContext servletContext,
        boolean reloadConfig) {
    this.reloadConfig = reloadConfig;

    classLoader = new ReloadingClassLoader(ClassReloadingXMLWebApplicationContext.class.getClassLoader());

    //make a list of accepted classes
    if (StringUtils.isNotBlank(acceptClasses)) {
        String[] splitted = acceptClasses.split(",");
        Set<Pattern> patterns = new HashSet<Pattern>(splitted.length);
        for (String pattern : splitted)
            patterns.add(Pattern.compile(pattern));

        classLoader.setAccepClasses(patterns);
    }/*from  w  w  w. j av a 2 s  .  c o m*/

    fam = new FilesystemAlterationMonitor();

    //setup stores
    for (String watch : watchList) {
        File file = new File(watch);

        //make it absolute, if it is a relative path
        if (!file.isAbsolute())
            file = new File(servletContext.getRealPath(watch));

        if (watch.endsWith(".jar")) {
            classLoader.addResourceStore(new JarResourceStore(file));
            //register with the fam
            fam.addListener(file, this);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Watching [#0] for changes", file.getAbsolutePath());
            }
        } else {
            //get all subdirs
            List<File> dirs = new ArrayList<File>();
            getAllPaths(file, dirs);

            classLoader.addResourceStore(new FileResourceStore(file));

            for (File dir : dirs) {
                //register with the fam
                fam.addListener(dir, this);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Watching [#0] for changes", dir.getAbsolutePath());
                }
            }
        }
    }
    //setup the bean factory
    beanFactory = new ClassReloadingBeanFactory();
    beanFactory.setInstantiationStrategy(new ClassReloadingInstantiationStrategy());
    beanFactory.setBeanClassLoader(classLoader);

    //start watch thread
    fam.start();
}

From source file:org.jpublish.servlet.JPublishServlet.java

/**
 * Initialize the servlet./*from w ww  .  j a  v  a  2  s. co  m*/
 *
 * @param servletConfig The Servlet configuration
 * @throws ServletException
 */

public void init(ServletConfig servletConfig) throws ServletException {

    super.init(servletConfig);

    log.info("Initializing JPublish servlet; " + SiteContext.JPUBLISH_VERSION);

    ServletContext servletContext = getServletContext();

    String configLocation = servletConfig.getInitParameter("config");
    if (log.isDebugEnabled())
        log.debug("Config location: " + configLocation);

    // find the WEB-INF root
    String rootDir = servletContext.getRealPath("/");
    File contextRoot = new File(rootDir);
    File webInfPath = new File(contextRoot, "WEB-INF");

    // create the site context
    try {
        siteContext = new SiteContext(contextRoot, configLocation);
        servletContext.setAttribute(SiteContext.NAME, siteContext);
        siteContext.setWebInfPath(webInfPath);
        siteContext.setServletContext(servletContext);
        siteContext.setServletConfig(servletConfig);
        siteContext.setJPublishServlet(this);
        siteContext.init();
        formatParameterSupported = siteContext.getFormatChangeParameterName() != null
                && siteContext.getFormatChangeParameterName().trim().length() > 0;
    } catch (Exception e) {
        log.error("Error creating SiteContext: " + e.getMessage());
        throw new ServletException(e);
    }

    // set the ActionManager classpath
    ActionManager actionManager = siteContext.getActionManager();

    // configure BSF
    configureBSF();

    // construct the classpath for scripting support
    String classPath = constructClasspath(webInfPath);

    // configure classpath
    configureClasspath(classPath);

    // execute startup actions
    try {
        actionManager.executeStartupActions();
    } catch (Exception e) {
        log.error("Error executing startup actions: " + e.getMessage());
        throw new ServletException(e);
    }

    log.info("JPublish servlet initialized.");
}

From source file:com.dominion.salud.mpr.configuration.MPRInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.scan("com.dominion.salud.mpr.configuration");
    ctx.setServletContext(servletContext);
    System.setProperty("mpr.conf.home", findConfigurationAndLogger(ctx));
    ctx.refresh();/*from   w  ww.  ja  v a 2s.  co  m*/

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(ctx));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.addMapping("/controller/*");
    dispatcher.addMapping("/services/*");
    servletContext.addListener(new ContextLoaderListener(ctx));

    // Configuracion GENERAL DEL MODULO
    MPRConstantes._MPR_HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator)
            ? servletContext.getRealPath("/")
            : servletContext.getRealPath("/") + File.separator;
    MPRConstantes._MPR_CONF_HOME = ctx.getEnvironment().getProperty("mpr.conf.home");
    MPRConstantes._MPR_VERSION = ResourceBundle.getBundle("version").getString("version");
    MPRConstantes._MPR_RESOURCES = MPRConstantes._MPR_HOME + "resources" + File.separator;
    MPRConstantes._MPR_TEMP = MPRConstantes._MPR_HOME + "WEB-INF" + File.separator + "temp" + File.separator;
    MPRConstantes._MPR_CONTEXT_NAME = servletContext.getServletContextName();
    MPRConstantes._MPR_CONTEXT_PATH = servletContext.getContextPath();
    MPRConstantes._MPR_CONTEXT_SERVER = servletContext.getServerInfo();

    // Configuracion de LOGS DEL MODULO
    if (StringUtils.isBlank(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())) {
        ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE"))
                .setFile(MPRConstantes._MPR_HOME + "WEB-INF" + File.separator + "classes" + File.separator
                        + "logs" + File.separator + "mpr-desktop.log");
    }
    MPRConstantes._MPR_LOGS = new File(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())
                    .getParent();

    // Parametrizacion GENERAL DEL SISTEMA
    MPRConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.enable.technical.information"))
                    ? Boolean.parseBoolean(ctx.getEnvironment().getProperty("mpr.enable.technical.information"))
                    : false;

    // Parametrizacion de CONEXION A EMPI
    MPRConstantes._EMPI_ENABLE = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.enable"))
            ? Boolean.parseBoolean(ctx.getEnvironment().getProperty("mpr.empi.enable"))
            : false;
    MPRConstantes._EMPI_USUARIO = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.usuario"))
            ? ctx.getEnvironment().getProperty("mpr.empi.usuario")
            : "";
    MPRConstantes._EMPI_SISTEMA = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.sistema"))
            ? ctx.getEnvironment().getProperty("mpr.empi.sistema")
            : "";
    MPRConstantes._EMPI_URL = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.url"))
            ? ctx.getEnvironment().getProperty("mpr.empi.url")
            : "";

    // Parametrizacion de TAREAS PROGRAMADAS
    MPRConstantes._TASK_BUZON_IN_PROCESS_MESSAGES = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.process.messages"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.in.process.messages")
                    : MPRConstantes._TASK_BUZON_IN_PROCESS_MESSAGES;
    MPRConstantes._TASK_BUZON_OUT_PROCESS_MESSAGES = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.process.messages"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.out.process.messages")
                    : MPRConstantes._TASK_BUZON_OUT_PROCESS_MESSAGES;
    MPRConstantes._TASK_BUZON_IN_HIS_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean")
                    : MPRConstantes._TASK_BUZON_IN_HIS_CLEAN;
    MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean")
                    : MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN;
    MPRConstantes._TASK_BUZON_IN_HIS_CLEAN_OLD = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean.old"))
                    ? Integer.parseInt(ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean.old"))
                    : MPRConstantes._TASK_BUZON_IN_HIS_CLEAN_OLD;
    MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN_OLD = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean.old"))
                    ? Integer.parseInt(ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean.old"))
                    : MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN_OLD;
    MPRConstantes._TASK_BUZON_IN_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.in.clean")
                    : MPRConstantes._TASK_BUZON_IN_CLEAN;
    MPRConstantes._TASK_BUZON_OUT_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.out.clean")
                    : MPRConstantes._TASK_BUZON_OUT_CLEAN;
    MPRConstantes._TASK_BUZON_ERRORES_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.errores.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.errores.clean")
                    : MPRConstantes._TASK_BUZON_ERRORES_CLEAN;

    logger.info("Iniciando el modulo de [" + MPRConstantes._MPR_CONTEXT_NAME + "]");
    logger.debug("     Configuracion GENERAL DEL MODULO");
    logger.debug("          mpr.home: " + MPRConstantes._MPR_HOME);
    logger.debug("          mpr.conf.home: " + MPRConstantes._MPR_CONF_HOME);
    logger.debug("          mpr.version: " + MPRConstantes._MPR_VERSION);
    logger.debug("          mpr.resources: " + MPRConstantes._MPR_RESOURCES);
    logger.debug("          mpr.temp: " + MPRConstantes._MPR_TEMP);
    logger.debug("          mpr.logs: " + MPRConstantes._MPR_LOGS);
    logger.debug("          mpr.logs.file: "
            + ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile());
    logger.debug("          mpr.context.name: " + MPRConstantes._MPR_CONTEXT_NAME);
    logger.debug("          mpr.context.path: " + MPRConstantes._MPR_CONTEXT_PATH);
    logger.debug("          mpr.context.server: " + MPRConstantes._MPR_CONTEXT_SERVER);
    logger.debug("          java.version: " + ctx.getEnvironment().getProperty("java.version"));
    logger.debug("");
    logger.debug("     Parametrizacion GENERAL DEL SISTEMA");
    logger.debug("          mpr.enable.technical.information: " + MPRConstantes._ENABLE_TECHNICAL_INFORMATION);
    logger.debug("     Parametrizacion de CONEXION A EMPI");
    logger.debug("          mpr.empi.enable: " + MPRConstantes._EMPI_ENABLE);
    logger.debug("          mpr.empi.usuario: " + MPRConstantes._EMPI_USUARIO);
    logger.debug("          mpr.empi.sistema: " + MPRConstantes._EMPI_SISTEMA);
    logger.debug("          mpr.empi.url: " + MPRConstantes._EMPI_URL);
    logger.debug("     Parametrizacion de TAREAS PROGRAMADAS");
    logger.debug(
            "          mpr.task.buzon.in.process.messages: " + MPRConstantes._TASK_BUZON_IN_PROCESS_MESSAGES);
    logger.debug(
            "          mpr.task.buzon.out.process.messages: " + MPRConstantes._TASK_BUZON_OUT_PROCESS_MESSAGES);
    logger.debug("          mpr.task.buzon.in.his.clean: " + MPRConstantes._TASK_BUZON_IN_HIS_CLEAN);
    logger.debug("          mpr.task.buzon.out.his.clean: " + MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN);
    logger.debug("          mpr.task.buzon.in.his.clean.old: " + MPRConstantes._TASK_BUZON_IN_HIS_CLEAN_OLD);
    logger.debug("          mpr.task.buzon.out.his.clean.old: " + MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN_OLD);
    logger.debug("          mpr.task.buzon.in.clean: " + MPRConstantes._TASK_BUZON_IN_CLEAN);
    logger.debug("          mpr.task.buzon.out.clean: " + MPRConstantes._TASK_BUZON_OUT_CLEAN);
    logger.debug("          mpr.task.buzon.errores.clean: " + MPRConstantes._TASK_BUZON_ERRORES_CLEAN);
    logger.debug("     Variables de ENTORNO de utilidad");
    logger.debug("          catalina.home: " + ctx.getEnvironment().getProperty("catalina.home"));
    logger.debug("          jboss.home.dir: " + ctx.getEnvironment().getProperty("jboss.home.dir"));
    logger.info("Modulo [" + MPRConstantes._MPR_CONTEXT_NAME + "] iniciado correctamente");
}

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

public static int loadActions(ServletContext servletContext) throws Exception {

    // assume no actions
    int actionCount = 0;

    // create a list of json actions which we will sort later
    List<JSONObject> jsonActions = new ArrayList<JSONObject>();

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> actionConstructors = new HashMap<String, Constructor>();

    // build a collection of classes so we can re-initilise the JAXB context to recognise our injectable classes
    ArrayList<Action> actions = new ArrayList<Action>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/actions/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".action.xml");
        }//from www .jav  a  2s.  c o m
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/action.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonActionCollection = org.json.XML.toJSONObject(xml).getJSONObject("actions");

        JSONObject jsonAction;
        int index = 0;
        int count = 0;

        // the JSON library will add a single key of there is a single class, otherwise an array
        if (jsonActionCollection.optJSONArray("action") == null) {
            jsonAction = jsonActionCollection.getJSONObject("action");
        } else {
            jsonAction = jsonActionCollection.getJSONArray("action").getJSONObject(index);
            count = jsonActionCollection.getJSONArray("action").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonActions.size(); i++) {
                if (jsonAction.getString("type").equals(jsonActions.get(i).getString("type")))
                    throw new Exception(" action type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonActions.add(jsonAction);
            // get the named type from the json
            String type = jsonAction.getString("type");
            // get the class name from the json
            String className = jsonAction.getString("class");
            // get the class 
            Class classClass = Class.forName(className);
            // check the class extends com.rapid.Action
            if (!Classes.extendsClass(classClass, com.rapid.core.Action.class))
                throw new Exception(type + " action class " + classClass.getCanonicalName()
                        + " must extend com.rapid.core.Action.");
            // check this type is unique
            if (actionConstructors.get(type) != null)
                throw new Exception(type + " action already loaded. Type names must be unique.");
            // add to constructors hashmap referenced by type
            actionConstructors.put(type, classClass.getConstructor(RapidHttpServlet.class, JSONObject.class));
            // add to our jaxb classes collection            
            _jaxbClasses.add(classClass);
            // inc the control count
            actionCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonAction = jsonActionCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of actions by name
    Collections.sort(jsonActions, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayActions = new JSONArray(jsonActions);

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonActions", jsonArrayActions);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("actionConstructors", actionConstructors);

    _logger.info(actionCount + " actions loaded in .action.xml files");

    return actionCount;

}