/**
  * Helper method for testing which stores a copy of the message locally as the POP3
  *
  * <p>message will be deleted from the server
  *
  * @param msg the message to store
  * @throws IOException If a failure happens writing the message
  * @throws MessagingException If a failure happens reading the message
  */
 protected void storeMessage(Message msg) throws IOException, MessagingException {
   if (backupEnabled) {
     String filename = msg.getFileName();
     if (filename == null) {
       Address[] from = msg.getFrom();
       if (from != null && from.length > 0) {
         filename =
             from[0] instanceof InternetAddress
                 ? ((InternetAddress) from[0]).getAddress()
                 : from[0].toString();
       } else {
         filename = "(no from address)";
       }
       filename += "[" + UUID.getUUID() + "]";
     }
     filename = FileUtils.prepareWinFilename(filename);
     filename = backupFolder + filename + ".msg";
     if (logger.isDebugEnabled()) {
       logger.debug("Writing message to: " + filename);
     }
     File f = FileUtils.createFile(filename);
     FileOutputStream fos = new FileOutputStream(f);
     msg.writeTo(fos);
   }
 }
Exemple #2
0
 public void testConfig() throws Exception {
   MuleVisualizerPlugin plugin = new MuleVisualizerPlugin();
   String config = getXmlConfig();
   String path = FileUtils.getResourcePath(config, getClass());
   assertNotNull("missing config path: " + config, path);
   plugin.setFiles(Arrays.asList(new String[] {path}));
   plugin.setOutputdir(FileUtils.getResourcePath("target", getClass()));
   plugin.execute();
 }
Exemple #3
0
  // @Override
  protected void doSetUp() throws Exception {
    super.doSetUp();

    // The working directory is deleted on tearDown
    File tempDir = FileUtils.newFile(MuleManager.getConfiguration().getWorkingDirectory(), "tmp");
    if (!tempDir.exists()) {
      tempDir.mkdirs();
    }

    validMessage = File.createTempFile("simple", ".mule", tempDir);
    assertNotNull(validMessage);
    FileUtils.writeStringToFile(validMessage, "validMessage");
  }
Exemple #4
0
  protected Set<Class> processFileUrl(URL url, String basepath, Class clazz) throws IOException {
    Set<Class> set = new HashSet<Class>();
    String urlBase = url.getFile();
    // We can't URLDecoder.decode(path) since some encoded chars are allowed on file uris
    urlBase = urlBase.replaceAll("%20", " ");
    File dir = new File(urlBase);
    if (!dir.isDirectory()) {
      logger.warn("Cannot process File URL: " + url + ". Path is not a directory");
      return set;
    }

    Collection<File> files = FileUtils.listFiles(new File(urlBase), new String[] {"class"}, true);
    for (File file : files) {
      try {
        InputStream classStream = new FileInputStream(file);
        ClassReader reader = new ClosableClassReader(classStream);

        ClassScanner visitor = getScanner(clazz);
        reader.accept(visitor, 0);
        if (visitor.isMatch()) {
          Class c = loadClass(visitor.getClassName());
          if (c != null) {
            set.add(c);
          }
        }
      } catch (IOException e) {
        if (logger.isDebugEnabled()) {
          Throwable t = ExceptionHelper.getRootException(e);
          logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
        }
      }
    }
    return set;
  }
Exemple #5
0
  /**
   * This is something of a hack. Velocity loads files relative to the property
   * VelocityEngine.FILE_RESOURCE_LOADER_PATH. So if we can find the template ourselves then we can
   * infer what the property value should be so that velocity works ok.
   */
  private void inferVelocityLoaderPath(VelocityEngine ve) throws IOException {
    String defaultPath = (String) ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH);
    if (null == defaultPath || StringUtils.isEmpty(defaultPath)) {
      URL url = IOUtils.getResourceAsUrl(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
      if (FILE.equals(url.getProtocol())) {
        String path =
            FileUtils.getResourcePath(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
        if (!StringUtils.isEmpty(path)) {
          File fullPath = new File(path);
          File target = new File(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE);

          // drop trailing files until we are at the relative parent
          while (null != target && !StringUtils.isEmpty(target.getPath())) {
            env.log(fullPath.getPath() + " - " + target.getPath());
            target = target.getParentFile();
            fullPath = fullPath.getParentFile();
          }

          path = fullPath.getPath();
          if (path.endsWith("!")) {
            path = path + File.separator;
          }
          getEnv().log(VelocityEngine.FILE_RESOURCE_LOADER_PATH + " = " + path);
          ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
        }
      } else if (JAR.equals(url.getProtocol())) {
        env.log(url.toString());
        ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
        ve.setProperty(MAGIC_VELOCITY_RESOURCE_LOADER, ClasspathResourceLoader.class.getName());
      }
    }
  }
Exemple #6
0
  protected Set<Class> processFileUrl(URL url, String basepath, Class clazz) throws IOException {
    Set<Class> set = new HashSet<Class>();
    String urlBase = url.getFile();
    urlBase = URLDecoder.decode(urlBase);

    Collection<File> files = FileUtils.listFiles(new File(urlBase), new String[] {"class"}, true);
    for (File file : files) {
      try {
        ClassReader reader = new ClassReader(new FileInputStream(file));
        ClassScanner visitor = getScanner(clazz);
        reader.accept(visitor, 0);
        if (visitor.isMatch()) {
          Class c = loadClass(visitor.getClassName());
          if (c != null) {
            set.add(c);
          }
        }
      } catch (IOException e) {
        if (logger.isDebugEnabled()) {
          Throwable t = ExceptionHelper.getRootException(e);
          logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
        }
      }
    }
    return set;
  }
Exemple #7
0
 public void setTrustStore(String trustStore) throws IOException {
   this.trustStore = trustStore;
   if (this.trustStore != null) {
     this.trustStore = FileUtils.getResourcePath(trustStore, getClass());
     logger.debug("Normalised trustStore path to: " + getTrustStore());
   }
 }
Exemple #8
0
 public void setClientKeyStore(String clientKeyStore) throws IOException {
   this.clientKeyStore = clientKeyStore;
   if (this.clientKeyStore != null) {
     this.clientKeyStore = FileUtils.getResourcePath(clientKeyStore, getClass());
     logger.debug("Normalised clientKeyStore path to: " + getClientKeyStore());
   }
 }
Exemple #9
0
  public void testStreamingFromFileToTcp() throws Exception {
    String text =
        "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah "
            + "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah "
            + "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah "
            + "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\n\n";

    String basepath = muleContext.getConfiguration().getWorkingDirectory() + "/test-data";
    FileUtils.stringToFile(basepath + "/in/foo.txt", text);

    Thread.sleep(3000);

    String result =
        FileUtils.readFileToString(FileUtils.newFile(basepath, "out/foo.txt.processed"), "UTF8");
    assertEquals(text, result);
  }
Exemple #10
0
 public void createDirectories(File rootDir) throws IOException {
   FileUtils.createFile(rootDir.getAbsolutePath());
   FileUtils.createFile(new File(rootDir, COMPONENTS_DIR).getAbsolutePath());
   FileUtils.createFile(new File(rootDir, WORKSPACE_DIR).getAbsolutePath());
   FileUtils.createFile(new File(rootDir, LIBRARIES_DIR).getAbsolutePath());
   FileUtils.createFile(new File(rootDir, ASSEMBLIES_DIR).getAbsolutePath());
   FileUtils.createFile(getAutoInstallDir(rootDir).getAbsolutePath());
   FileUtils.createFile(getAutoDeployDir(rootDir).getAbsolutePath());
   FileUtils.createFile(getAutoDeployProcessedDir(rootDir).getAbsolutePath());
 }
Exemple #11
0
 public void setClientKeyStore(String name) throws IOException {
   clientKeyStoreName = name;
   if (null != clientKeyStoreName) {
     clientKeyStoreName = FileUtils.getResourcePath(clientKeyStoreName, getClass());
     if (logger.isDebugEnabled()) {
       logger.debug("Normalised clientKeyStore path to: " + clientKeyStoreName);
     }
   }
 }
  @Test
  public void testSynchProcessingStrategy() throws Exception {
    sendMessage("vm://testSynch");
    new FlowExecutionListener("synchFlow", muleContext).waitUntilFlowIsComplete();
    file = new File(FILE_PATH);
    String str = FileUtils.readFileToString(file);

    Assert.assertEquals("Part 1Part 2", str);
  }
Exemple #13
0
 public void setTrustStore(String name) throws IOException {
   trustStoreName = name;
   if (null != trustStoreName) {
     trustStoreName = FileUtils.getResourcePath(trustStoreName, getClass());
     if (logger.isDebugEnabled()) {
       logger.debug("Normalised trustStore path to: " + trustStoreName);
     }
   }
 }
Exemple #14
0
 public void deleteDir(File dir) {
   FileUtils.deleteTree(dir);
   if (dir.isDirectory()) {
     try {
       new File(dir, ".delete").createNewFile();
     } catch (IOException e) {
       logger.warn("Could not mark directory to be deleted", e);
     }
   }
 }
  @Test
  public void testStreamingFromFileToTcp() throws Exception {
    String text =
        "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah "
            + "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah "
            + "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah "
            + "\nblah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\n\n";

    String basepath = muleContext.getConfiguration().getWorkingDirectory() + "/test-data";

    FileUtils.stringToFile(basepath + "/in/foo.txt", text);

    File file = FileUtils.newFile(basepath, "out/foo.txt.processed");

    PollingProber pollingProber = new PollingProber(5000, 10);
    pollingProber.check(new FileExists(file));

    String result = FileUtils.readFileToString(file, "UTF8");
    assertEquals(text, result);
  }
 /** Copies a given app archive with a given target name to the apps folder for deployment */
 private void addAppArchive(URL url, String targetFile) throws IOException {
   // copy is not atomic, copy to a temp file and rename instead (rename is atomic)
   final String tempFileName =
       new File((targetFile == null ? url.getFile() : targetFile) + ".part").getName();
   final File tempFile = new File(appsDir, tempFileName);
   FileUtils.copyURLToFile(url, tempFile);
   boolean renamed =
       tempFile.renameTo(new File(StringUtils.removeEnd(tempFile.getAbsolutePath(), ".part")));
   if (!renamed) {
     throw new IllegalStateException("Unable to add application archive");
   }
 }
 public boolean isSatisfied() {
   if (file.exists()) {
     try {
       output = FileUtils.readFileToString(file);
     } catch (IOException e) {
       logger.debug("Could not read from file.");
     }
     return "Part 2Part 1".equals(output);
   } else {
     return false;
   }
 }
  private void setMuleFolders() throws IOException {
    appsDir = createFolder("apps");
    logsDir = createFolder("logs");
    pluginsDir = createFolder("plugins");
    domainsDir = createFolder("domains");

    File confDir = createFolder("conf");
    URL log4jFile = getClass().getResource("/log4j2-test.xml");
    FileUtils.copyURLToFile(log4jFile, new File(confDir, "log4j2-test.xml"));

    createFolder("lib/shared/default");
  }
 private void copyExplodedArtifactFromClasspathFolderToDeployFolder(
     String artifactFolder, File artifactDirectory, String artifactName) {
   ReentrantLock lock = this.deploymentService.getLock();
   lock.lock();
   try {
     URL resource = getClass().getClassLoader().getResource(artifactFolder);
     FileUtils.copyDirectory(
         new File(resource.getFile()), new File(artifactDirectory, artifactName));
   } catch (IOException e) {
     throw new MuleRuntimeException(e);
   } finally {
     lock.unlock();
   }
 }
Exemple #20
0
 // @Override
 protected void doTearDown() throws Exception {
   FileUtils.deleteDirectory(
       FileUtils.newFile(muleContext.getConfiguration().getWorkingDirectory() + "/test-data"));
 }
 @After
 public void cleanUp() {
   FileUtils.deleteQuietly(file);
 }
Exemple #22
0
 // @Override
 protected void doTearDown() throws Exception {
   // TestConnector dispatches events via the test: protocol to test://test
   // endpoints, which seems to end up in a directory called "test" :(
   FileUtils.deleteTree(FileUtils.newFile(getTestConnector().getProtocol()));
   super.doTearDown();
 }
Exemple #23
0
  public void doInitialise() throws InitialisationException {
    if (getProvider() == null) {
      throw new NullPointerException("The security provider cannot be null");
    }
    if (getKeyStore() != null) {
      if (getKeyPassword() == null) {
        throw new NullPointerException("The Key password cannot be null");
      }
      if (getStorePassword() == null) {
        throw new NullPointerException("The KeyStore password cannot be null");
      }
      if (getKeyManagerAlgorithm() == null) {
        throw new NullPointerException("The Key Manager Algorithm cannot be null");
      }
      if (getKeyStoreType() == null) {
        throw new NullPointerException("The KeyStore type cannot be null");
      }
    }

    if (getKeyStore() != null) {
      KeyStore keystore;
      try {
        Security.addProvider(getProvider());
        // Create keyStore
        keystore = KeyStore.getInstance(keyStoreType);
        InputStream is = IOUtils.getResourceAsStream(getKeyStore(), getClass());
        if (is == null) {
          throw new FileNotFoundException(
              "Failed to load keystore from classpath or local file: " + getKeyStore());
        }
        keystore.load(is, getKeyPassword().toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "KeyStore: " + getKeyStore()), e, this);
      }
      try {
        // Get key manager
        keyManagerFactory = KeyManagerFactory.getInstance(getKeyManagerAlgorithm());
        // Initialize the KeyManagerFactory to work with our keyStore
        keyManagerFactory.init(keystore, getStorePassword().toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "Key Manager (" + getKeyManagerAlgorithm() + ")"),
            e,
            this);
      }
    }

    if (getTrustStore() != null) {
      KeyStore truststore;
      try {
        truststore = KeyStore.getInstance(trustStoreType);
        InputStream is = IOUtils.getResourceAsStream(getTrustStore(), getClass());
        if (is == null) {
          throw new FileNotFoundException(
              "Failed to load truststore from classpath or local file: " + getTrustStore());
        }
        truststore.load(is, getTrustStorePassword().toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "TrustStore: " + getTrustStore()), e, this);
      }

      try {
        trustManagerFactory = TrustManagerFactory.getInstance(getTrustManagerAlgorithm());
        trustManagerFactory.init(truststore);
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(
                Messages.FAILED_LOAD_X, "Trust Manager (" + getTrustManagerAlgorithm() + ")"),
            e,
            this);
      }
    }

    super.doInitialise();

    if (protocolHandler != null) {
      System.setProperty("java.protocol.handler.pkgs", protocolHandler);
    }
    if (clientKeyStore != null) {
      try {
        String clientPath = FileUtils.getResourcePath(clientKeyStore, getClass());
        System.setProperty("javax.net.ssl.keyStore", clientPath);
        System.setProperty("javax.net.ssl.keyStorePassword", clientKeyStorePassword);

        logger.info("Set Client Key store: javax.net.ssl.keyStore=" + clientPath);
      } catch (IOException e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "Client KeyStore: " + clientKeyStore), e, this);
      }
    }

    if (trustStore != null) {
      System.setProperty("javax.net.ssl.trustStore", getTrustStore());
      System.setProperty("javax.net.ssl.trustStorePassword", getTrustStorePassword());
      logger.debug("Set Trust store: javax.net.ssl.trustStore=" + getTrustStore());
    } else if (!isExplicitTrustStoreOnly()) {
      logger.info("Defaulting trust store to client Key Store");
      trustStore = getClientKeyStore();
      trustStorePassword = getClientKeyStorePassword();
      System.setProperty("javax.net.ssl.trustStore", getTrustStore());
      System.setProperty("javax.net.ssl.trustStorePassword", getTrustStorePassword());
      logger.debug("Set Trust store: javax.net.ssl.trustStore=" + getTrustStore());
    }
  }
 public void addZippedPlugin(String resource) throws IOException, URISyntaxException {
   URL url = getClass().getClassLoader().getResource(resource).toURI().toURL();
   String baseName = FilenameUtils.getName(url.getPath());
   File tempFile = new File(getPluginsDir(), baseName);
   FileUtils.copyURLToFile(url, tempFile);
 }