Ejemplo n.º 1
0
 public List<SearchFilter> getFilters() {
   if (filters != null) {
     for (SearchFilter searchFilter : filters) {
       searchFilter.setModel(super.getModel());
     }
   }
   return filters;
 }
Ejemplo n.º 2
0
  public static void main(String[] args) throws CloudException {
    CloudApp.init("cpnbzclvxjts", "67d3f4e4-97e6-4f2b-91af-d553b9160e20");
    SearchFilter filter = new SearchFilter();
    filter.exists("name");
    CloudSearch search = new CloudSearch("data", null, filter);
    search.search(
        new CloudObjectArrayCallback() {

          @Override
          public void done(CloudObject[] x, CloudException t) throws CloudException {
            // TODO Auto-generated method stub

          }
        });
  }
Ejemplo n.º 3
0
  /**
   * Process all ACIs under the "cn=config" naming context and adds them to the ACI list cache. It
   * also logs messages about the number of ACIs added to the cache. This method is called once at
   * startup. It will put the server in lockdown mode if needed.
   *
   * @throws InitializationException If there is an error searching for the ACIs in the naming
   *     context.
   */
  private void processConfigAcis() throws InitializationException {
    LinkedHashSet<String> requestAttrs = new LinkedHashSet<String>(1);
    requestAttrs.add("aci");
    LinkedList<Message> failedACIMsgs = new LinkedList<Message>();
    InternalClientConnection conn = InternalClientConnection.getRootConnection();

    ConfigHandler configBackend = DirectoryServer.getConfigHandler();
    for (DN baseDN : configBackend.getBaseDNs()) {
      try {
        if (!configBackend.entryExists(baseDN)) {
          continue;
        }
      } catch (Exception e) {
        if (debugEnabled()) {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }

        // FIXME -- Is there anything that we need to do here?
        continue;
      }

      try {
        InternalSearchOperation internalSearch =
            new InternalSearchOperation(
                conn,
                InternalClientConnection.nextOperationID(),
                InternalClientConnection.nextMessageID(),
                null,
                baseDN,
                SearchScope.WHOLE_SUBTREE,
                DereferencePolicy.NEVER_DEREF_ALIASES,
                0,
                0,
                false,
                SearchFilter.createFilterFromString("aci=*"),
                requestAttrs,
                null);
        LocalBackendSearchOperation localSearch = new LocalBackendSearchOperation(internalSearch);

        configBackend.search(localSearch);

        if (!internalSearch.getSearchEntries().isEmpty()) {
          int validAcis = aciList.addAci(internalSearch.getSearchEntries(), failedACIMsgs);
          if (!failedACIMsgs.isEmpty()) {
            aciListenerMgr.logMsgsSetLockDownMode(failedACIMsgs);
          }
          Message message =
              INFO_ACI_ADD_LIST_ACIS.get(Integer.toString(validAcis), String.valueOf(baseDN));
          logError(message);
        }
      } catch (Exception e) {
        Message message = INFO_ACI_HANDLER_FAIL_PROCESS_ACI.get();
        throw new InitializationException(message, e);
      }
    }
  }
Ejemplo n.º 4
0
  @SuppressWarnings("unchecked")
  public static SearchFilter getSearchFilter(HttpServletRequest request) {
    SearchFilter searchFilter = new SearchFilter();
    Enumeration<String> enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
      String string = enumeration.nextElement();
      if (!string.startsWith(SearchFilter.STARTPREFIX)) continue;

      String[] split = string.split(SearchFilter.SPLITTAG);
      if (split.length != 3) continue;

      SearchType searchType = SearchType.parseString(split[1]);
      String fieldName = split[2];
      String fieldValue = request.getParameter(string);
      SearchOperator searchOperator = new SearchOperator(fieldName, fieldValue, searchType);
      searchFilter.getSearchOperatorList().add(searchOperator);
    }
    return searchFilter;
  }
Ejemplo n.º 5
0
  /**
   * Indicates whether the specified entry should be included in the import based on the configured
   * set of include and exclude filters.
   *
   * @param entry The entry for which to make the determination.
   * @return <CODE>true</CODE> if the specified entry should be included in the import, or <CODE>
   *     false</CODE> if not.
   * @throws DirectoryException If there is a problem with any of the search filters used to make
   *     the determination.
   */
  public boolean includeEntry(Entry entry) throws DirectoryException {
    if (!excludeFilters.isEmpty()) {
      for (SearchFilter filter : excludeFilters) {
        if (filter.matchesEntry(entry)) {
          return false;
        }
      }
    }

    if (!includeFilters.isEmpty()) {
      for (SearchFilter filter : includeFilters) {
        if (filter.matchesEntry(entry)) {
          return true;
        }
      }

      return false;
    }

    return true;
  }
  /**
   * Tests performing an internal search using the VLV control to retrieve a subset of the entries
   * using an assertion value that is after all values in the list.
   *
   * @throws Exception If an unexpected problem occurred.
   */
  @Test()
  public void testInternalSearchByValueAfterAll() throws Exception {
    populateDB();

    InternalClientConnection conn = InternalClientConnection.getRootConnection();

    ArrayList<Control> requestControls = new ArrayList<Control>();
    requestControls.add(new ServerSideSortRequestControl("sn"));
    requestControls.add(new VLVRequestControl(0, 3, ByteString.valueOf("zz")));

    InternalSearchOperation internalSearch =
        new InternalSearchOperation(
            conn,
            InternalClientConnection.nextOperationID(),
            InternalClientConnection.nextMessageID(),
            requestControls,
            DN.decode("dc=example,dc=com"),
            SearchScope.WHOLE_SUBTREE,
            DereferencePolicy.NEVER_DEREF_ALIASES,
            0,
            0,
            false,
            SearchFilter.createFilterFromString("(objectClass=person)"),
            null,
            null);

    internalSearch.run();

    // It will be successful because the control isn't critical.
    assertEquals(internalSearch.getResultCode(), ResultCode.SUCCESS);

    List<Control> responseControls = internalSearch.getResponseControls();
    assertNotNull(responseControls);

    VLVResponseControl vlvResponse = null;
    for (Control c : responseControls) {
      if (c.getOID().equals(OID_VLV_RESPONSE_CONTROL)) {
        if (c instanceof LDAPControl) {
          vlvResponse =
              VLVResponseControl.DECODER.decode(c.isCritical(), ((LDAPControl) c).getValue());
        } else {
          vlvResponse = (VLVResponseControl) c;
        }
      }
    }

    assertNotNull(vlvResponse);
    assertEquals(vlvResponse.getVLVResultCode(), LDAPResultCode.SUCCESS);
    assertEquals(vlvResponse.getTargetPosition(), 10);
    assertEquals(vlvResponse.getContentCount(), 9);
  }
Ejemplo n.º 7
0
 /**
  * Test the attribute types of the search filter for access. This method supports the search
  * right.
  *
  * @param container The container used in the access evaluation.
  * @param filter The filter to check access on.
  * @return True if all attribute types in the filter have access.
  * @throws DirectoryException If there is a problem matching the entry using the provided filter.
  */
 private boolean testFilter(AciLDAPOperationContainer container, SearchFilter filter)
     throws DirectoryException {
   boolean ret = true;
   // If the resource entry has a dn equal to "cn=debugsearch" and it
   // contains the special attribute type "debugsearchindex", then the
   // resource entry is a pseudo entry created for debug purposes.
   // Return true if that is the case.
   if (debugSearchIndexDN.equals(container.getResourceDN())
       && container.getResourceEntry().hasAttribute(debugSearchIndex)) {
     return true;
   }
   switch (filter.getFilterType()) {
     case AND:
     case OR:
       {
         for (SearchFilter f : filter.getFilterComponents()) {
           if (!testFilter(container, f)) {
             return false;
           }
         }
         break;
       }
     case NOT:
       {
         SearchFilter f = filter.getNotComponent();
         ret = testFilter(container, f);
         break;
       }
     default:
       {
         AttributeType attrType = filter.getAttributeType();
         container.setCurrentAttributeType(attrType);
         ret = accessAllowed(container);
       }
   }
   return ret;
 }
Ejemplo n.º 8
0
  /** * Force an update of the results */
  public void updateResults() {
    resultList.clear();
    int count = 0;
    for (int x = 0; x < searchables.size(); x++) {
      SearchResult searchable = searchables.get(x);

      if (mSearchFilter.onFilter(searchable, getSearchText()) && count < 5) {
        addResult(searchable);
        count++;
      }
    }
    if (resultList.size() == 0) {
      results.setVisibility(View.GONE);
    } else {
      results.setVisibility(View.VISIBLE);
    }
  }
Ejemplo n.º 9
0
  protected void search(View view, final int offset) {
    String query = etSearchBox.getText().toString();
    if (!query.isEmpty()) {
      AsyncHttpClient client = new AsyncHttpClient();
      String request =
          "https://ajax.googleapis.com/ajax/services/search/images?rsz=8&start="
              + offset
              + "&v=1.0&q="
              + Uri.encode(query)
              + filter.toString();
      client.get(
          request,
          new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject response) {
              try {
                JSONArray jsonArray = null;
                jsonArray = response.getJSONObject("responseData").getJSONArray("results");
                if (offset == 0) {
                  imageResults.clear();
                }
                imageResults.addAll(ImageResult.fromJSONArray(jsonArray));
                imageAdapter.addAll(imageResults);
              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onFailure(
                int statusCode, java.lang.Throwable e, org.json.JSONObject errorResponse) {
              Log.d(this.toString(), statusCode + " " + errorResponse.toString());
            }
          });
    }
  }
  /**
   * Handles any controls contained in the request.
   *
   * @throws DirectoryException If there is a problem with any of the request controls.
   */
  private void handleRequestControls() throws DirectoryException {
    LocalBackendWorkflowElement.removeAllDisallowedControls(baseDN, this);

    List<Control> requestControls = getRequestControls();
    if (requestControls != null && !requestControls.isEmpty()) {
      for (Control c : requestControls) {
        String oid = c.getOID();

        if (OID_LDAP_ASSERTION.equals(oid)) {
          LDAPAssertionRequestControl assertControl =
              getRequestControl(LDAPAssertionRequestControl.DECODER);

          SearchFilter assertionFilter;
          try {
            assertionFilter = assertControl.getSearchFilter();
          } catch (DirectoryException de) {
            if (debugEnabled()) {
              TRACER.debugCaught(DebugLogLevel.ERROR, de);
            }

            throw new DirectoryException(
                de.getResultCode(),
                ERR_SEARCH_CANNOT_PROCESS_ASSERTION_FILTER.get(de.getMessageObject()),
                de);
          }

          Entry entry;
          try {
            entry = DirectoryServer.getEntry(baseDN);
          } catch (DirectoryException de) {
            if (debugEnabled()) {
              TRACER.debugCaught(DebugLogLevel.ERROR, de);
            }

            throw new DirectoryException(
                de.getResultCode(),
                ERR_SEARCH_CANNOT_GET_ENTRY_FOR_ASSERTION.get(de.getMessageObject()));
          }

          if (entry == null) {
            throw new DirectoryException(
                ResultCode.NO_SUCH_OBJECT, ERR_SEARCH_NO_SUCH_ENTRY_FOR_ASSERTION.get());
          }

          // Check if the current user has permission to make
          // this determination.
          if (!AccessControlConfigManager.getInstance()
              .getAccessControlHandler()
              .isAllowed(this, entry, assertionFilter)) {
            throw new DirectoryException(
                ResultCode.INSUFFICIENT_ACCESS_RIGHTS,
                ERR_CONTROL_INSUFFICIENT_ACCESS_RIGHTS.get(oid));
          }

          try {
            if (!assertionFilter.matchesEntry(entry)) {
              throw new DirectoryException(
                  ResultCode.ASSERTION_FAILED, ERR_SEARCH_ASSERTION_FAILED.get());
            }
          } catch (DirectoryException de) {
            if (de.getResultCode() == ResultCode.ASSERTION_FAILED) {
              throw de;
            }

            if (debugEnabled()) {
              TRACER.debugCaught(DebugLogLevel.ERROR, de);
            }

            throw new DirectoryException(
                de.getResultCode(),
                ERR_SEARCH_CANNOT_PROCESS_ASSERTION_FILTER.get(de.getMessageObject()),
                de);
          }
        } else if (OID_PROXIED_AUTH_V1.equals(oid)) {
          // Log usage of legacy proxy authz V1 control.
          addAdditionalLogItem(
              AdditionalLogItem.keyOnly(getClass(), "obsoleteProxiedAuthzV1Control"));

          // The requester must have the PROXIED_AUTH privilege in order to be
          // able to use this control.
          if (!clientConnection.hasPrivilege(Privilege.PROXIED_AUTH, this)) {
            throw new DirectoryException(
                ResultCode.AUTHORIZATION_DENIED, ERR_PROXYAUTH_INSUFFICIENT_PRIVILEGES.get());
          }

          ProxiedAuthV1Control proxyControl = getRequestControl(ProxiedAuthV1Control.DECODER);

          Entry authorizationEntry = proxyControl.getAuthorizationEntry();
          setAuthorizationEntry(authorizationEntry);
          setProxiedAuthorizationDN(getDN(authorizationEntry));
        } else if (OID_PROXIED_AUTH_V2.equals(oid)) {
          // The requester must have the PROXIED_AUTH privilege in order to be
          // able to use this control.
          if (!clientConnection.hasPrivilege(Privilege.PROXIED_AUTH, this)) {
            throw new DirectoryException(
                ResultCode.AUTHORIZATION_DENIED, ERR_PROXYAUTH_INSUFFICIENT_PRIVILEGES.get());
          }

          ProxiedAuthV2Control proxyControl = getRequestControl(ProxiedAuthV2Control.DECODER);

          Entry authorizationEntry = proxyControl.getAuthorizationEntry();
          setAuthorizationEntry(authorizationEntry);
          setProxiedAuthorizationDN(getDN(authorizationEntry));
        } else if (OID_PERSISTENT_SEARCH.equals(oid)) {
          final PersistentSearchControl ctrl = getRequestControl(PersistentSearchControl.DECODER);

          persistentSearch =
              new PersistentSearch(
                  this, ctrl.getChangeTypes(), ctrl.getChangesOnly(), ctrl.getReturnECs());
        } else if (OID_LDAP_SUBENTRIES.equals(oid)) {
          SubentriesControl subentriesControl = getRequestControl(SubentriesControl.DECODER);
          setReturnSubentriesOnly(subentriesControl.getVisibility());
        } else if (OID_LDUP_SUBENTRIES.equals(oid)) {
          // Support for legacy draft-ietf-ldup-subentry.
          addAdditionalLogItem(AdditionalLogItem.keyOnly(getClass(), "obsoleteSubentryControl"));

          setReturnSubentriesOnly(true);
        } else if (OID_MATCHED_VALUES.equals(oid)) {
          MatchedValuesControl matchedValuesControl =
              getRequestControl(MatchedValuesControl.DECODER);
          setMatchedValuesControl(matchedValuesControl);
        } else if (OID_ACCOUNT_USABLE_CONTROL.equals(oid)) {
          setIncludeUsableControl(true);
        } else if (OID_REAL_ATTRS_ONLY.equals(oid)) {
          setRealAttributesOnly(true);
        } else if (OID_VIRTUAL_ATTRS_ONLY.equals(oid)) {
          setVirtualAttributesOnly(true);
        } else if (OID_GET_EFFECTIVE_RIGHTS.equals(oid)
            && DirectoryServer.isSupportedControl(OID_GET_EFFECTIVE_RIGHTS)) {
          // Do nothing here and let AciHandler deal with it.
        }
        // NYI -- Add support for additional controls.

        else if (c.isCritical() && !backendSupportsControl(oid)) {
          throw new DirectoryException(
              ResultCode.UNAVAILABLE_CRITICAL_EXTENSION,
              ERR_SEARCH_UNSUPPORTED_CRITICAL_CONTROL.get(oid));
        }
      }
    }
  }
Ejemplo n.º 11
0
  /** {@inheritDoc} */
  @Override
  public void search(SearchOperation searchOperation) throws DirectoryException {
    // Get the base entry for the search, if possible.  If it doesn't exist,
    // then this will throw an exception.
    DN baseDN = searchOperation.getBaseDN();
    Entry baseEntry = getEntry(baseDN);

    // Look at the base DN and see if it's the backup base DN, a backup
    // directory entry DN, or a backup entry DN.
    DN parentDN;
    SearchScope scope = searchOperation.getScope();
    SearchFilter filter = searchOperation.getFilter();
    if (backupBaseDN.equals(baseDN)) {
      if ((scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE)
          && filter.matchesEntry(baseEntry)) {
        searchOperation.returnEntry(baseEntry, null);
      }

      if (scope != SearchScope.BASE_OBJECT && !backupDirectories.isEmpty()) {
        AttributeType backupPathType =
            DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
        for (File f : backupDirectories) {
          // Check to see if the descriptor file exists.  If not, then skip this
          // backup directory.
          File descriptorFile = new File(f, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
          if (!descriptorFile.exists()) {
            continue;
          }

          DN backupDirDN = makeChildDN(backupBaseDN, backupPathType, f.getAbsolutePath());

          Entry backupDirEntry;
          try {
            backupDirEntry = getBackupDirectoryEntry(backupDirDN);
          } catch (Exception e) {
            if (debugEnabled()) {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }

            continue;
          }

          if (filter.matchesEntry(backupDirEntry)) {
            searchOperation.returnEntry(backupDirEntry, null);
          }

          if (scope != SearchScope.SINGLE_LEVEL) {
            List<Attribute> attrList = backupDirEntry.getAttribute(backupPathType);
            if (attrList != null && !attrList.isEmpty()) {
              for (AttributeValue v : attrList.get(0)) {
                try {
                  BackupDirectory backupDirectory =
                      BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
                  AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
                  for (String backupID : backupDirectory.getBackups().keySet()) {
                    DN backupEntryDN = makeChildDN(backupDirDN, idType, backupID);
                    Entry backupEntry = getBackupEntry(backupEntryDN);
                    if (filter.matchesEntry(backupEntry)) {
                      searchOperation.returnEntry(backupEntry, null);
                    }
                  }
                } catch (Exception e) {
                  if (debugEnabled()) {
                    TRACER.debugCaught(DebugLogLevel.ERROR, e);
                  }

                  continue;
                }
              }
            }
          }
        }
      }
    } else if (backupBaseDN.equals(parentDN = baseDN.getParentDNInSuffix())) {
      Entry backupDirEntry = getBackupDirectoryEntry(baseDN);

      if ((scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE)
          && filter.matchesEntry(backupDirEntry)) {
        searchOperation.returnEntry(backupDirEntry, null);
      }

      if (scope != SearchScope.BASE_OBJECT) {
        AttributeType t = DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
        List<Attribute> attrList = backupDirEntry.getAttribute(t);
        if (attrList != null && !attrList.isEmpty()) {
          for (AttributeValue v : attrList.get(0)) {
            try {
              BackupDirectory backupDirectory =
                  BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
              AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
              for (String backupID : backupDirectory.getBackups().keySet()) {
                DN backupEntryDN = makeChildDN(baseDN, idType, backupID);
                Entry backupEntry = getBackupEntry(backupEntryDN);
                if (filter.matchesEntry(backupEntry)) {
                  searchOperation.returnEntry(backupEntry, null);
                }
              }
            } catch (Exception e) {
              if (debugEnabled()) {
                TRACER.debugCaught(DebugLogLevel.ERROR, e);
              }

              continue;
            }
          }
        }
      }
    } else {
      if (parentDN == null || !backupBaseDN.equals(parentDN.getParentDNInSuffix())) {
        Message message = ERR_BACKUP_NO_SUCH_ENTRY.get(String.valueOf(backupBaseDN));
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
      }

      if (scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE) {
        Entry backupEntry = getBackupEntry(baseDN);
        if (backupEntry == null) {
          Message message = ERR_BACKUP_NO_SUCH_ENTRY.get(String.valueOf(backupBaseDN));
          throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
        }

        if (filter.matchesEntry(backupEntry)) {
          searchOperation.returnEntry(backupEntry, null);
        }
      }
    }
  }
  @Test(enabled = true)
  public void testValidRequest() throws Exception {
    final CryptoManagerImpl cm = DirectoryServer.getCryptoManager();
    final String secretMessage = "zyxwvutsrqponmlkjihgfedcba";
    final String cipherTransformationName = "AES/CBC/PKCS5Padding";
    final int cipherKeyLength = 128;

    CryptoManagerImpl.publishInstanceKeyEntryInADS();

    // Initial encryption ensures a cipher key entry is in ADS.
    cm.encrypt(cipherTransformationName, cipherKeyLength, secretMessage.getBytes());

    // Retrieve all uncompromised cipher key entries corresponding to the
    // specified transformation and key length.
    final String baseDNStr // TODO: is this DN defined elsewhere as a constant?
        = "cn=secret keys," + ADSContext.getAdministrationSuffixDN();
    final DN baseDN = DN.decode(baseDNStr);
    final String FILTER_OC_INSTANCE_KEY =
        new StringBuilder("(objectclass=")
            .append(ConfigConstants.OC_CRYPTO_CIPHER_KEY)
            .append(")")
            .toString();
    final String FILTER_NOT_COMPROMISED =
        new StringBuilder("(!(")
            .append(ConfigConstants.ATTR_CRYPTO_KEY_COMPROMISED_TIME)
            .append("=*))")
            .toString();
    final String FILTER_CIPHER_TRANSFORMATION_NAME =
        new StringBuilder("(")
            .append(ConfigConstants.ATTR_CRYPTO_CIPHER_TRANSFORMATION_NAME)
            .append("=")
            .append(cipherTransformationName)
            .append(")")
            .toString();
    final String FILTER_CIPHER_KEY_LENGTH =
        new StringBuilder("(")
            .append(ConfigConstants.ATTR_CRYPTO_KEY_LENGTH_BITS)
            .append("=")
            .append(String.valueOf(cipherKeyLength))
            .append(")")
            .toString();
    final String searchFilter =
        new StringBuilder("(&")
            .append(FILTER_OC_INSTANCE_KEY)
            .append(FILTER_NOT_COMPROMISED)
            .append(FILTER_CIPHER_TRANSFORMATION_NAME)
            .append(FILTER_CIPHER_KEY_LENGTH)
            .append(")")
            .toString();
    final LinkedHashSet<String> requestedAttributes = new LinkedHashSet<String>();
    requestedAttributes.add(ConfigConstants.ATTR_CRYPTO_SYMMETRIC_KEY);
    final InternalClientConnection icc = InternalClientConnection.getRootConnection();
    InternalSearchOperation searchOp =
        icc.processSearch(
            baseDN,
            SearchScope.SINGLE_LEVEL,
            DereferencePolicy.NEVER_DEREF_ALIASES,
            /* size limit */ 0, /* time limit */
            0,
            /* types only */ false,
            SearchFilter.createFilterFromString(searchFilter),
            requestedAttributes);
    assertTrue(0 < searchOp.getSearchEntries().size());

    final InternalClientConnection internalConnection =
        InternalClientConnection.getRootConnection();
    final String instanceKeyID = cm.getInstanceKeyID();
    final AttributeType attrSymmetricKey =
        DirectoryServer.getAttributeType(ConfigConstants.ATTR_CRYPTO_SYMMETRIC_KEY);
    for (Entry e : searchOp.getSearchEntries()) {
      final String symmetricKeyAttributeValue =
          e.getAttributeValue(attrSymmetricKey, DirectoryStringSyntax.DECODER);
      final ByteString requestValue =
          GetSymmetricKeyExtendedOperation.encodeRequestValue(
              symmetricKeyAttributeValue, instanceKeyID);
      final ExtendedOperation extendedOperation =
          internalConnection.processExtendedOperation(
              ServerConstants.OID_GET_SYMMETRIC_KEY_EXTENDED_OP, requestValue);
      assertEquals(extendedOperation.getResultCode(), ResultCode.SUCCESS);
      // The key should be re-wrapped, and hence have a different binary
      // representation....
      final String responseValue = extendedOperation.getResponseValue().toString();
      assertFalse(symmetricKeyAttributeValue.equals(responseValue));
      // ... but the keyIDs should be equal (ideally, the validity of
      // the returned value would be checked by decoding the
      // returned ds-cfg-symmetric-key attribute value; however, there
      // is no non-private method to call.
      assertEquals(responseValue.split(":")[0], symmetricKeyAttributeValue.split(":")[0]);
    }
  }
Ejemplo n.º 13
0
	/**
	 * 创建动态查询条件组合.
	 * @param userId
	 * @param searchParams
	 * @return
	 */
	private Specification<Task> buildSpecification(Long userId, Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId));
		Specification<Task> spec = DynamicSpecifications.bySearchFilter(filters.values(), Task.class);
		return spec;
	}
  /**
   * Tests performing an internal search using the VLV control with a start start position beyond
   * the end of the result set.
   *
   * @throws Exception If an unexpected problem occurred.
   */
  @Test()
  public void testInternalSearchByOffsetStartPositionTooHigh() throws Exception {
    populateDB();

    InternalClientConnection conn = InternalClientConnection.getRootConnection();

    ArrayList<Control> requestControls = new ArrayList<Control>();
    requestControls.add(new ServerSideSortRequestControl("givenName"));
    requestControls.add(new VLVRequestControl(3, 3, 30, 0));

    InternalSearchOperation internalSearch =
        new InternalSearchOperation(
            conn,
            InternalClientConnection.nextOperationID(),
            InternalClientConnection.nextMessageID(),
            requestControls,
            DN.decode("dc=example,dc=com"),
            SearchScope.WHOLE_SUBTREE,
            DereferencePolicy.NEVER_DEREF_ALIASES,
            0,
            0,
            false,
            SearchFilter.createFilterFromString("(objectClass=person)"),
            null,
            null);

    internalSearch.run();

    assertEquals(internalSearch.getResultCode(), ResultCode.SUCCESS);

    ArrayList<DN> expectedDNOrder = new ArrayList<DN>();
    expectedDNOrder.add(maryJonesDN); // Mary
    expectedDNOrder.add(samZweckDN); // Sam
    expectedDNOrder.add(zorroDN); // No first name

    ArrayList<DN> returnedDNOrder = new ArrayList<DN>();
    for (Entry e : internalSearch.getSearchEntries()) {
      returnedDNOrder.add(e.getDN());
    }

    assertEquals(returnedDNOrder, expectedDNOrder);

    List<Control> responseControls = internalSearch.getResponseControls();
    assertNotNull(responseControls);

    VLVResponseControl vlvResponse = null;
    for (Control c : responseControls) {
      if (c.getOID().equals(OID_VLV_RESPONSE_CONTROL)) {
        if (c instanceof LDAPControl) {
          vlvResponse =
              VLVResponseControl.DECODER.decode(c.isCritical(), ((LDAPControl) c).getValue());
        } else {
          vlvResponse = (VLVResponseControl) c;
        }
      }
    }

    assertNotNull(vlvResponse);
    assertEquals(vlvResponse.getVLVResultCode(), LDAPResultCode.SUCCESS);
    assertEquals(vlvResponse.getTargetPosition(), 10);
    assertEquals(vlvResponse.getContentCount(), 9);
  }
  /**
   * Retrieves a set of virtual attribute rules that may be used for testing purposes. The return
   * data will also include a Boolean value indicating whether the rule would apply to a minimal
   * "o=test" entry.
   *
   * @return A set of virtual attribute rules that may be used for testing purposes.
   * @throws Exception If an unexpected problem occurs.
   */
  @DataProvider(name = "testRules")
  public Object[][] getVirtualAttributeRules() throws Exception {
    EntryDNVirtualAttributeProvider provider = new EntryDNVirtualAttributeProvider();

    LinkedHashSet<DN> dnSet1 = new LinkedHashSet<DN>(1);
    dnSet1.add(DN.decode("o=test"));

    LinkedHashSet<DN> dnSet2 = new LinkedHashSet<DN>(1);
    dnSet2.add(DN.decode("dc=example,dc=com"));

    LinkedHashSet<DN> dnSet3 = new LinkedHashSet<DN>(2);
    dnSet3.add(DN.decode("o=test"));
    dnSet3.add(DN.decode("dc=example,dc=com"));

    LinkedHashSet<DN> groupSet1 = new LinkedHashSet<DN>(1);
    groupSet1.add(DN.decode("cn=Test Group,o=test"));

    LinkedHashSet<DN> groupSet2 = new LinkedHashSet<DN>(1);
    groupSet2.add(DN.decode("cn=Example Group,o=test"));

    LinkedHashSet<DN> groupSet3 = new LinkedHashSet<DN>(2);
    groupSet3.add(DN.decode("cn=Test Group,o=test"));
    groupSet3.add(DN.decode("cn=Example Group,o=test"));

    LinkedHashSet<SearchFilter> filterSet1 = new LinkedHashSet<SearchFilter>(1);
    filterSet1.add(SearchFilter.createFilterFromString("(objectClass=*)"));

    LinkedHashSet<SearchFilter> filterSet2 = new LinkedHashSet<SearchFilter>(1);
    filterSet2.add(SearchFilter.createFilterFromString("(o=test)"));

    LinkedHashSet<SearchFilter> filterSet3 = new LinkedHashSet<SearchFilter>(1);
    filterSet3.add(SearchFilter.createFilterFromString("(foo=bar)"));

    LinkedHashSet<SearchFilter> filterSet4 = new LinkedHashSet<SearchFilter>(2);
    filterSet4.add(SearchFilter.createFilterFromString("(o=test)"));
    filterSet4.add(SearchFilter.createFilterFromString("(foo=bar)"));

    return new Object[][] {
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            dnSet1,
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            dnSet2,
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        false
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            dnSet3,
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            groupSet1,
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            groupSet2,
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        false
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            groupSet3,
            Collections.<SearchFilter>emptySet(),
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            filterSet1,
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            filterSet2,
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            filterSet3,
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        false
      },
      new Object[] {
        new VirtualAttributeRule(
            entryDNType,
            provider,
            Collections.<DN>emptySet(),
            SearchScope.WHOLE_SUBTREE,
            Collections.<DN>emptySet(),
            filterSet4,
            ConflictBehavior.VIRTUAL_OVERRIDES_REAL),
        true
      },
    };
  }
  /**
   * Tests performing an internal search using the VLV control to retrieve a subset of the entries
   * using an assertion value before any actual value in the list.
   *
   * @throws Exception If an unexpected problem occurred.
   */
  @Test()
  public void testInternalSearchByValueBeforeAll() throws Exception {
    populateDB();

    InternalClientConnection conn = InternalClientConnection.getRootConnection();

    ArrayList<Control> requestControls = new ArrayList<Control>();
    requestControls.add(new ServerSideSortRequestControl("givenName"));
    requestControls.add(new VLVRequestControl(0, 3, ByteString.valueOf("a")));

    InternalSearchOperation internalSearch =
        new InternalSearchOperation(
            conn,
            InternalClientConnection.nextOperationID(),
            InternalClientConnection.nextMessageID(),
            requestControls,
            DN.decode("dc=example,dc=com"),
            SearchScope.WHOLE_SUBTREE,
            DereferencePolicy.NEVER_DEREF_ALIASES,
            0,
            0,
            false,
            SearchFilter.createFilterFromString("(objectClass=person)"),
            null,
            null);

    internalSearch.run();
    assertEquals(internalSearch.getResultCode(), ResultCode.SUCCESS);

    ArrayList<DN> expectedDNOrder = new ArrayList<DN>();
    expectedDNOrder.add(aaccfJohnsonDN); // Aaccf
    expectedDNOrder.add(aaronZimmermanDN); // Aaron
    expectedDNOrder.add(albertZimmermanDN); // Albert, lower entry ID
    expectedDNOrder.add(albertSmithDN); // Albert, higher entry ID

    ArrayList<DN> returnedDNOrder = new ArrayList<DN>();
    for (Entry e : internalSearch.getSearchEntries()) {
      returnedDNOrder.add(e.getDN());
    }

    assertEquals(returnedDNOrder, expectedDNOrder);

    List<Control> responseControls = internalSearch.getResponseControls();
    assertNotNull(responseControls);
    assertEquals(responseControls.size(), 2);

    ServerSideSortResponseControl sortResponse = null;
    VLVResponseControl vlvResponse = null;
    for (Control c : responseControls) {
      if (c.getOID().equals(OID_SERVER_SIDE_SORT_RESPONSE_CONTROL)) {
        if (c instanceof LDAPControl) {
          sortResponse =
              ServerSideSortResponseControl.DECODER.decode(
                  c.isCritical(), ((LDAPControl) c).getValue());
        } else {
          sortResponse = (ServerSideSortResponseControl) c;
        }
      } else if (c.getOID().equals(OID_VLV_RESPONSE_CONTROL)) {
        if (c instanceof LDAPControl) {
          vlvResponse =
              VLVResponseControl.DECODER.decode(c.isCritical(), ((LDAPControl) c).getValue());
        } else {
          vlvResponse = (VLVResponseControl) c;
        }
      } else {
        fail("Response control with unexpected OID " + c.getOID());
      }
    }

    assertNotNull(sortResponse);
    assertEquals(sortResponse.getResultCode(), 0);

    assertNotNull(vlvResponse);
    assertEquals(vlvResponse.getVLVResultCode(), 0);
    assertEquals(vlvResponse.getTargetPosition(), 1);
    assertEquals(vlvResponse.getContentCount(), 9);
  }
Ejemplo n.º 17
0
	/**
	 * 创建动态查询条件组合.
	 * @param roleId
	 * @param searchParams
	 * @return
	 */
	private Specification<Role> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<Role> spec = DynamicSpecifications.bySearchFilter(filters.values(), Role.class);
		return spec;
	}