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.apache.axis.configuration.EngineConfigurationFactoryServlet.java

/**
 * Get a default server engine configuration in a servlet environment.
 *
 * @param ctx a ServletContext/*from w ww  .j a  v  a 2 s  .  c  o  m*/
 * @return a server EngineConfiguration
 */
private static EngineConfiguration getServerEngineConfig(ServletConfig cfg) {

    ServletContext ctx = cfg.getServletContext();

    // Respect the system property setting for a different config file
    String configFile = cfg.getInitParameter(OPTION_SERVER_CONFIG_FILE);
    if (configFile == null)
        configFile = AxisProperties.getProperty(OPTION_SERVER_CONFIG_FILE);
    if (configFile == null) {
        configFile = SERVER_CONFIG_FILE;
    }

    /**
     * Flow can be confusing.  Here is the logic:
     * 1) Make all attempts to open resource IF it exists
     *    - If it exists as a file, open as file (r/w)
     *    - If not a file, it may still be accessable as a stream (r)
     *    (env will handle security checks).
     * 2) If it doesn't exist, allow it to be opened/created
     * 
     * Now, the way this is done below is:
     * a) If the file does NOT exist, attempt to open as a stream (r)
     * b) Open named file (opens existing file, creates if not avail).
     */

    /*
     * Use the WEB-INF directory
     * (so the config files can't get snooped by a browser)
     */
    String appWebInfPath = "/WEB-INF";

    FileProvider config = null;

    String realWebInfPath = ctx.getRealPath(appWebInfPath);

    /**
     * If path/file doesn't exist, it may still be accessible
     * as a resource-stream (i.e. it may be packaged in a JAR
     * or WAR file).
     */
    if (realWebInfPath == null || !(new File(realWebInfPath, configFile)).exists()) {
        String name = appWebInfPath + "/" + configFile;
        InputStream is = ctx.getResourceAsStream(name);
        if (is != null) {
            // FileProvider assumes responsibility for 'is':
            // do NOT call is.close().
            config = new FileProvider(is);
        }

        if (config == null) {
            log.error(Messages.getMessage("servletEngineWebInfError03", name));
        }
    }

    /**
     * Couldn't get data  OR  file does exist.
     * If we have a path, then attempt to either open
     * the existing file, or create an (empty) file.
     */
    if (config == null && realWebInfPath != null) {
        try {
            config = new FileProvider(realWebInfPath, configFile);
        } catch (ConfigurationException e) {
            log.error(Messages.getMessage("servletEngineWebInfError00"), e);
        }
    }

    /**
     * Fall back to config file packaged with AxisEngine
     */
    if (config == null) {
        log.warn(Messages.getMessage("servletEngineWebInfWarn00"));
        try {
            InputStream is = ClassUtils.getResourceAsStream(AxisServer.class, SERVER_CONFIG_FILE);
            config = new FileProvider(is);
        } catch (Exception e) {
            log.error(Messages.getMessage("servletEngineWebInfError02"), e);
        }
    }

    return config;
}

From source file:org.intermine.web.struts.KeywordSearchResultsController.java

/**
 * {@inheritDoc}/*from www.  j  a va2 s.  com*/
 */
@Override
public ActionForward execute(ComponentContext context, @SuppressWarnings("unused") ActionMapping mapping,
        @SuppressWarnings("unused") ActionForm form, HttpServletRequest request,
        @SuppressWarnings("unused") HttpServletResponse response) throws Exception {
    long time = System.currentTimeMillis();
    final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
    javax.servlet.ServletContext servletContext = request.getSession().getServletContext();
    String contextPath = servletContext.getRealPath("/");
    synchronized (this) {
        // if this decreases performance too much we might have to change it
        intialiseLogging(SessionMethods.getWebProperties(servletContext).getProperty("project.title", "unknown")
                .toLowerCase());
    }
    KeywordSearch.initKeywordSearch(im, contextPath);
    Vector<KeywordSearchFacetData> facets = KeywordSearch.getFacets();
    int totalHits = 0;

    // term
    String searchTerm = request.getParameter("searchTerm");
    LOG.debug("SEARCH TERM: '" + searchTerm + "'");

    //track the keyword search
    Profile profile = SessionMethods.getProfile(request.getSession());
    im.getTrackerDelegate().trackKeywordSearch(searchTerm, profile, request.getSession().getId());

    // search in bag (list)
    String searchBag = request.getParameter("searchBag");
    if (searchBag == null) {
        searchBag = "";
    }
    List<Integer> ids = getBagIds(im, request, searchBag);
    int offset = getOffset(request);
    Map<String, String> facetValues = getFacetValues(request, facets);
    LOG.debug("Initializing took " + (System.currentTimeMillis() - time) + " ms");

    // show overview by default
    if (StringUtils.isBlank(searchTerm)) {
        searchTerm = "*:*";
    }

    //TODO remove - just  for performance testing
    // KeywordSearch.runLuceneSearch(searchTerm);

    long searchTime = System.currentTimeMillis();
    BrowseResult result = KeywordSearch.runBrowseSearch(searchTerm, offset, facetValues, ids);
    searchTime = System.currentTimeMillis() - searchTime;
    Vector<KeywordSearchResult> searchResultsParsed = new Vector<KeywordSearchResult>();
    Vector<KeywordSearchFacet> searchResultsFacets = new Vector<KeywordSearchFacet>();
    Set<Integer> objectIds = new HashSet<Integer>();

    if (result != null) {
        totalHits = result.getNumHits();
        LOG.debug("Browse found " + result.getNumHits() + " hits");
        BrowseHit[] browseHits = result.getHits();
        objectIds = KeywordSearch.getObjectIds(browseHits);
        Map<Integer, InterMineObject> objMap = KeywordSearch.getObjects(im, objectIds);
        Vector<KeywordSearchHit> searchHits = KeywordSearch.getSearchHits(browseHits, objMap);
        WebConfig wc = SessionMethods.getWebConfig(request);
        searchResultsParsed = KeywordSearch.parseResults(im, wc, searchHits);
        searchResultsFacets = KeywordSearch.parseFacets(result, facets, facetValues);
    }

    logSearch(searchTerm, totalHits, time, offset, searchTime, facetValues, searchBag);
    LOG.debug("SEARCH RESULTS: " + searchResultsParsed.size());

    // don't display *:* in search box
    if ("*:*".equals(searchTerm)) {
        searchTerm = "";
    }

    // there are needed in the form too so we have to use request (i think...)
    request.setAttribute("searchResults", searchResultsParsed);
    request.setAttribute("searchTerm", searchTerm);
    request.setAttribute("searchBag", searchBag);
    request.setAttribute("searchFacetValues", facetValues);

    // used for re-running the search in case of creating a list for ALL results
    request.setAttribute("jsonFacets", javaMapToJSON(facetValues));

    context.putAttribute("searchResults", request.getAttribute("searchResults"));
    context.putAttribute("searchTerm", request.getAttribute("searchTerm"));
    context.putAttribute("searchBag", request.getAttribute("searchBag"));
    context.putAttribute("searchFacetValues", request.getAttribute("searchFacetValues"));
    context.putAttribute("jsonFacets", request.getAttribute("jsonFacets"));

    // pagination
    context.putAttribute("searchOffset", new Integer(offset));
    context.putAttribute("searchPerPage", new Integer(KeywordSearch.PER_PAGE));
    context.putAttribute("searchTotalHits", new Integer(totalHits));

    // facet lists
    context.putAttribute("searchFacets", searchResultsFacets);

    // facet values
    for (Entry<String, String> facetValue : facetValues.entrySet()) {
        context.putAttribute("facet_" + facetValue.getKey(), facetValue.getValue());
    }

    // time for debugging
    long totalTime = System.currentTimeMillis() - time;
    context.putAttribute("searchTime", new Long(totalTime));
    LOG.debug("--> TOTAL: " + (System.currentTimeMillis() - time) + " ms");
    return null;
}

From source file:stella.stella.Bean.java

public void gerarCarne() {
    List<Boleto> boletos = new ArrayList<>();
    for (int i = 0; i < 10; i++) {

        Datas datas = Datas.novasDatas().comDocumento(1, 5, 2008).comProcessamento(1, 5, 2008).comVencimento(2,
                1, 2015);/*w  w  w .  j a v  a  2 s  .c  om*/

        Endereco enderecoBeneficiario = Endereco.novoEndereco().comLogradouro("Av das Empresas, 555")
                .comBairro("Bairro Grande").comCep("01234-555").comCidade("So Paulo").comUf("SP");

        //Quem emite o boleto
        Beneficiario beneficiario = Beneficiario.novoBeneficiario().comNomeBeneficiario("Fulano de Tal")
                .comAgencia("3614").comCodigoBeneficiario("01034602").comDigitoCodigoBeneficiario("4")
                .comNumeroConvenio("1207113").comCarteira("18").comEndereco(enderecoBeneficiario)
                .comNossoNumero("9000206");

        Endereco enderecoPagador = Endereco.novoEndereco().comLogradouro("Av dos testes, 111 apto 333")
                .comBairro("Bairro Teste").comCep("01234-111").comCidade("So Paulo").comUf("SP");

        //Quem paga o boleto
        Pagador pagador = Pagador.novoPagador().comNome("Fulano da Silva").comDocumento("111.222.333-12")
                .comEndereco(enderecoPagador);

        Banco banco = new BancoDoBrasil();

        Boleto boleto2 = Boleto.novoBoleto().comBanco(banco).comDatas(datas).comBeneficiario(beneficiario)
                .comPagador(pagador).comValorBoleto("2036.47").comNumeroDoDocumento("1234" + i)
                .comInstrucoes("instrucao 1", "instrucao 2", "instrucao 3", "instrucao 4", "instrucao 5")
                .comLocaisDePagamento("local 1", "local 2");
        boletos.add(boleto2);

    }

    GeradorDeBoleto gerador = new GeradorDeBoleto(boletos);

    File pdf = new File(System.getProperty("user.home") + File.separator + "carne.pdf");

    gerador.geraPDF(pdf.getAbsolutePath());

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String absoluteDiskPath = servletContext.getRealPath("/resources/arquivos");
    File a = new File(absoluteDiskPath + File.separator + "carne.pdf");
    byte[] bytes = gerador.geraPDF();
    try {
        FileUtils.writeByteArrayToFile(a, bytes);
    } catch (IOException ex) {
        Logger.getLogger(Bean.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.carne = pdf.getAbsolutePath();
}

From source file:RestrictedService.java

public void init() throws ServletException {
    if (!gateInited) {
        try {/*w ww  . ja v  a2 s  . c om*/
            // GATE home is setted, so it can be used by SAGA.
            ServletContext ctx = getServletContext();
            File gateHome = new File(ctx.getRealPath("/WEB-INF"));
            Gate.setGateHome(gateHome);
            // GATE user configuration file is setted. 
            Gate.setUserConfigFile(new File(gateHome, "user-gate.xml"));
            //GATE is initialized as non visible.
            Gate.init();
            // We load the plugins that are going to be used by the SAGA modules.
            // Load ANNIE.
            Gate.getCreoleRegister().registerDirectories(ctx.getResource("/WEB-INF/plugins/ANNIE"));
            // Load processingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/processingResources"));
            // Load webProcessingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/webProcessingResources"));
            // Now we create the sentiment analysis modules that are going to be provided by the service.
            // English financial module.
            ArrayList<URL> dictionaries = new ArrayList<URL>();
            dictionaries.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def"));
            modules.put("enFinancial",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries));
            // English financial + emoticon module.
            ArrayList<URL> dictionaries2 = new ArrayList<URL>();
            dictionaries2.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def"));
            dictionaries2.add((new RestrictedService()).getClass()
                    .getResource("/resources/gazetteer/emoticon/lists.def"));
            modules.put("enFinancialEmoticon",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries2));
            // Mongo login
            String user = "";
            String password = "";
            MongoCredential credential = MongoCredential.createMongoCRCredential(user, "RestrictedDictionaries",
                    password.toCharArray());
            MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"),
                    Arrays.asList(credential));
            db = mongoClient.getDB("RestrictedDictionaries");

            gateInited = true;

        } catch (Exception ex) {
            throw new ServletException("Exception initialising GATE", ex);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.utils.FedoraConfiguration.java

private void internalSetup(ServletContext context) {
    this.configurationStatus = "";
    StringBuffer status = new StringBuffer("");

    if (connected && configured)
        return;/*  www.j  a  v a2  s.c  o m*/

    Properties props = new Properties();
    String path = context.getRealPath(FEDORA_PROPERTIES);
    try {
        InputStream in = new FileInputStream(new File(path));
        props.load(in);
        fedoraUrl = props.getProperty("fedoraUrl");
        adminUser = props.getProperty("adminUser");
        adminPassword = props.getProperty("adminPassword");
        pidNamespace = props.getProperty("pidNamespace");
        if (fedoraUrl == null || adminUser == null || adminPassword == null) {
            if (fedoraUrl == null) {
                log.error("'fedoraUrl' not found in properties file");
                status.append("<p>'fedoraUrl' not found in properties file.</p>\n");
            }
            if (adminUser == null) {
                log.error("'adminUser' was not found in properties file, the "
                        + "user name of the fedora admin is needed to access the " + "fedora API-M services.");
                status.append("<p>'adminUser' was not found in properties file, the "
                        + "user name of the fedora admin is needed to access the "
                        + "fedora API-M services.</p>\n");
            }
            if (adminPassword == null) {
                log.error("'adminPassword' was not found in properties file, the "
                        + "admin password is needed to access the fedora API-M services.");
                status.append("<p>'adminPassword' was not found in properties file, the "
                        + "admin password is needed to access the fedora API-M services.</p>\n");
            }
            if (pidNamespace == null) {
                log.error("'pidNamespace' was not found in properties file, the "
                        + "PID namespace indicates which namespace to use when creating "
                        + "new fedor digital objects.");
                status.append("<p>'pidNamespace' was not found in properties file, the "
                        + "PID namespace indicates which namespace to use when creating "
                        + "new fedor digital objects.</p>\n");
            }
            fedoraUrl = null;
            adminUser = null;
            adminPassword = null;
            configured = false;
        } else {
            configured = true;
        }
    } catch (FileNotFoundException e) {
        log.error("No fedora.properties file found," + "it should be located at " + path);
        status.append("<h1>Fedora configuration failed.</h1>\n");
        status.append("<p>No fedora.properties file found," + "it should be located at " + path + "</p>\n");
        configured = false;
        return;
    } catch (Exception ex) {
        status.append("<p>Fedora configuration failed.</p>\n");
        status.append("<p>Exception while loading" + path + "</p>\n");
        status.append("<p>" + ex.getMessage() + "</p>\n");
        log.error("could not load fedora properties", ex);
        fedoraUrl = null;
        adminUser = null;
        adminPassword = null;
        configured = false;
        return;
    }

    status.append(RELOAD_MSG);
    this.configurationStatus += status.toString();
}

From source file:nl.strohalm.cyclos.http.lifecycle.CustomizedFileInitialization.java

public void init(final ServletContext context) {
    // First, clear the customized css files to ensure proper migration from previous versions when css files were not customized
    final File customizedStylesDir = new File(
            context.getRealPath(CustomizationHelper.customizedPathFor(context, CustomizedFile.Type.STYLE)));
    for (final File css : customizedStylesDir.listFiles((FilenameFilter) new SuffixFileFilter(".css"))) {
        css.delete();// www . j a  v a 2 s .c o m
    }

    final LocalSettings localSettings = SettingsHelper.getLocalSettings(context);
    final CustomizedFileQuery query = new CustomizedFileQuery();
    query.fetch(CustomizedFile.Relationships.GROUP);
    query.setAll(true);
    final List<CustomizedFile> files = customizedFileService.search(query);
    for (final CustomizedFile customizedFile : files) {
        final CustomizedFile.Type type = customizedFile.getType();
        final String name = customizedFile.getName();
        final File physicalFile = CustomizationHelper.customizedFileOf(context, customizedFile);
        final File originalFile = CustomizationHelper.originalFileOf(context, type, name);

        try {
            // No conflicts are checked for style sheet files
            if (type != CustomizedFile.Type.STYLE) {
                final boolean wasConflict = customizedFile.isConflict();

                // Check if the file contents has changed since the customization
                String originalFileContents = null;
                if (originalFile.exists()) {
                    originalFileContents = FileUtils.readFileToString(originalFile);
                    if (originalFileContents.length() == 0) {
                        originalFileContents = null;
                    }
                }
                // Check if the file is now on conflict (or the new contents has changed)
                boolean contentsChanged;
                boolean newContentsChanged;
                if (type == CustomizedFile.Type.APPLICATION_PAGE) {
                    contentsChanged = !StringUtils.trimToEmpty(originalFileContents)
                            .equals(StringUtils.trimToEmpty(customizedFile.getOriginalContents()))
                            && !StringUtils.trimToEmpty(originalFileContents)
                                    .equals(StringUtils.trimToEmpty(customizedFile.getContents()));
                    newContentsChanged = contentsChanged && !StringUtils.trimToEmpty(originalFileContents)
                            .equals(StringUtils.trimToEmpty(customizedFile.getNewContents()));
                } else {
                    contentsChanged = !StringUtils.trimToEmpty(originalFileContents)
                            .equals(StringUtils.trimToEmpty(customizedFile.getOriginalContents()));
                    newContentsChanged = !StringUtils.trimToEmpty(originalFileContents)
                            .equals(StringUtils.trimToEmpty(customizedFile.getNewContents()));
                }

                if (!wasConflict && contentsChanged) {
                    // Save the new contents, marking the file as conflicts
                    customizedFile.setNewContents(originalFileContents);
                    customizedFileService.save(customizedFile);

                    // Generate an alert if the file is customized for the whole system
                    if (customizedFile.getGroup() == null && customizedFile.getGroupFilter() == null) {
                        SystemAlert.Alerts alertType = null;
                        switch (type) {
                        case APPLICATION_PAGE:
                            alertType = SystemAlert.Alerts.NEW_VERSION_OF_APPLICATION_PAGE;
                            break;
                        case HELP:
                            alertType = SystemAlert.Alerts.NEW_VERSION_OF_HELP_FILE;
                            break;
                        case STATIC_FILE:
                            alertType = SystemAlert.Alerts.NEW_VERSION_OF_STATIC_FILE;
                            break;
                        }
                        alertService.create(alertType, customizedFile.getName());
                    }
                } else if (wasConflict && newContentsChanged) {
                    // The file has changed again. Update the new contents
                    customizedFile.setNewContents(originalFileContents);
                    customizedFileService.save(customizedFile);
                }
            }

            // Check if we must update an style file
            final long lastModified = customizedFile.getLastModified() == null ? System.currentTimeMillis()
                    : customizedFile.getLastModified().getTimeInMillis();
            if (!physicalFile.exists() || physicalFile.lastModified() != lastModified) {
                physicalFile.getParentFile().mkdirs();
                FileUtils.writeStringToFile(physicalFile, customizedFile.getContents(),
                        localSettings.getCharset());
                physicalFile.setLastModified(lastModified);
            }
        } catch (final IOException e) {
            LOG.warn("Error handling customized file: " + physicalFile.getAbsolutePath(), e);
        }
    }
    // We must copy all non-customized style sheets to the customized dir, so there will be no problems for locating images
    final File originalDir = new File(
            context.getRealPath(CustomizationHelper.originalPathFor(context, CustomizedFile.Type.STYLE)));
    for (final File original : originalDir.listFiles()) {
        final File customized = new File(customizedStylesDir, original.getName());
        if (!customized.exists()) {
            try {
                FileUtils.copyFile(original, customized);
            } catch (final IOException e) {
                LOG.warn("Error copying style sheet file: " + customized.getAbsolutePath(), e);
            }
        }
    }
}

From source file:org.squale.jraf.initializer.struts.StrutsInitializer.java

public void init(ActionServlet in_actionServlet, ModuleConfig in_moduleConfig) throws ServletException {

    // initializer
    IInitializable lc_initialize = null;

    // map des parametres
    Map lc_paramMap = null;//from w w w.  j  a  v a  2 s  .  c  om

    // context
    ServletContext lc_context = in_actionServlet.getServletContext();
    ServletConfig lc_config = in_actionServlet.getServletConfig();
    // log
    log.info("Debut de l'initialisation de l'application Jraf...");

    // repertoire racine
    String lc_rootPath = lc_context.getRealPath("");

    // Initialisation
    lc_context.log("INIT Ok - Recupration du Bean initializer ... ");
    ApplicationContextFactoryInitializer
            .init(lc_context.getInitParameter(IBootstrapConstants.SPRING_CONTEXT_CONFIG));
    // Rcupration du bean initialize.         
    initializer = (Initializer) ApplicationContextFactoryInitializer.getApplicationContext()
            .getBean("initialize");
    lc_context.log("Provider config file = " + initializer.getConfigFile());
    // classe d'initialisation
    String lc_initClassName = initializer.getClass().getName();

    // fichier de configuration d'un provider
    String lc_providerConfigFile = initializer.getConfigFile();

    // bind jndi
    String lc_isJndi = Boolean.toString(initializer.isJndi());

    try {
        // test des parametres recuperees
        if (lc_rootPath == null || lc_rootPath.equals("") || lc_providerConfigFile == null
                || lc_providerConfigFile.equals("")) {

            // affiche une erreur de configuration
            String lc_error = "Pb de configuration : le chemin du contexte racine est vide ou le fichier de configuration des plugins n'est pas specifie.";
            log.fatal(lc_error);
            throw new JrafConfigException(lc_error);

        } else {
            // les parametres ont bien ete recuperes
            // creation de l'initializer
            lc_initialize = InitializableHelper.instanciateInitializable(lc_initClassName);

            // recuperation/creation des parametres
            lc_paramMap = new HashMap();
            lc_paramMap.put(IBootstrapConstants.ROOT_PATH_KEY, lc_rootPath);

            lc_paramMap.put(IBootstrapConstants.PROVIDER_CONFIG_KEY, lc_providerConfigFile);

            // si le bind jndi est positionne
            if (lc_isJndi != null) {
                lc_paramMap.put(IBootstrapConstants.JNDI_BIND, lc_isJndi);
            }

            // execution de la methode d'initialisation
            IBootstrapProvider lc_bootstrapProvider = (IBootstrapProvider) lc_initialize
                    .initialize(lc_paramMap);

            // log de succes
            log.info("L'application s'est initialisee avec succes");
            log.info("Les providers suivants ont ete initialises:" + lc_bootstrapProvider.getProviders());
        }
    } catch (JrafConfigException e) {
        // log
        log.fatal("Probleme lors de l'intialisation de l'application : ", e);
        throw new ServletException("Probleme lors de l'intialisation de l'application : ", e);
    } catch (RuntimeException e) {
        // log
        log.fatal("Probleme lors de l'intialisation de l'application : ", e);
        throw new ServletException("Probleme lors de l'intialisation de l'application : ", e);
    }
}

From source file:com.artglorin.web.utils.ResourcesHelper.java

/**
 * ?  ?    ?  ??//from   ww w . ja v  a2s  .c  o m
 *
 * @param pathToResources   ? ?  ? ? ??,    null
 * @param servletContext  ?  ?,      ? ?? ??
 */
public ResourcesHelper(String pathToResources, ServletContext servletContext) {
    if (pathToResources == null) {
        throw new IllegalArgumentException("Required argument pathToResources is null");
    }
    if (servletContext == null) {
        throw new IllegalArgumentException("Required argument servletContext is null");
    }
    this.pathToResources = pathToResources;
    realPath = servletContext.getRealPath(pathToResources);
}

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

@RequestMapping(value = "/colellaImport")
public @ResponseBody String colellaImport(HttpServletRequest request) {

    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    String folder = sc.getRealPath("/") + "dist" + File.separator + "colella";

    List<Produttore> pList = XMLParser.parseCartellaProduttori(folder);

    for (Produttore prod : pList) {
        System.out.println("*******************************");

        //Dati obbligatori
        CompletePOI p = new CompletePOI();
        String den = prod.getDenominazione().replace("'", "&#039;");
        den = den.replace("\"", "&quot;").replace("\n", "").replace("\r", "");
        p.setName(den);/*w w  w.  j  av a2  s.com*/

        System.out.println("Name: " + p.getName());

        p.setVisibility("1");
        p.setLocation(
                new double[] { Double.parseDouble(prod.getSedeLat()), Double.parseDouble(prod.getSedeLon()) });
        p.setAddress(prod.getSedeVia());
        if (prod.getDescrizione() != null && !prod.getDescrizione().trim().equals("")) {
            if (prod.getDescrizione().length() <= 100) {
                String desc = prod.getDescrizione().replace("'", "&#039;");
                desc = desc.replace("\"", "&quot;").replace("\n", "").replace("\r", "");
                p.setShortDescription(desc.substring(0, desc.length()));
            } else {
                String desc = prod.getDescrizione().replace("'", "&#039;");
                desc = desc.replace("\"", "&quot;").replace("\n", "").replace("\r", "");
                p.setShortDescription(desc.substring(0, 100));
            }

            System.out.println(p.getShortDescription());
        }

        ArrayList<String> l = new ArrayList<String>();
        l.add("food");
        p.setCategories(l);

        //componenti
        ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

        //componente cover
        if (true) {
            CoverImgComponent coverimg = new CoverImgComponent();
            coverimg.setLink("cover.jpg");
            listComponent.add(coverimg);
        }

        //componente contatti
        ContactsComponent contacts_component = new ContactsComponent();
        boolean contacts = false;

        ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>();

        //Recapiti telefonici
        if (prod.getTelFissoList() != null && prod.getTelFissoList().size() > 0) {

            for (String t : prod.getTelFissoList()) {

                if (!t.trim().equals("")) {

                    PhoneContact phone = new PhoneContact();
                    phone.setLabel("Fisso");

                    phone.setNumber(t);
                    phoneList.add(phone);

                    System.out.println("Tel: " + phone.getLabel() + " " + phone.getNumber());
                }

            }
            contacts = true;
            contacts_component.setPhoneList(phoneList);
            for (PhoneContact ph : contacts_component.getPhoneList()) {
                System.out.println("Tel****: " + ph.getLabel() + " " + ph.getNumber());
            }
        }
        if (prod.getTelMobList() != null && prod.getTelMobList().size() > 0) {

            for (String t : prod.getTelMobList()) {

                if (!t.trim().equals("")) {
                    PhoneContact phone = new PhoneContact();
                    phone.setLabel("Mobile");

                    phone.setNumber(t);
                    phoneList.add(phone);

                    System.out.println("Tel M: " + phone.getLabel() + " " + phone.getNumber());
                }
            }
            contacts = true;
            contacts_component.setPhoneList(phoneList);
        }
        if (prod.getEmailList() != null && prod.getEmailList().size() > 0) {

            ArrayList<EmailContact> emailList = new ArrayList<EmailContact>();

            for (String t : prod.getEmailList()) {

                if (!t.trim().equals("")) {
                    EmailContact email = new EmailContact();
                    email.setEmail(t);
                    emailList.add(email);

                    System.out.println("Email: " + email.getLabel() + " " + email.getEmail());
                }
            }
            contacts = true;
            contacts_component.setEmailsList(emailList);
        }

        if (prod.getFacebook() != null && !prod.getFacebook().trim().equals("")) {

            contacts_component.setFacebook(prod.getFacebook());
            System.out.println("Face: " + prod.getFacebook());
        }

        if (prod.getTwitter() != null && !prod.getTwitter().trim().equals("")) {

            contacts_component.setTwitter(prod.getTwitter());
            System.out.println("Twit: " + prod.getTwitter());
        }

        if (prod.getWebSite() != null && !prod.getWebSite().trim().equals("")) {
            ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>();
            GenericSocial social = new GenericSocial();
            contacts = true;
            social.setLabel("Website");
            social.setSocial(prod.getWebSite());
            customsocial.add(social);
            contacts_component.setSocialList(customsocial);

            System.out.println("Social: " + social.getLabel() + " " + social.getSocial());
        }
        if (contacts) {
            System.out.println("### INSERT CONTACTS ###### SIZE: " + contacts_component.getPhoneList().size());

            listComponent.add(contacts_component);
        }

        //DESCRIPTION COMPONENT
        if (prod.getDescrizione() != null && !prod.getDescrizione().trim().equals("")) {
            ArrayList<Section> list = new ArrayList<Section>();

            //descrizione
            Section section = new Section();
            section.setDescription(prod.getDescrizione());
            list.add(section);
            System.out.println("Desc: " + section.getDescription());

            //dati storici
            if (prod.getDatiStorici() != null && !prod.getDatiStorici().trim().equals("")) {
                Section section_d = new Section();
                section_d.setTitle("Dati Storici");
                section_d.setDescription(prod.getDatiStorici());
                list.add(section_d);
                System.out.println("Dati Sto: " + section_d.getDescription());
            }

            //curiosit
            if (prod.getCuriosita() != null && !prod.getCuriosita().trim().equals("")) {
                Section section_c = new Section();
                section_c.setTitle("Curiosit");
                section_c.setDescription(prod.getCuriosita());
                list.add(section_c);
                System.out.println("Curiosita: " + section_c.getDescription());
            }

            //note
            if (prod.getNoteList() != null && prod.getNoteList().size() > 0) {

                for (String n : prod.getNoteList()) {

                    if (!n.trim().equals("")) {

                        Section section_n = new Section();
                        section_n.setTitle("Note");
                        section_n.setDescription(n);
                        list.add(section_n);

                        System.out.println("Note: " + section_n.getDescription());
                    }
                }

            }

            DescriptionComponent description_component = new DescriptionComponent();
            description_component.setSectionsList(list);
            listComponent.add(description_component);
        }

        p.setComponents(listComponent);

        pm.savePoi(p);

        System.out.println(prod.getDenominazione());
    }

    return "ok";

}

From source file:org.mobicents.servlet.restcomm.RvdProjectsMigrator.java

public RvdProjectsMigrator(ServletContext servletContext, Configuration configuration) throws Exception {
    this.migrationHelper = new RvdProjectsMigrationHelper(servletContext, configuration);
    this.migrationSucceeded = true;
    this.logPath = servletContext.getRealPath("/") + "../../../"; // Equivalent to RESTCOMM_HOME
    this.errorCode = 0;
    this.projectsProcessed = 0;
    this.projectsSuccess = 0;
    this.projectsError = 0;
    this.updatedDids = 0;
    this.updatedClients = 0;
}