private String normalizePath(String errorPath) {
   String result = StringUtils.cleanPath(errorPath);
   if (!result.startsWith("/")) {
     result = "/" + result;
   }
   return result;
 }
Ejemplo n.º 2
0
 public ServletContextOrClassPathResource(ServletContext servletContext, String path) {
   Assert.notNull(servletContext, "Cannot resolve ServletContextResource without ServletContext");
   this.servletContext = servletContext;
   // check path
   Assert.notNull(path, "path is required");
   this.path = StringUtils.cleanPath(path);
 }
 private void resolveRelativeFileUri() {
   if (getUri().startsWith("file:///./")) {
     String path = getUri().substring(8);
     String absolutePath = new File(path).getAbsolutePath();
     setUri("file:///" + StringUtils.cleanPath(absolutePath));
   }
 }
 /**
  * Generate a modified version of the supplied locations array and return it.
  *
  * <p>A plain path &mdash; for example, &quot;context.xml&quot; &mdash; will be treated as a
  * classpath resource that is relative to the package in which the specified class is defined. A
  * path starting with a slash is treated as an absolute classpath location, for example:
  * &quot;/org/springframework/whatever/foo.xml&quot;. A path which references a URL (e.g., a path
  * prefixed with {@link ResourceUtils#CLASSPATH_URL_PREFIX classpath:}, {@link
  * ResourceUtils#FILE_URL_PREFIX file:}, <code>http:</code>, etc.) will be added to the results
  * unchanged.
  *
  * <p>Subclasses can override this method to implement a different <em>location modification</em>
  * strategy.
  *
  * @param clazz the class with which the locations are associated
  * @param locations the resource locations to be modified
  * @return an array of modified application context resource locations
  * @since 2.5
  */
 protected String[] modifyLocations(Class<?> clazz, String... locations) {
   String[] modifiedLocations = new String[locations.length];
   for (int i = 0; i < locations.length; i++) {
     String path = locations[i];
     if (path.startsWith(SLASH)) {
       modifiedLocations[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
     } else if (!ResourcePatternUtils.isUrl(path)) {
       modifiedLocations[i] =
           ResourceUtils.CLASSPATH_URL_PREFIX
               + SLASH
               + StringUtils.cleanPath(
                   ClassUtils.classPackageAsResourcePath(clazz) + SLASH + path);
     } else {
       modifiedLocations[i] = StringUtils.cleanPath(path);
     }
   }
   return modifiedLocations;
 }
 /**
  * Create a new ClassPathResource for ClassLoader usage. A leading slash will be removed, as the
  * ClassLoader resource access methods will not accept it.
  *
  * @param path the absolute path within the classpath
  * @param classLoader the class loader to load the resource with, or <code>null</code> for the
  *     thread context class loader
  * @see java.lang.ClassLoader#getResourceAsStream(String)
  */
 public ClassPathResource(String path, ClassLoader classLoader) {
   Assert.notNull(path, "Path must not be null");
   String pathToUse = StringUtils.cleanPath(path);
   if (pathToUse.startsWith("/")) {
     pathToUse = pathToUse.substring(1);
   }
   this.path = pathToUse;
   this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
 }
 /**
  * Subclasses can override this method to return the locations of their config files.
  *
  * <p>A plain path will be treated as class path location, e.g.:
  * "org/springframework/whatever/foo.xml". Note however that you may prefix path locations with
  * standard Spring resource prefixes. Therefore, a config location path prefixed with "classpath:"
  * with behave the same as a plain path, but a config location such as
  * "file:/some/path/path/location/appContext.xml" will be treated as a filesystem location.
  *
  * <p>The default implementation builds config locations for the config paths specified through
  * {@link #getConfigPaths()}.
  *
  * @return an array of config locations
  * @see #getConfigPaths()
  * @see org.springframework.core.io.ResourceLoader#getResource(String)
  */
 protected final String[] getConfigLocations() {
   String[] paths = getConfigPaths();
   String[] convertedPaths = new String[paths.length];
   for (int i = 0; i < paths.length; i++) {
     String path = paths[i];
     if (path.startsWith(SLASH)) {
       convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
     } else if (!ResourcePatternUtils.isUrl(path)) {
       convertedPaths[i] =
           ResourceUtils.CLASSPATH_URL_PREFIX
               + SLASH
               + StringUtils.cleanPath(
                   ClassUtils.classPackageAsResourcePath(getClass()) + SLASH + path);
     } else {
       convertedPaths[i] = StringUtils.cleanPath(path);
     }
   }
   return convertedPaths;
 }
 /**
  * Attempt to resolve the xd.home placeholder and take care of corner cases where the user may
  * have provided a trailing slash, etc.
  */
 private static String resolveXDHome() {
   Assert.state(
       CommandLinePropertySourceOverridingListener.getCurrentEnvironment() != null,
       "Expected to be called in the control flow of "
           + CommandLinePropertySourceOverridingListener.class.getSimpleName()
           + ".onApplicationEvent()");
   // TODO: I'm not sure if this works. compare to resolveMessageBusPath() above
   String resolved =
       CommandLinePropertySourceOverridingListener.getCurrentEnvironment()
           .resolvePlaceholders("${xd.home:.}/lib/*");
   resolved = StringUtils.cleanPath(resolved).replace("//", "/");
   return "file:" + resolved;
 }
 private HttpResponse forward(
     HttpClient httpclient,
     String verb,
     String uri,
     HttpServletRequest request,
     MultiValueMap<String, String> headers,
     MultiValueMap<String, String> params,
     InputStream requestEntity)
     throws Exception {
   Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
   URL host = RequestContext.getCurrentContext().getRouteHost();
   HttpHost httpHost = getHttpHost(host);
   uri = StringUtils.cleanPath(host.getPath() + uri);
   HttpRequest httpRequest;
   switch (verb.toUpperCase()) {
     case "POST":
       HttpPost httpPost = new HttpPost(uri + getQueryString());
       httpRequest = httpPost;
       httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     case "PUT":
       HttpPut httpPut = new HttpPut(uri + getQueryString());
       httpRequest = httpPut;
       httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     case "PATCH":
       HttpPatch httpPatch = new HttpPatch(uri + getQueryString());
       httpRequest = httpPatch;
       httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     default:
       httpRequest = new BasicHttpRequest(verb, uri + getQueryString());
       log.debug(uri + getQueryString());
   }
   try {
     httpRequest.setHeaders(convertHeaders(headers));
     log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
     HttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
     this.helper.appendDebug(
         info,
         zuulResponse.getStatusLine().getStatusCode(),
         revertHeaders(zuulResponse.getAllHeaders()));
     return zuulResponse;
   } finally {
     // When HttpClient instance is no longer needed,
     // shut down the connection manager to ensure
     // immediate deallocation of all system resources
     // httpclient.getConnectionManager().shutdown();
   }
 }
 private String[] getPaths(String application, String profile, String label) {
   String[] locations =
       getSearchLocations(getSvnPath(getWorkingDirectory(), label), application, profile, label);
   boolean exists = false;
   for (String location : locations) {
     location = StringUtils.cleanPath(location);
     URI locationUri = URI.create(location);
     if (new File(locationUri).exists()) {
       exists = true;
       break;
     }
   }
   if (!exists) {
     throw new NoSuchLabelException("No label found for: " + label);
   }
   return locations;
 }
 private Set<String> getSearchLocations() {
   Set<String> locations = new LinkedHashSet<String>();
   // User-configured settings take precedence, so we do them first
   if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
     for (String path :
         asResolvedSet(this.environment.getProperty(CONFIG_LOCATION_PROPERTY), null)) {
       if (!path.contains("$")) {
         if (!path.contains(":")) {
           path = "file:" + path;
         }
         path = StringUtils.cleanPath(path);
       }
       locations.add(path);
     }
   }
   locations.addAll(
       asResolvedSet(
           ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS));
   return locations;
 }
Ejemplo n.º 11
0
  public void afterPropertiesSet() {

    // ToDo Instead of stdout, use servletContext.log( "...") [NOTE: it writes to localhost.*.log
    // rather than catalina.out].
    if (servletContext == null)
      throw new IllegalArgumentException("ServletContext must not be null.");

    // ToDo LOOK - Are we still using this.
    ServletUtil.initDebugging(servletContext);

    // Set the webapp name.
    this.webappName = servletContext.getServletContextName();

    // Set the context path.
    // Servlet 2.5 allows the following.
    // contextPath = servletContext.getContextPath();
    String tmpContextPath =
        servletContext.getInitParameter(
            "ContextPath"); // cannot be overridden in the ThreddsConfig file
    if (tmpContextPath == null) tmpContextPath = "thredds";
    contextPath = "/" + tmpContextPath;
    // ToDo LOOK - Get rid of need for setting contextPath in ServletUtil.
    ServletUtil.setContextPath(contextPath);

    // Set the root directory and source.
    String rootPath = servletContext.getRealPath("/");
    if (rootPath == null) {
      String msg =
          "Webapp ["
              + this.webappName
              + "] must run with exploded deployment directory (not from .war).";
      System.out.println("ERROR - TdsContext.init(): " + msg);
      // logServerStartup.error( "TdsContext.init(): " + msg );
      throw new IllegalStateException(msg);
    }
    this.rootDirectory = new File(rootPath);
    this.rootDirSource = new BasicDescendantFileSource(this.rootDirectory);
    this.rootDirectory = this.rootDirSource.getRootDirectory();
    // ToDo LOOK - Get rid of need for setting rootPath in ServletUtil.
    ServletUtil.setRootPath(this.rootDirSource.getRootDirectoryPath());

    // Set the startup (initial install) content directory and source.
    this.startupContentDirectory = new File(this.rootDirectory, this.startupContentPath);
    this.startupContentDirSource = new BasicDescendantFileSource(this.startupContentDirectory);
    this.startupContentDirectory = this.startupContentDirSource.getRootDirectory();

    this.webinfPath = this.rootDirectory + "/WEB-INF";

    // set the tomcat logging directory
    try {
      String base = System.getProperty("catalina.base");
      if (base != null) {
        this.tomcatLogDir = new File(base, "logs").getCanonicalFile();
        if (!this.tomcatLogDir.exists()) {
          String msg = "'catalina.base' directory not found";
          System.out.println("WARN - TdsContext.init(): " + msg);
          // logServerStartup.error( "TdsContext.init(): " + msg );
        }
      } else {
        String msg = "'catalina.base' property not found - probably not a tomcat server";
        System.out.println("WARN - TdsContext.init(): " + msg);
        // logServerStartup.warn( "TdsContext.init(): " + msg );
      }

    } catch (IOException e) {
      String msg = "tomcatLogDir could not be created";
      System.out.println("WARN - TdsContext.init(): " + msg);
      // logServerStartup.error( "TdsContext.init(): " + msg );
    }

    // Set the content directory and source.
    File contentRootDir = new File(this.contentRootPath);
    if (!contentRootDir.isAbsolute())
      this.contentDirectory =
          new File(new File(this.rootDirectory, this.contentRootPath), this.contentPath);
    else {
      if (contentRootDir.isDirectory())
        this.contentDirectory = new File(contentRootDir, this.contentPath);
      else {
        String msg = "Content root directory [" + this.contentRootPath + "] not a directory.";
        System.out.println("ERROR - TdsContext.init(): " + msg);
        // logServerStartup.error( "TdsContext.init(): " + msg );
        throw new IllegalStateException(msg);
      }
    }
    // If the content directory doesn't exist, try to copy startup content directory.
    if (!this.contentDirectory.exists()) {
      try {
        IO.copyDirTree(this.startupContentDirectory.getPath(), this.contentDirectory.getPath());
      } catch (IOException e) {
        String tmpMsg = "Content directory does not exist and could not be created";
        System.out.println(
            "ERROR - TdsContext.init(): "
                + tmpMsg
                + " ["
                + this.contentDirectory.getAbsolutePath()
                + "].");
        // logServerStartup.error( "TdsContext.init(): " + tmpMsg + " [" +
        // this.contentDirectory.getAbsolutePath() + "]" );
        throw new IllegalStateException(tmpMsg);
      }
    }

    // If content directory exists, make sure it is a directory.
    if (this.contentDirectory.isDirectory()) {
      this.contentDirSource =
          new BasicDescendantFileSource(
              StringUtils.cleanPath(this.contentDirectory.getAbsolutePath()));
      this.contentDirectory = this.contentDirSource.getRootDirectory();
    } else {
      String tmpMsg = "Content directory not a directory";
      System.out.println(
          "ERROR - TdsContext.init(): "
              + tmpMsg
              + " ["
              + this.contentDirectory.getAbsolutePath()
              + "].");
      // logServerStartup.error( "TdsContext.init(): " + tmpMsg + " [" +
      // this.contentDirectory.getAbsolutePath() + "]" );
      throw new IllegalStateException(tmpMsg);
    }
    ServletUtil.setContentPath(this.contentDirSource.getRootDirectoryPath());

    File logDir = new File(this.contentDirectory, "logs");
    if (!logDir.exists()) {
      if (!logDir.mkdirs()) {
        String msg = "Couldn't create TDS log directory [" + logDir.getPath() + "].";
        // System.out.println( "ERROR - TdsContext.init(): " + msg);
        logServerStartup.error("TdsContext.init(): " + msg);
        throw new IllegalStateException(msg);
      }
    }
    String loggingDirectory = StringUtil2.substitute(logDir.getPath(), "\\", "/");
    System.setProperty("tds.log.dir", loggingDirectory); // variable substitution

    // LOOK Remove log4j init JC 6/13/2012
    // which is used in log4j.xml file loaded here.
    Log4jWebConfigurer.initLogging(servletContext);
    logServerStartup.info("TdsConfigContextListener.contextInitialized() start[2]: ");
    logServerStartup.info("TdsContext.init()  intializating logging...");

    // read in persistent user-defined params from threddsConfig.xml
    File tdsConfigFile = this.contentDirSource.getFile(this.getTdsConfigFileName());
    String tdsConfigFilename = tdsConfigFile != null ? tdsConfigFile.getPath() : "";
    ThreddsConfig.init(tdsConfigFilename);

    this.publicContentDirectory = new File(this.contentDirectory, "public");
    if (!publicContentDirectory.exists()) {
      if (!publicContentDirectory.mkdirs()) {
        String msg =
            "Couldn't create TDS public directory [" + publicContentDirectory.getPath() + "].";
        // System.out.println( "ERROR - TdsContext.init(): " + msg);
        logServerStartup.error("TdsContext.init(): " + msg);
        throw new IllegalStateException(msg);
      }
    }
    this.publicContentDirSource = new BasicDescendantFileSource(this.publicContentDirectory);

    this.iddContentDirectory = new File(this.rootDirectory, this.iddContentPath);
    this.iddContentPublicDirSource = new BasicDescendantFileSource(this.iddContentDirectory);

    this.motherlodeContentDirectory = new File(this.rootDirectory, this.motherlodeContentPath);
    this.motherlodeContentPublicDirSource =
        new BasicDescendantFileSource(this.motherlodeContentDirectory);

    List<DescendantFileSource> chain = new ArrayList<DescendantFileSource>();
    DescendantFileSource contentMinusPublicSource =
        new BasicWithExclusionsDescendantFileSource(
            this.contentDirectory, Collections.singletonList("public"));
    chain.add(contentMinusPublicSource);
    for (String curContentRoot : ThreddsConfig.getContentRootList()) {
      if (curContentRoot.equalsIgnoreCase("idd")) chain.add(this.iddContentPublicDirSource);
      else if (curContentRoot.equalsIgnoreCase("motherlode"))
        chain.add(this.motherlodeContentPublicDirSource);
      else {
        try {
          chain.add(new BasicDescendantFileSource(StringUtils.cleanPath(curContentRoot)));
        } catch (IllegalArgumentException e) {
          String msg = "Couldn't add content root [" + curContentRoot + "]: " + e.getMessage();
          // System.out.println( "WARN - TdsContext.init(): " + msg );
          logServerStartup.warn("TdsContext.init(): " + msg, e);
        }
      }
    }
    this.configSource = new ChainedFileSource(chain);
    this.publicDocSource = this.publicContentDirSource;

    // ToDo LOOK Find a better way once thredds.catalog2 is used.
    InvDatasetScan.setContext(contextPath);
    InvDatasetScan.setCatalogServletName("/catalog");
    InvDatasetFeatureCollection.setContext(contextPath);
    // GridServlet.setContextPath( contextPath ); // Won't need when switch GridServlet to use Swing
    // MVC and TdsContext

    jspRequestDispatcher = servletContext.getNamedDispatcher("jsp");
    defaultRequestDispatcher = servletContext.getNamedDispatcher("default");

    TdsConfigMapper tdsConfigMapper = new TdsConfigMapper();
    tdsConfigMapper.setTdsServerInfo(this.serverInfo);
    tdsConfigMapper.setHtmlConfig(this.htmlConfig);
    tdsConfigMapper.setWmsConfig(this.wmsConfig);
    tdsConfigMapper.init(this);
  }
 /**
  * Create a new FileSystemResource.
  *
  * @param path a file path
  */
 public FileSystemResource(String path) {
   Assert.notNull(path, "Path must not be null");
   this.file = new File(path);
   this.path = StringUtils.cleanPath(path);
 }
 /**
  * Create a new FileSystemResource.
  *
  * @param file a File handle
  */
 public FileSystemResource(File file) {
   Assert.notNull(file, "File must not be null");
   this.file = file;
   this.path = StringUtils.cleanPath(file.getPath());
 }
Ejemplo n.º 14
0
  /**
   * Creates an {@link InputStream} to the requested path. This will look in both the defined
   * classpath and within the META-INF of the application.
   *
   * @param path The path to generate an {@link InputStream} to.
   * @return The {@link InputStream} for the requested resource and <code>null</code> if the
   *     resource could not be found.
   * @throws IOException Thrown when an error occurs attempting to generate an {@link InputStream}
   */
  public InputStream getResourceInputStream(String path) throws IOException {
    InputStream in = null;

    // TODO: Check the sentinel isn't returned...
    ResourceInfo resourceInfo = getCachedResourceInfo(path);
    if (resourceInfo == getResourceInfoSentinel()) {
      // No action required - the ResourceInfoSentinel indicates that we've previously searched
      // for this path and the resource couldn't be found.
    } else if (resourceInfo != null) {
      in = resourceInfo.getInputStream();
    } else {
      // Generate a list of paths that should be checked for the current mode...
      List<String> pathsToCheck = generatePathsForClientMode(path);
      Iterator<String> paths;
      if (this.webFrameworkConfigElement.isRemoteResourceResolvingEnabled()) {
        paths = pathsToCheck.iterator();
        while (in == null && paths.hasNext()) {
          String currPath = paths.next();
          in = this.remoteResourcesHandler.getRemoteResource(currPath);
          if (in != null) {
            addResourceInfoToCache(path, new RemoteResource(currPath));
            in = this.getCachedResourceInfo(path).getInputStream();
          }
        }
      }

      paths = pathsToCheck.iterator();
      while (in == null && paths.hasNext()) {
        String currPath = paths.next();
        Resource r = applicationContext.getResource("classpath*:" + currPath);
        if (r != null && r.exists()) {
          addResourceInfoToCache(path, new ApplicationContextResource(currPath));
          in = this.getCachedResourceInfo(path).getInputStream();
        }
      }

      paths = pathsToCheck.iterator();
      while (in == null && paths.hasNext()) {
        String currPath = paths.next();
        if (currPath.startsWith("/")) {
          currPath = currPath.substring(1);
        }
        URL resourceUrl = ClassUtils.getDefaultClassLoader().getResource("META-INF/" + currPath);
        if (resourceUrl != null) {
          addResourceInfoToCache(path, new ClassLoaderResource(currPath));
          in = this.getCachedResourceInfo(path).getInputStream();
        }
      }

      paths = pathsToCheck.iterator();
      while (this.servletContext != null && in == null && paths.hasNext()) {
        final String p = paths.next();
        // servlet resource paths cannot start with a relative operator - they should always begin
        // at the root - note that ServletContextResource() will prepend "/" automatically to all
        // paths
        // and "/../something" is invalid for most modern containers
        if (!StringUtils.cleanPath(p).startsWith("..")) {
          ServletContextResource resource = new ServletContextResource(this.servletContext, p);
          {
            if (resource.exists()) {
              addResourceInfoToCache(path, new ServletContextRes(p));
              in = this.getCachedResourceInfo(path).getInputStream();
            }
          }
        }
      }
    }

    // If the input stream is still null, add a sentinel...
    if (in == null) {
      addResourceInfoToCache(path, getResourceInfoSentinel());
    }
    return in;
  }
 /**
  * Create a new ClassPathResource for Class usage. The path can be relative to the given class, or
  * absolute within the classpath via a leading slash.
  *
  * @param path relative or absolute path within the class path
  * @param clazz the class to load resources with
  * @see java.lang.Class#getResourceAsStream
  */
 public ClassPathResource(String path, Class<?> clazz) {
   Assert.notNull(path, "Path must not be null");
   this.path = StringUtils.cleanPath(path);
   this.clazz = clazz;
 }
 /**
  * Create a new ClassPathResource with optional ClassLoader and Class. Only for internal usage.
  *
  * @param path relative or absolute path within the classpath
  * @param classLoader the class loader to load the resource with, if any
  * @param clazz the class to load resources with, if any
  */
 protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) {
   this.path = StringUtils.cleanPath(path);
   this.classLoader = classLoader;
   this.clazz = clazz;
 }