/*
Initializes the value of the {@link ManagedArtifactRepository#REPO_FOLDER_NAME} from JVM arguments or
SeLionConfig.json. Default value returned is "repository".
779878
private static String initializeBaseDir() {
        LOGGER.entering();
        String repoFolderName = System.getProperty(ARTIFACT_BASE_CONFIG_PROPERTY,
                ConfigParser.parse().getString(ARTIFACT_BASE_CONFIG_PROPERTY, "repository"));
        repoFolderName = StringUtils.defaultIfEmpty(repoFolderName, "repository");
        LOGGER.exiting(repoFolderName);
        return repoFolderName;
    }
594134
public synchronized static void initConfig(Map<ConfigProperty, String> initialValues) {
        SeLionLogger.getLogger().entering(initialValues);

        // only do this if the global config is not already initialized.
        if (xmlConfig == null) {
            xmlConfig = new XMLConfiguration();
            // don't auto throw, let each config value decide
            xmlConfig.setThrowExceptionOnMissing(false);
            // because we can config on the fly, don't auto-save
            xmlConfig.setAutoSave(false);

            // Set defaults
            loadInitialValues();
        }

        /*
         * otherwise, update the global config
         */

        // Load in our supplied values (if defined)
        loadValuesFromUser(initialValues);

        // Load in environment & system variables (if defined)
        loadValuesFromEnvironment();

        // Init Selenium configuration
        boolean runLocally = xmlConfig.getBoolean(ConfigProperty.SELENIUM_RUN_LOCALLY.getName());
        if (runLocally) {
            xmlConfig.setProperty(ConfigProperty.SELENIUM_HOST.getName(), "localhost");
        }

        SeLionLogger.getLogger().exiting();
    }
316812
public static RepositoryId getRepository(final MavenProject project,
			final String owner, final String name) {
		// Use owner and name if specified
		if (!StringUtils.isEmpty(owner, name))
			return RepositoryId.create(owner, name);

		if (project == null)
			return null;

		RepositoryId repo = null;
		// Extract repository from SCM URLs first if present
		final Scm scm = project.getScm();
		if (scm != null) {
			repo = RepositoryId.createFromUrl(scm.getUrl());
			if (repo == null)
				repo = extractRepositoryFromScmUrl(scm.getConnection());
			if (repo == null)
				repo = extractRepositoryFromScmUrl(scm.getDeveloperConnection());
		}

		// Check project URL last
		if (repo == null)
			repo = RepositoryId.createFromUrl(project.getUrl());

		return repo;
	}
507558
protected String getRepositoryName(String repoName) throws RepositoryException
   {
      // To be cloud compliant we need now to ignore the provided repository name (more details in JCR-2138)
      ManageableRepository repo = repositoryService.getCurrentRepository();
      String currentRepositoryName = repo.getConfiguration().getName();
      if (PropertyManager.isDevelopping() && log.isWarnEnabled())
      {
         if (!currentRepositoryName.equals(repoName))
         {
            log.warn("The expected repository was '" + repoName
               + "' but we will use the current repository instead which is '" + currentRepositoryName + "'");
         }
      }
      return currentRepositoryName;
   }
1374022
@Override
    public Collection<Throwable> restoreRepository(final FedoraSession session,
                                      final File backupDirectory) {
        final Session jcrSession = getJcrSession(session);
        try {
            final RepositoryManager repoMgr = ((org.modeshape.jcr.api.Session) jcrSession)
                    .getWorkspace()
                    .getRepositoryManager();

            final Collection<Throwable> problems = new ArrayList<>();

            repoMgr.restoreRepository(backupDirectory).forEach(x -> problems.add(x.getThrowable()));

            return problems;
        } catch (final RepositoryException e) {
            throw new RepositoryRuntimeException(e);
        }
    }
1027816
private Boolean getInitialValueForUseDefaultLocationOption(CmsResource folderResource) {

        String rootPath = folderResource.getRootPath();
        return Boolean.valueOf(OpenCms.getSiteManager().getSiteForRootPath(rootPath) != null);
    }
291105
private synchronized Map<String, JsonObject> getAssetMap() throws IOException {
        if (!file.canRead()) {
            throw new IOException("Cannot read repository file: " + file.getAbsolutePath());
        } else if (assets == null || file.lastModified() != fileLastModified || file.length() != fileLastSize) {
            // Re-read the file if either we've never read it or it's changed length since we last read it
            assets = null;
            fileLastModified = file.lastModified();
            fileLastSize = file.length();

            idCounter = new AtomicInteger(1);
            assets = new HashMap<String, JsonObject>();
            try (JsonReader reader = Json.createReader(new FileInputStream(file))) {
                JsonArray assetList = reader.readArray();
                for (JsonValue val : assetList) {
                    String id = Integer.toString(idCounter.getAndIncrement());
                    if (val.getValueType() == ValueType.OBJECT) {
                        assets.put(id, (JsonObject) val);
                    }
                }
            }
        }

        return assets;

    }
589705
public void initialize(URI name, Configuration conf) throws IOException {
    this.conf = conf;

    Class<?> clazz = conf.getClass("fs.lookasidecache.underlyingfs.impl",
        DistributedFileSystem.class);
    if (clazz == null) {
      throw new IOException("No FileSystem for " +
                            "fs.lookasidecache.underlyingfs.impl.");
    }

    this.fs = (FileSystem)ReflectionUtils.newInstance(clazz, null);
    super.initialize(name, conf);

    // find configured cache directory
    cacheDir = conf.get("fs.lookasidecache.dir");
    if (cacheDir == null) {
      LOG.info("fs.lookasidecache.dir is not defined");
      return;
    }
    cacheDir += "/" + System.currentTimeMillis();
    cachePath = new Path(cacheDir);
    assert cachePath.isAbsolute();
    cacheURI = URI.create("file:///" + cacheDir);

    if (cacheURI == null) {
      LOG.info("fs.lookasidecache.dir is not defined");
      return;
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("CacheDir is " + cacheURI);
    }

    // create an instance of a RawLocalFileSystem to read from the cache
    cacheFs = new RawLocalFileSystem();
    cacheFs.initialize(cacheURI, conf);

    // Create the cachedir if it does not exist
    // There could be pre-exisiting files in the cachedir, do not do
    // anything to them. They will not be served by this cache, but they
    // will not be deleted by this cache either.
    cacheFs.mkdirs(cachePath);

    // create a lookaside cache
    lookasideCache = new LookasideCache(conf, this);

    // create a metrics updater object
    metrics = new LookasideMetrics();
  }
287073
private static Cache<String, Map<String, List<Object>>> initializeCache(final CachingPrincipalAttributesRepository repository) {
        val unit = TimeUnit.valueOf(StringUtils.defaultString(repository.getTimeUnit(), DEFAULT_CACHE_EXPIRATION_UNIT));
        return Caffeine.newBuilder()
            .initialCapacity(DEFAULT_MAXIMUM_CACHE_SIZE)
            .maximumSize(DEFAULT_MAXIMUM_CACHE_SIZE)
            .expireAfterWrite(repository.getExpiration(), unit)
            .build(s -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER));
    }
322991
@Override
    public void init(ServletConfig config) throws ServletException {
        LOGGER.info("Initializing filesystem resource servlet");
        super.init(config);

        final String directory = config.getInitParameter("directory");
        if (StringUtils.isNotBlank(directory)) {
            this.directory = directory;
        }

        final String absolute = config.getInitParameter("absolute");
        if (StringUtils.isNotBlank(absolute)) {
            this.absolute = BooleanUtil.valueOf(absolute);
        }
    }
864569
protected void prepareRootDir(String rootDirPath) throws IOException, RepositoryConfigurationException
   {
      this.rootDir = new File(rootDirPath);

      if (!rootDir.exists())
      {
         if (rootDir.mkdirs())
         {
            LOG.info("Value storage directory created: " + rootDir.getAbsolutePath());
            
            // create internal temp dir
            File tempDir = new File(rootDir, TEMP_DIR_NAME);
            tempDir.mkdirs();

            if (tempDir.exists() && tempDir.isDirectory())
            {
               // care about storage temp dir cleanup
               for (File tmpf : tempDir.listFiles())
                  if (!tmpf.delete())
                     LOG.warn("Storage temporary directory contains un-deletable file " + tmpf.getAbsolutePath()
                        + ". It's recommended to leave this directory for JCR External Values Storage private use.");
            }
            else
               throw new RepositoryConfigurationException("Cannot create " + TEMP_DIR_NAME
                  + " directory under External Value Storage.");
         }
         else
         {
            LOG.warn("Directory IS NOT created: " + rootDir.getAbsolutePath());
         }
      }
      else
      {
         if (!rootDir.isDirectory())
         {
            throw new RepositoryConfigurationException("File exists but is not a directory " + rootDirPath);
         }
      }
   }
319497
@Override
   public synchronized void retain() throws RepositoryException
   {
      try
      {
         if (!isRetainable())
            throw new RepositoryException("Unsupported  configuration place "
               + configurationService.getURL(param.getValue())
               + " If you want to save configuration, start repository from standalone file."
               + " Or persister-class-name not configured");

         OutputStream saveStream = null;

         if (configurationPersister != null)
         {
            saveStream = new ByteArrayOutputStream();
         }
         else
         {
            URL filePath = configurationService.getURL(param.getValue());
            final File sourceConfig = new File(filePath.toURI());
            final File backUp = new File(sourceConfig.getAbsoluteFile() + "." + indexBackupFile++);

            if (indexBackupFile > maxBackupFiles)
            {
               indexBackupFile = 1;
            }

            try
            {
               SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Void>()
               {
                  public Void run() throws IOException
                  {
                     DirectoryHelper.deleteDstAndRename(sourceConfig, backUp);
                     return null;
                  }
               });
            }
            catch (IOException ioe)
            {
               throw new RepositoryException("Can't back up configuration on path "
                  + PrivilegedFileHelper.getAbsolutePath(sourceConfig), ioe);
            }

            saveStream = PrivilegedFileHelper.fileOutputStream(sourceConfig);
         }

         IBindingFactory bfact;
         try
         {
            bfact = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<IBindingFactory>()
            {
               public IBindingFactory run() throws Exception
               {
                  return BindingDirectory.getFactory(RepositoryServiceConfiguration.class);
               }
            });
         }
         catch (PrivilegedActionException pae)
         {
            Throwable cause = pae.getCause();
            if (cause instanceof JiBXException)
            {
               throw (JiBXException)cause;
            }
            else if (cause instanceof RuntimeException)
            {
               throw (RuntimeException)cause;
            }
            else
            {
               throw new RuntimeException(cause);
            }
         }
         
         IMarshallingContext mctx = bfact.createMarshallingContext();

         mctx.marshalDocument(this, "ISO-8859-1", null, saveStream);
         saveStream.close();

         // writing configuration in to the persister
         if (configurationPersister != null)
         {
            configurationPersister.write(new ByteArrayInputStream(((ByteArrayOutputStream)saveStream).toByteArray()));
         }
      }
      catch (JiBXException e)
      {
         throw new RepositoryException(e);
      }
      catch (FileNotFoundException e)
      {
         throw new RepositoryException(e);
      }
      catch (IOException e)
      {
         throw new RepositoryException(e);
      }
      catch (RepositoryConfigurationException e)
      {
         throw new RepositoryException(e);
      }
      catch (Exception e)
      {
         throw new RepositoryException(e);
      }
   }
952835
public static void initJNI()
  {
    if (_isInitJNI.getAndSet(true)) {
      return;
    }

    // order matters because of static init and license checking
    FilesystemPath jniFilePath = JniFilePath.create();

    if (jniFilePath != null) {
      DEFAULT_SCHEME_MAP.put("file", jniFilePath);

      SchemeMap localMap = _localSchemeMap.get();
      if (localMap != null)
        localMap.put("file", jniFilePath);

      localMap = _localSchemeMap.get(ClassLoader.getSystemClassLoader());
      if (localMap != null)
        localMap.put("file", jniFilePath);

      VfsOld.PWD = jniFilePath;
      VfsOld.setPwd(jniFilePath);
    }
  }
832208
@Override
    protected void initializeImpl(Map<String,String> configuration)
    {
        //create configuration holder
        ConfigurationHolder configurationHolder=new ConfigurationHolderImpl(configuration);

        this.fileContentParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.FILE_CONTENT_PARAMETER_NAME_PROPERTY_KEY);
        if(this.fileContentParameter==null)
        {
            this.fileContentParameter="file";
        }
        this.fileNameParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.FILE_NAME_PARAMETER_NAME_PROPERTY_KEY);
        if(this.fileNameParameter==null)
        {
            this.fileNameParameter="filename";
        }
        this.priorityParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.PRIORITY_PARAMETER_NAME_PROPERTY_KEY);
        if(this.priorityParameter==null)
        {
            this.priorityParameter="priority";
        }
        this.targetAddressParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.TARGET_ADDRESS_PARAMETER_NAME_PROPERTY_KEY);
        if(this.targetAddressParameter==null)
        {
            this.targetAddressParameter="targetaddress";
        }
        this.targetNameParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.TARGET_NAME_PARAMETER_NAME_PROPERTY_KEY);
        if(this.targetNameParameter==null)
        {
            this.targetNameParameter="targetname";
        }
        this.senderNameParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.SENDER_NAME_PARAMETER_NAME_PROPERTY_KEY);
        if(this.senderNameParameter==null)
        {
            this.senderNameParameter="sendername";
        }
        this.senderFaxNumberParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.SENDER_FAX_NUMBER_PARAMETER_NAME_PROPERTY_KEY);
        if(this.senderFaxNumberParameter==null)
        {
            this.senderFaxNumberParameter="senderfaxnumber";
        }
        this.senderEMailParameter=configurationHolder.getConfigurationValue(HTTPRequestParserConfigurationConstants.SENDER_EMAIL_PARAMETER_NAME_PROPERTY_KEY);
        if(this.senderEMailParameter==null)
        {
            this.senderEMailParameter="senderemail";
        }
    }
978604
public void set(String propName, Object value) {
        if (propName.equals("repositoryId")) {
            setRepositoryId(((String) value));
        }
        if (propName.equals("repositoryCheckPoint")) {
            setRepositoryCheckPoint(((String) value));
        }
    }
489124
private Settings enrichWithLocalRepository(Settings settings) {

        // set default value if not set at all
        if (settings.getLocalRepository() == null || settings.getLocalRepository().length() == 0) {
            settings.setLocalRepository(DEFAULT_REPOSITORY_PATH);
        }

        // override any value with system property based location
        String altLocalRepository = SecurityActions.getProperty(ALT_LOCAL_REPOSITORY_LOCATION);
        if (altLocalRepository != null && altLocalRepository.length() > 0) {
            settings.setLocalRepository(altLocalRepository);
        }
        return settings;
    }
639197
public Response backupRepository( ServletContext context, 
                                      HttpServletRequest request, 
                                      String repositoryName,
                                      BackupOptions options ) throws RepositoryException {
        final File backupLocation = resolveBackupLocation(context);

        Session session = getSession(request, repositoryName, null);
        String repositoryVersion = session.getRepository().getDescriptorValue(Repository.REP_VERSION_DESC).getString().replaceAll("\\.","");
        final String backupName = "modeshape_" + repositoryVersion + "_" + repositoryName + "_backup_" + DATE_FORMAT.format(new Date());
        final File backup = new File(backupLocation, backupName);
        if (!backup.mkdirs()) {
            throw new RuntimeException("Cannot create backup folder: " + backup);
        }
        logger.debug("Backing up repository '{0}' to '{1}', using '{2}'", repositoryName, backup, options);


        RepositoryManager repositoryManager = ((org.modeshape.jcr.api.Workspace)session.getWorkspace()).getRepositoryManager();
        repositoryManager.backupRepository(backup, options);
        final String backupURL;
        try {
            backupURL = backup.toURI().toURL().toString();
        } catch (MalformedURLException e) {
            //should never happen
            throw new RuntimeException(e);
        }
        JSONAble responseContent = new JSONAble() {
            @Override
            public JSONObject toJSON() throws JSONException {
                JSONObject object = new JSONObject();
                object.put("name", backupName);
                object.put("url", backupURL);
                return object;
            }
        }; 
        return Response.status(Response.Status.CREATED).entity(responseContent).build();
    }