コード例 #1
0
 public void writePropertyFile(Resource res, Properties props) {
   FileOutputStream fos = null;
   try {
     fos = new FileOutputStream(res.getFile());
     props.store(fos, "Database Configuration updated");
     jsfService.addMessage(
         "Database Configuration successfully saved to "
             + res.getURL()
             + ". Redeploy the web application for changes to take effect.");
     logger.info("Database properties saved to " + res.getURL());
   } catch (Exception e) {
     warnAndDisplay("Error writing Property file: " + e.getMessage());
     return;
   }
 }
コード例 #2
0
ファイル: IoTests.java プロジェクト: erwink/Gemini-Blueprint
  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());
  }
コード例 #3
0
  /**
   * Retrieves the static resource path for the given Grails resource artifact (controller/taglib
   * etc.)
   *
   * @param resource The Resource
   * @param contextPath The additonal context path to prefix
   * @return The resource path
   */
  public static String getStaticResourcePathForResource(Resource resource, String contextPath) {

    if (contextPath == null) contextPath = "";
    if (resource == null) return contextPath;

    String url;
    try {
      url = resource.getURL().toString();
    } catch (IOException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Error reading URL whilst resolving static resource path from ["
                + resource
                + "]: "
                + e.getMessage(),
            e);
      }
      return contextPath;
    }

    Matcher m = PLUGIN_RESOURCE_PATTERN.matcher(url);
    if (m.find()) {
      return (contextPath.length() > 0 ? contextPath + "/" : "") + m.group(1);
    }

    return contextPath;
  }
コード例 #4
0
  /**
   * Takes a Grails resource (one located inside the grails-app dir) and gets its relative path
   * inside the WEB-INF directory when deployed.
   *
   * @param resource The Grails resource, which is a file inside the grails-app dir
   * @return The relative URL of the file inside the WEB-INF dir at deployment time or null if it
   *     cannot be established
   */
  public static String getRelativeInsideWebInf(Resource resource) {
    if (resource == null) return null;

    try {
      String url = resource.getURL().toString();
      int i = url.indexOf(WEB_INF);
      if (i > -1) {
        return url.substring(i);
      }

      Matcher m = PLUGIN_PATTERN.matcher(url);
      if (m.find()) {
        return WEB_INF + m.group(1);
      }

      i = url.lastIndexOf(GRAILS_APP_DIR);
      if (i > -1) {
        return WEB_INF + "/" + url.substring(i);
      }
    } catch (IOException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Error reading URL whilst resolving relative path within WEB-INF from ["
                + resource
                + "]: "
                + e.getMessage(),
            e);
      }
      return null;
    }
    return null;
  }
コード例 #5
0
  /**
   * Attempts to establish what the last modified date of the given resource is. If the last
   * modified date cannot be etablished -1 is returned
   *
   * @param resource The Resource to evaluate
   * @return The last modified date or -1
   */
  private long establishLastModified(Resource resource) {
    if (resource == null) return -1;
    long lastModified;
    URLConnection urlc = null;

    try {
      urlc = resource.getURL().openConnection();

      urlc.setDoInput(false);
      urlc.setDoOutput(false);

      lastModified = urlc.getLastModified();
    } catch (FileNotFoundException fnfe) {
      lastModified = -1;
    } catch (IOException e) {
      lastModified = -1;
    } finally {
      if (urlc != null) {
        try {
          InputStream is = urlc.getInputStream();
          if (is != null) {
            is.close();
          }
        } catch (IOException e) {
          // ignore
        }
      }
    }

    return lastModified;
  }
コード例 #6
0
 public static boolean isGrailsResource(Resource r) {
   try {
     return isGrailsPath(r.getURL().getFile());
   } catch (IOException e) {
     return false;
   }
 }
コード例 #7
0
  /**
   * 基类基于子类提供的相关参数数据, 生成JXLS报表
   *
   * @see #exportXlsForGrid(List, Sort, GroupPropertyFilter) 此方法中基于参数组装好相关的data数据后,调用此方法生成Excel响应
   * @param dataMap
   */
  protected void exportExcel(
      String templateFileName, String exportFileName, Map<String, Object> dataMap) {
    // 日期格式定义
    dataMap.put("dateFormatter", new SimpleDateFormat(DateUtils.DEFAULT_DATE_FORMAT));
    dataMap.put("timeFormatter", new SimpleDateFormat(DateUtils.DEFAULT_TIME_FORMAT));

    HttpServletResponse response = ServletActionContext.getResponse();
    InputStream fis = null;
    OutputStream fos = null;
    try {
      Resource resource = new ClassPathResource("/template/xls/" + templateFileName);
      logger.debug("Open template file inputstream: {}", resource.getURL());
      fis = resource.getInputStream();

      XLSTransformer transformer = new XLSTransformer();
      // generate the excel workbook according to the template and
      // parameters
      Workbook workbook = transformer.transformXLS(fis, dataMap);
      String filename = exportFileName;
      filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
      response.setHeader("Content-Disposition", "attachment;filename=" + filename);
      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      fos = response.getOutputStream();
      // output the generated excel file
      workbook.write(fos);
    } catch (Exception e) {
      throw new WebException(e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(fis);
      IOUtils.closeQuietly(fos);
    }
  }
コード例 #8
0
  private int executeScriptFile(
      CommandLine commandLine,
      String scriptName,
      String env,
      GantBinding binding,
      Resource scriptFile) {
    // We can now safely set the default environment
    String scriptFileName = getScriptNameFromFile(scriptFile);
    setRunningEnvironment(commandLine, env);
    binding.setVariable("scriptName", scriptFileName);

    // Setup the script to call.
    ScriptBindingInitializer bindingInitializer =
        new ScriptBindingInitializer(commandLine, settings, pluginPathSupport, isInteractive);
    Gant gant = new Gant(bindingInitializer.initBinding(binding, scriptName), classLoader);
    gant.setUseCache(true);
    gant.setCacheDirectory(scriptCacheDir);
    GantResult result = null;
    try {
      gant.loadScript(scriptFile.getURL());
      result = executeWithGantInstance(gant, DO_NOTHING_CLOSURE);
      return result.exitCode;
    } catch (IOException e) {
      console.error("I/O exception loading script [" + e.getMessage() + "]: " + e.getMessage());
      return 1;
    } finally {
      cleanup(result, binding);
    }
  }
コード例 #9
0
ファイル: Configuration.java プロジェクト: bbrower/jetstream
  @Override
  protected Resource getResourceByPath(String path) {
    if (m_configResources != null)
      for (Resource r : m_configResources)
        try {
          URL url = r.getURL();
          if (url != null && path.equals(url.toExternalForm())) return r;
        } catch (IOException e) { // NOPMD
          // Ignore
        }

    try {
      if (path.startsWith("http:") || path.startsWith("https:")) return new UrlResource(path);

      if (path.startsWith("mongo:") || path.startsWith("mongos:"))
        return new MongoDbResource(this, path);

      if (path.startsWith("classpath:")) return new ClassPathResource(path, Configuration.class);

      return new FileSystemResource(path);
    } catch (Throwable t) {
      LOGGER.error("Failed to load " + path + ": " + t);
      throw CommonUtils.runtimeException(t);
    }
  }
コード例 #10
0
 public List<ResourceHandle> members() throws IOException {
   Resource[] resources = this.resourceLoader.getResources(getName());
   List<ResourceHandle> files = new ArrayList<ResourceHandle>();
   for (Resource resource : resources) {
     if (!resource.getURL().getPath().endsWith("/") && !shouldFilter(resource)) {
       files.add(new FileHandle(resource.getFilename(), resource));
     }
   }
   return files;
 }
コード例 #11
0
ファイル: XslFormattersTest.java プロジェクト: dlacy27/main
 private SAXSource createSourceAndSetSystemId(Resource inputStream) {
   try {
     InputSource inputSource = new InputSource(inputStream.getInputStream());
     inputSource.setEncoding(CharEncoding.UTF_8);
     inputSource.setSystemId(inputStream.getURL().toExternalForm());
     return new SAXSource(inputSource);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
コード例 #12
0
 protected final Source getStylesheetSource(final Resource stylesheetLocation) {
   try {
     final URL url = stylesheetLocation.getURL();
     final String urlPath = url.toString();
     final String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1);
     return new StreamSource(url.openStream(), systemId);
   } catch (final IOException ex) {
     throw new ApplicationContextException(
         "Can't load XSLT stylesheet from " + stylesheetLocation, ex);
   }
 }
コード例 #13
0
 /**
  * Sets the image content of the widget based on a resource
  *
  * @param resource points to a image resource
  */
 public void setImage(Resource resource) {
   ImageIcon image = null;
   if (resource != null && resource.exists()) {
     try {
       image = new ImageIcon(resource.getURL());
     } catch (IOException e) {
       logger.warn("Error reading resource: " + resource);
       throw new RuntimeException("Error reading resource " + resource, e);
     }
   }
   setImage(image);
 }
コード例 #14
0
 /**
  * Try to determine the persistence unit root URL based on the given
  * "defaultPersistenceUnitRootLocation".
  *
  * @return the persistence unit root URL to pass to the JPA PersistenceProvider
  * @see #setDefaultPersistenceUnitRootLocation
  */
 private URL determineDefaultPersistenceUnitRootUrl() {
   if (this.defaultPersistenceUnitRootLocation == null) {
     return null;
   }
   try {
     Resource res =
         this.resourcePatternResolver.getResource(this.defaultPersistenceUnitRootLocation);
     return res.getURL();
   } catch (IOException ex) {
     throw new PersistenceException("Unable to resolve persistence unit root URL", ex);
   }
 }
コード例 #15
0
  @Override
  public String getName() {
    String name = super.getName();

    if (name == null) {
      try {
        name = resource.getURL().getPath();
      } catch (IOException e) {
      }
    }

    return name;
  }
コード例 #16
0
 public void displayInfo(Resource r) {
   System.out.println(r.getClass());
   try {
     System.out.println(r.getURL().getContent());
     System.out.println(r.contentLength());
     System.out.println(r.getFilename());
     System.out.println(r.isOpen());
     System.out.println(r.getInputStream().read());
     // System.out.println(r.);
   } catch (IOException e) {
     System.out.println("crazy error!");
   }
 }
コード例 #17
0
 /**
  * Read a properties file, returning the result.
  *
  * @param res Descriptor of the resource's location
  * @return True on success, false if a read error occurred
  */
 public boolean readDatabaseProperties(Resource res, Properties prop) {
   try {
     FileInputStream fis = new FileInputStream(res.getFile());
     if (fis != null) {
       prop.load(fis);
       fis.close();
     }
     logger.debug("Read properties from " + res.getURL());
     return true;
   } catch (IOException e) {
     warnAndDisplay("Error in reading Property file: " + e.getMessage());
     return false;
   }
 }
コード例 #18
0
  private void loadCorePluginsFromResources(Resource[] resources) throws IOException {

    LOG.debug("Attempting to load [" + resources.length + "] core plugins");
    for (int i = 0; i < resources.length; i++) {
      Resource resource = resources[i];
      String url = resource.getURL().toString();
      int packageIndex = url.indexOf("org/codehaus/groovy/griffon");
      url = url.substring(packageIndex, url.length());
      url = url.substring(0, url.length() - 6);
      String className = url.replace('/', '.');

      loadCorePlugin(className);
    }
  }
コード例 #19
0
 public URL getResource(String path) throws MalformedURLException {
   Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
   if (!resource.exists()) {
     return null;
   }
   try {
     return resource.getURL();
   } catch (MalformedURLException ex) {
     throw ex;
   } catch (IOException ex) {
     logger.warn("Couldn't get URL for " + resource, ex);
     return null;
   }
 }
コード例 #20
0
  @Bean(name = "graviteeProperties")
  public static Properties graviteeProperties() throws IOException {
    LOGGER.info("Loading Gravitee configuration.");

    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

    String yamlConfiguration = System.getProperty(GRAVITEE_CONFIGURATION);
    Resource yamlResource = new FileSystemResource(yamlConfiguration);

    LOGGER.info("\tGravitee configuration loaded from {}", yamlResource.getURL().getPath());

    yaml.setResources(yamlResource);
    Properties properties = yaml.getObject();
    LOGGER.info("Loading Gravitee configuration. DONE");

    return properties;
  }
コード例 #21
0
  public static Resource getViewsDir(Resource resource) {
    if (resource == null) return null;

    try {
      Resource appDir = getAppDir(resource);
      return new UrlResource(appDir.getURL().toString() + "/views");
    } catch (IOException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Error reading URL whilst resolving views dir from ["
                + resource
                + "]: "
                + e.getMessage(),
            e);
      }
      return null;
    }
  }
コード例 #22
0
ファイル: Transform.java プロジェクト: pdrummond/olzserver
 private Transform() {
   try {
     ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
     Resource[] resources = resolver.getResources(TEMPLATES_PATH);
     for (Resource resource : resources) {
       templates.put(
           getName(resource),
           transformerFactory.newTemplates(new StreamSource(resource.getURL().openStream())));
     }
   } catch (IOException e) {
     throw new RuntimeException(
         "Failed to discover XSLT resources in '" + TEMPLATES_PATH + "'", e);
   } catch (TransformerConfigurationException e) {
     throw new RuntimeException("Error loading XSLT stylesheets", e);
   }
   if (log.isDebugEnabled()) {
     log.debug("templates=" + new TreeSet<String>(templates.keySet()));
   }
 }
コード例 #23
0
  /**
   * Establishes the name to use for the given resource
   *
   * @param res The Resource to calculate the name for
   * @param pageName The name of the page, can be null, in which case method responsible for
   *     calculation
   * @return The name as a String
   */
  protected String establishPageName(Resource res, String pageName) {
    if (res == null) {
      return generateTemplateName();
    }
    String name;
    try {
      name = pageName != null ? pageName : res.getURL().getPath();
      // As the name take the first / off and then replace all characters that aren't
      // a word character or a digit with an underscore
      if (name.startsWith("/")) name = name.substring(1);
      name = name.replaceAll("[^\\w\\d]", "_");

    } catch (IllegalStateException e) {
      name = generateTemplateName();
    } catch (IOException ioex) {
      name = generateTemplateName();
    }
    return name;
  }
コード例 #24
0
ファイル: ElSqlBundle.java プロジェクト: evpaassen/ElSql
 private static ElSqlBundle parseResource(Resource[] resources, ElSqlConfig config) {
   List<List<String>> files = new ArrayList<List<String>>();
   boolean resourceFound = false;
   for (Resource resource : resources) {
     if (resource.exists()) {
       resourceFound = true;
       URL url;
       try {
         url = resource.getURL();
       } catch (IOException ex) {
         throw new RuntimeException(ex);
       }
       List<String> lines = SqlFragments.loadResource(url);
       files.add(lines);
     }
   }
   if (!resourceFound) {
     throw new IllegalArgumentException("No matching resource was found");
   }
   return new ElSqlBundle(SqlFragments.parse(files, config));
 }
 @Override
 public Collection<ApplicationResource> getResources(String path) {
   Resource[] resources;
   try {
     resources = this.resolver.getResources(path);
   } catch (IOException ex) {
     return Collections.<ApplicationResource>emptyList();
   }
   Collection<ApplicationResource> resourceList = new ArrayList<ApplicationResource>();
   if (!ObjectUtils.isEmpty(resources)) {
     for (Resource resource : resources) {
       URL url;
       try {
         url = resource.getURL();
         resourceList.add(new URLApplicationResource(url.toExternalForm(), url));
       } catch (IOException ex) {
         // shouldn't happen with the kind of resources we're using
         throw new IllegalArgumentException("No URL for " + resource.toString(), ex);
       }
     }
   }
   return resourceList;
 }
コード例 #26
0
  public static Resource getAppDir(Resource resource) {
    if (resource == null) return null;

    try {
      String url = resource.getURL().toString();

      int i = url.lastIndexOf(GRAILS_APP_DIR);
      if (i > -1) {
        url = url.substring(0, i + 10);
        return new UrlResource(url);
      }

      return null;
    } catch (MalformedURLException e) {
      return null;
    } catch (IOException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Error reading URL whilst resolving app dir from [" + resource + "]: " + e.getMessage(),
            e);
      }
      return null;
    }
  }
コード例 #27
0
  @Override
  public void visit(ASTNode[] astNodes, SourceUnit source) {
    if (!(astNodes[0] instanceof AnnotationNode) || !(astNodes[1] instanceof AnnotatedNode)) {
      throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class");
    }

    AnnotatedNode parent = (AnnotatedNode) astNodes[1];
    AnnotationNode node = (AnnotationNode) astNodes[0];
    if (!MY_TYPE.equals(node.getClassNode()) || !(parent instanceof ClassNode)) {
      return;
    }

    ClassNode classNode = (ClassNode) parent;
    if (classNode.isInterface() || Modifier.isAbstract(classNode.getModifiers())) {
      return;
    }

    boolean junit3Test = isJunit3Test(classNode);
    boolean spockTest = isSpockTest(classNode);
    boolean isJunit = classNode.getName().endsWith("Tests");

    if (!junit3Test && !spockTest && !isJunit) return;

    Expression value = node.getMember("value");
    ClassExpression ce;
    if (value instanceof ClassExpression) {
      ce = (ClassExpression) value;
      testFor(classNode, ce);
    } else {
      if (!junit3Test) {
        List<AnnotationNode> annotations = classNode.getAnnotations(MY_TYPE);
        if (annotations.size() > 0)
          return; // bail out, in this case it was already applied as a local transform
        // no explicit class specified try by convention
        String fileName = source.getName();
        String className = GrailsResourceUtils.getClassName(new FileSystemResource(fileName));
        if (className != null) {
          boolean isSpock = className.endsWith("Spec");
          String targetClassName = null;

          if (isJunit) {
            targetClassName = className.substring(0, className.indexOf("Tests"));
          } else if (isSpock) {
            targetClassName = className.substring(0, className.indexOf("Spec"));
          }

          if (targetClassName != null) {
            Resource targetResource =
                getResourceLocator().findResourceForClassName(targetClassName);
            if (targetResource != null) {
              try {
                if (GrailsResourceUtils.isDomainClass(targetResource.getURL())) {
                  testFor(
                      classNode,
                      new ClassExpression(
                          new ClassNode(targetClassName, 0, ClassHelper.OBJECT_TYPE)));
                } else {
                  for (String artefactType : artefactTypeToTestMap.keySet()) {
                    if (targetClassName.endsWith(artefactType)) {
                      testFor(
                          classNode,
                          new ClassExpression(
                              new ClassNode(targetClassName, 0, ClassHelper.OBJECT_TYPE)));
                      break;
                    }
                  }
                }
              } catch (IOException e) {
                // ignore
              }
            }
          }
        }
      }
    }
  }
コード例 #28
0
 @Override
 public URL getURL() throws IOException {
   return delegate.getURL();
 }
コード例 #29
0
  @Override
  @SuppressWarnings("unchecked")
  protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();
    if (dataSource != null) {
      // Make given DataSource available for SessionFactory configuration.
      configTimeDataSourceHolder.set(dataSource);
    }
    if (this.jtaTransactionManager != null) {
      // Make Spring-provided JTA TransactionManager available.
      configTimeTransactionManagerHolder.set(this.jtaTransactionManager);
    }
    if (this.cacheRegionFactory != null) {
      // Make Spring-provided Hibernate RegionFactory available.
      configTimeRegionFactoryHolder.set(this.cacheRegionFactory);
    }
    if (this.lobHandler != null) {
      // Make given LobHandler available for SessionFactory configuration.
      // Do early because because mapping resource might refer to custom types.
      configTimeLobHandlerHolder.set(this.lobHandler);
    }

    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader =
        (this.beanClassLoader != null && !this.beanClassLoader.equals(threadContextClassLoader));
    if (overrideClassLoader) {
      currentThread.setContextClassLoader(this.beanClassLoader);
    }

    try {
      if (isExposeTransactionAwareSessionFactory()) {
        // Set Hibernate 3.1+ CurrentSessionContext implementation,
        // providing the Spring-managed Session as current Session.
        // Can be overridden by a custom value for the corresponding Hibernate property.
        config.setProperty(
            Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
      }

      if (this.jtaTransactionManager != null) {
        // Set Spring-provided JTA TransactionManager as Hibernate property.
        config.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName());
        config.setProperty(
            Environment.TRANSACTION_MANAGER_STRATEGY,
            LocalTransactionManagerLookup.class.getName());
      } else {
        // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.
        // Also sets connection release mode to ON_CLOSE by default.
        config.setProperty(
            Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());
      }

      if (this.entityInterceptor != null) {
        // Set given entity interceptor at SessionFactory level.
        config.setInterceptor(this.entityInterceptor);
      }

      if (this.namingStrategy != null) {
        // Pass given naming strategy to Hibernate Configuration.
        config.setNamingStrategy(this.namingStrategy);
      }

      if (this.typeDefinitions != null) {
        // Register specified Hibernate type definitions.
        Mappings mappings = config.createMappings();
        for (TypeDefinitionBean typeDef : this.typeDefinitions) {
          mappings.addTypeDef(
              typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
        }
      }

      if (this.filterDefinitions != null) {
        // Register specified Hibernate FilterDefinitions.
        for (FilterDefinition filterDef : this.filterDefinitions) {
          config.addFilterDefinition(filterDef);
        }
      }

      if (this.configLocations != null) {
        for (Resource resource : this.configLocations) {
          // Load Hibernate configuration from given location.
          config.configure(resource.getURL());
        }
      }

      if (this.hibernateProperties != null) {
        // Add given Hibernate properties to Configuration.
        config.addProperties(this.hibernateProperties);
      }

      if (dataSource != null) {
        Class<?> providerClass = LocalDataSourceConnectionProvider.class;
        if (isUseTransactionAwareDataSource()
            || dataSource instanceof TransactionAwareDataSourceProxy) {
          providerClass = TransactionAwareDataSourceConnectionProvider.class;
        } else if (config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) {
          providerClass = LocalJtaDataSourceConnectionProvider.class;
        }
        // Set Spring-provided DataSource as Hibernate ConnectionProvider.
        config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
      }

      if (this.cacheRegionFactory != null) {
        // Expose Spring-provided Hibernate RegionFactory.
        config.setProperty(
            Environment.CACHE_REGION_FACTORY, LocalRegionFactoryProxy.class.getName());
      }

      if (this.mappingResources != null) {
        // Register given Hibernate mapping definitions, contained in resource files.
        for (String mapping : this.mappingResources) {
          Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
          config.addInputStream(resource.getInputStream());
        }
      }

      if (this.mappingLocations != null) {
        // Register given Hibernate mapping definitions, contained in resource files.
        for (Resource resource : this.mappingLocations) {
          config.addInputStream(resource.getInputStream());
        }
      }

      if (this.cacheableMappingLocations != null) {
        // Register given cacheable Hibernate mapping definitions, read from the file system.
        for (Resource resource : this.cacheableMappingLocations) {
          config.addCacheableFile(resource.getFile());
        }
      }

      if (this.mappingJarLocations != null) {
        // Register given Hibernate mapping definitions, contained in jar files.
        for (Resource resource : this.mappingJarLocations) {
          config.addJar(resource.getFile());
        }
      }

      if (this.mappingDirectoryLocations != null) {
        // Register all Hibernate mapping definitions in the given directories.
        for (Resource resource : this.mappingDirectoryLocations) {
          File file = resource.getFile();
          if (!file.isDirectory()) {
            throw new IllegalArgumentException(
                "Mapping directory location [" + resource + "] does not denote a directory");
          }
          config.addDirectory(file);
        }
      }

      // Tell Hibernate to eagerly compile the mappings that we registered,
      // for availability of the mapping information in further processing.
      postProcessMappings(config);
      config.buildMappings();

      if (this.entityCacheStrategies != null) {
        // Register cache strategies for mapped entities.
        for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames();
            classNames.hasMoreElements(); ) {
          String className = (String) classNames.nextElement();
          String[] strategyAndRegion =
              StringUtils.commaDelimitedListToStringArray(
                  this.entityCacheStrategies.getProperty(className));
          if (strategyAndRegion.length > 1) {
            config.setCacheConcurrencyStrategy(
                className, strategyAndRegion[0], strategyAndRegion[1]);
          } else if (strategyAndRegion.length > 0) {
            config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
          }
        }
      }

      if (this.collectionCacheStrategies != null) {
        // Register cache strategies for mapped collections.
        for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames();
            collRoles.hasMoreElements(); ) {
          String collRole = (String) collRoles.nextElement();
          String[] strategyAndRegion =
              StringUtils.commaDelimitedListToStringArray(
                  this.collectionCacheStrategies.getProperty(collRole));
          if (strategyAndRegion.length > 1) {
            config.setCollectionCacheConcurrencyStrategy(
                collRole, strategyAndRegion[0], strategyAndRegion[1]);
          } else if (strategyAndRegion.length > 0) {
            config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
          }
        }
      }

      if (this.eventListeners != null) {
        // Register specified Hibernate event listeners.
        for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
          String listenerType = entry.getKey();
          Object listenerObject = entry.getValue();
          if (listenerObject instanceof Collection) {
            Collection<Object> listeners = (Collection<Object>) listenerObject;
            EventListeners listenerRegistry = config.getEventListeners();
            Object[] listenerArray =
                (Object[])
                    Array.newInstance(
                        listenerRegistry.getListenerClassFor(listenerType), listeners.size());
            listenerArray = listeners.toArray(listenerArray);
            config.setListeners(listenerType, listenerArray);
          } else {
            config.setListener(listenerType, listenerObject);
          }
        }
      }

      // Perform custom post-processing in subclasses.
      postProcessConfiguration(config);

      // Build SessionFactory instance.
      logger.info("Building new Hibernate SessionFactory");
      this.configuration = config;
      return newSessionFactory(config);
    } finally {
      if (dataSource != null) {
        configTimeDataSourceHolder.remove();
      }
      if (this.jtaTransactionManager != null) {
        configTimeTransactionManagerHolder.remove();
      }
      if (this.cacheRegionFactory != null) {
        configTimeRegionFactoryHolder.remove();
      }
      if (this.lobHandler != null) {
        configTimeLobHandlerHolder.remove();
      }
      if (overrideClassLoader) {
        // Reset original thread context ClassLoader.
        currentThread.setContextClassLoader(threadContextClassLoader);
      }
    }
  }
コード例 #30
0
  public void test() throws Exception {
    IRSwapTradeParser tradeParser = new IRSwapTradeParser();
    Resource resource =
        ResourceUtils.createResource(
            "classpath:com/opengamma/financial/analytics/test/Trades14Oct.csv");
    List<IRSwapSecurity> trades = tradeParser.parseCSVFile(resource.getURL());
    List<IRSwapSecurity> tradesClean = Lists.newArrayList();
    for (IRSwapSecurity irSwapSecurity : trades) {

      String currency = irSwapSecurity.getRawInput().getString(PAY_CURRENCY);
      if (currency.equals(CURRENCY)) {
        tradesClean.add(irSwapSecurity);
      }
    }
    // Build the curve bundle
    final HashMap<String, Currency> ccyMap = new HashMap<>();
    ccyMap.put(discountingCurvename, ccy);
    ccyMap.put(forward3MCurveName, ccy);
    ccyMap.put(forward6MCurveName, ccy);
    final FXMatrix fx = new FXMatrix(ccy);
    final YieldCurveBundle curvesClean = new YieldCurveBundle(fx, ccyMap);

    IRCurveParser curveParser = new IRCurveParser();
    Resource resourceCurve =
        ResourceUtils.createResource(
            "classpath:com/opengamma/financial/analytics/test/Base_Curves_20131014_Clean.csv");
    List<InterpolatedDoublesCurve> curves = curveParser.parseCSVFile(resourceCurve.getURL());

    for (InterpolatedDoublesCurve interpolatedDoublesCurve : curves) {

      String name = interpolatedDoublesCurve.getName();
      if (name.equals(ON_NAME)) {
        curvesClean.setCurve(discountingCurvename, DiscountCurve.from(interpolatedDoublesCurve));
      }
      if (name.equals(ONE_MONTH_NAME)) {
        curvesClean.setCurve(forward1MCurveName, DiscountCurve.from(interpolatedDoublesCurve));
      }
      if (name.equals(THREE_MONTH_NAME)) {
        curvesClean.setCurve(forward3MCurveName, DiscountCurve.from(interpolatedDoublesCurve));
      }
      if (name.equals(SIX_MONTH_NAME)) {
        curvesClean.setCurve(forward6MCurveName, DiscountCurve.from(interpolatedDoublesCurve));
      }
    }

    // Convert the swap security into a swap definition
    final SwapSecurityConverterDeprecated swapConverter =
        new SwapSecurityConverterDeprecated(
            _holidaySource, _conventionBundleSource, _regionSource, false);
    final FRASecurityConverterDeprecated fraConverter =
        new FRASecurityConverterDeprecated(_holidaySource, _regionSource, _conventionBundleSource);
    final ZeroDepositConverter ZeroCouponConverter =
        new ZeroDepositConverter(_conventionBundleSource, _holidaySource);
    List<SwapDefinition> swapsDefinition = Lists.newArrayList();
    List<ForwardRateAgreementDefinition> frasDefinition = Lists.newArrayList();
    List<DepositZeroDefinition> zcsDefinition = Lists.newArrayList();
    /*for (IRSwapSecurity irSwapSecurity : tradesClean) {
      switch (irSwapSecurity.getRawInput().getString("PRODUCT_TYPE")) {
        case "SWAP":
          swapsDefinition.add((SwapDefinition) swapConverter.visitSwapSecurity(irSwapSecurity.getSwapSecurity()));

          // we don't treat the fra case at the moment
          case "FRA":
            frasDefinition.add((ForwardRateAgreementDefinition) fraConverter.visitSwapSecurity(irSwapSecurity.getSwapSecurity()));
          case "OIS":
            swapsDefinition.add((SwapDefinition) swapConverter.visitSwapSecurity(irSwapSecurity.getSwapSecurity()));

          // we don't treat the fra case at the moment
           case "ZCS":
             zcsDefinition.add((DepositZeroDefinition) ZeroCouponConverter.visitSwapSecurity(irSwapSecurity.getSwapSecurity()));
      }
    }
    */
    // Load the historical time series from a csv file

    /* NonVersionedRedisHistoricalTimeSeriesSource source = new NonVersionedRedisHistoricalTimeSeriesSource(getJedisPool(), getRedisPrefix());
    CMECurveFixingTSLoader loader = new CMECurveFixingTSLoader(source);*/
    /*  loader.loadCurveFixingCSVFile("/vols/ogdev/CME/curve-fixing/sample-cme-curve-fixing.csv");

    HistoricalTimeSeries historicalTimeSeries = source.getHistoricalTimeSeries(UniqueId.of(ExternalSchemes.ISDA.getName(), "CHF-LIBOR-BBA-6M"));
    assertNotNull(historicalTimeSeries);
    LocalDateDoubleTimeSeries timeSeries = historicalTimeSeries.getTimeSeries();
    assertNotNull(timeSeries);
    assertEquals(5996, timeSeries.size());*/

    // convert the definition into a derivative
    /*   List<Swap> swapDerivatives = Lists.newArrayList();
    for (SwapDefinition swapDefinition : swapsDefinition) {
      swapDerivatives.add(swapDefinition.toDerivative(TODAY, data, curvesClean));
    }
    List<Swap> frasDerivatives = Lists.newArrayList();
    for (ForwardRateAgreementDefinition fraDefinition : frasDefinition) {
      frasDerivatives.add(fraDefinition.toDerivative(TODAY, data, curvesClean));
    }
    List<Swap> zcsDerivatives = Lists.newArrayList();
    for (DepositZeroDefinition zcDefinition : zcsDefinition) {
      zcsDerivatives.add(zcDefinition.toDerivative(TODAY, data, curvesClean));
    }*/

    // Check the npv

    s_logger.warn("Got {} trades", trades.size());
  }