Пример #1
0
  private View createGrailsView(String viewName) throws Exception {
    // try GSP if res is null

    GrailsWebRequest webRequest = WebUtils.retrieveGrailsWebRequest();

    HttpServletRequest request = webRequest.getCurrentRequest();
    GroovyObject controller = webRequest.getAttributes().getController(request);

    if (grailsApplication == null) {

      grailsApplication =
          getApplicationContext()
              .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
    }

    ResourceLoader loader = establishResourceLoader(grailsApplication);

    String format =
        request.getAttribute(GrailsApplicationAttributes.CONTENT_FORMAT) != null
            ? request.getAttribute(GrailsApplicationAttributes.CONTENT_FORMAT).toString()
            : null;
    String gspView = localPrefix + viewName + DOT + format + GSP_SUFFIX;
    Resource res = null;

    if (format != null) {
      res = loader.getResource(gspView);
      if (!res.exists()) {
        View v = lookupBinaryPluginView(webRequest, controller, gspView);
        if (v != null) {
          return v;
        }
        gspView = resolveViewForController(controller, grailsApplication, viewName, loader);
        res = loader.getResource(gspView);
      }
    }

    if (res == null || !res.exists()) {
      gspView = localPrefix + viewName + GSP_SUFFIX;
      res = loader.getResource(gspView);
      if (!res.exists()) {
        View v = lookupBinaryPluginView(webRequest, controller, gspView);
        if (v != null) {
          return v;
        }
        gspView = resolveViewForController(controller, grailsApplication, viewName, loader);
        res = loader.getResource(gspView);
      }
    }

    if (res.exists()) {
      return createGroovyPageView(webRequest, gspView);
    }

    AbstractUrlBasedView view = buildView(viewName);
    view.setApplicationContext(getApplicationContext());
    view.afterPropertiesSet();
    return view;
  }
Пример #2
0
  private void validatePaths(
      String path, ResourcePatternResolver resourceLoader, boolean shouldExist) throws IOException {
    Resource res = resourceLoader.getResource(path);

    if (shouldExist) {
      Assert.isTrue(res.exists(), "The input path [" + path + "] does not exist");
    } else {
      Assert.isTrue(!res.exists(), "The output path [" + path + "] already exists");
    }
  }
Пример #3
0
  public void testNonExistentFileOutsideOSGi() throws Exception {
    String nonExistingLocation = thisClass.getURL().toExternalForm().concat("-bogus-extension");

    Resource nonExistingFile = defaultLoader.getResource(nonExistingLocation);
    assertNotNull(nonExistingFile);
    assertFalse(nonExistingFile.exists());

    Resource nonExistingFileOutsideOsgi = resourceLoader.getResource(nonExistingLocation);
    assertNotNull(nonExistingFileOutsideOsgi);
    assertFalse(nonExistingFileOutsideOsgi.exists());
  }
Пример #4
0
 // adapted from DefaultGrailsApplication
 private static Map loadMetadata() {
   Resource r = new ClassPathResource(PROJECT_META_FILE);
   if (r.exists()) {
     return loadMetadata(r);
   }
   String basedir = System.getProperty("base.dir");
   if (basedir != null) {
     r = new FileSystemResource(new File(basedir, PROJECT_META_FILE));
     if (r.exists()) {
       return loadMetadata(r);
     }
   }
   return null;
 }
 /**
  * Attempts to retrieve a reference to a GSP as a Spring Resource instance for the given URI.
  *
  * @param uri The URI to check
  * @return A Resource instance
  */
 private Resource getResourceForUri(String uri) {
   Resource r;
   r = getResourceWithinContext(uri);
   if (r == null || !r.exists()) {
     // try plugin
     String pluginUri = GrailsResourceUtils.WEB_INF + uri;
     r = getResourceWithinContext(pluginUri);
     if (r == null || !r.exists()) {
       uri = getUriWithinGrailsViews(uri);
       return getResourceWithinContext(uri);
     }
   }
   return r;
 }
Пример #6
0
  public void testFileOutsideOSGi() throws Exception {
    String fileLocation = "file:///" + thisClass.getFile().getAbsolutePath();
    // use file system resource defaultLoader
    Resource fileResource = defaultLoader.getResource(fileLocation);
    assertTrue(fileResource.exists());

    // try loading the file using OsgiBundleResourceLoader
    Resource osgiResource = resourceLoader.getResource(fileLocation);
    // check existence of the same file when loading through the
    // OsgiBundleRL
    // NOTE andyp -- we want this to work!!
    assertTrue(osgiResource.exists());

    assertEquals(fileResource.getURL(), osgiResource.getURL());
  }
  public void setAdsResource(Resource resource)
      throws ParserConfigurationException, IOException, SAXException {
    advertisementBlocks.clear();

    if (resource != null && resource.exists() && resource.isReadable()) {
      final DocumentBuilder builder = BUILDER_FACTORY.newDocumentBuilder();
      final Document document = builder.parse(resource.getInputStream());

      final Element root = document.getDocumentElement();
      final String client = root.getAttribute("client");

      final NodeList blocks = root.getElementsByTagName("block");
      for (int i = 0; i < blocks.getLength(); i++) {
        final Element block = (Element) blocks.item(i);
        final String name = block.getAttribute("name");

        final NodeList items = block.getElementsByTagName("item");
        for (int j = 0; j < items.getLength(); j++) {
          final Element item = (Element) items.item(j);
          final String slot = item.getAttribute("slot");
          final Language language = Language.byCode(item.getAttribute("language"));
          final int width = Integer.valueOf(item.getAttribute("width"));
          final int height = Integer.valueOf(item.getAttribute("height"));

          advertisementBlocks.put(
              new AdsBlockKey(name, language),
              new AdvertisementBlock(client, slot, width, height, AdvertisementProvider.GOOGLE));
        }
      }
    }
  }
Пример #8
0
  private boolean renderTemplate(
      Object target, GroovyObject controller, GrailsWebRequest webRequest, Map argMap, Writer out) {
    boolean renderView;
    String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
    String contextPath = getContextPath(webRequest, argMap);

    String var = (String) argMap.get(ARGUMENT_VAR);
    // get the template uri
    String templateUri = GroovyPageUtils.getTemplateURI(controller, templateName);

    // retrieve gsp engine
    GroovyPagesTemplateEngine engine =
        (GroovyPagesTemplateEngine)
            webRequest.getApplicationContext().getBean(GroovyPagesTemplateEngine.BEAN_ID);
    try {
      Resource r = engine.getResourceForUri(contextPath + templateUri);
      if (!r.exists()) {
        r = engine.getResourceForUri(contextPath + "/grails-app/views/" + templateUri);
      }

      Template t = engine.createTemplate(r); // templateUri);

      if (t == null) {
        throw new ControllerExecutionException(
            "Unable to load template for uri [" + templateUri + "]. Template not found.");
      }
      Map binding = new HashMap();

      if (argMap.containsKey(ARGUMENT_BEAN)) {
        Object bean = argMap.get(ARGUMENT_BEAN);
        if (argMap.containsKey(ARGUMENT_MODEL)) {
          Object modelObject = argMap.get(ARGUMENT_MODEL);
          if (modelObject instanceof Map) binding.putAll((Map) modelObject);
        }
        renderTemplateForBean(t, binding, bean, var, out);
      } else if (argMap.containsKey(ARGUMENT_COLLECTION)) {
        Object colObject = argMap.get(ARGUMENT_COLLECTION);
        if (argMap.containsKey(ARGUMENT_MODEL)) {
          Object modelObject = argMap.get(ARGUMENT_MODEL);
          if (modelObject instanceof Map) binding.putAll((Map) modelObject);
        }
        renderTemplateForCollection(t, binding, colObject, var, out);
      } else if (argMap.containsKey(ARGUMENT_MODEL)) {
        Object modelObject = argMap.get(ARGUMENT_MODEL);
        renderTemplateForModel(t, modelObject, target, out);
      } else {
        Writable w = t.make(new BeanMap(target));
        w.writeTo(out);
      }
      renderView = false;
    } catch (GroovyRuntimeException gre) {
      throw new ControllerExecutionException(
          "Error rendering template [" + templateName + "]: " + gre.getMessage(), gre);
    } catch (IOException ioex) {
      throw new ControllerExecutionException(
          "I/O error executing render method for arguments [" + argMap + "]: " + ioex.getMessage(),
          ioex);
    }
    return renderView;
  }
 /** Find extended mime.types from the spring-context-support module. */
 private static FileTypeMap initFileTypeMap() {
   Resource resource = new ClassPathResource("org/springframework/mail/javamail/mime.types");
   if (resource.exists()) {
     if (logger.isTraceEnabled()) {
       logger.trace("Loading JAF FileTypeMap from " + resource);
     }
     InputStream inputStream = null;
     try {
       inputStream = resource.getInputStream();
       return new MimetypesFileTypeMap(inputStream);
     } catch (IOException ex) {
       // ignore
     } finally {
       if (inputStream != null) {
         try {
           inputStream.close();
         } catch (IOException ex) {
           // ignore
         }
       }
     }
   }
   if (logger.isTraceEnabled()) {
     logger.trace("Loading default Java Activation Framework FileTypeMap");
   }
   return FileTypeMap.getDefaultFileTypeMap();
 }
  private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists()) return;
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String[] scripts;
    try {
      String[] list =
          StringUtils.delimitedListToStringArray(
              stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
      scripts = list;
    } catch (IOException e) {
      throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
    }
    for (int i = 0; i < scripts.length; i++) {
      final String script = scripts[i].trim();
      TransactionTemplate transactionTemplate =
          new TransactionTemplate(new DataSourceTransactionManager(dataSource));
      transactionTemplate.execute(
          new TransactionCallback<Void>() {

            @Override
            public Void doInTransaction(TransactionStatus status) {
              if (StringUtils.hasText(script)) {
                try {
                  jdbcTemplate.execute(script);
                } catch (DataAccessException e) {
                  if (!script.toUpperCase().startsWith("DROP")) {
                    throw e;
                  }
                }
              }
              return null;
            }
          });
    }
  }
 public final void afterPropertiesSet() throws GeneralSecurityException, IOException {
   if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) {
     keyStore = KeyStore.getInstance(type, provider);
   } else if (StringUtils.hasLength(type)) {
     keyStore = KeyStore.getInstance(type);
   } else {
     keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
   }
   InputStream is = null;
   try {
     if (location != null && location.exists()) {
       is = location.getInputStream();
       if (logger.isInfoEnabled()) {
         logger.info("Loading key store from " + location);
       }
     } else if (logger.isWarnEnabled()) {
       logger.warn("Creating empty key store");
     }
     keyStore.load(is, password);
   } finally {
     if (is != null) {
       is.close();
     }
   }
 }
  @Override
  protected void doOpen() throws Exception {
    Assert.notNull(resource, "Input resource must be set");
    Assert.notNull(recordSeparatorPolicy, "RecordSeparatorPolicy must be set");

    noInput = true;
    if (!resource.exists()) {
      if (strict) {
        throw new IllegalStateException(
            "Input resource must exist (reader is in 'strict' mode): " + resource);
      }
      logger.warn("Input resource does not exist " + resource.getDescription());
      return;
    }

    if (!resource.isReadable()) {
      if (strict) {
        throw new IllegalStateException(
            "Input resource must be readable (reader is in 'strict' mode): " + resource);
      }
      logger.warn("Input resource is not readable " + resource.getDescription());
      return;
    }

    reader = bufferedReaderFactory.create(resource, encoding);
    for (int i = 0; i < linesToSkip; i++) {
      String line = readLine();
      if (skippedLinesCallback != null) {
        skippedLinesCallback.handleLine(line);
      }
    }
    noInput = false;
  }
 private ModuleOptionsMetadata resolveNormalMetadata(ModuleDefinition definition) {
   try {
     ClassLoader classLoaderToUse =
         definition.getClasspath() != null
             ? new ParentLastURLClassLoader(
                 definition.getClasspath(), ModuleOptionsMetadataResolver.class.getClassLoader())
             : ModuleOptionsMetadataResolver.class.getClassLoader();
     Resource propertiesResource =
         definition.getResource().createRelative(definition.getName() + ".properties");
     if (!propertiesResource.exists()) {
       return inferModuleOptionsMetadata(definition, classLoaderToUse);
     } else {
       Properties props = new Properties();
       props.load(propertiesResource.getInputStream());
       String pojoClass = props.getProperty(OPTIONS_CLASS);
       if (pojoClass != null) {
         try {
           Class<?> clazz = Class.forName(pojoClass, true, classLoaderToUse);
           return new PojoModuleOptionsMetadata(
               clazz, resourceLoader, environment, conversionService);
         } catch (ClassNotFoundException e) {
           throw new IllegalStateException(
               "Unable to load class used by ModuleOptionsMetadata: " + pojoClass, e);
         }
       }
       return makeSimpleModuleOptions(props);
     }
   } catch (IOException e) {
     return new PassthruModuleOptionsMetadata();
   }
 }
 private static FileTypeMap loadFileTypeMapFromContextSupportModule() {
   // see if we can find the extended mime.types from the context-support module
   Resource mappingLocation =
       new ClassPathResource("org/springframework/mail/javamail/mime.types");
   if (mappingLocation.exists()) {
     if (logger.isTraceEnabled()) {
       logger.trace("Loading Java Activation Framework FileTypeMap from " + mappingLocation);
     }
     InputStream inputStream = null;
     try {
       inputStream = mappingLocation.getInputStream();
       return new MimetypesFileTypeMap(inputStream);
     } catch (IOException ex) {
       // ignore
     } finally {
       if (inputStream != null) {
         try {
           inputStream.close();
         } catch (IOException ex) {
           // ignore
         }
       }
     }
   }
   if (logger.isTraceEnabled()) {
     logger.trace("Loading default Java Activation Framework FileTypeMap");
   }
   return FileTypeMap.getDefaultFileTypeMap();
 }
Пример #15
0
  @Override
  public PageResponse process(RackRequest request) {
    RouteMatchResult matchResult = routeMatcher.matches(request);

    if (matchResult.matched) {
      // try {
      String[] templates = this.fileExtensions(matchResult.matchedParams.splats().last());

      Resource template =
          loader.getResource("classpath:templates/" + matchResult.matchedParams.splats().join("/"));
      if (template.exists()) {
        try {
          StringExpression rawContent = ExpressionFactory.string(template.getInputStream());
          StringExpression rendered =
              templateEngine.render(new Context(request), rawContent, templates);
          return PageResponseFactory.html(rendered);
        } catch (IOException e) {
          return PageResponseFactory.internalError();
        }
      } else {
        return PageResponseFactory.notFound();
      }

    } else {
      return null;
    }
  }
  protected Set<String> getTemplateNamesFromPath(String path) throws IOException {

    if (resourceLoader != null && grailsApplication.isWarDeployed()) {
      try {
        PathMatchingResourcePatternResolver resolver =
            new PathMatchingResourcePatternResolver(resourceLoader);
        return extractNames(
            resolver.getResources("/WEB-INF/templates/angular-scaffolding/" + path + "/*.gsp"));
      } catch (Exception e) {
        return Collections.emptySet();
      }
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Set<String> resources = new HashSet<String>();

    String templatesDirPath = basedir + "/src/templates/angular-scaffolding/" + path;
    Resource templatesDir = new FileSystemResource(templatesDirPath);
    if (templatesDir.exists()) {
      try {
        resources.addAll(
            extractNames(resolver.getResources("file:" + templatesDirPath + "/*.gsp")));
      } catch (Exception e) {
        log.error("Error while loading views from " + basedir, e);
      }
    }

    return resources;
  }
 public Template createTemplateForUri(String[] uri) {
   Template t;
   if (!isReloadEnabled()) {
     for (String anUri : uri) {
       t = createTemplateFromPrecompiled(anUri);
       if (t != null) {
         return t;
       }
     }
   }
   Resource resource = null;
   for (String anUri : uri) {
     Resource r = getResourceForUri(anUri);
     if (r.exists()) {
       resource = r;
       break;
     }
   }
   if (resource != null) {
     if (precompiledGspMap != null && precompiledGspMap.size() > 0) {
       if (LOG.isWarnEnabled()) {
         LOG.warn(
             "Precompiled GSP not found for uri: "
                 + Arrays.asList(uri)
                 + ". Using resource "
                 + resource);
       }
     }
     return createTemplate(resource);
   }
   return null;
 }
Пример #18
0
 /**
  * Return the path to a service's design-time service definition xml.
  *
  * @param serviceId
  * @return
  */
 @Deprecated
 public Resource getServiceDefXml(String serviceId, boolean fallbackToClassPath) {
   try {
     Resource serviceDef =
         getServiceDesigntimeDirectory(serviceId).createRelative(SERVICE_DEF_XML);
     if (!serviceDef.exists() && fallbackToClassPath) {
       Resource runtimeServiceDef =
           new ClassPathResource(SERVICES_DIR + serviceId + "/" + SERVICE_DEF_XML);
       if (runtimeServiceDef.exists()) {
         return runtimeServiceDef;
       }
     }
     return serviceDef;
   } catch (IOException ex) {
     throw new WMRuntimeException(ex);
   }
 }
Пример #19
0
 public void testFileResource() {
   File file = new File("d:/test.txt");
   Resource resource = new FileSystemResource(file);
   if (resource.exists()) {
     dumpStream(resource);
   }
   Assert.assertEquals(false, resource.isOpen());
 }
Пример #20
0
 public void testClasspathResourceByDefaultClassLoader() throws IOException {
   Resource resource = new ClassPathResource("com/iss/expense/demo/chapter4/test1.properties");
   if (resource.exists()) {
     dumpStream(resource);
   }
   System.out.println("path:--->" + resource.getFile().getAbsolutePath());
   Assert.assertEquals(false, resource.isOpen());
 }
 /**
  * Set the temporary directory where uploaded files get stored. Default is the servlet container's
  * temporary directory for the web application.
  *
  * @see org.springframework.web.util.WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE
  */
 public void setUploadTempDir(Resource uploadTempDir) throws IOException {
   if (!uploadTempDir.exists() && !uploadTempDir.getFile().mkdirs()) {
     throw new IllegalArgumentException(
         "Given uploadTempDir [" + uploadTempDir + "] could not be created");
   }
   this.fileItemFactory.setRepository(uploadTempDir.getFile());
   this.uploadTempDirSpecified = true;
 }
 public JMSPropertyPlaceholderConfigurer(Resource defaultFile, JMSConfiguration config)
     throws IOException {
   if (!defaultFile.exists()) {
     throw new IOException("Unable to locate the default properties file at:" + defaultFile);
   }
   this.defaults = defaultFile;
   this.config = config;
 }
Пример #23
0
 public InputStream loadInputStream() throws IOException {
   InputStream in = null;
   Resource r = applicationContext.getResource("classpath*:" + path);
   if (r != null && r.exists()) {
     in = r.getInputStream();
   }
   return in;
 }
Пример #24
0
 public void testInputStreamResource() {
   ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());
   Resource resource = new InputStreamResource(bis);
   if (resource.exists()) {
     dumpStream(resource);
   }
   Assert.assertEquals(true, resource.isOpen());
 }
Пример #25
0
  @Override
  public void initialize(ConfigurableWebApplicationContext applicationContext) {

    Resource resource = null;
    ServletContext servletContext = applicationContext.getServletContext();
    WebApplicationContextUtils.initServletPropertySources(
        applicationContext.getEnvironment().getPropertySources(),
        servletContext,
        applicationContext.getServletConfig());

    ServletConfig servletConfig = applicationContext.getServletConfig();
    String locations =
        servletConfig == null
            ? null
            : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
    resource = getResource(servletContext, applicationContext, locations);

    if (resource == null) {
      servletContext.log(
          "No YAML environment properties from servlet.  Defaulting to servlet context.");
      locations = servletContext.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
      resource = getResource(servletContext, applicationContext, locations);
    }

    try {
      servletContext.log("Loading YAML environment properties from location: " + resource);
      YamlMapFactoryBean factory = new YamlMapFactoryBean();
      factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);

      List<Resource> resources = new ArrayList<Resource>();

      String defaultLocation =
          servletConfig == null
              ? null
              : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_DEFAULT);
      if (defaultLocation != null) {
        Resource defaultResource = new ClassPathResource(defaultLocation);
        if (defaultResource.exists()) {
          resources.add(defaultResource);
        }
      }

      resources.add(resource);
      factory.setResources(resources.toArray(new Resource[resources.size()]));

      Map<String, Object> map = factory.getObject();
      String yamlStr = (new Yaml()).dump(map);
      map.put(rawYamlKey, yamlStr);
      NestedMapPropertySource properties = new NestedMapPropertySource("servletConfigYaml", map);
      applicationContext.getEnvironment().getPropertySources().addLast(properties);
      applySpringProfiles(applicationContext.getEnvironment(), servletContext);
      applyLog4jConfiguration(applicationContext.getEnvironment(), servletContext);

    } catch (Exception e) {
      servletContext.log("Error loading YAML environment properties from location: " + resource, e);
    }
  }
  public Resource findResourceForClassName(String className) {

    if (className.contains(CLOSURE_MARKER)) {
      className = className.substring(0, className.indexOf(CLOSURE_MARKER));
    }
    Resource resource = classNameToResourceCache.get(className);
    if (resource == null) {
      String classNameWithPathSeparator = className.replace(".", FILE_SEPARATOR);
      for (String pathPattern :
          getSearchPatternForExtension(classNameWithPathSeparator, ".groovy", ".java")) {
        resource = resolveExceptionSafe(pathPattern);
        if (resource != null && resource.exists()) {
          classNameToResourceCache.put(className, resource);
          break;
        }
      }
    }
    return resource != null && resource.exists() ? resource : null;
  }
Пример #27
0
  private Resource getLocalTestSitePropertyResouce() {
    ResourceLoader testResourceLoader = new FileSystemResourceLoader();
    Resource testResource =
        testResourceLoader.getResource("classpath:com/enonic/cms/business/test.site.properties");

    if (!testResource.exists()) {
      fail("Could not load test resource: " + testResource);
    }
    return testResource;
  }
  protected Resource findSchemaResource() {

    for (String location : SCHEMA_RESOURCE_LOCATIONS) {
      Resource schemaLocation = new ClassPathResource(location);
      if (schemaLocation.exists()) {
        return schemaLocation;
      }
    }
    return null;
  }
  public static Resource[] getPropertyResources() {
    List<Resource> resources = Lists.newArrayList(getDefaultProperties());

    Resource envResource = getEnvProperties();
    if (envResource.exists()) {
      resources.add(envResource);
    }

    return resources.toArray(new Resource[resources.size()]);
  }
Пример #30
0
 @Override
 public Resource getResource(String location) {
   Resource r = super.getResource(location);
   if (!r.exists() && isNotPrefixed(location)) {
     if (!location.startsWith("/")) {
       location = "/" + location;
     }
     r = new FileSystemResource(new File("./web-app/WEB-INF" + location));
   }
   return r;
 }