2016-11-29 92 views
0

我在Java中它有一個對象有錯誤而recurssing雖然包含另一個列表

List<GroupNavigationItemSRO> children 

有一類對象的list現在GroupNaviagationItemSRO具有相同的列表

List<GroupNavigationItemSRO> children 

現在我想遍歷每個GroupNavigationSRO並填充字符串列表。目前,我想是這樣做的

void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){ 
     System.out.println("PRINT"); 
     for(GroupNavigationItemSRO item : items) { 
      nitems.add(item.getUrl()); 
      System.out.println(item.getUrl()); 
      // g.add(item.getUrl()); 
      System.out.println("PRINT"); 
      List<GroupNavigationItemSRO> nextItem = item.getChildren(); 
      if (nextItem != null && nextItem.size()>0) { 
       getNavItems(nextItem,nitems); 
      } 
     } 

    } 

當我只打印的對象,它不給任何錯誤,但只要我嘗試並添加到列表中recurssion停止

nitems.add(item.getUrl()) 

這是爲什麼發生。下面是情況下,整個Java文件,樂於助人

@Service("labelSearchService") 
public class LabelSearchServiceImpl extends AbstractSearchService { 
private static final String    version = SearchVersion.VERSION_2.getValue(); 

private static final Logger    LOG  = LoggerFactory.getLogger(LabelSearchServiceImpl.class); 

private static final String   EXPIRY_SET  = "expiry"; 
private static final String   DATA_SET   = "data"; 

@Autowired 
@Qualifier("searchServiceFactory") 
private ISearchServiceFactory searchServiceFactory; 

@Autowired 
IAerospikeTopSellingBrandsCacheService topSellingBrandsCacheService; 

@Autowired 
private LabelSearchCacheServiceImplFactory labelSearchCacheServiceImplFactory; 

@Autowired 
AerospikeGuidedResponse aerospikeGuidedResponse ; 

List<String> g = null; 


@Override 
public SearchSRO getSolrResponse(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number, String sortBy, 
    String userZone, String vertical, String clickSrc, boolean isSpellCheckEnabled, String categoryURL, boolean isNested) throws SearchException, ShardNotFoundException, IllegalAccessException { 
    String originalKeyword = searchTerm; 

    searchTerm = SearchUtils.modifySearchTerm(searchTerm); 
    SearchSRO sro = new SearchSRO(); 
    boolean isPartialSearch = SearchUtils.isPartialSearchEnabled(); 
    keyGenerator.setPartialSearch(SearchUtils.isPartialSearchEnabled()); 
    LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL); 
    // for 'ALL' categories labelNode would be null. 
    LOG.info("categoryURL : " + categoryURL); 
    if (ALL.equals(categoryURL)) { 
     if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) { 
      return new SearchSRO(); 
     } 
     sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical, 
       isPartialSearch, isSpellCheckEnabled, originalKeyword, false, isNested); 
    } else if (labelNode != null) { 
     sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, 
       originalKeyword, isNested, false,categoryURL); 
    } else { 
     throw new SearchException("Search was hit without selecting any category"); 
    } 

    // this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget' 

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); 

    if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) { 

     LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS) 
       + " but number of matched results are " + sro.getNoOfMatches()); 
     sro = new SearchSRO(); 

    } 

    return sro; 
} 

@Override 
public SearchSRO getSolrResponseForMobile(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number, 
     String sortBy, String userZone, String vertical, String clickSrc, boolean isBinSearch, int noOfResultsPerBin, boolean isSpellCheckEnabled, boolean isPartialSearch, 
     String categoryURL) throws SearchException, ShardNotFoundException, IllegalAccessException { 
    String originalKeyword = searchTerm; 
    searchTerm = SearchUtils.modifySearchTerm(searchTerm); 
    SearchSRO sro = new SearchSRO(); 
    isPartialSearch = isPartialSearch && SearchUtils.isPartialSearchEnabled(); 

    // this is to disable partial search in case of PWSTBT 
    if (ClickSourceType.PWSTBT_WIDGET.getValue().equalsIgnoreCase(clickSrc)) { 

     isPartialSearch = false; 

    } 
    LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL); 
    // for 'ALL' categories labelNode would be null 
    if (ALL.equals(categoryURL)) { 
     if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) { 
      return new SearchSRO(); 
     } 
     // Response for Search result page in mobile - same as web. 
     sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical, 
       isPartialSearch, isSpellCheckEnabled, originalKeyword, true, false); 
    } else if (labelNode != null) { 
     sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, 
       originalKeyword, false, true,categoryURL); 
    } else { 
     throw new SearchException("Search was hit without selecting any category"); 
    } 

    // this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget' 

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); 

    if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) { 
     LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS) 
       + " but number of matched results are " + sro.getNoOfMatches()); 
     sro = new SearchSRO(); 
    } 

    return sro; 

} 

@Autowired 
private IUserPersonaSegmentService   personaSegmentService; 

@Autowired 
private IContextHolder<SearchRequestContext> ctxProvider; 

private boolean isClientPersonaEnabled(SearchRequestContext ctx) { 
    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); 
    String clientsEnabled = cache.getProperty(SearchProperty.PERSONA_CLIENTS_ENABLED); 
    String client = ctx.req.getContextSRO().getAppIdent(); 

    return !StringUtils.isEmpty(client) && !StringUtils.isEmpty(clientsEnabled) && Pattern.matches("(?i).*\\b" + client + "\\b.*", clientsEnabled); 
} 

protected UserSegmentDTO setupPersonalizationContext(LabelNodeSRO labelNode, String searchTerm, String sortBy) { 
    SearchRequestContext ctx = ctxProvider.getContext(); 

    if (ctx == null || ctx.req == null) { 
     LOG.warn("No Request Context found"); 
     return null; 
    } 

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); 

    // check if Personalization is enabled 
    if (labelNode == null || !cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) || StringUtils.isEmpty(searchTerm) 
      || !SolrSortCategory.RELEVANCY.getValue().equalsIgnoreCase(sortBy) || !isClientPersonaEnabled(ctx)) { 
     LOG.debug("Personalization not enabled"); 
     return null; 
    } 

    LOG.info("Trying to set up personalization context"); 

    // setup the context for later use 
    ctx.personaSegments = personaSegmentService.getUserSegments(ctx.req.getUserTrackingId(), labelNode.getNodePath()); 

    return ctx.personaSegments; 
} 

@Override 
public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode, 
     int start, int number, String sortBy, String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword, boolean isNested, boolean isMobile,String categoryURL) 
throws SearchException, ShardNotFoundException, IllegalAccessException { 
    LOG.info("------------------Product category page---------------"); 
    // build cache key considering campaign id 
    keyGenerator.setCampaignId(String.valueOf(campaignId)); 
    // Search results will vary based on isNested flag even for exact same keywords hence, when we cache 
    // we cache both results with different key 
    keyGenerator.setNested(isNested); 

    SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); 

    LOG.info("sortBy : " + sortBy + ", personalization Enabled : " + cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) + ", labelNode : " + labelNode); 

    // try to set persona context 
    keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, searchTerm, sortBy)); 

    SearchSRO searchSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch, 
      isSpellCheckEnabled, originalKeyword, isNested, isMobile,categoryURL); 

    /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext(); 

    if (coreContext != null) { 
     if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) { 
      String cacheKey = keyGenerator.buildKey(); 
      try { 
       final AerospikeClient aClient = AerospikeClientFactory.getInstance(); 
       LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey); 
       aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey)); 
       aClient.delete(null, new Key("search", DATA_SET, cacheKey)); 
      } catch (AerospikeException e) { 
       e.printStackTrace(); 
      } 
     } 
    }*/ 
    return searchSRO; 
} 

@Override 
public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword, boolean partialSearch, boolean isBrand, String categoryUrl, 
     String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes, GetFiltersRequest request) throws SearchException, ShardNotFoundException { 
    String key = new KeyGenerator(String.valueOf(categoryId), String.valueOf(campaignId), q, keyword, partialSearch, null, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey(); 
    if (campaignId != null) { 
     LOG.info("Get Filters for Campaign Products wrt : " + key); 
    } 

    FilterListSRO filterListSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFiltersForProducts(key, categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,request); 
    return filterListSRO; 
} 

@Override 
public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword, 
     boolean partialSearch, boolean isBrand, String categoryUrl, String userZone, 
     HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) 
       throws SearchException, ShardNotFoundException { 
    return getFiltersForProducts(categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,null); 
} 

@Override 
public FilterListSRO getFilterValuesForFilter(String categoryId, String campaignId, String q, String keyword, boolean partialSearch, String filterName, String fullQ, 
     String categoryUrl, String[] filtersToFetch, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException, NumberFormatException, ShardNotFoundException { 
    String uniqueFilterKey = new KeyGenerator(categoryId, campaignId, q, keyword, partialSearch, filterName, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey(); 
    String[] filterNames = filterName.split(","); 
    FilterListSRO filterListSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFilterValuesForFilter(uniqueFilterKey, categoryId, campaignId, q, keyword, partialSearch, filterNames, categoryUrl, filtersToFetch, 
      userZone, hyperlocalCriteria, pinCodes); 
    /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext(); 
    if (coreContext != null) { 
     if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) { 
      String cacheKey = uniqueFilterKey.concat(".FilterSRO"); 
      try { 
       final AerospikeClient aClient = AerospikeClientFactory.getInstance(); 
       LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey); 
       aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey)); 
       aClient.delete(null, new Key("search", DATA_SET, cacheKey)); 
      } catch (AerospikeException e) { 
       e.printStackTrace(); 
      } 
     } 
    }*/ 
    return filterListSRO; 
} 

@Override 
public GroupNavigationSRO getGroupNavigation(KeyGenerator keyGenerator, String keyword, String q, String categoryUrl, Integer campaignId, boolean isSpellCheck, String userZone) throws IllegalAccessException { 
    GroupNavigationSRO sro = new GroupNavigationSRO(); 
    try { 
     ProductCategoryCache categoryCache = CacheManager.getInstance().getCache(ProductCategoryCache.class); 

     LabelNodeSRO labelNode = ALL.equals(categoryUrl) ? null : categoryCache.getLabelForLabelPath(categoryUrl); 

     if (!ALL.equals(categoryUrl) && labelNode == null) { 
      LOG.error("Invalid label : " + categoryUrl); 
      return null; 
     } 

     // try to setup persona context - using sort to relevancy since group left nav doesn't change with sortBy 
     keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, keyword, SolrSortCategory.RELEVANCY.getValue())); 

     sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGroupNavigation(keyGenerator, keyword, q, categoryUrl, campaignId, isSpellCheck, userZone); 

     /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext(); 

     if (coreContext != null) { 
      if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) { 
       String cacheKey = keyGenerator.buildKey().concat(".GroupNavigationSRO"); 
       try { 
        final AerospikeClient aClient = AerospikeClientFactory.getInstance(); 
        LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey); 
        aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey)); 
        aClient.delete(null, new Key("search", DATA_SET, cacheKey)); 
       } catch (AerospikeException e) { 
        e.printStackTrace(); 
       } 
      } 
     }*/ 

    } catch (SearchException e) { 
     LOG.error("Error in fetching GroupSRO: ", e); 
    } 
    return sro; 
} 

@Override 
public QueryResponse setCategoryFilterQueryAndExecute(SearchCriteria sc, Integer id) throws SearchException { 
    labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().setCategoryFilterQuery(sc, id); 
    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().executeQuery(sc.buildQuery(), id); 
} 

@Override 
public Long getProductCategoryCount(Integer categoryId, String categoryUrl) { 
    Long count = CacheManager.getInstance().getCache(ProductCategoryCache.class).getCategoryCountByUrl(categoryUrl); 
    if (count == null) { 
     count = new Long(0); 
    } 
    LOG.info("Product Category Counts for CategoryUrl: " + categoryUrl + " = " + count); 
    return count; 
} 

@Override 
public List<TopSellingProductCategorySRO> getTopSellingProductsforCategories(List<Integer> categoryIds, List<String> categoryUrls) { 
    List<TopSellingProductCategorySRO> topSellingProductCategorySROs = new ArrayList<TopSellingProductCategorySRO>(); 
    for (String categoryUrl : categoryUrls) { 
     try { 
      TopSellingProductCategorySRO topSellingProductCategorySRO = null; 
      Integer searchId = ShardResolverService.getSearchIdByLabel(categoryUrl); 
      QueryResponse rsp = searchServiceFactory.getSearchService(SearchVersion.VERSION_2.getValue()).getTopProductsInfoById(searchId, 
        CacheManager.getInstance().getCache(SearchConfigurationCache.class).getIntegerProperty(SearchProperty.MAX_TOP_SELLING_PRODUCTS_PER_CATEGORY)); 
      List<Long> pogIds = SearchUtils.extractTopProductsByCategoryId(rsp); 
      if (pogIds != null && !pogIds.isEmpty()) { 
       topSellingProductCategorySRO = new TopSellingProductCategorySRO(categoryUrl, pogIds); 
       topSellingProductCategorySROs.add(topSellingProductCategorySRO); 
      } 
     } catch (Exception e) { 
      LOG.error("Unable to get Top Selling Products for categoryId: " + categoryUrl + ", Exception:" + e.getMessage()); 
     } 
    } 
    return topSellingProductCategorySROs; 
} 

@Override 
public List<TopSellingBrandSRO> getTopSellingBrandsforCategories(List<Integer> categoryIds, List<String> categoryUrls) { 
    List<TopSellingBrandSRO> topSellingBrandSROs = new ArrayList<TopSellingBrandSRO>(); 
    for (String categoryUrl : categoryUrls) { 
     TopSellingBrandSRO topSellingBrandSRO = topSellingBrandsCacheService.getTopSellingBrandsByUrl(categoryUrl); 
     if (topSellingBrandSRO != null) { 
      topSellingBrandSROs.add(topSellingBrandSRO); 
     } 
    } 
    return topSellingBrandSROs; 
} 

@Override 
public List<TopSellingBrandSRO> getAllTopSellingProducts(){ 
    List<TopSellingBrandSRO> topSellingBrandSROs = topSellingBrandsCacheService.getAllTopSellingProducts(); 
    return topSellingBrandSROs; 
} 

@Override 
public FacetSRO getFacets(String cachekey, String keyword, String queryFieldName, String[] facetFields, Map<String, List<String>> filterMap, int number) throws SearchException { 

    // update values for mainCategoryXpath & categoryXpath fields 
    /*if(SolrFields.CATEGORY_XPATH.equals(queryFieldName) || SolrFields.MAIN_CATEGORY_XPATH.equals(queryFieldName)) { 
     String labelPath = SearchUtils.getLabelPathByUrl(keyword); 
     keyword = String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath)); 
    }*/ 
    for (String filterField : filterMap.keySet()) { 
     if (SolrFields.CATEGORY_XPATH.equals(filterField) || SolrFields.MAIN_CATEGORY_XPATH.equals(filterField)) { 
      List<String> searchIds = new ArrayList<String>(); 
      for (String val : filterMap.get(filterField)) { 
       String labelPath = SearchUtils.getLabelPathByUrl(val); 
       searchIds.add(String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath))); 
      } 
      filterMap.put(filterField, searchIds); 
     } 
    } 
    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFacets(cachekey, keyword, queryFieldName, facetFields, filterMap, number); 
} 

@Override 
public FilterListSRO getSRPFilters(KeyGenerator keyGenerator, String q, String keyword, boolean partialSearch, String categoryUrl, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException { 
    if (StringUtils.isEmpty(keyword)) { 
     LOG.error("Invalid parameters."); 
     return null; 
    } 
    keyword = SearchUtils.modifySearchTerm(keyword); 
    if (StringUtils.isEmpty(keyword)) { 
     LOG.info(" Returning empty filters for empty keyword."); 
     return new FilterListSRO(); 
    } 
    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSRPFilters(keyGenerator.buildKey(), q, keyword, partialSearch, categoryUrl, userZone, hyperlocalCriteria, pinCodes); 
} 

@Override 
public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, 
     Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode, int start, int number, String sortBy, 
     String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword, 
     boolean isNested, boolean isMobile) throws SearchException, ShardNotFoundException, IllegalAccessException { 
    // TODO Auto-generated method stub 
    return getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, isNested, isMobile, null); 
} 

@Override 
public String getmodelSearch(String query, String type) throws SearchException { 

    return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getmodelSearch(query, type); 
} 

@Override 
public String classifierResponse(String query, String type) throws SearchException { 
    try { 
     return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getClassifierResponse(query, type); 
    } catch (JsonGenerationException e) { 
     return e.getMessage(); 
    } catch (JsonMappingException e) { 
     return e.getMessage(); 
    } catch (IOException e) { 
     return e.getMessage(); 
    } 
} 

public GetGuidedSearchResponse getGuides(String query, String url) { 

    if(!StringUtils.isEmpty(query) && !StringUtils.isEmpty(url) && url.equalsIgnoreCase("ALL")) 
    { 
     KeyGenerator keyGenerator = new KeyGenerator(); 
     keyGenerator.setQ("sNapDeAl.sEarcH.getGuides=" +"##"+ query+ "##"+ url); 
     return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGuides(keyGenerator, query, url); 
    } 
    return null; 
} 

public GetGuidedSearchResponse getFilteredGuides(String query ,GetGroupLeftNavResponse leftNavBarResponse) {  
    g=null; 
    GroupNavigationSRO groups = leftNavBarResponse.getGroups(); 
    List<GroupNavigationItemSRO> items = groups.getItems() ; 
// List<String> nitems = getNavItems(items); 
    List<String> nitems = null; 
    getNavItems(items,nitems); 
    System.out.println("SIZE" + nitems.size()); 
    List<String> navItems = new ArrayList<String>(); 
    System.out.println("GETTING GUIDED FILE FROM AEROSPIKE"); 
    List<String> guideItems = aerospikeGuidedResponse.getGuides(query); 
    //HashMap<String,String> nodeUrlMapping = new HashMap<String,String>(); 
    if(guideItems.isEmpty()) 
    { 
     System.out.println("\n\n\n\n" + "EMPTY GUIDED" + " \n\n\n\n\n"); 
    } 
    guideItems.set(0, guideItems.get(0).trim()); 
    System.out.println("GUIDED RESPONSE"); 
    for(int i=0 ; i < guideItems.size() ;i ++) 
    { 
     System.out.println(guideItems.get(i)); 

    } 
    /*for (int i =0 ;i < items.size() ;i++) { 
     List<GroupNavigationItemSRO> children_items = items.get(i).getChildren(); 
     String s = items.get(i).getNodePath(); 
     String m = items.get(i).getUrl(); 
     System.out.println(s + " " + m); 
     navItems.add(m); 
     //nodeUrlMapping.put(s,m); 
     for (int j=0;j<children_items.size();j++) { 
      String r = children_items.get(j).getNodePath(); 
      String n = children_items.get(j).getUrl(); 
      System.out.println(r +" " + n); 
     // nodeUrlMapping.put(r,n); 
      navItems.add(n); 
     } 


    }*/ 
    System.out.println("ITEM RESPONSE"); 
    //navItems = g ; 
    for(int i=0 ; i < navItems.size() ;i ++) 
    { 
     System.out.println(navItems.get(i)); 

    } 
    List<String> filteredGuides = new ArrayList<String>(); 

    for(int i=0 ; i < guideItems.size() ;i++) 
    { 
     if(navItems.contains(guideItems.get(i))) 
      filteredGuides.add(guideItems.get(i)); 
     else { 

     } 

    } 
    System.out.println("NAV ITEMS" + navItems.size() + navItems.toString()); 
    System.out.println("GUIDE ITEMS" + filteredGuides.size() + filteredGuides.toString()); 
    List<WidgetEntity> entities = new ArrayList<WidgetEntity>(); 
/* Iterator it = nodeUrlMapping.entrySet().iterator(); 
    while (it.hasNext()) { 
     Map.Entry pair = (Map.Entry)it.next(); 
     System.out.println(pair.getKey() + " = " + pair.getValue()); 
    }*/ 
    for(int i=0;i<filteredGuides.size();i++) 
    { 
     String guide = filteredGuides.get(i); 
     guide = guide.trim(); 
     System.out.println(guide); 
     LabelNodeSRO labelSRO = getLableSRO(guide); 
     System.out.println(labelSRO.toString() + guide); 
     WidgetEntity entity = new WidgetEntity(); 
     entity.setId(labelSRO.getUrl()); 
     entity.setName(labelSRO.getDisplayName()); 
     entity.setType("category"); 
     entities.add(entity); 

    } 
    System.out.println("ENTITIES DEtails"); 
    GetGuidedSearchResponse response = new GetGuidedSearchResponse(); 
    for(int i =0 ;i<entities.size();i++) 
    { 
     System.out.println(entities.get(i).getId() + entities.get(i).getName() + entities.get(i).getType()); 
    // System.out.println(nodeUrlMapping.get(entities.get(i).getId())); 
    } 
    response.setEntities(entities); 
    return response; 

} 
LabelNodeSRO getLableSRO(String guide) 
{ 
    System.out.println(guide + "GET"); 
    LabelNodeSRO label =SearchUtils.getLabelNodeByNodePath(guide); 
    return label; 


} 

void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){ 
    System.out.println("PRINT"); 
    for(GroupNavigationItemSRO item : items) { 
     nitems.add(item.getUrl()); 
     System.out.println(item.getUrl()); 
     // g.add(item.getUrl()); 
     System.out.println("PRINT"); 
     List<GroupNavigationItemSRO> nextItem = item.getChildren(); 
     if (nextItem != null && nextItem.size()>0) { 
      getNavItems(nextItem,nitems); 
     } 
    } 

} 

}

+0

你很可能會得到一個空指針nitems.add(item.getUrl())被調用的行上的異常,因爲您尚未使用ArrayList <>()初始化列表。例如。 列表 nitems = null; <<<< add:new ArrayList <>(); getNavItems(items,nitems); – Beowolve

回答

0

你可以嘗試這樣的事情,當你返回一個列表的所有字符串,如果沒有更多elments停止遞歸性和返回空單

List<String> getNavItems(List<GroupNavigationItemSRO> items){ 
    List<String> results = new ArrayList(); 
    System.out.println("PRINT"); 
    if(items != null && !items.isEmpty()){ 
     for(GroupNavigationItemSRO item : items) { 
      results.add(item.getUrl()); 
      System.out.println(item.getUrl()); 
      // g.add(item.getUrl()); 
      System.out.println("PRINT"); 
      results.addAll(getNavItems(item.getChildren())); 
      } 
     } 
    } 
    return results; 
} 
0

getFilteredGuides()方法要傳遞NITEMS爲空,這將導致NullPointerException

只是通過它,如下所示:

List<String> nitems = new ArrayList<String>(); 
getNavItems(items,nitems); 

也可以爲空添加一個檢查內部getNavItems()方法,並相應地將其初始化:

void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){ 

     if(nitems == null) 
     { 
      nitems = new ArrayList<String>(); 
     } 
     System.out.println("PRINT"); 
     for(GroupNavigationItemSRO item : items) { 
      nitems.add(item.getUrl()); 
      System.out.println(item.getUrl()); 
      // g.add(item.getUrl()); 
      System.out.println("PRINT"); 
      List<GroupNavigationItemSRO> nextItem = item.getChildren(); 
      if (nextItem != null && nextItem.size()>0) { 
       getNavItems(nextItem,nitems); 
      } 
     } 

    } 
相關問題