@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;
  }
  public static List<ServiceDefinition> load(ClassLoader classLoader) throws IOException {
    ServiceDefinitionReader reader = new ServiceDefinitionReader();
    List<ServiceDefinition> services = new ArrayList<>();
    for (Resource resource : getResources(classLoader)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Reading service definition: " + resource.getDescription());
      }
      try (InputStream in = resource.getInputStream()) {
        ServiceDefinition service = reader.readService(in);
        if (service != null) {
          if (!service.disabled) {
            services.add(service);
          } else {
            LOG.debug("Skipping disabled service");
          }
        } else {
          LOG.warn("Error reading service definition " + resource.getDescription());
        }
      } catch (IOException | RuntimeException e) {
        LOG.error("Error reading service definition: " + resource.getDescription(), e);
      }
    }

    return services;
  }
  /**
   * @return string corresponding to logical record according to {@link
   *     #setRecordSeparatorPolicy(RecordSeparatorPolicy)} (might span multiple lines in file).
   */
  @Override
  protected T doRead() throws Exception {
    if (noInput) {
      return null;
    }

    String line = readLine();

    if (line == null) {
      return null;
    } else {
      try {
        return lineMapper.mapLine(line, lineCount);
      } catch (Exception ex) {
        throw new FlatFileParseException(
            "Parsing error at line: "
                + lineCount
                + " in resource=["
                + resource.getDescription()
                + "], input=["
                + line
                + "]",
            ex,
            line,
            lineCount);
      }
    }
  }
 /**
  * Return the description for the given Resource; if the description is empty, return the class
  * name of the resource plus its identity hash code.
  *
  * @see org.springframework.core.io.Resource#getDescription()
  */
 private static String getNameForResource(Resource resource) {
   String name = resource.getDescription();
   if (!StringUtils.hasText(name)) {
     name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
   }
   return name;
 }
 /**
  * load.
  *
  * @param resource a {@link org.springframework.core.io.Resource} object.
  * @return a {@link java.util.List} object.
  */
 public List<ReconfigBeanDefinitionHolder> load(Resource resource) {
   List<ReconfigBeanDefinitionHolder> holders = new ArrayList<ReconfigBeanDefinitionHolder>();
   try {
     InputStream inputStream = resource.getInputStream();
     try {
       InputSource inputSource = new InputSource(inputStream);
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder docBuilder = factory.newDocumentBuilder();
       Document doc = docBuilder.parse(inputSource);
       Element root = doc.getDocumentElement();
       NodeList nl = root.getChildNodes();
       BeanDefinitionParser parser = new BeanDefinitionParser();
       for (int i = 0; i < nl.getLength(); i++) {
         Node node = nl.item(i);
         if (node instanceof Element) {
           Element ele = (Element) node;
           ReconfigBeanDefinitionHolder holder = parser.parseBeanDefinitionElement(ele);
           holders.add(holder);
         }
       }
     } finally {
       if (null != inputStream) {
         inputStream.close();
       }
     }
   } catch (Exception ex) {
     throw new RuntimeException(
         "IOException parsing XML document from " + resource.getDescription(), ex);
   }
   return holders;
 }
  /**
   * Constructs a GroovyPageMetaInfo instance which holds the script class, modified date and so on
   *
   * @param inputStream The InputStream to construct the GroovyPageMetaInfo instance from
   * @param res The Spring Resource to construct the MetaInfo from
   * @param pageName The name of the page (can be null, in which case method responsible for
   *     calculating appropriate alternative)
   * @return The GroovyPageMetaInfo instance
   */
  protected GroovyPageMetaInfo buildPageMetaInfo(
      InputStream inputStream, Resource res, String pageName) {
    String name = establishPageName(res, pageName);

    long lastModified = establishLastModified(res);

    GroovyPageParser parser;
    String path = getPathForResource(res);
    try {
      parser = new GroovyPageParser(name, path, path, inputStream);
    } catch (IOException e) {
      throw new GroovyPagesException(
          "I/O parsing Groovy page ["
              + (res != null ? res.getDescription() : name)
              + "]: "
              + e.getMessage(),
          e);
    }
    InputStream in = parser.parse();

    // Make a new metaInfo
    GroovyPageMetaInfo metaInfo = createPageMetaInfo(parser, lastModified, in);
    try {
      metaInfo.setPageClass(compileGroovyPage(in, name, path, metaInfo));
      metaInfo.setHtmlParts(parser.getHtmlPartsArray());
    } catch (GroovyPagesException e) {
      metaInfo.setCompilationException(e);
    }

    if (!name.startsWith(GENERATED_GSP_NAME_PREFIX)) {
      pageCache.put(name, metaInfo);
    }

    return metaInfo;
  }
  public static void main(String[] args) throws Throwable {

    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource resources[] = resolver.getResources("classpath*:com/baobaotao/**/*.xml");
    for (Resource resource : resources) {
      System.out.println(resource.getDescription());
    }
  }
 private String getPathForResource(Resource res) {
   if (res == null) return "";
   String path = null;
   try {
     File file = res.getFile();
     if (file != null) path = file.getAbsolutePath();
   } catch (IOException e) {
     // ignore
   }
   if (path != null) {
     return path;
   }
   if (res.getDescription() != null) {
     return res.getDescription();
   }
   return "";
 }
Example #9
0
 public static Reader getReaderForResource(Resource resource) {
   InputStreamReader reader = null;
   try {
     reader = new InputStreamReader(resource.getInputStream(), "UTF8");
   } catch (Exception e) {
     throw new ExecutionException("Unable to read resource " + resource.getDescription(), e);
   }
   return reader;
 }
 public static void main(String[] args) {
   ApplicationContext ac = new ClassPathXmlApplicationContext();
   /**
    * Spring可以根据file: http: classpath: 判断要使用的Resource实现类; 如果没有前缀,则根据ApplicationContext实现类判定
    * ApplicationContext 实现了ResourceLoader接口,可以通过getResource("")获得Resource
    */
   Resource res = ac.getResource("com/tyy/spring_senior/resource/more/demoFile");
   System.out.println(res.getDescription());
 }
 /**
  * Load bean definitions from the specified properties file.
  *
  * @param resource the resource descriptor for the properties file
  * @return the number of bean definitions found
  * @throws BeansException in case of loading or parsing errors
  */
 public int loadBeanDefinitions(Resource resource, String prefix) {
   Properties props = new Properties();
   try {
     InputStream is = resource.getInputStream();
     try {
       props.load(is);
     } finally {
       is.close();
     }
     return registerBeanDefinitions(props, prefix, resource.getDescription());
   } catch (IOException ex) {
     throw new BeanDefinitionStoreException("IOException parsing properties from " + resource, ex);
   }
 }
 /**
  * Actually load bean definitions from the specified XML file.
  *
  * @param inputSource the SAX InputSource to read from
  * @param resource the resource descriptor for the XML file
  * @return the number of bean definitions found
  * @throws BeanDefinitionStoreException in case of loading or parsing errors
  */
 protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
     throws BeanDefinitionStoreException {
   try {
     int validationMode = getValidationModeForResource(resource);
     Document doc =
         this.documentLoader.loadDocument(
             inputSource,
             getEntityResolver(),
             this.errorHandler,
             validationMode,
             isNamespaceAware());
     return registerBeanDefinitions(doc, resource);
   } catch (BeanDefinitionStoreException ex) {
     throw ex;
   } catch (SAXParseException ex) {
     throw new XmlBeanDefinitionStoreException(
         resource.getDescription(),
         "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid",
         ex);
   } catch (SAXException ex) {
     throw new XmlBeanDefinitionStoreException(
         resource.getDescription(), "XML document from " + resource + " is invalid", ex);
   } catch (ParserConfigurationException ex) {
     throw new BeanDefinitionStoreException(
         resource.getDescription(),
         "Parser configuration exception parsing XML from " + resource,
         ex);
   } catch (IOException ex) {
     throw new BeanDefinitionStoreException(
         resource.getDescription(), "IOException parsing XML document from " + resource, ex);
   } catch (Throwable ex) {
     throw new BeanDefinitionStoreException(
         resource.getDescription(),
         "Unexpected exception parsing XML document from " + resource,
         ex);
   }
 }
Example #13
0
 public static String readText(Resource resource) {
   Reader reader = null;
   try {
     reader = getReaderForResource(resource);
     return FileCopyUtils.copyToString(reader);
   } catch (Exception e) {
     throw new ExecutionException("Unable to read resource " + resource.getDescription(), e);
   } finally {
     if (reader != null) {
       try {
         reader.close();
       } catch (IOException e) {
       }
     }
   }
 }
  protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
      RepositoryService repositoryService = processEngine.getRepositoryService();

      DeploymentBuilder deploymentBuilder =
          repositoryService
              .createDeployment()
              .enableDuplicateFiltering(false)
              .name(deploymentName)
              .tenantId(deploymentTenantId);

      for (Resource resource : deploymentResources) {
        String resourceName = null;

        if (resource instanceof ContextResource) {
          resourceName = ((ContextResource) resource).getPathWithinContext();

        } else if (resource instanceof ByteArrayResource) {
          resourceName = resource.getDescription();

        } else {
          try {
            resourceName = resource.getFile().getAbsolutePath();
          } catch (IOException e) {
            resourceName = resource.getFilename();
          }
        }

        try {
          if (resourceName.endsWith(".bar")
              || resourceName.endsWith(".zip")
              || resourceName.endsWith(".jar")) {
            deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
          } else {
            deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
          }
        } catch (IOException e) {
          throw new ProcessEngineException(
              "couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
        }
      }

      deploymentBuilder.deploy();
    }
  }
Example #15
0
  /**
   * 设置BaseNames。
   *
   * @param baseNames String[]
   */
  public void setBaseNames(String[] baseNames) {
    List<String> baseNameList = new ArrayList<String>();
    try {
      for (String baseName : baseNames) {
        Resource[] resources = resolver.getResources(baseName);
        for (Resource resource : resources) {
          String fileName = resource.getURI().toString();
          baseNameList.add(fileName.substring(0, fileName.indexOf(PROPERTY_POSTFIX)));

          if (log.isInfoEnabled()) {
            log.info("Add properties file: [" + resource.getDescription() + "]");
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    this.rMessageSource.setCacheSeconds(this.getCacheMillis());
    this.rMessageSource.setBasenames(baseNameList.toArray(new String[baseNameList.size()]));
  }
Example #16
0
 /**
  * Reads all of the resource files under the specified path and returns a sequence of String
  * arrays. The resource files are specified as comma-separated values. Each row in a resource file
  * is one element of the resulting list.
  *
  * @param suffix filename suffix. Matches against files with this suffix in their filename.
  * @return list of String[] elements that represent CSV values
  */
 public static List<String[]> readProperties(String suffix) {
   List<String[]> result = new ArrayList<>();
   try {
     String locationPattern = "classpath*:plugins/*" + suffix;
     Resource[] resources = resolver.getResources(locationPattern);
     for (Resource resource : resources) {
       log.debug("readProperties found resource {}", resource);
       String filename = resource.getDescription();
       InputStreamReader reader = new InputStreamReader(resource.getInputStream());
       try (CsvListReader csvParser = new CsvListReader(reader, csvParserOptions)) {
         List<String> next;
         while ((next = csvParser.read()) != null) {
           result.add(next.toArray(new String[next.size()]));
         }
       } catch (SuperCsvException e) {
         log.warn("In " + filename + ", " + e);
       }
     }
   } catch (IOException e) {
     log.error(e.toString());
   }
   return result;
 }
Example #17
0
 public QueryReader(final Resource queryResource) {
   this.queryResource = queryResource;
   LOGGER.info("Using queries in: {}", queryResource.getDescription());
 }
 @Override
 public String getDescription() {
   return delegate.getDescription();
 }
 /**
  * Load the profile-specific properties from the specified resource (if any) and add it as the
  * first source.
  *
  * @param resource the source resource (may be {@code null}).
  * @param profile a specific profile to load or {@code null} to load the default.
  * @return the loaded property source or {@code null}
  * @throws IOException if the source cannot be loaded
  */
 public PropertySource<?> load(Resource resource, String profile) throws IOException {
   return load(resource, resource.getDescription(), profile);
 }