Пример #1
0
  public void reloadPolicies()
      throws DataAdapterException, CacheSizeExceedCapacityException, PolicySyntaxException,
          BuiltInFunctionNotFoundException {
    System.out.println("Reloading policies ...");
    try {
      // update status
      status.updateProperty(KEY_RUN_STATUS, STATUS_RUN_RELOADPOLICY);

      cacheMgr.policyCache.writeLock();
      // clear both result and policy cache
      cacheMgr.removeAll();
      // reload all policies
      loadPolicies();
      if (logger.isDebugEnabled()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        cacheMgr.policyCache.dump(out);
        logger.debug(
            "=================Dump all Cacheables that current in Policy Cache=================");
        logger.debug(
            "\nCurrent non-indexed empty target cache size = "
                + cacheMgr.policyCache.emptyTargetCache.size()
                + ".\n"
                + cacheMgr.policyCache.emptyTargetCache
                + "\n"
                + out.toString());
        logger.debug(
            "=====================================Done=========================================");
      }
    } finally {
      cacheMgr.policyCache.writeUnlock();
      status.updateProperty(KEY_RUN_STATUS, STATUS_RUN_RUNING);
    }
  }
Пример #2
0
 /**
  * Initialize the PDP, load policies and cache them, and other things.
  *
  * @throws CacheSizeExceedCapacityException
  * @throws DataAdapterException
  * @throws PolicySyntaxException
  * @throws ClassNotFoundException
  * @throws IOException
  * @throws BuiltInFunctionExistsException
  * @throws BuiltInFunctionNotFoundException
  */
 protected void startPDP()
     throws CacheSizeExceedCapacityException, DataAdapterException, PolicySyntaxException,
         IOException, ClassNotFoundException, BuiltInFunctionExistsException,
         BuiltInFunctionNotFoundException {
   // load all functions
   funcReg = BuiltInFunctionRegistry.getInstance();
   // load all policies
   loadPolicies();
   if (logger.isDebugEnabled()) {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     cacheMgr.policyCache.dump(out);
     logger.debug(
         "=================Dump all Cacheables that current in Policy Cache=================");
     logger.debug(
         "\nCurrent non-indexed empty target cache size = "
             + cacheMgr.policyCache.emptyTargetCache.size()
             + ".\n"
             + cacheMgr.policyCache.emptyTargetCache
             + "\n"
             + out.toString());
     logger.debug(
         "=====================================Done=========================================");
   }
   // update status
   status.updateProperty(KEY_RUN_STATUS, STATUS_RUN_RUNING);
 }
Пример #3
0
  /**
   * Load all policies from a specific path, return an Iterator of DataAdapter, caller may call
   * DataAdapter.getEngineElement method to get the corresponding engine element which is going to
   * be evaluated.
   *
   * @throws ConfigurationException
   */
  public DataAdapter[] load() throws DataAdapterException {
    try {
      policyFilesByID.clear();
      Vector<DataAdapter> adapters = new Vector<DataAdapter>();
      File dir = new File(path);

      if (dir.isDirectory()) {
        File[] policyFiles =
            dir.listFiles(
                new FilenameFilter() {
                  public boolean accept(File dir, String name) {
                    if (pattern == null || pattern.length() == 0) {
                      return true;
                    } else {
                      return name.matches(pattern);
                    }
                  }
                });

        System.out.println("Loading policies from '" + dir.toString() + "' ...");
        System.out.println("nbre de fichier =" + policyFiles.length);
        PDP currentPDP = DataStoreHelper.getPDP(this);
        // Retrieve the schema file from given path or classpath, and verify if it exists.
        String defaultSchema = null;
        try {
          defaultSchema = verifySchemaFile(getPolicyDefaultSchema());
        } catch (ConfigurationException ce) {
          System.err.println("Erreur1 sur schéma xacml " + ce.toString());
          throw new DataAdapterException(ce.toString(), ce);
        } catch (XMLGeneralException xe) {
          System.err.println("Erreur1 sur schéma xacml " + xe.toString());
          throw new DataAdapterException(xe.toString(), xe);
        }
        InputStream in = null;
        int actualPolicyNum = 0;
        boolean warn = false;
        boolean error = false;

        System.gc();
        long memBegin = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        long begin = System.currentTimeMillis();
        System.out.println("boucle des fichiers schema=" + defaultSchema);
        for (int i = 0; i < policyFiles.length; i++) {
          try {
            in = new FileInputStream(policyFiles[i]);
            Element root = parse(in, defaultSchema);
            // check if there are duplicated policy IDs in different files
            URI policyId = getPolicyOrPolicySetId(root);
            if (policyFilesByID.get(policyId) != null) {
              throw new DataAdapterException(
                  "The policy loaded from '"
                      + policyFiles[i]
                      + "' with ID<"
                      + policyId
                      + "> already exists.");
            }

            // This is used to build up a URI->Policy File index. The index will be used in
            // load(URI[])
            // method.
            policyFilesByID.put(policyId, policyFiles[i]);
            DataAdapter da = createPolicyDataAdapterFromXMLElement(root);
            // We may use configuration of PDP in engine element.
            ((AbstractPolicy) da.getEngineElement()).setOwnerPDP(currentPDP);
            adapters.add(da);

            // 10 policies one dot, 1000 policies one line
            actualPolicyNum++;

            if (actualPolicyNum % 10 == 0) {
              System.out.print(".");
            }
            if (actualPolicyNum % 1000 == 0 && i < policyFiles.length - 1) {
              System.out.println();
            }

            // Check if loaded policy is correct
            if (logger.isDebugEnabled()) {
              try {
                // Create a new dataAdapter, do not use the loaded one, since it holds the original
                // XML element. We should use the one data adapter generated.
                XACMLElement engineElem = da.getEngineElement();
                Constructor<?> cons = da.getClass().getConstructor(XACMLElement.class);
                DataAdapter daGenFromEngineElem = (DataAdapter) cons.newInstance(engineElem);
                logger.debug(
                    "Dump policy loaded from '"
                        + policyFiles[i]
                        + "': "
                        + getNodeXMLText((Element) daGenFromEngineElem.getDataStoreObject()));
              } catch (Exception debugEx) {
                logger.debug("Dump policy failed due to: ", debugEx);
              }
            }
          } catch (Exception e) {
            if (e instanceof XMLGeneralException || e instanceof PolicySyntaxException) {
              logger.warn(
                  "Could not load file '"
                      + policyFiles[i]
                      + "' since it should not be a valid policy file.",
                  e);
              warn = true;
            } else if (e instanceof DataAdapterException) {
              throw e;
            } else {
              logger.error("Error occurs when parsing policy file : " + policyFiles[i], e);
              error = true;
            }
          } finally {
            try {
              in.close();
            } catch (Exception ex) {
            }
          }
        }

        // Print some hints
        if (actualPolicyNum > 0) {
          long end = System.currentTimeMillis();
          System.gc();
          long memEnd = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

          System.out.println(
              "\n"
                  + actualPolicyNum
                  + " policies loaded. "
                  + "Time elapsed "
                  + (end - begin) / 1000
                  + " second. "
                  + "Memory used "
                  + (memEnd - memBegin) / 1024 / 1024
                  + " MB.");
          if (error || warn) {
            System.out.println(
                "There are "
                    + (error ? "errors" : "warnings")
                    + " occur while loading policies, please check log file for details.");
          }
        }
      }
      return adapters.toArray(new DataAdapter[0]);
    } catch (DataAdapterException daEx) {
      throw daEx;
    } catch (Exception ex) {
      throw new DataAdapterException("Failed to get default policy schema from configuration.", ex);
    }
  }