コード例 #1
0
ファイル: JpaBaseDao.java プロジェクト: GladiusK/unitwork
  /**
   * 按SQL分页查询对象列表.
   *
   * @param values 命名参数,按名称绑定.
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public <X> SearchResult<X> findPageWithNameParamByNativeSQL(
      final int firstResult, final int maxResult, final String sql, final Map<String, ?> values) {

    SearchResult searResult = new SearchResult();

    List<Object[]> objectList =
        createNativeQueryWithNameParam(sql, values)
            .setFirstResult(firstResult)
            .setMaxResults(maxResult)
            .getResultList();
    String databaseType = DialectUtils.getDataBaseType(smartDataSource.getDataSource());
    if (databaseType.equals("db2")) {
      List<Object[]> newobjectList = new ArrayList();
      for (Object[] object : objectList) {
        Object[] newobject = new Object[object.length - 1];
        for (int i = 0; i < object.length - 1; i++) {
          newobject[i] = object[i + 1];
        }
        newobjectList.add(newobject);
      }
      objectList = newobjectList;
    }

    // 查询记录总数
    String countSql = SQLUtils.buildCountSQL(sql);
    Object totalCount = createNativeQueryWithNameParam(countSql, values).getSingleResult();
    searResult.setResult(objectList);
    searResult.setTotalCount(totalCount);

    return searResult;
  }
コード例 #2
0
  public SearchResult searchCommand(String name, String[] args) {
    CommandContainer command = commandMap.get(name);

    // Try to find the deepest available sub-command
    int index = 0;
    boolean subFound;

    if (args.length > 0) {
      do {
        subFound = false;

        Set<CommandContainer> childs = command.getChildCommands();

        if (childs != null) {
          for (CommandContainer child : childs) {
            if (child.getName().equals(args[index])) {
              command = child;
              index++;
              subFound = true;
              break;
            }
          }
        }
      } while (index < args.length && subFound);
    }

    SearchResult result = new SearchResult();
    result.container = command;
    result.deepness = index;

    return result;
  }
コード例 #3
0
 @Override
 public Set<String> retrieveUserGroups(LdapUserContext userContext) throws LdapException {
   Set<String> groups = new HashSet<String>();
   try {
     Filter groupClassFilter;
     if (groupObjectClass != null && !groupObjectClass.isEmpty()) {
       groupClassFilter = Filter.createEqualityFilter("objectClass", groupObjectClass);
     } else {
       groupClassFilter = Filter.createPresenceFilter("objectClass");
     }
     Filter filter =
         Filter.createANDFilter(
             groupClassFilter,
             Filter.createEqualityFilter(groupMemberAttribute, userContext.getDn()));
     LOGGER.debug(filter.toString());
     SearchResult searchResult =
         ldapConnectionPool.search(
             StringUtils.join(groupBase, ','), SearchScope.SUB, filter, "cn");
     for (SearchResultEntry entry : searchResult.getSearchEntries()) {
       groups.add(entry.getAttributeValue("cn"));
     }
     return groups;
   } catch (com.unboundid.ldap.sdk.LDAPException e) {
     throw new LdapException(e);
   }
 }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389");
    DirContext ctx = new InitialDirContext(env);

    String search =
        "(cn=" + data + ")"; /* POTENTIAL FLAW: unsanitized data from untrusted source */

    NamingEnumeration<SearchResult> answer = ctx.search("", search, null);
    while (answer.hasMore()) {
      SearchResult sr = answer.next();
      Attributes a = sr.getAttributes();
      NamingEnumeration<?> attrs = a.getAll();
      while (attrs.hasMore()) {
        Attribute attr = (Attribute) attrs.next();
        NamingEnumeration<?> values = attr.getAll();
        while (values.hasMore()) {
          response.getWriter().println(" Value: " + values.next().toString());
        }
      }
    }
  }
コード例 #5
0
ファイル: PlaceSelection.java プロジェクト: harrymahar/josm
 @Override
 public void valueChanged(ListSelectionEvent lse) {
   SearchResult r = model.getSelectedSearchResult();
   if (r != null) {
     parent.boundingBoxChanged(r.getDownloadArea(), PlaceSelection.this);
   }
 }
コード例 #6
0
  public static SearchResult search(Mapx map) {
    SearchParameters sps = new SearchParameters();
    String site = map.getString("site");
    String id = map.getString("id");
    String catalog = map.getString("catalog");
    if (StringUtil.isEmpty(catalog)) {
      catalog = map.getString("Catalog");
    }
    String order = map.getString("order");
    String time = map.getString("time");
    String keyword = map.getString("keyword");
    String query = map.getString("query");
    if (StringUtil.isEmpty(keyword)) {
      keyword = query;
    }
    String page = map.getString("page");
    String size = map.getString("size");

    if (StringUtil.isEmpty(id)) {
      id = SearchAPI.getIndexIDBySiteID(site);
    }

    if (StringUtil.isNotEmpty(keyword)) {
      sps.addFulltextField("Title", keyword, false);
      sps.addFulltextField("Content", keyword, false);
      sps.addFulltextField("_Keyword", keyword, true);
    }

    if ("time".equalsIgnoreCase(order)) {
      sps.setSortField("PublishDate", 3, true);
    }

    if (StringUtil.isNotEmpty(time)) {
      Date today = new Date();
      String StartDate = DateUtil.toString(DateUtil.addDay(today, -36500));
      if (time.equals("week")) StartDate = DateUtil.toString(DateUtil.addDay(today, -7));
      else if (time.equals("month")) StartDate = DateUtil.toString(DateUtil.addDay(today, -30));
      else if (time.equals("quarter")) {
        StartDate = DateUtil.toString(DateUtil.addDay(today, -90));
      }
      String EndDate = "2999-01-01";
      sps.setDateRange("PublishDate", StartDate, EndDate);
    }
    if (StringUtil.isNotEmpty(catalog)) {
      sps.addLeftLikeField("CatalogInnerCode", catalog);
    }
    if (StringUtil.isNotEmpty(page)) {
      sps.setPageIndex(Integer.parseInt(page) - 1);
    }
    if (StringUtil.isNotEmpty(size)) {
      sps.setPageSize(Integer.parseInt(size));
    }
    if (StringUtil.isEmpty(id)) {
      SearchResult sr = new SearchResult();
      sr.Data = new DataTable();
      return sr;
    }
    sps.setIndexID(Long.parseLong(id));
    return ArticleIndexer.search(sps);
  }
コード例 #7
0
  /**
   * after a user has successfully logged in we want to build an access object for use in the
   * scheduling system
   *
   * @param String username
   * @param String group a group name to check for username in (via memberUid string)
   * @return boolean yes or no in the group
   * @throws NamingException when the search fails by DN this will be thrown
   */
  private boolean userInGroup(String username, String group) throws NamingException {
    // assume they are not
    boolean inGroup = false;

    // Specify the attributes to match
    Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
    // set the common name for the group using defined prefix ie 'cn' or 'ou'
    matchAttrs.put(
        new BasicAttribute(
            this.GROUPS_LOC.substring(0, this.GROUPS_LOC.indexOf("=")),
            group)); // named group for access rights

    // Search for objects that have those matching attributes in the specified group location
    NamingEnumeration answer = ctx.search(this.GROUPS_LOC + this.BASE_DN, matchAttrs);

    // search for that user id in the member list
    while (answer.hasMore()) {
      SearchResult sr = (SearchResult) answer.next();
      if ((sr.getAttributes().get("memberuid").toString()).indexOf(username) >= 0) {
        // this user is in the specified group
        inGroup = true;
      }
    }
    System.err.println(username + " in " + group + ": " + new Boolean(inGroup).toString());
    return inGroup;
  }
コード例 #8
0
  public SearchResult search(String field, String query) {
    SearchResult searchResult = new SearchResult();
    try {
      Analyzer analyzer = new StandardAnalyzer();
      QueryParser queryParser = new QueryParser(field, analyzer);
      Query q = queryParser.parse(query);
      long start = System.currentTimeMillis();
      IndexSearcher searcher = getSearcher();
      TopDocs hits = searcher.search(q, 50);
      searchResult.setTotalHits(hits.totalHits);
      long end = System.currentTimeMillis();
      searchResult.setTime(end - start);
      System.err.println(
          "Found "
              + hits.totalHits
              + " document(s) (in "
              + (end - start)
              + " milliseconds) that matched query '"
              + q
              + "':");
      for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = searcher.doc(scoreDoc.doc);
        ResultDocument document = new ResultDocument();
        document.setFullpath("\"" + doc.get("fullpath").replace("\"", "") + "\"");
        document.setFilename("\"" + doc.get("filename").replace("\"", "") + "\"");
        document.setTeaser("\"" + doc.get("teaser") + "\"");
        searchResult.addDocumnent(document);
      }
      close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return searchResult;
  }
コード例 #9
0
 public int compareTo(Object o) throws ClassCastException {
   if (!(o instanceof SearchResult)) {
     throw new ClassCastException(
         "Error in SearchResult.compareTo(): expected SearchResult object.");
   }
   SearchResult sr = (SearchResult) o;
   return label.compareToIgnoreCase(sr.getLabel());
 }
コード例 #10
0
ファイル: SpatialTestCase.java プロジェクト: pkarmstr/NYBC
 public StringBuilder toDebugString() {
   StringBuilder str = new StringBuilder();
   str.append("found: ").append(numFound).append('[');
   for (SearchResult r : results) {
     String id = r.getId();
     str.append(id).append(", ");
   }
   str.append(']');
   return str;
 }
コード例 #11
0
  @Test
  public void query_EndPoints() throws Exception {
    Map<String, Object> json = Helper.getBigJsonText(20);

    String fortress = "epFortress";
    String company = "epCompany";
    String doc = "epDocType";
    String user = "******";

    Entity entity = Helper.getEntity(company, fortress, user, doc);

    EntitySearchChange change = new EntitySearchChange(entity);
    change.setDescription("Test Description");
    change.setWhat(json);

    deleteEsIndex(entity);
    Thread.sleep(1000);

    SearchResults searchResults =
        trackService.createSearchableChange(new EntitySearchChanges(change));
    SearchResult searchResult = searchResults.getSearchResults().iterator().next();
    Thread.sleep(2000);
    assertNotNull(searchResult);
    assertNotNull(searchResult.getSearchKey());

    QueryParams qp = new QueryParams(entity.getSegment());
    qp.setCompany(company);
    qp.setSearchText("*");
    // Sanity check - there is only one document in the index
    EsSearchResult queryResult = queryServiceEs.doFdViewSearch(qp);
    assertEquals(1, queryResult.getResults().size());
    assertEquals(entity.getMetaKey(), queryResult.getResults().iterator().next().getMetaKey());
    MetaKeyResults metaResults = queryServiceEs.doMetaKeyQuery(qp);
    assertEquals(1, metaResults.getResults().size());
    assertEquals(entity.getMetaKey(), metaResults.getResults().iterator().next());

    // Find with just a fortress
    qp = new QueryParams(entity.getSegment());
    qp.setSearchText("description");
    queryResult = queryServiceEs.doFdViewSearch(qp);
    assertEquals(1, queryResult.getResults().size());
    assertEquals(entity.getMetaKey(), queryResult.getResults().iterator().next().getMetaKey());

    qp = new QueryParams().setCompany(company.toLowerCase());
    qp.setSearchText("description");
    queryResult = queryServiceEs.doFdViewSearch(qp);
    assertEquals(1, queryResult.getResults().size());
    assertEquals(entity.getMetaKey(), queryResult.getResults().iterator().next().getMetaKey());

    qp = new QueryParams(entity.getSegment());
    qp.setSearchText("-description"); // Ignore description
    queryResult = queryServiceEs.doFdViewSearch(qp);
    assertEquals(0, queryResult.getResults().size());
  }
  /* uses badsource and badsink - see how tools report flaws that don't always occur */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      /* retrieve the property */
      Properties props = new Properties();
      FileInputStream finstr = null;
      try {
        finstr = new FileInputStream("../common/config.properties");
        props.load(finstr);
        data = props.getProperty("data");
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (finstr != null) {
            finstr.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        }
      }
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389");
    DirContext ctx = new InitialDirContext(env);

    String search =
        "(cn=" + data + ")"; /* POTENTIAL FLAW: unsanitized data from untrusted source */

    NamingEnumeration<SearchResult> answer = ctx.search("", search, null);
    while (answer.hasMore()) {
      SearchResult sr = answer.next();
      Attributes a = sr.getAttributes();
      NamingEnumeration<?> attrs = a.getAll();
      while (attrs.hasMore()) {
        Attribute attr = (Attribute) attrs.next();
        NamingEnumeration<?> values = attr.getAll();
        while (values.hasMore()) {
          response.getWriter().println(" Value: " + values.next().toString());
        }
      }
    }
  }
コード例 #13
0
  /** Gets the initial list of ids */
  private SearchResult getIds(String term, int start, int pacing) {

    String baseUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils";
    String medlineUrl =
        baseUrl
            + "/esearch.fcgi?db=pubmed&retmax="
            + Integer.toString(pacing)
            + "&retstart="
            + Integer.toString(start)
            + "&term=";

    Pattern idPattern = Pattern.compile("<Id>(\\d+)</Id>");
    Pattern countPattern = Pattern.compile("<Count>(\\d+)<\\/Count>");
    Pattern retMaxPattern = Pattern.compile("<RetMax>(\\d+)<\\/RetMax>");
    Pattern retStartPattern = Pattern.compile("<RetStart>(\\d+)<\\/RetStart>");

    boolean doCount = true;
    SearchResult result = new SearchResult();
    try {
      URL ncbi = new URL(medlineUrl + term);
      // get the ids
      BufferedReader in = new BufferedReader(new InputStreamReader(ncbi.openStream()));
      String inLine;
      while ((inLine = in.readLine()) != null) {

        // get the count
        Matcher idMatcher = idPattern.matcher(inLine);
        if (idMatcher.find()) {
          result.addID(idMatcher.group(1));
        }
        Matcher retMaxMatcher = retMaxPattern.matcher(inLine);
        if (retMaxMatcher.find()) {
          result.retmax = Integer.parseInt(retMaxMatcher.group(1));
        }
        Matcher retStartMatcher = retStartPattern.matcher(inLine);
        if (retStartMatcher.find()) {
          result.retstart = Integer.parseInt(retStartMatcher.group(1));
        }
        Matcher countMatcher = countPattern.matcher(inLine);
        if (doCount && countMatcher.find()) {
          result.count = Integer.parseInt(countMatcher.group(1));
          doCount = false;
        }
      }
    } catch (MalformedURLException e) { // new URL() failed
      System.out.println("bad url");
      e.printStackTrace();
    } catch (IOException e) { // openConnection() failed
      System.out.println("connection failed");
      e.printStackTrace();
    }
    return result;
  }
コード例 #14
0
ファイル: IndexManager.java プロジェクト: erwink/Samples
  /**
   * This method searches across multiple indexes and combines the answers. Create the business
   * object and only initialize the attributes you want to actually use in the query. You can AND or
   * OR all these attributes.
   *
   * @param criteria A business object with only attributes in the query set. Others must be null
   * @param isAND TRUE if results are to be ANDed otherwise the results are ORed
   * @return The list of keys for the matching entries @See TestSubstringIndex
   */
  public SearchResult<RK> searchMultipleIndexes(A criteria, boolean isAND) {
    try {
      Set<ByteArrayKey> result = null;
      // first run the individual queries for each attribute in parallel
      Collection<Future<SearchResult<byte[]>>> threads =
          new ArrayList<Future<SearchResult<byte[]>>>();
      for (Field f : indexedFields) {
        final String value = (String) f.get(criteria); // non null field means it's in the query
        if (value != null) {
          final Index<A, RK> index = getIndex(f.getName());

          Callable<SearchResult<byte[]>> c =
              new Callable<SearchResult<byte[]>>() {
                public SearchResult<byte[]> call() {
                  SearchResult<byte[]> r = index.rawContains(value);
                  return r;
                }
              };

          Future<SearchResult<byte[]>> future = utils.getExecutorService().submit(c);
          threads.add(future);
        }
      }
      // the collect the results and AND/OR them
      for (Future<SearchResult<byte[]>> future : threads) {
        SearchResult<byte[]> r = future.get();
        if (!r.isTooManyMatches()) {
          Collection<ByteArrayKey> rr = convertToKeys(r.getResults());
          if (result == null) result = new HashSet<ByteArrayKey>(rr);
          else if (isAND) {
            // AND this index match with the current running results
            LinkedList<ByteArrayKey> removeList = new LinkedList<ByteArrayKey>();
            for (ByteArrayKey k : rr) {
              if (!result.contains(k)) removeList.add(k);
            }
            for (ByteArrayKey k : result) {
              if (!rr.contains(k)) removeList.add(k);
            }
            result.removeAll(removeList);
          } else result.addAll(rr);
        }
      }
      if (result != null) {
        Map<ByteArrayKey, RK> rc =
            utils.getAll(result, utils.getObjectGrid().getMap(internalKeyToRealKeyMapName));
        return new SearchResult<RK>(new ArrayList<RK>(rc.values()));
      } else return new SearchResult<RK>();
    } catch (Exception e) {
      throw new ObjectGridRuntimeException(e);
    }
  }
コード例 #15
0
ファイル: DeleteTest.java プロジェクト: gvodianytskyi/CIS
  @Test
  public void deleteTest() {
    navigationPage.typeSearchInfo(SEARCH_TEXT);
    SearchResult searchResult = navigationPage.clickSearch();
    int id = searchResult.openPersonalData(SEARCH_TEXT);
    personalData = PageFactory.initElements(driver, PersonalDataPage.class);
    personalData.setNavigationPage(navigationPage);

    if (id >= 0) {
      personalData.clickDelete().clickOk();
    } else {
      fail("No such sportsman.");
    }
  }
コード例 #16
0
ファイル: VimUtils.java プロジェクト: cyburs/vrapper
 public static SearchResult wrapAroundSearch(
     final EditorAdaptor vim, final Search search, final Position position) {
   final SearchAndReplaceService searcher = vim.getSearchAndReplaceService();
   SearchResult result = searcher.find(search, position);
   if (!result.isFound() && vim.getConfiguration().get(Options.WRAP_SCAN)) {
     // redo search from beginning / end of document
     final TextContent p = vim.getModelContent();
     final int index =
         search.isBackward()
             ? p.getLineInformation(p.getNumberOfLines() - 1).getEndOffset() - 1
             : 0;
     result = searcher.find(search, position.setModelOffset(index));
   }
   return result;
 }
コード例 #17
0
  /* goodG2B1() - use goodsource and badsink by changing IO.staticTrue to IO.staticFalse */
  private void goodG2B1() throws Throwable {
    String data;
    if (IO.staticFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    Hashtable<String, String> environmentHashTable = new Hashtable<String, String>();
    environmentHashTable.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentHashTable.put(Context.PROVIDER_URL, "ldap://localhost:389");
    DirContext directoryContext = null;

    try {
      directoryContext = new InitialDirContext(environmentHashTable);
      /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection */
      String search = "(cn=" + data + ")";

      NamingEnumeration<SearchResult> answer = directoryContext.search("", search, null);
      while (answer.hasMore()) {
        SearchResult searchResult = answer.next();
        Attributes attributes = searchResult.getAttributes();
        NamingEnumeration<?> allAttributes = attributes.getAll();
        while (allAttributes.hasMore()) {
          Attribute attribute = (Attribute) allAttributes.next();
          NamingEnumeration<?> allValues = attribute.getAll();
          while (allValues.hasMore()) {
            IO.writeLine(" Value: " + allValues.next().toString());
          }
        }
      }
    } catch (NamingException exceptNaming) {
      IO.logger.log(Level.WARNING, "The LDAP service was not found or login failed.", exceptNaming);
    } finally {
      if (directoryContext != null) {
        try {
          directoryContext.close();
        } catch (NamingException exceptNaming) {
          IO.logger.log(Level.WARNING, "Error closing DirContext", exceptNaming);
        }
      }
    }
  }
コード例 #18
0
  /** @return */
  public boolean verifySearchResultPubMatchesDetailedViewPub() {

    if (BaseTestCaseUtil.match(
        selenium.getText(DetailedSearchResultUiLocator.getPub()), searchResult.getPub(), true)) {
      return true;
    }

    return false;
  }
コード例 #19
0
  @Test
  public void testUnicode() {
    AhoCorasick tree = new AhoCorasick();

    tree.add(".", ".".toCharArray());
    tree.add("...", "...".toCharArray());
    tree.prepare();

    Iterator<SearchResult> it = tree.search("Questa prova è molto cattiva..".toCharArray());
    while (it.hasNext()) {
      SearchResult sr = it.next();
      System.out.println(sr.getLastIndex());

      Set<Object> outputs = sr.getOutputs();

      for (Object s : outputs) System.out.println(new String((char[]) s));
    }
  }
コード例 #20
0
ファイル: PlaceSelection.java プロジェクト: codesman/josm
 /** Detect ending elements. */
 @Override
 public void endElement(String namespaceURI, String localName, String qName)
     throws SAXException {
   if ("description".equals(qName) && description != null) {
     currentResult.description = description.toString();
     description = null;
   }
   depth--;
 }
コード例 #21
0
ファイル: MapSearcher.java プロジェクト: Jakegogo/concurrent
 /**
  * 获取到目标点的最短路径
  *
  * @param target 目标点
  * @return
  */
 public SearchResult<T> getResult(T target) {
   Maps.Node<T> targetNode = this.map.getNodes().get(target);
   if (targetNode == null) {
     throw new RuntimeException("目标节点不存在!");
   }
   this.targetNode = targetNode;
   // 开始计算
   this.computePath(startNode);
   return SearchResult.valueOf(pathInfo.get(target), path.get(targetNode));
 }
コード例 #22
0
  /** @return */
  public boolean verifySearchResultDocumentTypeMatchesDetailedViewDocumentType() {
    if (selenium
            .getText(DetailedSearchResultUiLocator.getDocumentType())
            .indexOf(searchResult.getDocumentType().trim().split("((es)|(s))$")[0])
        >= 0) {
      return true;
    }

    return false;
  }
コード例 #23
0
  public SearchResult deserialize(
      JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();

    String query = jsonObj.get(QUERY_TAG).getAsString();
    // Unused.
    // int numResults = jsonObj.get(NUM_RESULTS_TAG).getAsInt();

    SearchResult result = new SearchResult(query);

    JsonArray digestsArray = jsonObj.get(DIGESTS_TAG).getAsJsonArray();

    for (JsonElement e : digestsArray) {
      Digest digest = context.deserialize(e, Digest.class);
      result.addDigest(digest);
    }

    return result;
  }
コード例 #24
0
  public void bad() throws Throwable {
    String data;

    badPrivate = true;
    data = bad_source();

    Hashtable<String, String> environmentHashTable = new Hashtable<String, String>();
    environmentHashTable.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentHashTable.put(Context.PROVIDER_URL, "ldap://localhost:389");
    DirContext directoryContext = null;

    try {
      directoryContext = new InitialDirContext(environmentHashTable);
      /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection */
      String search = "(cn=" + data + ")";

      NamingEnumeration<SearchResult> answer = directoryContext.search("", search, null);
      while (answer.hasMore()) {
        SearchResult searchResult = answer.next();
        Attributes attributes = searchResult.getAttributes();
        NamingEnumeration<?> allAttributes = attributes.getAll();
        while (allAttributes.hasMore()) {
          Attribute attribute = (Attribute) allAttributes.next();
          NamingEnumeration<?> allValues = attribute.getAll();
          while (allValues.hasMore()) {
            IO.writeLine(" Value: " + allValues.next().toString());
          }
        }
      }
    } catch (NamingException exceptNaming) {
      IO.logger.log(Level.WARNING, "The LDAP service was not found or login failed.", exceptNaming);
    } finally {
      if (directoryContext != null) {
        try {
          directoryContext.close();
        } catch (NamingException exceptNaming) {
          IO.logger.log(Level.WARNING, "Error closing DirContext", exceptNaming);
        }
      }
    }
  }
コード例 #25
0
ファイル: JpaBaseDao.java プロジェクト: GladiusK/unitwork
  /**
   * 按JQL分页查询对象列表.
   *
   * @param values 命名参数,按名称绑定.
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public <X> SearchResult<X> findPageWithNameParam(
      final int firstResult, final int maxResult, final String jql, final Map<String, ?> values) {
    SearchResult searResult = new SearchResult();

    List objectList =
        this.getEntityManager()
            .createQueryWithNameParam(jql, values)
            .setFirstResult(firstResult)
            .setMaxResults(maxResult)
            .getResultList();
    // 查询记录总数
    String countJql = SQLUtils.buildCountSQL(jql);
    Long totalCount =
        (Long) this.getEntityManager().createQueryWithNameParam(countJql, values).getSingleResult();

    searResult.setResult(objectList);
    searResult.setTotalCount(totalCount.intValue());

    return searResult;
  }
コード例 #26
0
ファイル: SearchPanel.java プロジェクト: igorhvr/zaproxy
  protected void highlightNextResult() {
    if (resultsList.getSelectedValue() == null) {
      this.highlightFirstResult();
      return;
    }

    SearchResult sr = (SearchResult) resultsList.getSelectedValue();
    SearchMatch sm = sr.getNextMatch();

    if (sm != null) {
      highlightMatch(sm);
    } else {
      // Next record
      if (resultsList.getSelectedIndex() < resultsList.getModel().getSize() - 1) {
        resultsList.setSelectedIndex(resultsList.getSelectedIndex() + 1);
        resultsList.ensureIndexIsVisible(resultsList.getSelectedIndex());
      } else {
        this.highlightFirstResult();
      }
    }
  }
コード例 #27
0
 /**
  * Updates the instance key public-key certificate value of this context from the local truststore
  * of the instance bound by this context. Any current value of the certificate is overwritten. The
  * intent of this method is to retrieve the instance-key public-key certificate when this context
  * is bound to an instance, and cache it for later use in registering the instance into ADS.
  *
  * @param desc The map to update with the instance key-pair public-key certificate.
  * @param ctx The bound server instance.
  * @throws NamingException if unable to retrieve certificate from bound instance.
  */
 private static void updatePublicKeyCertificate(
     ServerDescriptor desc, InitialLdapContext ctx, TopologyCacheFilter filter)
     throws NamingException {
   /* TODO: this DN is declared in some core constants file. Create a constants
   file for the installer and import it into the core. */
   final String dnStr = "ds-cfg-key-id=ads-certificate,cn=ads-truststore";
   final LdapName dn = new LdapName(dnStr);
   for (int i = 0; i < 2; ++i) {
     /* If the entry does not exist in the instance's truststore backend, add
     it (which induces the CryptoManager to create the public-key
     certificate attribute), then repeat the search. */
     try {
       final SearchControls searchControls = new SearchControls();
       searchControls.setSearchScope(SearchControls.OBJECT_SCOPE);
       final String attrIDs[] = {"ds-cfg-public-key-certificate;binary"};
       searchControls.setReturningAttributes(attrIDs);
       final SearchResult certEntry =
           ctx.search(dn, "(objectclass=ds-cfg-instance-key)", searchControls).next();
       final Attribute certAttr = certEntry.getAttributes().get(attrIDs[0]);
       if (null != certAttr) {
         /* attribute ds-cfg-public-key-certificate is a MUST in the schema */
         desc.serverProperties.put(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE, certAttr.get());
       }
       break;
     } catch (NameNotFoundException x) {
       if (0 == i) {
         /* Poke CryptoManager to initialize truststore. Note the special
         attribute in the request. */
         final Attributes attrs = new BasicAttributes();
         final Attribute oc = new BasicAttribute("objectclass");
         oc.add("top");
         oc.add("ds-cfg-self-signed-cert-request");
         attrs.put(oc);
         ctx.createSubcontext(dn, attrs).close();
       } else {
         throw x;
       }
     }
   }
 }
コード例 #28
0
ファイル: SearchPanel.java プロジェクト: igorhvr/zaproxy
  protected void highlightPrevResult() {
    if (resultsList.getSelectedValue() == null) {
      this.highlightFirstResult();
      return;
    }

    SearchResult sr = (SearchResult) resultsList.getSelectedValue();
    SearchMatch sm = sr.getPrevMatch();

    if (sm != null) {
      highlightMatch(sm);
    } else {
      // Previous record
      if (resultsList.getSelectedIndex() > 0) {
        resultsList.setSelectedIndex(resultsList.getSelectedIndex() - 1);
      } else {
        resultsList.setSelectedIndex(resultsList.getModel().getSize() - 1);
      }
      resultsList.ensureIndexIsVisible(resultsList.getSelectedIndex());
      highlightLastResult((SearchResult) resultsList.getSelectedValue());
    }
  }
コード例 #29
0
 @Override
 public LdapUserContext findUser(String identityAttributeValue) throws LdapException {
   try {
     Filter userClassFilter;
     if (userObjectClass != null && !userObjectClass.isEmpty()) {
       userClassFilter = Filter.createEqualityFilter("objectClass", userObjectClass);
     } else {
       userClassFilter = Filter.createPresenceFilter("objectClass");
     }
     Filter filter =
         Filter.createANDFilter(
             userClassFilter,
             Filter.createEqualityFilter(userIdentityAttribute, identityAttributeValue));
     LOGGER.debug(filter.toString());
     String[] attributesToRetrieve;
     if (userAdditionalAttributes != null) {
       attributesToRetrieve = userAdditionalAttributes;
       if (!ArrayUtils.contains(attributesToRetrieve, "cn")
           || !ArrayUtils.contains(attributesToRetrieve, "CN")) {
         ArrayUtils.add(attributesToRetrieve, "cn");
       }
     } else {
       attributesToRetrieve = new String[] {"cn"};
     }
     SearchResult searchResult =
         ldapConnectionPool.search(
             StringUtils.join(userBase, ','), SearchScope.SUB, filter, attributesToRetrieve);
     if (searchResult.getEntryCount() != 1) {
       throw new UnknownAccountException();
     }
     SearchResultEntry searchResultEntry = searchResult.getSearchEntries().get(0);
     String dn = searchResultEntry.getDN();
     DefaultLdapUserContext ldapUserContext = internalCreateUser(dn);
     ldapUserContext.getKnownAttributes().put("cn", searchResultEntry.getAttributeValue("cn"));
     return ldapUserContext;
   } catch (com.unboundid.ldap.sdk.LDAPException e) {
     throw new LdapException(e);
   }
 }
コード例 #30
0
ファイル: SearchOverlay.java プロジェクト: fayf/wakeupnow
  @Override
  public boolean onTap(GeoPoint p, MapView mapView) {
    tappedIndex = -1;
    boolean itemTapped = super.onTap(p, mapView);
    if (!isPinch && itemTapped) {
      PopupViewHolder popupVH = (PopupViewHolder) popupView.getTag();

      SearchResult item = items.get(tappedIndex);
      mapParams.point = item.getPoint();
      mapView.setTag(R.id.tag_geopoint, item.getPoint());
      popupVH.buttonCreate.setVisibility(View.VISIBLE);
      popupVH.buttonDelete.setVisibility(View.GONE);
      popupVH.buttonSave.setVisibility(View.GONE);

      Address address = item.getAddress();
      String feature = address.getFeatureName();
      if (feature != null) popupVH.editTitle.setText(feature);
      else popupVH.editTitle.setText(null);

      String addressStr = "";
      int lines = address.getMaxAddressLineIndex() + 1;
      for (int i = 0; i < lines; i++) {
        addressStr += address.getAddressLine(i);
        if (i != lines - 1) addressStr += "\n";
      }
      popupVH.editSnippet.setText(addressStr);

      mapView.removeView(popupView);
      popupView.setLayoutParams(mapParams);
      mapView.addView(popupView);

      tappedItem = item;
    } else {
      tappedItem = null;
    }
    return false;
  }