public OSGiRuntimeService(OSGiRuntimeContext runtimeContext, BundleContext context) {
   super(runtimeContext);
   bundleContext = context;
   bundles = new ConcurrentHashMap<String, Bundle>();
   contexts = new ConcurrentHashMap<String, RuntimeContext>();
   String bindAddress = context.getProperty(PROP_NUXEO_BIND_ADDRESS);
   if (bindAddress != null) {
     properties.put(PROP_NUXEO_BIND_ADDRESS, bindAddress);
   }
   String homeDir = getProperty(PROP_HOME_DIR);
   log.debug("Home directory: " + homeDir);
   if (homeDir != null) {
     workingDir = new File(homeDir);
   } else {
     workingDir = bundleContext.getDataFile("/");
   }
   // environment may not be set by some bootstrappers (like tests) - we
   // create it now if not yet created
   Environment env = Environment.getDefault();
   if (env == null) {
     Environment.setDefault(new Environment(workingDir));
   }
   workingDir.mkdirs();
   persistence = new ComponentPersistence(this);
   log.debug("Working directory: " + workingDir);
 }
 public static final boolean isJBoss4(Environment env) {
   if (env == null) {
     return false;
   }
   String hn = env.getHostApplicationName();
   String hv = env.getHostApplicationVersion();
   if (hn == null || hv == null) {
     return false;
   }
   return "JBoss".equals(hn) && hv.startsWith("4");
 }
 public ConnectBroker(Environment env) throws IOException, PackageException {
   this.env = env;
   service = new StandaloneUpdateService(env);
   service.initialize();
   cbHolder = new StandaloneCallbackHolder(env, service);
   NuxeoConnectClient.setCallBackHolder(cbHolder);
   targetPlatform =
       env.getProperty(Environment.DISTRIBUTION_NAME)
           + "-"
           + env.getProperty(Environment.DISTRIBUTION_VERSION);
   distributionMPDir = env.getProperty(PARAM_MP_DIR, DISTRIBUTION_MP_DIR_DEFAULT);
 }
Example #4
0
 protected boolean loadConfigurationFromProvider() throws IOException {
   // TODO use a OSGi service for this.
   Iterable<URL> provider = Environment.getDefault().getConfigurationProvider();
   if (provider == null) {
     return false;
   }
   Iterator<URL> it = provider.iterator();
   ArrayList<URL> props = new ArrayList<>();
   ArrayList<URL> xmls = new ArrayList<>();
   while (it.hasNext()) {
     URL url = it.next();
     String path = url.getPath();
     if (path.endsWith("-config.xml")) {
       xmls.add(url);
     } else if (path.endsWith(".properties")) {
       props.add(url);
     }
   }
   Comparator<URL> comp =
       new Comparator<URL>() {
         @Override
         public int compare(URL o1, URL o2) {
           return o1.getPath().compareTo(o2.getPath());
         }
       };
   Collections.sort(xmls, comp);
   for (URL url : props) {
     loadProperties(url);
   }
   for (URL url : xmls) {
     context.deploy(url);
   }
   return true;
 }
 @Override
 public void reloadProperties() throws Exception {
   File dir = Environment.getDefault().getConfig();
   String[] names = dir.list();
   if (names != null) {
     Arrays.sort(
         names,
         new Comparator<String>() {
           @Override
           public int compare(String o1, String o2) {
             return o1.compareToIgnoreCase(o2);
           }
         });
     Properties props = new Properties();
     for (String name : names) {
       if (name.endsWith(".config") || name.endsWith(".ini") || name.endsWith(".properties")) {
         FileInputStream in = new FileInputStream(new File(dir, name));
         try {
           props.load(in);
         } finally {
           in.close();
         }
       }
     }
     // replace the current runtime properties
     properties = props;
   }
 }
 @Override
 public void beforeMethodRun(FeaturesRunner runner, FrameworkMethod method, Object test)
     throws Exception {
   File temp = Environment.getDefault().getTemp();
   temp.mkdirs();
   tempPath = temp.toPath();
   tracked.clear();
   created.clear();
   listener.install();
 }
Example #7
0
 protected String getTmpDirectory() {
   String tmp = null;
   Map<String, String> parameters = descriptor.getParameters();
   if (parameters != null && parameters.containsKey(TMP_PATH_PARAMETER)) {
     tmp = parameters.get(TMP_PATH_PARAMETER);
   }
   if (tmp == null) {
     tmp = Environment.getDefault().getTemp().getPath();
   }
   return tmp;
 }
 public File resolveAndCreate(File aFile) {
   File temp = Environment.getDefault().getTemp();
   File actual = temp.toPath().resolve(aFile.toPath()).toFile();
   try {
     actual.createNewFile();
   } catch (IOException e) {
     throw new RuntimeException("Cannot create temp file " + actual);
   }
   created.add(actual);
   return actual;
 }
 /**
  * Looks for a package file from its path
  *
  * @param pkgFile Absolute or relative package file path
  * @return the file if found, else null
  */
 protected File getLocalPackageFile(String pkgFile) {
   if (pkgFile.startsWith("file:")) {
     pkgFile = pkgFile.substring(5);
   }
   // Try absolute path
   File fileToCheck = new File(pkgFile);
   if (!fileToCheck.exists()) { // Try relative path
     fileToCheck = new File(env.getServerHome(), pkgFile);
   }
   if (fileToCheck.exists()) {
     return fileToCheck;
   } else {
     return null;
   }
 }
Example #10
0
 @Override
 public void runDeploymentPreprocessor() throws IOException {
   if (log.isDebugEnabled()) {
     log.debug("Start running deployment preprocessor");
   }
   String rootPath = Environment.getDefault().getHome().getAbsolutePath();
   File root = new File(rootPath);
   DeploymentPreprocessor processor = new DeploymentPreprocessor(root);
   // initialize
   processor.init();
   // and predeploy
   processor.predeploy();
   if (log.isDebugEnabled()) {
     log.debug("Deployment preprocessing done");
   }
 }
  @Override
  public void initialize(BinaryManagerDescriptor binaryManagerDescriptor) throws IOException {
    String path = binaryManagerDescriptor.storePath;
    if (path == null || path.trim().length() == 0) {
      path = DEFAULT_PATH;
    }
    path = Framework.expandVars(path);
    path = path.trim();
    File base;
    if (path.startsWith("/")
        || path.startsWith("\\")
        || path.contains("://")
        || path.contains(":\\")) {
      // absolute
      base = new File(path);
    } else {
      // relative
      File home = Environment.getDefault().getData();
      base = new File(home, path);

      // Backward compliance with versions before 5.4 (NXP-5370)
      File oldBase = new File(Framework.getRuntime().getHome().getPath(), path);
      if (oldBase.exists()) {
        log.warn("Old binaries path used (NXP-5370). Please move " + oldBase + " to " + base);
        base = oldBase;
      }
    }

    log.info(
        "Repository '"
            + binaryManagerDescriptor.repositoryName
            + "' using "
            + (this.getClass().equals(LocalBinaryManager.class)
                ? ""
                : (this.getClass().getSimpleName() + " and "))
            + "binary store: "
            + base);
    storageDir = new File(base, DATA);
    tmpDir = new File(base, TMP);
    storageDir.mkdirs();
    tmpDir.mkdirs();
    descriptor = getDescriptor(new File(base, CONFIG_FILE));
    createGarbageCollector();
  }
Example #12
0
  protected void initOsgiRuntime() throws Exception {
    try {
      if (!restart) {
        Environment.setDefault(null);
        if (System.getProperties().remove("nuxeo.home") != null) {
          log.warn("Removed System property nuxeo.home.");
        }
        workingDir =
            File.createTempFile(
                "nxruntime-" + Thread.currentThread().getName() + "-", null, new File("target"));
        workingDir.delete();
      }
    } catch (IOException e) {
      log.error("Could not init working directory", e);
      throw e;
    }
    osgi = new OSGiAdapter(workingDir);
    BundleFile bf = new SystemBundleFile(workingDir);
    bundleLoader = new StandaloneBundleLoader(osgi, NXRuntimeTestCase.class.getClassLoader());
    SystemBundle systemBundle =
        new SystemBundle(osgi, bf, bundleLoader.getSharedClassLoader().getLoader());
    osgi.setSystemBundle(systemBundle);
    Thread.currentThread().setContextClassLoader(bundleLoader.getSharedClassLoader().getLoader());

    for (WorkingDirectoryConfigurator cfg : wdConfigs) {
      cfg.configure(this, workingDir);
    }

    bundleLoader.setScanForNestedJARs(false); // for now
    bundleLoader.setExtractNestedJARs(false);

    BundleFile bundleFile = lookupBundle("org.nuxeo.runtime");
    runtimeBundle =
        new RootRuntimeBundle(osgi, bundleFile, bundleLoader.getClass().getClassLoader(), true);
    runtimeBundle.start();

    runtime = handleNewRuntime((OSGiRuntimeService) Framework.getRuntime());

    assertNotNull(runtime);
  }
 /**
  * Uninstall a local package. The package is not removed from cache.
  *
  * @param pkgId Package ID or Name
  * @return The uninstalled LocalPackage or null if failed
  */
 public LocalPackage pkgUninstall(String pkgId) {
   if (env.getProperty(LAUNCHER_CHANGED_PROPERTY, "false").equals("true")) {
     System.exit(LAUNCHER_CHANGED_EXIT_CODE);
   }
   CommandInfo cmdInfo = cset.newCommandInfo(CommandInfo.CMD_UNINSTALL);
   cmdInfo.param = pkgId;
   try {
     LocalPackage pkg = service.getPackage(pkgId);
     if (pkg == null) {
       // Check whether this is the name of an installed package
       String realPkgId = getInstalledPackageIdFromName(pkgId);
       if (realPkgId != null) {
         pkgId = realPkgId;
         pkg = service.getPackage(realPkgId);
       }
     }
     if (pkg == null) {
       throw new PackageException("Package not found: " + pkgId);
     }
     log.info("Uninstalling " + pkgId);
     Task uninstallTask = pkg.getUninstallTask();
     try {
       performTask(uninstallTask);
     } catch (PackageException e) {
       uninstallTask.rollback();
       throw e;
     }
     // Refresh state
     pkg = service.getPackage(pkgId);
     newPackageInfo(cmdInfo, pkg);
     return pkg;
   } catch (Exception e) {
     log.error("Failed to uninstall package: " + pkgId, e);
     cmdInfo.exitCode = 1;
     return null;
   }
 }
 /**
  * Install a local package.
  *
  * @param pkgId Package ID or Name
  * @return The installed LocalPackage or null if failed
  */
 public LocalPackage pkgInstall(String pkgId) {
   if (env.getProperty(LAUNCHER_CHANGED_PROPERTY, "false").equals("true")) {
     System.exit(LAUNCHER_CHANGED_EXIT_CODE);
   }
   CommandInfo cmdInfo = cset.newCommandInfo(CommandInfo.CMD_INSTALL);
   cmdInfo.param = pkgId;
   try {
     LocalPackage pkg = getLocalPackage(pkgId);
     if (pkg == null) {
       // We don't know this package, try to add it first
       pkg = pkgAdd(pkgId);
     }
     if (pkg == null) {
       // Nothing worked - can't find the package anywhere
       throw new PackageException("Package not found: " + pkgId);
     }
     pkgId = pkg.getId();
     cmdInfo.param = pkgId;
     log.info("Installing " + pkgId);
     Task installTask = pkg.getInstallTask();
     try {
       performTask(installTask);
     } catch (PackageException e) {
       installTask.rollback();
       throw e;
     }
     // Refresh state
     pkg = service.getPackage(pkgId);
     newPackageInfo(cmdInfo, pkg);
     return pkg;
   } catch (Exception e) {
     log.error(String.format("Failed to install package: %s (%s)", pkgId, e.getMessage()));
     cmdInfo.exitCode = 1;
     cmdInfo.newMessage(e);
     return null;
   }
 }
  public List<DocumentModel> parse(File file) throws IOException {
    mvelCtx.put("source", file);

    Document doc = null;
    File directory = null;
    try {
      doc = new SAXReader().read(file);
      workingDirectory = file.getParentFile();
    } catch (DocumentException e) {
      File tmp = Environment.getDefault().getTemp();
      directory = new File(tmp, file.getName() + System.currentTimeMillis());
      directory.mkdir();
      ZipUtils.unzip(file, directory);
      for (File child : directory.listFiles()) {
        if (child.getName().endsWith(".xml")) {
          return parse(child);
        }
      }
      throw new NuxeoException("Can not find XML file inside the zip archive", e);
    } finally {
      FileUtils.deleteQuietly(directory);
    }
    return parse(doc);
  }
  protected void loadConfig() throws Exception {
    Environment env = Environment.getDefault();
    if (env != null) {
      log.info("Configuration: host application: " + env.getHostApplicationName());
    } else {
      log.warn("Configuration: no host application");
    }

    File blacklistFile = new File(env.getConfig(), "blacklist");
    if (blacklistFile.isFile()) {
      List<String> lines = FileUtils.readLines(blacklistFile);
      Set<String> blacklist = new HashSet<String>();
      for (String line : lines) {
        line = line.trim();
        if (line.length() > 0) {
          blacklist.add(line);
        }
      }
      manager.setBlacklist(new HashSet<String>(lines));
    }

    String configDir = bundleContext.getProperty(PROP_CONFIG_DIR);
    if (configDir != null && configDir.contains(":/")) { // an url of a
      // config file
      log.debug("Configuration: " + configDir);
      URL url = new URL(configDir);
      log.debug("Configuration:   loading properties url: " + configDir);
      loadProperties(url);
      return;
    }

    if (env == null) {
      return;
    }

    // TODO: in JBoss there is a deployer that will deploy nuxeo
    // configuration files ..
    boolean isNotJBoss4 = !isJBoss4(env);

    File dir = env.getConfig();
    // File dir = new File(configDir);
    String[] names = dir.list();
    if (names != null) {
      Arrays.sort(
          names,
          new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
              return o1.compareToIgnoreCase(o2);
            }
          });
      for (String name : names) {
        if (name.endsWith("-config.xml") || name.endsWith("-bundle.xml")) {
          // TODO
          // because of some dep bugs (regarding the deployment of
          // demo-ds.xml)
          // we cannot let the runtime deploy config dir at
          // beginning...
          // until fixing this we deploy config dir from
          // NuxeoDeployer
          if (isNotJBoss4) {
            File file = new File(dir, name);
            log.debug("Configuration: deploy config component: " + name);
            context.deploy(file.toURI().toURL());
          }
        } else if (name.endsWith(".config")
            || name.endsWith(".ini")
            || name.endsWith(".properties")) {
          File file = new File(dir, name);
          log.debug("Configuration: loading properties: " + name);
          loadProperties(file);
        } else {
          log.debug("Configuration: ignoring: " + name);
        }
      }
    } else if (dir.isFile()) { // a file - load it
      log.debug("Configuration: loading properties: " + dir);
      loadProperties(dir);
    } else {
      log.debug("Configuration: no configuration file found");
    }

    loadDefaultConfig();
  }
Example #17
0
 public SchemaManagerImpl() {
   schemaDir = new File(Environment.getDefault().getTemp(), SCHEMAS_DIR_NAME);
   schemaDir.mkdirs();
   clearSchemaDir();
   registerBuiltinTypes();
 }
Example #18
0
 protected static File getAppDir() {
   return Environment.getDefault().getConfig().getParentFile();
 }
Example #19
0
  /**
   * @param doOverwrite
   * @since 5.5
   */
  protected Command doCopy(
      Task task, Map<String, String> prefs, File fileToCopy, File dst, boolean doOverwrite)
      throws PackageException {
    String dstmd5;
    File bak = null;
    CompositeCommand rollbackCommand = new CompositeCommand();
    if (fileToCopy.isDirectory()) {
      if (fileToCopy != file) {
        dst = new File(dst, fileToCopy.getName());
      }
      dst.mkdirs();
      for (File childFile : fileToCopy.listFiles()) {
        rollbackCommand.addCommand(doCopy(task, prefs, childFile, dst, doOverwrite));
      }
      return rollbackCommand;
    }
    if (dst.isDirectory()) {
      dst = new File(dst, fileToCopy.getName());
    }
    try {
      FileMatcher filenameMatcher = FileMatcher.getMatcher("{n:.*-}[0-9]+.*\\.jar");
      if (filenameMatcher.match(fileToCopy.getName()) && (overwriteIfNewerVersion || upgradeOnly)) {
        // Compare source and destination versions set in filename
        FileVersion fileToCopyVersion, dstVersion = null;
        String filenameWithoutVersion = filenameMatcher.getValue();
        FileMatcher versionMatcher =
            FileMatcher.getMatcher(filenameWithoutVersion + "{v:[0-9]+.*}\\.jar");
        // Get new file version
        if (versionMatcher.match(fileToCopy.getName())) {
          fileToCopyVersion = new FileVersion(versionMatcher.getValue());
          // Get original file name and version
          File dir = dst.getParentFile();
          File[] list = dir.listFiles();
          if (list != null) {
            for (File f : list) {
              if (versionMatcher.match(f.getName())) {
                dst = f;
                dstVersion = new FileVersion(versionMatcher.getValue());
                break;
              }
            }
          }
          if (dstVersion == null) {
            if (upgradeOnly) {
              return null;
            }
          } else if (fileToCopyVersion.greaterThan(dstVersion)) {
            // backup dst and generate rollback command
            File oldDst = dst;
            dst = new File(dst.getParentFile(), fileToCopy.getName());
            File backup = IOUtils.backup(task.getPackage(), oldDst);
            rollbackCommand.addCommand(new Copy(backup, oldDst, null, false));
            // Delete old dst as its name differs from new version
            oldDst.delete();
          } else if (fileToCopyVersion.isSnapshot() && fileToCopyVersion.equals(dstVersion)) {
            doOverwrite = true;
          } else if (!doOverwrite) {
            log.info(
                "Ignore "
                    + fileToCopy
                    + " because not newer than "
                    + dstVersion
                    + " and 'overwrite' is set to false.");
            return null;
          }
        }
      }
      if (dst.exists()) { // backup the destination file if exist.
        if (!doOverwrite && !append) { // force a rollback
          throw new PackageException(
              "Copy command has overwrite flag on false but destination file exists: " + dst);
        }
        if (task instanceof UninstallTask) {
          // no backup for uninstall task
        } else if (append) {
          bak = IOUtils.backup(task.getPackage(), fileToCopy);
        } else {
          bak = IOUtils.backup(task.getPackage(), dst);
        }
      } else { // target file doesn't exists - it will be created
        dst.getParentFile().mkdirs();
      }

      // copy the file - use getContentToCopy to allow parameterization
      // for subclasses
      String content = getContentToCopy(fileToCopy, prefs);
      if (content != null) {
        if (append && dst.exists()) {
          RandomAccessFile rfile = new RandomAccessFile(dst, "r");
          try {
            rfile.seek(dst.length());
            if (!"".equals(rfile.readLine())) {
              content = System.getProperty("line.separator") + content;
            }
          } catch (IOException e) {
            log.error(e);
          } finally {
            rfile.close();
          }
        }
        FileUtils.writeFile(dst, content, append);
      } else {
        File tmp = new File(dst.getPath() + ".tmp");
        FileUtils.copy(fileToCopy, tmp);
        if (!tmp.renameTo(dst)) {
          tmp.delete();
          FileUtils.copy(fileToCopy, dst);
        }
      }
      // check whether the copied or restored file was the launcher
      if (dst.getName().equals(LAUNCHER_JAR) || fileToCopy.getName().equals(LAUNCHER_JAR)) {
        Environment env = Environment.getDefault();
        env.setProperty(LAUNCHER_CHANGED_PROPERTY, "true");
      }
      // get the md5 of the copied file.
      dstmd5 = IOUtils.createMd5(dst);
    } catch (Exception e) {
      throw new PackageException("Failed to copy " + fileToCopy, e);
    }
    if (bak == null) { // no file was replaced
      rollbackCommand.addCommand(new Delete(dst, dstmd5, removeOnExit));
    } else if (append) {
      rollbackCommand.addCommand(new UnAppend(bak, dst));
    } else {
      rollbackCommand.addCommand(new Copy(bak, dst, dstmd5, true));
    }
    return rollbackCommand;
  }