public XsltUriResolver(CamelContext context, String location) {
   this.context = context;
   this.location = location;
   if (ResourceHelper.hasScheme(location)) {
     baseScheme = ResourceHelper.getScheme(location);
   } else {
     // default to use classpath
     baseScheme = "classpath:";
   }
 }
  @Override
  public Source resolve(String href, String base) throws TransformerException {
    // supports the empty href
    if (ObjectHelper.isEmpty(href)) {
      href = location;
    }
    if (ObjectHelper.isEmpty(href)) {
      throw new TransformerException("include href is empty");
    }

    LOG.trace("Resolving URI with href: {} and base: {}", href, base);

    String scheme = ResourceHelper.getScheme(href);
    if (scheme != null) {
      // need to compact paths for file/classpath as it can be relative paths using .. to go
      // backwards
      if ("file:".equals(scheme)) {
        // compact path use file OS separator
        href = FileUtil.compactPath(href);
      } else if ("classpath:".equals(scheme)) {
        // for classpath always use /
        href = FileUtil.compactPath(href, '/');
      }
      LOG.debug("Resolving URI from {}: {}", scheme, href);

      InputStream is;
      try {
        is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, href);
      } catch (IOException e) {
        throw new TransformerException(e);
      }
      return new StreamSource(is);
    }

    // if href and location is the same, then its the initial resolve
    if (href.equals(location)) {
      String path = baseScheme + href;
      return resolve(path, base);
    }

    // okay then its relative to the starting location from the XSLT component
    String path = FileUtil.onlyPath(location);
    if (ObjectHelper.isEmpty(path)) {
      path = baseScheme + href;
      return resolve(path, base);
    } else {
      if (ResourceHelper.hasScheme(path)) {
        path = path + "/" + href;
      } else {
        path = baseScheme + path + "/" + href;
      }
      return resolve(path, base);
    }
  }
  /**
   * Copied from CamelBlueprintHelper since there it is also a private method.
   *
   * <p>Gets the bundle descriptors as {@link URL} resources.
   *
   * @param descriptors the bundle descriptors, can be separated by comma
   * @return the bundle descriptors.
   * @throws FileNotFoundException is thrown if a bundle descriptor cannot be found
   */
  private static Collection<URL> getBlueprintDescriptors(String descriptors)
      throws FileNotFoundException, MalformedURLException {
    List<URL> answer = new ArrayList<URL>();
    String descriptor = descriptors;
    if (descriptor != null) {
      // there may be more resources separated by comma
      Iterator<Object> it = ObjectHelper.createIterator(descriptor);
      while (it.hasNext()) {
        String s = (String) it.next();
        LOG.trace("Resource descriptor: {}", s);

        // remove leading / to be able to load resource from the classpath
        s = FileUtil.stripLeadingSeparator(s);

        // if there is wildcards for *.xml then we need to find the urls from the package
        if (s.endsWith("*.xml")) {
          String packageName = s.substring(0, s.length() - 5);
          // remove trailing / to be able to load resource from the classpath
          Enumeration<URL> urls = ObjectHelper.loadResourcesAsURL(packageName);
          while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            File dir = new File(url.getFile());
            if (dir.isDirectory()) {
              File[] files = dir.listFiles();
              if (files != null) {
                for (File file : files) {
                  if (file.isFile() && file.exists() && file.getName().endsWith(".xml")) {
                    String name = packageName + file.getName();
                    LOG.debug("Resolving resource: {}", name);
                    URL xmlUrl = ObjectHelper.loadResourceAsURL(name);
                    if (xmlUrl != null) {
                      answer.add(xmlUrl);
                    }
                  }
                }
              }
            }
          }
        } else {
          LOG.debug("Resolving resource: {}", s);
          URL url = ResourceHelper.resolveMandatoryResourceAsUrl(RESOLVER, s);
          if (url == null) {
            throw new FileNotFoundException("Resource " + s + " not found");
          }
          answer.add(url);
        }
      }
    } else {
      throw new IllegalArgumentException(
          "No bundle descriptor configured. Override getBlueprintDescriptor() or getBlueprintDescriptors() method");
    }

    if (answer.isEmpty()) {
      throw new IllegalArgumentException(
          "Cannot find any resources in classpath from descriptor " + descriptors);
    }
    return answer;
  }
 @Override
 public InputStream getByteStream() {
   try {
     return ResourceHelper.resolveMandatoryResourceAsInputStream(
         camelContext.getClassResolver(), uri);
   } catch (IOException e) {
     throw ObjectHelper.wrapRuntimeCamelException(e);
   }
 }
  /**
   * Resolves the script.
   *
   * @param script script or uri for a script to load
   * @return the script
   * @throws IOException is thrown if error loading the script
   */
  protected String resolveScript(String script) throws IOException {
    String answer;
    if (ResourceHelper.hasScheme(script)) {
      InputStream is = loadResource(script);
      answer = currentExchange.get().getContext().getTypeConverter().convertTo(String.class, is);
      IOHelper.close(is);
    } else {
      answer = script;
    }

    return answer;
  }
 private String getInputUri() {
   // find the xsd with relative path
   if (ObjectHelper.isNotEmpty(relatedURI)) {
     try {
       ResourceHelper.resolveMandatoryResourceAsInputStream(
           camelContext.getClassResolver(), relatedURI);
       return relatedURI;
     } catch (IOException e) {
       // ignore the exception
     }
   }
   // don't use the relative path
   return getUri(systemId);
 }
Exemple #7
0
 @Override
 protected void doStart() throws Exception {
   super.doStart();
   if (cacheManagerFactory == null) {
     InputStream is = null;
     if (configurationFile != null) {
       is =
           ResourceHelper.resolveMandatoryResourceAsInputStream(
               getCamelContext().getClassResolver(), configurationFile);
     }
     cacheManagerFactory = new DefaultCacheManagerFactory(is, configurationFile);
   }
   ServiceHelper.startService(cacheManagerFactory);
 }
Exemple #8
0
 protected Parser createFixedParser(String resourceUri, Reader bodyReader) throws IOException {
   InputStream is =
       ResourceHelper.resolveMandatoryResourceAsInputStream(
           getCamelContext().getClassResolver(), resourceUri);
   InputStreamReader reader = new InputStreamReader(is);
   Parser parser = getParserFactory().newFixedLengthParser(reader, bodyReader);
   if (allowShortLines) {
     parser.setHandlingShortLines(true);
     parser.setIgnoreParseWarnings(true);
   }
   if (ignoreExtraColumns) {
     parser.setIgnoreExtraColumns(true);
     parser.setIgnoreParseWarnings(true);
   }
   return parser;
 }
Exemple #9
0
 public Parser createDelimitedParser(Exchange exchange)
     throws InvalidPayloadException, IOException {
   Reader bodyReader = exchange.getIn().getMandatoryBody(Reader.class);
   if (ObjectHelper.isEmpty(getResourceUri())) {
     return getParserFactory().newDelimitedParser(bodyReader, delimiter, textQualifier);
   } else {
     InputStream is =
         ResourceHelper.resolveMandatoryResourceAsInputStream(
             getCamelContext().getClassResolver(), resourceUri);
     InputStreamReader reader = new InputStreamReader(is, IOHelper.getCharsetName(exchange));
     Parser parser =
         getParserFactory()
             .newDelimitedParser(reader, bodyReader, delimiter, textQualifier, ignoreFirstRecord);
     if (isAllowShortLines()) {
       parser.setHandlingShortLines(true);
       parser.setIgnoreParseWarnings(true);
     }
     if (isIgnoreExtraColumns()) {
       parser.setIgnoreExtraColumns(true);
       parser.setIgnoreParseWarnings(true);
     }
     return parser;
   }
 }
Exemple #10
0
  protected Session createSession(final RemoteFileConfiguration configuration)
      throws JSchException {
    final JSch jsch = new JSch();
    JSch.setLogger(new JSchLogger());

    SftpConfiguration sftpConfig = (SftpConfiguration) configuration;

    if (isNotEmpty(sftpConfig.getCiphers())) {
      LOG.debug("Using ciphers: {}", sftpConfig.getCiphers());
      Hashtable<String, String> ciphers = new Hashtable<String, String>();
      ciphers.put("cipher.s2c", sftpConfig.getCiphers());
      ciphers.put("cipher.c2s", sftpConfig.getCiphers());
      JSch.setConfig(ciphers);
    }

    if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
      LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile());
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());
      } else {
        jsch.addIdentity(sftpConfig.getPrivateKeyFile());
      }
    }

    if (sftpConfig.getPrivateKey() != null) {
      LOG.debug("Using private key information from byte array");
      byte[] passphrase = null;
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        try {
          passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new JSchException("Cannot transform passphrase to byte[]", e);
        }
      }
      jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase);
    }

    if (sftpConfig.getPrivateKeyUri() != null) {
      LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri());
      byte[] passphrase = null;
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        try {
          passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new JSchException("Cannot transform passphrase to byte[]", e);
        }
      }
      try {
        InputStream is =
            ResourceHelper.resolveMandatoryResourceAsInputStream(
                endpoint.getCamelContext().getClassResolver(), sftpConfig.getPrivateKeyUri());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(is, bos);
        jsch.addIdentity("ID", bos.toByteArray(), null, passphrase);
      } catch (IOException e) {
        throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e);
      }
    }

    if (sftpConfig.getKeyPair() != null) {
      LOG.debug("Using private key information from key pair");
      KeyPair keyPair = sftpConfig.getKeyPair();
      if (keyPair.getPrivate() != null && keyPair.getPublic() != null) {
        if (keyPair.getPrivate() instanceof RSAPrivateKey
            && keyPair.getPublic() instanceof RSAPublicKey) {
          jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null);
        } else if (keyPair.getPrivate() instanceof DSAPrivateKey
            && keyPair.getPublic() instanceof DSAPublicKey) {
          jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null);
        } else {
          LOG.warn("Only RSA and DSA key pairs are supported");
        }
      } else {
        LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled");
      }
    }

    if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
      LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile());
      jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
    }

    if (isNotEmpty(sftpConfig.getKnownHostsUri())) {
      LOG.debug("Using knownhosts uri: {}", sftpConfig.getKnownHostsUri());
      try {
        InputStream is =
            ResourceHelper.resolveMandatoryResourceAsInputStream(
                endpoint.getCamelContext().getClassResolver(), sftpConfig.getKnownHostsUri());
        jsch.setKnownHosts(is);
      } catch (IOException e) {
        throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
      }
    }

    if (sftpConfig.getKnownHosts() != null) {
      LOG.debug("Using knownhosts information from byte array");
      jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
    }

    final Session session =
        jsch.getSession(
            configuration.getUsername(), configuration.getHost(), configuration.getPort());

    if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
      LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
      session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
    }

    session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
    session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());

    // compression
    if (sftpConfig.getCompression() > 0) {
      LOG.debug("Using compression: {}", sftpConfig.getCompression());
      session.setConfig("compression.s2c", "[email protected],zlib,none");
      session.setConfig("compression.c2s", "[email protected],zlib,none");
      session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
    }

    // set the PreferredAuthentications
    if (sftpConfig.getPreferredAuthentications() != null) {
      LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
      session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
    }

    // set user information
    session.setUserInfo(
        new ExtendedUserInfo() {
          public String getPassphrase() {
            return null;
          }

          public String getPassword() {
            return configuration.getPassword();
          }

          public boolean promptPassword(String s) {
            return true;
          }

          public boolean promptPassphrase(String s) {
            return true;
          }

          public boolean promptYesNo(String s) {
            LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
            // Return 'false' indicating modification of the hosts file is disabled.
            return false;
          }

          public void showMessage(String s) {
            LOG.trace("Message received from Server: " + s);
          }

          public String[] promptKeyboardInteractive(
              String destination,
              String name,
              String instruction,
              String[] prompt,
              boolean[] echo) {
            // must return an empty array if password is null
            if (configuration.getPassword() == null) {
              return new String[0];
            } else {
              return new String[] {configuration.getPassword()};
            }
          }
        });

    // set the SO_TIMEOUT for the time after the connect phase
    if (configuration.getSoTimeout() > 0) {
      session.setTimeout(configuration.getSoTimeout());
    }

    // set proxy if configured
    if (proxy != null) {
      session.setProxy(proxy);
    }

    return session;
  }
 /**
  * Loads the given resource.
  *
  * @param uri uri of the resource.
  * @return the loaded resource
  * @throws IOException is thrown if resource is not found or cannot be loaded
  */
 protected InputStream loadResource(String uri) throws IOException {
   return ResourceHelper.resolveMandatoryResourceAsInputStream(
       currentExchange.get().getContext(), uri);
 }