/**
   * 批量执行sql文件
   *
   * @param connection jdbc 链接对象
   * @param sqlResourcePaths sql 文件路径
   * @throws java.sql.SQLException
   */
  private void executeScript(Connection connection, String... sqlResourcePaths)
      throws SQLException {

    for (String sqlResourcePath : sqlResourcePaths) {
      Resource resource = resourceLoader.getResource(sqlResourcePath);
      ScriptUtils.executeSqlScript(connection, resource);
    }
    connection.close();
  }
Esempio n. 2
0
  /**
   * Streams content back to client from a given resource path.
   *
   * @param req The request
   * @param res The response
   * @param resourcePath The classpath resource path the content is required for.
   * @param attach Indicates whether the content should be streamed as an attachment or not
   * @param attachFileName Optional file name to use when attach is <code>true</code>
   * @throws IOException
   */
  protected void streamContent(
      WebScriptRequest req,
      WebScriptResponse res,
      String resourcePath,
      boolean attach,
      String attachFileName,
      Map<String, Object> model)
      throws IOException {
    if (logger.isDebugEnabled())
      logger.debug(
          "Retrieving content from resource path " + resourcePath + " (attach: " + attach + ")");

    // get extension of resource
    String ext = "";
    int extIndex = resourcePath.lastIndexOf('.');
    if (extIndex != -1) {
      ext = resourcePath.substring(extIndex);
    }

    // We need to retrieve the modification date/time from the resource itself.
    StringBuilder sb = new StringBuilder("classpath:").append(resourcePath);
    final String classpathResource = sb.toString();

    long resourceLastModified = resourceLoader.getResource(classpathResource).lastModified();

    // create temporary file
    File file = TempFileProvider.createTempFile("streamContent-", ext);

    InputStream is = resourceLoader.getResource(classpathResource).getInputStream();
    OutputStream os = new FileOutputStream(file);
    FileCopyUtils.copy(is, os);

    // stream the contents of the file, but using the modifiedDate of the original resource.
    streamContent(req, res, file, resourceLastModified, attach, attachFileName, model);
  }
Esempio n. 3
0
  private SAMLProperties setupForKeyManager() {
    final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
    this.config.setResourceLoader(resourceLoader);
    final Resource storeFile = Mockito.mock(Resource.class);

    final SAMLProperties properties = Mockito.mock(SAMLProperties.class);
    this.config.setSamlProperties(properties);

    final String keyStorePassword = UUID.randomUUID().toString();
    final String keyStoreName = UUID.randomUUID().toString() + ".jks";
    final String defaultKeyName = UUID.randomUUID().toString();
    final String defaultKeyPassword = UUID.randomUUID().toString();

    final SAMLProperties.Keystore keyStore = Mockito.mock(SAMLProperties.Keystore.class);
    final SAMLProperties.Keystore.DefaultKey defaultKey =
        Mockito.mock(SAMLProperties.Keystore.DefaultKey.class);
    Mockito.when(properties.getKeystore()).thenReturn(keyStore);
    Mockito.when(keyStore.getName()).thenReturn(keyStoreName);
    Mockito.when(keyStore.getPassword()).thenReturn(keyStorePassword);
    Mockito.when(keyStore.getDefaultKey()).thenReturn(defaultKey);
    Mockito.when(defaultKey.getName()).thenReturn(defaultKeyName);
    Mockito.when(defaultKey.getPassword()).thenReturn(defaultKeyPassword);
    Mockito.when(resourceLoader.getResource(Mockito.eq("classpath:" + keyStoreName)))
        .thenReturn(storeFile);

    return properties;
  }
  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;
  }
 /**
  * Finds an X509Cetificate using a resoureName and populates it on the request.
  *
  * @param resourceName the name of the X509Certificate resource
  * @return the {@link org.springframework.test.web.servlet.request.RequestPostProcessor} to use.
  * @throws IOException
  * @throws CertificateException
  */
 public static RequestPostProcessor x509(String resourceName)
     throws IOException, CertificateException {
   ResourceLoader loader = new DefaultResourceLoader();
   Resource resource = loader.getResource(resourceName);
   InputStream inputStream = resource.getInputStream();
   CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
   X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(inputStream);
   return x509(certificate);
 }
  public Resource findResourceForURI(String uri) {
    Resource resource = uriToResourceCache.get(uri);
    if (resource == null) {

      PluginResourceInfo info = inferPluginNameFromURI(uri);
      if (warDeployed) {
        Resource defaultResource = defaultResourceLoader.getResource(uri);
        if (defaultResource != null && defaultResource.exists()) {
          resource = defaultResource;
        }
      } else {
        String uriWebAppRelative = WEB_APP_DIR + uri;

        for (String resourceSearchDirectory : resourceSearchDirectories) {
          Resource res = resolveExceptionSafe(resourceSearchDirectory + uriWebAppRelative);
          if (res.exists()) {
            resource = res;
          } else if (!warDeployed) {
            Resource dir = resolveExceptionSafe(resourceSearchDirectory);
            if (dir.exists() && info != null) {
              try {
                String filename = dir.getFilename();
                if (filename != null && filename.equals(info.pluginName)) {
                  Resource pluginFile = dir.createRelative(WEB_APP_DIR + info.uri);
                  if (pluginFile.exists()) {
                    resource = pluginFile;
                  }
                }
              } catch (IOException e) {
                // ignore
              }
            }
          }
        }
      }

      if (resource == null && info != null) {
        resource = findResourceInBinaryPlugins(info);
      }

      if (resource == null || !resource.exists()) {
        Resource tmp =
            defaultResourceLoader != null ? defaultResourceLoader.getResource(uri) : null;
        if (tmp != null && tmp.exists()) {
          resource = tmp;
        }
      }

      if (resource != null) {
        uriToResourceCache.put(uri, resource);
      } else if (warDeployed) {
        uriToResourceCache.put(uri, NULL_RESOURCE);
      }
    }
    return resource == NULL_RESOURCE ? null : resource;
  }
Esempio n. 7
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;
  }
 private Resource getResourceWithinContext(String uri) {
   if (resourceLoader == null)
     throw new IllegalStateException(
         "TemplateEngine not initialised correctly, no [resourceLoader] specified!");
   if (Environment.getCurrent().isReloadEnabled() && Metadata.getCurrent().isWarDeployed()) {
     return resourceLoader.getResource(uri);
   }
   Resource r = servletContextLoader.getResource(uri);
   if (r.exists()) return r;
   return resourceLoader.getResource(uri);
 }
  public static Resource getConfigFile(String fileName) {
    ResourceLoader loader = new DefaultResourceLoader();

    return loader.getResource(
        "file:"
            + InitConfigPath.getParamsRoot()
            + File.separator
            + "files"
            + File.separator
            + fileName);
  }
Esempio n. 10
0
 public void testResourceLoad() {
   ResourceLoader loader = new DefaultResourceLoader();
   Resource resource =
       loader.getResource("classpath:com/iss/expense/demo/chapter4/test1.properties");
   // 验证返回的是ClassPathResource
   Assert.assertEquals(ClassPathResource.class, resource.getClass());
   Resource resource2 = loader.getResource("file:com/iss/expense/demo/chapter4/test1.properties");
   // 验证返回的是ClassPathResource
   Assert.assertEquals(UrlResource.class, resource2.getClass());
   Resource resource3 = loader.getResource("com/iss/expense/demo/chapter4/test1.properties");
   // 验证返默认可以加载ClasspathResource
   Assert.assertTrue(resource3 instanceof ClassPathResource);
 }
Esempio n. 11
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;
    }
  }
Esempio n. 12
0
 @Bean(name = "appConfig")
 public AppConfiguration appConfiguration() throws IOException {
   AppXMLLoader xmlLoader = new AppXMLLoader();
   File appSetup1 = resourceLoader.getResource("WEB-INF/conf/appConfiguration.xml").getFile();
   xmlLoader.loadAppProperties(appSetup1);
   return xmlLoader.getAppConfiguration();
 }
Esempio n. 13
0
 // 利用BeanUtils注值
 // 利用resourceLoader加载文件
 @Override
 public void afterPropertiesSet() throws Exception {
   dataSource = new ComboPooledDataSource();
   Properties p = new Properties();
   p.load(resourceLoader.getResource(configFileName).getInputStream());
   BeanUtils.populate(dataSource, p);
 }
Esempio n. 14
0
  private void mockAndLoadTestProperties() {
    try {
      Resource homeResource = new UrlResource("http:mockURL");
      expect(homeService.getHomeDir()).andReturn(homeResource);
    } catch (Exception e) {
      e.printStackTrace();
      fail("Could not mock homeService.getHomeDir");
    }
    replay(homeService);

    expect(resourceLoader.getResource(isA(String.class)))
        .andReturn(getLocalTestDefaultPropertyResouce());
    expect(resourceLoader.getResource(isA(String.class)))
        .andReturn(getLocalTestSitePropertyResouce());
    replay(resourceLoader);
  }
  public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
    try {
      // setPROPERTIES_DIR();
      webapp = getWebAppName(resourceLoader.getResource("/").getURI().getPath());
      logMe("is web app name null?" + webapp);

      String dbName = dataInfo.getProperty("dbType");

      DATAINFO = dataInfo;
      dataInfo =
          setDataInfoProperties(); // weird, but there are references to dataInfo...MainMenuServlet
                                   // for instance
      // setDataInfoPath();
      EXTRACTINFO = extractInfo;

      DB_NAME = dbName;
      SQLFactory factory = SQLFactory.getInstance();
      factory.run(dbName, resourceLoader);
      copyBaseToDest(resourceLoader);
      extractProperties = findExtractProperties();
      // tbh, following line to be removed
      // reportUrl();

    } catch (OpenClinicaSystemException e) {
      logger.debug(e.getMessage());
      logger.debug(e.toString());
      throw new OpenClinicaSystemException(e.getMessage(), e.fillInStackTrace());
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 /**
  * Create a new LocalSessionFactoryBuilder for the given DataSource.
  *
  * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be
  *     using
  * @param classLoader the ResourceLoader to load application classes from
  */
 public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
   getProperties()
       .put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
   getProperties().put(Environment.DATASOURCE, dataSource);
   getProperties().put("hibernate.classLoader.application", resourceLoader.getClassLoader());
   this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
 }
  /**
   * Attempts to resolve a view relative to a controller.
   *
   * @param controller The controller to resolve the view relative to
   * @param application The GrailsApplication instance
   * @param viewName The views name
   * @param loader The ResourceLoader to use
   * @return The URI of the view
   */
  protected String resolveViewForController(
      GroovyObject controller,
      GrailsApplication application,
      String viewName,
      ResourceLoader loader) {

    String
        gspView; // try to resolve the view relative to the controller first, this allows us to
                 // support views provided by plugins
    if (controller != null && application != null) {
      String pathToView =
          pluginManager != null ? pluginManager.getPluginViewsPathForInstance(controller) : null;
      if (pathToView != null) {
        gspView = GrailsResourceUtils.WEB_INF + pathToView + viewName + GSP_SUFFIX;
      } else {
        gspView = localPrefix + viewName + GSP_SUFFIX;
      }
    } else {
      gspView = localPrefix + viewName + GSP_SUFFIX;
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Attempting to resolve view for URI ["
              + gspView
              + "] using ResourceLoader ["
              + loader.getClass().getName()
              + "]");
    }
    return gspView;
  }
Esempio n. 18
0
 protected void onSetUp() throws Exception {
   // load file using absolute path
   defaultLoader = new DefaultResourceLoader();
   thisClass = defaultLoader.getResource(getClass().getName().replace('.', '/').concat(".class"));
   bundle = bundleContext.getBundle();
   loader = new OsgiBundleResourceLoader(bundle);
   patternLoader = new OsgiBundleResourcePatternResolver(loader);
 }
 private void loadProperties(String file) {
   InputStream in = null;
   try {
     ResourceLoader loader = new DefaultResourceLoader();
     Resource res = loader.getResource(file);
     in = res.getInputStream();
     this.load(in);
   } catch (Exception e) {
     throw new RuntimeException("Resource " + file + " not found");
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ignore) {
       }
     }
   }
 }
  /**
   * Create HazelcastInstance bean.
   *
   * @param hazelcastConfigLocation String representation of hazelcast xml config.
   * @param resourceLoader resource loader for loading hazelcast xml configuration resource.
   * @return HazelcastInstance bean.
   * @throws IOException if parsing of hazelcast xml configuration fails
   */
  @Bean
  public HazelcastInstance hazelcast(
      @Value("${hz.config.location:NO_CONFIG_PROVIDED}") final String hazelcastConfigLocation,
      final ResourceLoader resourceLoader)
      throws IOException {

    final Config hzConfig = getConfig(resourceLoader.getResource(hazelcastConfigLocation));
    return Hazelcast.newHazelcastInstance(hzConfig);
  }
 /**
  * configures logging using custom properties file if specified, or the default one. Log4j also
  * uses any file called log4.properties in the classpath
  *
  * <p>To configure a custom logging file, set a JVM system property on using -D. For example
  * -Dalt.log4j.config.location=file:/home/me/kuali/test/dev/log4j.properties
  *
  * <p>The above option can also be set in the run configuration for the unit test in the IDE. To
  * avoid log4j using files called log4j.properties that are defined in the classpath, add the
  * following system property: -Dlog4j.defaultInitOverride=true
  *
  * @throws IOException
  */
 protected void configureLogging() throws IOException {
   ResourceLoader resourceLoader = new FileSystemResourceLoader();
   String altLog4jConfigLocation = System.getProperty(ALT_LOG4J_CONFIG_LOCATION_PROP);
   Resource log4jConfigResource = null;
   if (!StringUtils.isEmpty(altLog4jConfigLocation)) {
     log4jConfigResource = resourceLoader.getResource(altLog4jConfigLocation);
   }
   if (log4jConfigResource == null || !log4jConfigResource.exists()) {
     System.out.println(
         "Alternate Log4j config resource does not exist! " + altLog4jConfigLocation);
     System.out.println("Using default log4j configuration: " + DEFAULT_LOG4J_CONFIG);
     log4jConfigResource = resourceLoader.getResource(DEFAULT_LOG4J_CONFIG);
   } else {
     System.out.println("Using alternate log4j configuration at: " + altLog4jConfigLocation);
   }
   Properties p = new Properties();
   p.load(log4jConfigResource.getInputStream());
   PropertyConfigurator.configure(p);
 }
 private void loadSchema() {
   SchemaFactory schemaFactory =
       SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
   try {
     schemaFactory.setResourceResolver(new ClasspathResourceResolver());
     Resource schemaResource = resourceLoader.getResource(schemaPath);
     messageSchema = schemaFactory.newSchema(schemaResource.getFile());
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 /**
  * Create a new LocalSessionFactoryBuilder for the given DataSource.
  *
  * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be
  *     using (may be {@code null})
  * @param resourceLoader the ResourceLoader to load application classes from
  */
 @SuppressWarnings("deprecation") // to be able to build against Hibernate 4.3
 public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
   getProperties()
       .put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
   if (dataSource != null) {
     getProperties().put(Environment.DATASOURCE, dataSource);
   }
   // APP_CLASSLOADER is deprecated as of Hibernate 4.3 but we need to remain compatible with 4.0+
   getProperties().put(AvailableSettings.APP_CLASSLOADER, resourceLoader.getClassLoader());
   this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
 }
  @Test
  @Ignore
  public void test1() throws IOException {

    Resource resource = resourceLoader.getResource("/CounterPush.json");

    String data = IOUtils.toString(resource.getInputStream());

    RiskFact fact = Utils.JSON.parseObject(data, RiskFact.class);

    service.executeCounterPushRules(fact, false);
  }
  protected String getTemplateText(String template, String folder) throws IOException {
    InputStream inputStream = null;
    if (resourceLoader != null && grailsApplication.isWarDeployed()) {
      inputStream = resourceLoader.getResource(folder + template).getInputStream();
    } else {
      AbstractResource templateFile = getTemplateResource(template);
      if (templateFile.exists()) {
        inputStream = templateFile.getInputStream();
      }
    }

    return inputStream == null ? null : IOGroovyMethods.getText(inputStream);
  }
 @Override
 public Reader getReader(final String resourceName) throws LoaderException {
   final String fullyQualifiedResourceName = getFullyQualifiedResourceName(resourceName);
   final Resource resource = resourceLoader.getResource(fullyQualifiedResourceName);
   if (resource.exists()) {
     try {
       return new InputStreamReader(resource.getInputStream(), charset);
     } catch (IOException e) {
       throw new LoaderException(e, "Failed to load template: " + fullyQualifiedResourceName);
     }
   }
   throw new LoaderException(null, "No template exists named: " + fullyQualifiedResourceName);
 }
Esempio n. 27
0
  public void showBanner() throws IOException {
    Resource banner = bannerloader.getResource("file:resources/banner.txt");
    InputStream in = banner.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    while (true) {
      String line = reader.readLine();
      if (line == null) break;
      System.out.println(line);
    }
    reader.close();
    num = 100;
  }
Esempio n. 28
0
  protected Properties getProperties() {

    String bootstrapLocationsResource = getResourceName();

    ResourceLoader resourceLoader = getResourceLoader();
    Resource bootStrapResource = null;

    if (bootstrapLocationsResource == null) {
      bootStrapResource = resourceLoader.getResource(defaultBootstrapResource);
    } else {
      // figure out which resource loader to use
      bootStrapResource = resourceLoader.getResource(bootstrapLocationsResource);
    }
    Properties properties = null;
    if (bootStrapResource == null || !bootStrapResource.exists()) {
      logger.info("Unable to load locations resource from " + bootstrapLocationsResource + ".");
      properties = new Properties();
    } else {
      properties = PropertyUtils.loadProperties(bootStrapResource);
    }

    return properties;
  }
 public void setPROPERTIES_DIR() {
   String resource = "classpath:properties/placeholder.properties";
   // System.out.println("Resource " + resource);
   Resource scr = resourceLoader.getResource(resource);
   String absolutePath = null;
   try {
     // System.out.println("Resource" + resource);
     absolutePath = scr.getFile().getAbsolutePath();
     // System.out.println("Resource" + ((ClassPathResource) scr).getPath());
     // System.out.println("Resource" + resource);
     PROPERTIES_DIR = absolutePath.replaceAll("placeholder.properties", "");
     // System.out.println("Resource " + PROPERTIES_DIR);
   } catch (IOException e) {
     throw new OpenClinicaSystemException(e.getMessage(), e.fillInStackTrace());
   }
 }
Esempio n. 30
0
 public String readResource(String absolutePathToFile, ResourceLoader resourceLoader)
     throws IOException {
   // This line will be changed for all versions of other examples :
   // "file:c:/temp/filesystemdata.txt"
   Resource banner = resourceLoader.getResource("file:" + absolutePathToFile);
   InputStream in = banner.getInputStream();
   BufferedReader reader = new BufferedReader(new InputStreamReader(in));
   StringBuilder sb = new StringBuilder();
   while (true) {
     String line = reader.readLine();
     if (line == null) break;
     sb.append(line).append(System.getProperty("line.separator"));
   }
   reader.close();
   return sb.toString();
 }