Java Code Examples for javax.servlet.ServletContext#getRealPath()

The following examples show how to use javax.servlet.ServletContext#getRealPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ValidationPlugin.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Override
public String generateHTML(ContextTag context) {

  ServletContext ctxt = context.getPageContext().getServletContext();
  HttpServletRequest request =
    (HttpServletRequest)context.getPageContext().getRequest();

  String tm = context.getTopicMapId();

  // Does the schme exist?
  String path = ctxt.getRealPath("/WEB-INF/schemas/" + tm + ".osl");
  if (!new File(path).exists())
    return "<span title=\"No OSL schema found at: " + path + "\">No schema</span>";
  else 
    return super.generateHTML(context);
}
 
Example 2
Source File: SwaggerResource.java    From geowave with Apache License 2.0 6 votes vote down vote up
/** This resource returns the swagger.json */
@Get("json")
public String listResources() {
  final ServletContext servlet =
      (ServletContext) getContext().getAttributes().get("org.restlet.ext.servlet.ServletContext");
  final String realPath = servlet.getRealPath("/");
  final JacksonRepresentation<ApiDeclaration> result =
      new JacksonRepresentation<>(
          new FileRepresentation(realPath + "swagger.json", MediaType.APPLICATION_JSON),
          ApiDeclaration.class);
  try {
    return result.getText();
  } catch (final IOException e) {
    LOGGER.warn("Error building swagger json", e);
  }
  return "Not Found: swagger.json";
}
 
Example 3
Source File: WebUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substitution with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
				"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException("Web app root system property already set to different value: '" +
				key + "' = [" + oldValue + "] instead of [" + root + "] - " +
				"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
Example 4
Source File: WebUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substitution with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
			"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException(
			"Web app root system property already set to different value: '" +
			key + "' = [" + oldValue + "] instead of [" + root + "] - " +
			"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
Example 5
Source File: PluginInstallationServletContextListener.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void contextInitialized( ServletContextEvent event) {
	ServletContext servletContext = event.getServletContext();
	
	String reportDesignPath = servletContext.getRealPath( ComExtensionConstants.PLUGIN_BIRT_RPTDESIGN_BASE);
	String scriptlibPath = servletContext.getRealPath(ComExtensionConstants.PLUGIN_BIRT_SCRIPTLIB_BASE);
	String pluginsPath;
	try {
		pluginsPath = ConfigService.getInstance().getValue(ConfigValue.EmmPluginsHome);
	} catch (Exception e) {
		logger.error("Cannot read EmmPluginsHome: " + e.getMessage(), e);
		throw new RuntimeException("Cannot read EmmPluginsHome: " + e.getMessage(), e);
	}
	
	if( logger.isDebugEnabled()) {
		logger.debug( "Path for report designs: " + reportDesignPath);
		logger.debug( "Path for script libs: " + scriptlibPath);
		logger.debug( "Path for plugin ZIPs: " + pluginsPath);
	}
	
	BirtPluginInstaller installer = new BirtPluginInstaller( pluginsPath, reportDesignPath, scriptlibPath);
	installer.installPlugins();
}
 
Example 6
Source File: MyResteasyBootstrap.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private File findConfigurationFileInWebInf(ServletContext servletContext, String configurationFileName) {
    String pathToConfigurationFile = servletContext.getRealPath("WEB-INF/" + configurationFileName);
    if (pathToConfigurationFile == null) {
        return null;
    }
    return new File(pathToConfigurationFile);
}
 
Example 7
Source File: WebUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the real path of the given path within the web application,
 * as provided by the servlet container.
 * <p>Prepends a slash if the path does not already start with a slash,
 * and throws a FileNotFoundException if the path cannot be resolved to
 * a resource (in contrast to ServletContext's {@code getRealPath},
 * which returns null).
 * @param servletContext the servlet context of the web application
 * @param path the path within the web application
 * @return the corresponding real path
 * @throws FileNotFoundException if the path cannot be resolved to a resource
 * @see javax.servlet.ServletContext#getRealPath
 */
public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	// Interpret location as relative to the web application root directory.
	if (!path.startsWith("/")) {
		path = "/" + path;
	}
	String realPath = servletContext.getRealPath(path);
	if (realPath == null) {
		throw new FileNotFoundException(
				"ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +
				"web application archive not expanded?");
	}
	return realPath;
}
 
Example 8
Source File: Config.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean load(ServletContext context) {
    try {
        PROPS.load(context.getResourceAsStream(FILE_PATH));
        _fullPath = context.getRealPath("") + FILE_PATH;
        startConfigMonitoring(_fullPath);
        LOG.debug("Balancer config successfully loaded.");
        return true;
    }
    catch (IOException ioe) {
        LOG.error("Failed to load Balancer config");
    }
    return false;
}
 
Example 9
Source File: JasperReportRunner.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the virtualizer. (the slowest)
 * 
 * @param tmpDirectory
 *            the tmp directory
 * @param servletContext
 *            the servlet context
 * @return the virtualizer
 */
public JRFileVirtualizer getVirtualizer(String tmpDirectory, ServletContext servletContext) {
	logger.debug("IN");
	JRFileVirtualizer virtualizer = null;

	SourceBean config = EnginConf.getInstance().getConfig();
	String maxSizeStr = (String) config.getAttribute("VIRTUALIZER.maxSize");
	int maxSize = 2;
	if (maxSizeStr != null)
		maxSize = Integer.parseInt(maxSizeStr);
	String dir = (String) config.getAttribute("VIRTUALIZER.dir");
	if (dir == null) {
		dir = tmpDirectory;
	} else {
		if (!dir.startsWith("/")) {
			String contRealPath = servletContext.getRealPath("/");
			if (contRealPath.endsWith("\\") || contRealPath.endsWith("/")) {
				contRealPath = contRealPath.substring(0, contRealPath.length() - 1);
			}
			dir = contRealPath + "/" + dir;
		}
	}
	dir = dir + System.getProperty("file.separator") + "jrcache";
	File file = new File(dir);
	file.mkdirs();
	logger.debug("Max page cached during virtualization process: " + maxSize);
	logger.debug("Dir used as storing area during virtualization: " + dir);
	virtualizer = new JRFileVirtualizer(maxSize, dir);
	virtualizer.setReadOnly(false);
	logger.debug("OUT");
	return virtualizer;
}
 
Example 10
Source File: PredictorInitialiser.java    From browserprint with MIT License 5 votes vote down vote up
@Override
  public void contextInitialized(ServletContextEvent event) {
//Do stuff when the server starts up.
//Initialise directory for browser guesser
ServletContext context = event.getServletContext();
String browserModelPath = context.getRealPath("/WEB-INF/browserOsGuessFiles/browserGuess.randomForest.model");
String osModelPath = context.getRealPath("/WEB-INF/browserOsGuessFiles/osGuess.randomForest.model");
String fontsPath = context.getRealPath("/WEB-INF/browserOsGuessFiles/fontsIndices.fontsJS_CSS");
try {
	Predictor.initialise(browserModelPath, osModelPath, fontsPath);
} catch (Exception e) {
	e.printStackTrace();
	System.exit(-1);
}
  }
 
Example 11
Source File: AnnotationProcessor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Find the URL pointing to "/WEB-INF/classes"  This method may not work in conjunction with IteratorFactory
 * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory
 *
 * @param servletContext
 * @return null if cannot determin /WEB-INF/classes
 */
private static URL findWebInfClassesPath(ServletContext servletContext) {
    String path = servletContext.getRealPath("/WEB-INF/classes");
    if (path == null) return null;
    File fp = new File(path);
    if (fp.exists() == false) return null;
    try {
        URI uri = fp.toURI();
        return uri.toURL();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: AjaxAction.java    From OASystem with MIT License 5 votes vote down vote up
/**
 * ��ȡ��֤��
 * ��codeStr����֤���ַ���
 * @param req
 * @return ��֤�����ڵ�·��
 */
@RequestMapping(value="ajax/getLoginCodeAjax.do")
@ResponseBody
public String getLoginCode(HttpServletRequest req){
	HttpSession session = req.getSession();
	String codeStr = "";//��֤���
	String codeCon = "";//��֤������
	String path = "img/loginCode";//��֤��·��
	
	ServletContext application = req.getServletContext();
	String realPath = application.getRealPath("img/loginCode");
	String fileName = new Date().getTime()+".jpg";
	File file = new File(realPath+File.separator+fileName);//File.separator
	int num1 = (int)(Math.random()*10);
	int num2 = (int)(Math.random()*10);
	int fu = (int)(new Date().getTime()%2);
	if(fu==1){
		codeStr = (num1+num2)+"";
		codeCon = num1+"+"+num2;
	}else{
		codeStr = (num1-num2)+"";
		codeCon = num1+"-"+num2;
	}
	codeCon += "=?";
	try {
		CodeOfLogin.outputImage(600,200,file,codeCon);
	} catch (IOException e) {
		e.printStackTrace();
		return "error,jpg";
	}
	String name = fileName;//��֤���ļ���
	session.setAttribute("codeStr", codeStr);
	return path+"/"+name;
}
 
Example 13
Source File: NoopServlet.java    From wt1 with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
	ServletContext ctx = config.getServletContext();

	try {
		File f = new File(ctx.getRealPath(PIXEL_PATH));
		pixelData = FileUtils.readFileToByteArray(f);
	} catch (IOException e) {
		logger.error("Failed to read pixel", e);
		throw new ServletException(e);
	}
}
 
Example 14
Source File: JnlpResource.java    From webstart with MIT License 5 votes vote down vote up
long getLastModified( ServletContext context, URL resource, String path )
{
    long lastModified = 0;
    URLConnection conn;
    try
    {
        // Get last modified time
        conn = resource.openConnection();
        lastModified = conn.getLastModified();
    }
    catch ( Exception e )
    {
        // do nothing
    }

    if ( lastModified == 0 )
    {
        // Arguably a bug in the JRE will not set the lastModified for file URLs, and
        // always return 0. This is a workaround for that problem.
        String filepath = context.getRealPath( path );
        if ( filepath != null )
        {
            File f = new File( filepath );
            if ( f.exists() )
            {
                lastModified = f.lastModified();
            }
        }
    }
    return lastModified;
}
 
Example 15
Source File: CachedResourceFileNameHelper.java    From webdsl with Apache License 2.0 4 votes vote down vote up
public static void init(ServletContext ctx) {
  resourcePathRoot = ctx.getRealPath(File.separator);
  setCommonAndFavIcoTagSuffixes();
  invalidateOnChanges(resourcePathRoot);
}
 
Example 16
Source File: JspRuntimeContext.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Create a JspRuntimeContext for a web application context.
 *
 * Loads in any previously generated dependencies from file.
 *
 * @param context ServletContext for web application
 */
public JspRuntimeContext(ServletContext context, Options options) {

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

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

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

    parentClassLoader =  loader;
    classpath = initClassPath();

    if (context instanceof org.apache.jasper.servlet.JspCServletContext) {
        codeSource = null;
        permissionCollection = null;
        return;
    }

    if (Constants.IS_SECURITY_ENABLED) {
        SecurityHolder holder = initSecurity();
        codeSource = holder.cs;
        permissionCollection = holder.pc;
    } else {
        codeSource = null;
        permissionCollection = null;
    }

    // If this web application context is running from a
    // directory, start the background compilation thread
    String appBase = context.getRealPath("/");         
    if (!options.getDevelopment()
            && appBase != null
            && options.getCheckInterval() > 0) {
        lastCompileCheck = System.currentTimeMillis();
    }                                            

    if (options.getMaxLoadedJsps() > 0) {
        jspQueue = new FastRemovalDequeue<JspServletWrapper>(options.getMaxLoadedJsps());
        if (log.isDebugEnabled()) {
            log.debug(Localizer.getMessage("jsp.message.jsp_queue_created",
                                           "" + options.getMaxLoadedJsps(), context.getContextPath()));
        }
    }

    /* Init parameter is in seconds, locally we use milliseconds */
    jspIdleTimeout = options.getJspIdleTimeout() * 1000;
}
 
Example 17
Source File: ShowPrintableStoryAction.java    From ezScrum with GNU General Public License v2.0 4 votes vote down vote up
protected StreamInfo getStreamInfo(ActionMapping mapping,
        ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

	// get session info
	ProjectObject project = (ProjectObject) SessionManager.getProjectObject(request);
	IUserSession session = (IUserSession) request.getSession().getAttribute("UserSession");

	// get parameter info
	long sprintId = Long.parseLong(request.getParameter("sprintID"));
	SprintBacklogLogic sprintBacklogLogic = new SprintBacklogLogic(project, sprintId);
	SprintBacklogMapper backlog = sprintBacklogLogic.getSprintBacklogMapper();
	ArrayList<StoryObject> issues = sprintBacklogLogic.getStoriesSortedByImpInSprint();

	request.setAttribute("SprintID", backlog.getSprintId());
	request.setAttribute("Stories", issues);
	File file = null;

	try {
		//直接嵌入server上的pdf字型擋給系統 
		ServletContext sc = getServlet().getServletContext();
		String ttfPath = sc.getRealPath("") + "/WEB-INF/otherSetting/uming.ttf";

		MakePDFService makePDFService = new MakePDFService();
		file = makePDFService.getFile(ttfPath, issues);
	} catch (DocumentException de) {
		log.debug(de.toString());
	} catch (IOException ioe) {
		log.debug(ioe.toString());
	}

	response.setHeader("Content-disposition", "inline; filename=SprintStory.pdf");

	AccountObject account = session.getAccount();
	//		ScrumRole sr = new ScrumRoleManager().getScrumRole(project, acc);
	ScrumRole sr = new ScrumRoleLogic().getScrumRole(project, account);
	if (file == null) {
		throw new Exception(" pdf file is null");
	}
	if (sr.getAccessSprintBacklog()) {
		String contentType = "application/pdf";
		return new FileStreamInfo(contentType, file);
	} else {
		return null;
	}
}
 
Example 18
Source File: ServletContextPropertyFileHandler.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public ServletContextPropertyFileHandler(ServletContext ctx, String name) {
    super(ctx.getRealPath(name));
}
 
Example 19
Source File: AppPathService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Initialize The path service
 *
 * @param context
 *            The servlet context
 */
public static void init( ServletContext context )
{
    String strRealPath = context.getRealPath( "/" );
    _strWebAppPath = normalizeWebappPath( strRealPath );
}
 
Example 20
Source File: CGIServlet.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Uses the ServletContext to set some CGI variables
 *
 * @param  context   ServletContext for information provided by the
 *                   Servlet API
 */
protected void setupFromContext(ServletContext context) {
    this.context = context;
    this.webAppRootDir = context.getRealPath("/");
    this.tmpDir = (File) context.getAttribute(ServletContext.TEMPDIR);
}