/**
   * Scans the configured base package for files matching the configured mapping file name pattern.
   * Will simply return an empty {@link Set} in case no {@link ResourceLoader} or mapping file name
   * pattern was configured. Resulting paths are resource-loadable from the application classpath
   * according to the JPA spec.
   *
   * @see javax.persistence.spi.PersistenceUnitInfo.PersistenceUnitInfo#getMappingFileNames()
   * @return
   */
  private Set<String> scanForMappingFileLocations() {

    if (resolver == null || !StringUtils.hasText(mappingFileNamePattern)) {
      return Collections.emptySet();
    }

    /*
     * Note that we cannot use File.pathSeparator here since resourcePath uses a forward slash path ('/') separator
     * being an URI, while basePackagePathComponent has system dependent separator (on windows it's the backslash separator).
     *
     * @see DATAJPA-407
     */
    char slash = '/';
    String basePackagePathComponent = basePackage.replace('.', slash);
    String path =
        ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + basePackagePathComponent
            + slash
            + mappingFileNamePattern;
    Set<String> mappingFileUris = new HashSet<String>();
    Resource[] scannedResources = new Resource[0];

    try {
      scannedResources = resolver.getResources(path);
    } catch (IOException e) {
      throw new IllegalStateException(
          String.format("Cannot load mapping files from path %s!", path), e);
    }

    for (Resource resource : scannedResources) {
      try {
        String resourcePath = getResourcePath(resource.getURI());
        String resourcePathInClasspath =
            resourcePath.substring(resourcePath.indexOf(basePackagePathComponent));
        mappingFileUris.add(resourcePathInClasspath);
      } catch (IOException e) {
        throw new IllegalStateException(
            String.format("Couldn't get URI for %s!", resource.toString()), e);
      }
    }

    return mappingFileUris;
  }
コード例 #2
0
  @RequestMapping(value = "/uploadedPicture")
  public void getUploadedPicture(HttpServletResponse response) throws IOException {
    // ClassPathResource classPathResource = new
    // ClassPathResource("/images/anonymous.jpg");
    // response.setHeader("Content-Type",
    // URLConnection.guessContentTypeFromName(classPathResource.getFilename()));
    // IOUtils.copy(classPathResource.getInputStream(),
    // response.getOutputStream());

    // response.setHeader("Content-Type",
    // URLConnection.guessContentTypeFromName(anonymousPicture.getFilename()));
    // IOUtils.copy(anonymousPicture.getInputStream(),
    // response.getOutputStream());
    Resource picturePath = userProfileSession.getPicturePath();
    if (picturePath == null) {
      picturePath = anonymousPicture;
    }
    response.setHeader(
        "Content-Type", URLConnection.guessContentTypeFromName(picturePath.toString()));
    IOUtils.copy(picturePath.getInputStream(), response.getOutputStream());
  }
 @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;
 }
  /**
   * Scans the configured base package for files matching the configured mapping file name pattern.
   * Will simply return an empty {@link Set} in case no {@link ResourceLoader} or mapping file name
   * pattern was configured. Resulting paths are resource-loadable from the application classpath
   * according to the JPA spec.
   *
   * @see javax.persistence.spi.PersistenceUnitInfo.PersistenceUnitInfo#getMappingFileNames()
   * @return
   */
  private Set<String> scanForMappingFileLocations() {

    if (resolver == null || !StringUtils.hasText(mappingFileNamePattern)) {
      return Collections.emptySet();
    }

    String basePackagePathComponent = basePackage.replace('.', File.separatorChar);
    String path =
        ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + basePackagePathComponent
            + File.separator
            + mappingFileNamePattern;
    Set<String> mappingFileUris = new HashSet<String>();
    Resource[] scannedResources = new Resource[0];

    try {
      scannedResources = resolver.getResources(path);
    } catch (IOException e) {
      throw new IllegalStateException(
          String.format("Cannot load mapping files from path %s!", path), e);
    }

    for (Resource resource : scannedResources) {
      try {
        String resourcePath = resource.getURI().getPath();
        String resourcePathInClasspath =
            resourcePath.substring(resourcePath.indexOf(basePackagePathComponent));
        mappingFileUris.add(resourcePathInClasspath);
      } catch (IOException e) {
        throw new IllegalStateException(
            String.format("Couldn't get URI for %s!", resource.toString()), e);
      }
    }

    return mappingFileUris;
  }
コード例 #5
0
 @Override
 public String toString() {
   return delegate.toString();
 }
コード例 #6
0
ファイル: License.java プロジェクト: schakko/zabos
  /**
   * License-File einlesen und dekodieren
   *
   * @param _licensePath
   * @return
   */
  public boolean readLicense(Resource _licensePath) {
    try {
      if (!_licensePath.exists()) {
        throw new Exception("Lizenz-Datei [" + _licensePath.toString() + "]  nicht gefunden");
      }

      File f = _licensePath.getFile();

      FileInputStream ifs = new FileInputStream(f);

      byte[] senc = new byte[512];
      if (f.length() != 512) {
        // Filegroesse stimmt nicht
        return false;
      }
      int i;
      for (i = 0; i < 512; i++) {
        senc[i] = (byte) ((ifs.read() ^ xor_key[i]) & 0xFF);
      }
      // Bits extrahieren
      byte[] uenc = new byte[64];
      int off = 0;
      for (i = 0; i < 64; i++) {
        uenc[i] =
            (byte)
                (((senc[off + 0] & 0x01))
                    | (((senc[off + 1]) & 0x02))
                    | (((senc[off + 2]) & 0x04))
                    | (((senc[off + 3]) & 0x08))
                    | (((senc[off + 4]) & 0x10))
                    | (((senc[off + 5]) & 0x20))
                    | (((senc[off + 6]) & 0x40))
                    | (((senc[off + 7]) & 0x80)));
        off += 8;
      }
      // Felder extrahieren
      long t;
      long aus;
      aus = (uenc[OFF_AUSSTELLUNGSDATUM + 0] & 0xFF);
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 1] & 0xFF);
      aus |= t << 8;
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 2] & 0xFF);
      aus |= t << 16;
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 3] & 0xFF);
      aus |= t << 24;
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 4] & 0xFF);
      aus |= t << 32;
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 5] & 0xFF);
      aus |= t << 40;
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 6] & 0xFF);
      aus |= t << 48;
      t = (uenc[OFF_AUSSTELLUNGSDATUM + 7] & 0xFF);
      aus |= t << 56;
      ausstellungsdatum = new UnixTime(aus);

      long ab;
      ab = (uenc[OFF_ABLAUFDATUM + 0] & 0xFF);
      t = (uenc[OFF_ABLAUFDATUM + 1] & 0xFF);
      ab |= t << 8;

      t = (uenc[OFF_ABLAUFDATUM + 2] & 0xFF);
      ab |= t << 16;
      t = (uenc[OFF_ABLAUFDATUM + 3] & 0xFF);
      ab |= t << 24;
      t = (uenc[OFF_ABLAUFDATUM + 4] & 0xFF);
      ab |= t << 32;
      t = (uenc[OFF_ABLAUFDATUM + 5] & 0xFF);
      ab |= t << 40;
      t = (uenc[OFF_ABLAUFDATUM + 6] & 0xFF);
      ab |= t << 48;
      t = (uenc[OFF_ABLAUFDATUM + 7] & 0xFF);
      ab |= t << 56;
      ablaufdatum = new UnixTime(ab);

      kundennummer =
          (uenc[OFF_KUNDENNUMMER + 0] & 0xFF)
              | ((uenc[OFF_KUNDENNUMMER + 1] & 0xFF) << 8)
              | ((uenc[OFF_KUNDENNUMMER + 2] & 0xFF) << 16)
              | ((uenc[OFF_KUNDENNUMMER + 3] & 0xFF) << 24);
      majorVersion = uenc[OFF_MAJOR_VERSION];
      minorVersion = uenc[OFF_MINOR_VERSION];
      schleifen =
          (short) ((uenc[OFF_SCHLEIFEN + 0] & 0xFF) | ((uenc[OFF_SCHLEIFEN + 1] & 0xFF) << 8));
      personen = (short) ((uenc[OFF_PERSONEN + 0] & 0xFF) | ((uenc[OFF_PERSONEN + 1] & 0xFF) << 8));
      off = OFF_USER;
      i = 0;
      StringBuffer sb = new StringBuffer();
      while ((i++ < 18) && (uenc[off] != 0)) {
        sb.append((char) (uenc[off++] & 0xFF));
      }
      user = sb.toString();

      off = OFF_PASSWD;
      i = 0;
      sb = new StringBuffer();
      while ((i++ < 18) && (uenc[off] != 0)) {
        sb.append((char) (uenc[off++] & 0xFF));
      }
      passwd = sb.toString();

      // Debug
      System.err.println("====================================");
      System.err.println(" ZABOS LIZENZ INFORMATIONEN:");
      System.err.println("====================================");
      System.err.println("Ausstellungsdatum: " + ausstellungsdatum);
      System.err.println("Ablaufdatum: " + ablaufdatum);
      System.err.println("Kundennummer: " + kundennummer);
      System.err.println("Version: " + majorVersion + "." + minorVersion);
      System.err.println("Schleifen: " + schleifen);
      System.err.println("Personen: " + personen);
      System.err.println("Gateway-User: "******"Gateway-Passwd: xxx");
      return true;

    } catch (Exception e) {
      System.err.println(
          "Die Lizenz-Datei "
              + _licensePath
              + " konnte nicht geoeffnet werden (cwd=\""
              + System.getProperty("user.dir")
              + "\")");
      e.printStackTrace();
    }

    return false;
  }
  /**
   * Build a {@code SqlSessionFactory} instance.
   *
   * <p>The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
   * {@code SqlSessionFactory} instance based on an Reader.
   *
   * @return SqlSessionFactory
   * @throws IOException if loading the config file failed
   */
  protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configLocation != null) {
      xmlConfigBuilder =
          new XMLConfigBuilder(
              this.configLocation.getInputStream(), null, this.configurationProperties);
      configuration = xmlConfigBuilder.getConfiguration();
    } else {
      if (this.logger.isDebugEnabled()) {
        this.logger.debug(
            "Property 'configLocation' not specified, using default MyBatis Configuration");
      }
      configuration = new Configuration();
      configuration.setVariables(this.configurationProperties);
    }

    if (this.objectFactory != null) {
      configuration.setObjectFactory(this.objectFactory);
    }

    if (this.objectWrapperFactory != null) {
      configuration.setObjectWrapperFactory(this.objectWrapperFactory);
    }

    if (hasLength(this.typeAliasesPackage)) {
      String[] typeAliasPackageArray =
          tokenizeToStringArray(
              this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
      for (String packageToScan : typeAliasPackageArray) {
        configuration
            .getTypeAliasRegistry()
            .registerAliases(
                packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Scanned package: '" + packageToScan + "' for aliases");
        }
      }
    }

    if (!isEmpty(this.typeAliases)) {
      for (Class<?> typeAlias : this.typeAliases) {
        configuration.getTypeAliasRegistry().registerAlias(typeAlias);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Registered type alias: '" + typeAlias + "'");
        }
      }
    }

    if (!isEmpty(this.plugins)) {
      for (Interceptor plugin : this.plugins) {
        configuration.addInterceptor(plugin);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Registered plugin: '" + plugin + "'");
        }
      }
    }

    if (hasLength(this.typeHandlersPackage)) {
      String[] typeHandlersPackageArray =
          tokenizeToStringArray(
              this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
      for (String packageToScan : typeHandlersPackageArray) {
        configuration.getTypeHandlerRegistry().register(packageToScan);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
        }
      }
    }

    if (!isEmpty(this.typeHandlers)) {
      for (TypeHandler<?> typeHandler : this.typeHandlers) {
        configuration.getTypeHandlerRegistry().register(typeHandler);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Registered type handler: '" + typeHandler + "'");
        }
      }
    }

    if (xmlConfigBuilder != null) {
      try {
        xmlConfigBuilder.parse();

        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Parsed configuration file: '" + this.configLocation + "'");
        }
      } catch (Exception ex) {
        throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
      } finally {
        ErrorContext.instance().reset();
      }
    }

    if (this.transactionFactory == null) {
      this.transactionFactory = new SpringManagedTransactionFactory();
    }

    Environment environment =
        new Environment(this.environment, this.transactionFactory, this.dataSource);
    configuration.setEnvironment(environment);

    if (this.databaseIdProvider != null) {
      try {
        configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
      } catch (SQLException e) {
        throw new NestedIOException("Failed getting a databaseId", e);
      }
    }

    ArrayList<Resource> listado_resources = new ArrayList<Resource>();

    if (!isEmpty(this.mapperLocations1)) {
      for (Resource resource : this.mapperLocations1) {
        listado_resources.add(resource);
      }
    }

    if (!isEmpty(this.mapperLocations2)) {
      for (Resource resource : this.mapperLocations2) {
        listado_resources.add(resource);
      }
    }

    if (!isEmpty(this.mapperLocations3)) {
      for (Resource resource : this.mapperLocations3) {
        listado_resources.add(resource);
      }
    }

    if (!isEmpty(this.mapperLocations4)) {
      for (Resource resource : this.mapperLocations4) {
        listado_resources.add(resource);
      }
    }

    this.mapperLocations = new Resource[listado_resources.size()];
    int index = 0;
    for (Resource resource : listado_resources) {
      this.mapperLocations[index] = resource;
      index++;
    }

    if (!isEmpty(this.mapperLocations)) {
      for (Resource mapperLocation : this.mapperLocations) {
        if (mapperLocation == null) {
          continue;
        }

        //				//log.info("Mapa cargado: " + mapperLocation);

        try {
          XMLMapperBuilder xmlMapperBuilder =
              new XMLMapperBuilder(
                  mapperLocation.getInputStream(),
                  configuration,
                  mapperLocation.toString(),
                  configuration.getSqlFragments());
          xmlMapperBuilder.parse();
        } catch (Exception e) {
          throw new NestedIOException(
              "Failed to parse mapping resource: '" + mapperLocation + "'", e);
        } finally {
          ErrorContext.instance().reset();
        }

        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Parsed mapper file: '" + mapperLocation + "'");
        }
      }
    } else {
      if (this.logger.isDebugEnabled()) {
        this.logger.debug(
            "Property 'mapperLocations' was not specified or no matching resources found");
      }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
  }
コード例 #8
0
 @Override
 public String toString() {
   return resource.toString();
 }
  private void readPersistenceXml() {

    ErrorHandler handler = new SimpleSaxErrorHandler(logger);
    List infos = new LinkedList();
    String resourceLocation = null;
    try {

      Resource resource = new ClassPathResource("META-INF/persistence.xml");

      resourceLocation = resource.toString();
      InputStream stream = resource.getInputStream();
      try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);

        // Set schema location only if we found one inside the classpath.
        Resource schemaLocation = findSchemaResource();
        if (schemaLocation != null) {
          if (logger.isDebugEnabled()) {
            logger.debug("Found schema resource: " + schemaLocation.getURL());
          }
          dbf.setValidating(true);
          dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
          dbf.setAttribute(JAXP_SCHEMA_SOURCE, schemaLocation.getURL().toString());
        } else {
          logger.debug(
              "Schema resource ["
                  + SCHEMA_NAME
                  + "] not found - falling back to XML parsing without schema validation");
        }

        DocumentBuilder parser = dbf.newDocumentBuilder();
        parser.setErrorHandler(handler);
        Document document = parser.parse(stream);
        org.w3c.dom.Element persistence = document.getDocumentElement();

        List<org.w3c.dom.Element> units =
            DomUtils.getChildElementsByTagName(persistence, PERSISTENCE_UNIT);
        for (org.w3c.dom.Element unit : units) {
          NodeList childNodes = unit.getChildNodes();
          for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeName().equals("properties")) {
              NodeList propertyNodes = childNode.getChildNodes();
              for (int j = 0; j < propertyNodes.getLength(); j++) {
                NamedNodeMap attributes = propertyNodes.item(j).getAttributes();
                if (attributes != null && attributes.getLength() > 0) {
                  if (attributes
                      .getNamedItem("name")
                      .getNodeValue()
                      .equals("hibernate.connection.username")) {
                    USERNAME = attributes.getNamedItem("value").getNodeValue();
                  }
                  if (attributes
                      .getNamedItem("name")
                      .getNodeValue()
                      .equals("hibernate.connection.password")) {
                    PASSWORD = attributes.getNamedItem("value").getNodeValue();
                  }
                  if (attributes
                      .getNamedItem("name")
                      .getNodeValue()
                      .equals("hibernate.connection.url")) {
                    URL = attributes.getNamedItem("value").getNodeValue();
                  }
                }
              }
              break;
            }
          }
        }
      } finally {
        stream.close();
      }

    } catch (IOException ex) {
      throw new IllegalArgumentException(
          "Cannot parse persistence unit from " + resourceLocation, ex);
    } catch (SAXException ex) {
      throw new IllegalArgumentException(
          "Invalid XML in persistence unit from " + resourceLocation, ex);
    } catch (ParserConfigurationException ex) {
      throw new IllegalArgumentException(
          "Internal error parsing persistence unit from " + resourceLocation);
    }

    // return infos.toArray(new SpringPersistenceUnitInfo[infos.size()]);
  }