Java Code Examples for org.apache.solr.common.StringUtils#isEmpty()

The following examples show how to use org.apache.solr.common.StringUtils#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 6 votes vote down vote up
/**
 * Build the config for the client
 */
private Config buildConfig() throws APIManagementException {

    System.setProperty(TRY_KUBE_CONFIG, "false");
    System.setProperty(TRY_SERVICE_ACCOUNT, "true");
    ConfigBuilder configBuilder;

    configBuilder = new ConfigBuilder().withMasterUrl(kubernetesAPIServerUrl);

    if (!StringUtils.isEmpty(saTokenFileName)) {
        String token;
        String tokenFile = saTokenFilePath + "/" + saTokenFileName;
        try {
            token = FileUtil.readFileToString(tokenFile);
        } catch (IOException e) {
            throw new APIManagementException("Error while reading the SA Token FIle " + tokenFile);
        }
        configBuilder.withOauthToken(token);
    }

    return configBuilder.build();
}
 
Example 2
Source File: SolrLogLayout.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void appendMDC(StringBuilder sb) {
  if (!StringUtils.isEmpty(MDC.get(NODE_NAME_PROP)))  {
    sb.append(" n:").append(MDC.get(NODE_NAME_PROP));
  }
  if (!StringUtils.isEmpty(MDC.get(COLLECTION_PROP)))  {
    sb.append(" c:").append(MDC.get(COLLECTION_PROP));
  }
  if (!StringUtils.isEmpty(MDC.get(SHARD_ID_PROP))) {
    sb.append(" s:").append(MDC.get(SHARD_ID_PROP));
  }
  if (!StringUtils.isEmpty(MDC.get(REPLICA_PROP))) {
    sb.append(" r:").append(MDC.get(REPLICA_PROP));
  }
  if (!StringUtils.isEmpty(MDC.get(CORE_NAME_PROP))) {
    sb.append(" x:").append(MDC.get(CORE_NAME_PROP));
  }
}
 
Example 3
Source File: NodePreferenceRulesComparator.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private boolean hasCoreUrlPrefix(Object o, String prefix) {
  final String s;
  if (o instanceof String) {
    s = (String)o;
  }
  else if (o instanceof Replica) {
    s = ((Replica)o).getCoreUrl();
  } else {
    return false;
  }
  if (prefix.equals(ShardParams.REPLICA_LOCAL)) {
    return !StringUtils.isEmpty(localHostAddress) && s.startsWith(localHostAddress);
  } else {
    return s.startsWith(prefix);
  }
}
 
Example 4
Source File: SpellcheckComponent.java    From customized-symspell with MIT License 6 votes vote down vote up
private void loadDefault(String unigramsFile, String bigramsFile, String exclusionsFile,
    SpellChecker spellChecker,
    SolrCore core, String exclusionListSperatorRegex) {
  try {
    if (!StringUtils.isEmpty(unigramsFile)) {
      loadUniGramFile(core.getResourceLoader().openResource(unigramsFile),
          spellChecker.getDataHolder());
    }

    if (!StringUtils.isEmpty(bigramsFile)) {
      loadBiGramFile(core.getResourceLoader().openResource(bigramsFile),
          spellChecker.getDataHolder());
    }

    if (!StringUtils.isEmpty(exclusionsFile)) {
      loadExclusions(core.getResourceLoader().openResource(exclusionsFile),
          spellChecker.getDataHolder(), exclusionListSperatorRegex);
    }

  } catch (SpellCheckException | IOException ex) {
    log.error("Error occured while loading default Configs for Spellcheck");
  }
}
 
Example 5
Source File: SolrClientInterceptorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void testGet() throws Throwable {
    ModifiableSolrParams reqParams = new ModifiableSolrParams();
    if (StringUtils.isEmpty(reqParams.get("qt"))) {
        reqParams.set("qt", new String[] {"/get"});
    }
    reqParams.set("ids", new String[] {
        "99",
        "98"
    });
    QueryRequest request = new QueryRequest(reqParams);

    arguments = new Object[] {
        request,
        null,
        collection
    };
    interceptor.beforeMethod(enhancedInstance, method, arguments, argumentType, null);
    interceptor.afterMethod(enhancedInstance, method, arguments, argumentType, getGetResponse());

    List<TraceSegment> segments = segmentStorage.getTraceSegments();
    List<AbstractTracingSpan> spans = SegmentHelper.getSpans(segments.get(0));
    Assert.assertEquals(segments.size(), 1);
    Assert.assertEquals(spans.size(), 1);

    AbstractTracingSpan span = spans.get(0);
    querySpanAssert(span, "/get", 1, "solrJ/collection/get");
}
 
Example 6
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 5 votes vote down vote up
/**
 * @param parameterMap Map of parameters which passes to the executor
 */
public void init(Map parameterMap) {

    if (parameterMap != null) {

        istioSystemNamespace = (String) parameterMap.get("istioSystemNamespace");
        appNamespace = (String) parameterMap.get("appNamespace");
        kubernetesAPIServerUrl = (String) parameterMap.get("kubernetesAPIServerUrl");
        saTokenFileName = (String) parameterMap.get("saTokenFileName");
        saTokenFilePath = (String) parameterMap.get("saTokenFilePath");
        kubernetesServiceDomain = (String) parameterMap.get("kubernetesServiceDomain");
    }

    if (StringUtils.isEmpty(istioSystemNamespace)) {
        istioSystemNamespace = ISTIO_SYSTEM_NAMESPACE;
    }

    if (StringUtils.isEmpty(appNamespace)) {
        appNamespace = APP_NAMESPACE;
    }

    if (StringUtils.isEmpty(kubernetesAPIServerUrl)) {
        kubernetesAPIServerUrl = K8S_MASTER_URL;
    }

    if (StringUtils.isEmpty(saTokenFilePath)) {
        saTokenFilePath = SATOKEN_FILE_PATH;
    }

    if (StringUtils.isEmpty(kubernetesServiceDomain)) {
        kubernetesServiceDomain = K8S_SERVICE_DOMAIN;
    }
}
 
Example 7
Source File: RealTimeGetComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private List<Long> resolveVersionRanges(String versionsStr, UpdateLog ulog) {
  if (StringUtils.isEmpty(versionsStr)) {
    return Collections.emptyList();
  }
  
  List<String> ranges = StrUtils.splitSmart(versionsStr, ",", true);
  
  // TODO merge ranges.
  
  // get all the versions from updatelog and sort them
  List<Long> versionAvailable = null;
  try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {
    versionAvailable = recentUpdates.getVersions(ulog.getNumRecordsToKeep());
  }
  // sort versions
  Collections.sort(versionAvailable, PeerSync.absComparator);
  
  // This can be done with single pass over both ranges and versionsAvailable, that would require 
  // merging ranges. We currently use Set to ensure there are no duplicates.
  Set<Long> versionsToRet = new HashSet<>(ulog.getNumRecordsToKeep());
  for (String range : ranges) {
    String[] rangeBounds = range.split("\\.{3}");
    int indexStart = Collections.binarySearch(versionAvailable, Long.valueOf(rangeBounds[1]), PeerSync.absComparator);
    int indexEnd = Collections.binarySearch(versionAvailable, Long.valueOf(rangeBounds[0]), PeerSync.absComparator); 
    if(indexStart >=0 && indexEnd >= 0) {
      versionsToRet.addAll(versionAvailable.subList(indexStart, indexEnd + 1)); // indexEnd is exclusive
    }
  }
  // TODO do we need to sort versions using PeerSync.absComparator?
  return new ArrayList<>(versionsToRet);
}
 
Example 8
Source File: CatStream.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public CatStream(String commaDelimitedFilepaths, int maxLines) {
  if (commaDelimitedFilepaths == null) {
    throw new IllegalArgumentException("No filepaths provided to stream");
  }
  final String filepathsWithoutSurroundingQuotes = stripSurroundingQuotesIfTheyExist(commaDelimitedFilepaths);
  if (StringUtils.isEmpty(filepathsWithoutSurroundingQuotes)) {
    throw new IllegalArgumentException("No filepaths provided to stream");
  }

  this.commaDelimitedFilepaths = filepathsWithoutSurroundingQuotes;
  this.maxLines = maxLines;
}
 
Example 9
Source File: MDCLoggingContext.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static void setTracerId(String traceId) {
  if (!StringUtils.isEmpty(traceId)) {
    MDC.put(TRACE_ID, "t:" + traceId);
  } else {
    MDC.remove(TRACE_ID);
  }
}
 
Example 10
Source File: PublicKeyHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private CryptoKeys.RSAKeyPair createKeyPair(CloudConfig config) throws IOException, InvalidKeySpecException {
  if (config == null) {
    return new CryptoKeys.RSAKeyPair();
  }

  String publicKey = config.getPkiHandlerPublicKeyPath();
  String privateKey = config.getPkiHandlerPrivateKeyPath();

  // If both properties unset, then we fall back to generating a new key pair
  if (StringUtils.isEmpty(publicKey) && StringUtils.isEmpty(privateKey)) {
    return new CryptoKeys.RSAKeyPair();
  }

  return new CryptoKeys.RSAKeyPair(new URL(privateKey), new URL(publicKey));
}
 
Example 11
Source File: OverriddenZkACLAndCredentialsProvidersTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public SolrZkClient getSolrZkClient(String zkServerAddress, int zkClientTimeout) {
  return new SolrZkClient(zkServerAddress, zkClientTimeout) {
    
    @Override
    protected ZkCredentialsProvider createZkCredentialsToAddAutomatically() {
      return new DefaultZkCredentialsProvider() {
        @Override
        protected Collection<ZkCredentials> createCredentials() {
          List<ZkCredentials> result = new ArrayList<>();
          if (!StringUtils.isEmpty(digestUsername) && !StringUtils.isEmpty(digestPassword)) {
            result.add(new ZkCredentials("digest",
                (digestUsername + ":" + digestPassword).getBytes(StandardCharsets.UTF_8)));
          }
          return result;
        }

      };
    }

    @Override
    public ZkACLProvider createZkACLProvider() {
      return new VMParamsAllAndReadonlyDigestZkACLProvider() {
        @Override
        protected List<ACL> createNonSecurityACLsToAdd() {
          return createACLsToAdd(true, digestUsername, digestPassword, digestReadonlyUsername, digestReadonlyPassword);
        }

        /**
         * @return Set of ACLs to return security-related znodes
         */
        @Override
        protected List<ACL> createSecurityACLsToAdd() {
          return createACLsToAdd(false, digestUsername, digestPassword, digestReadonlyUsername, digestReadonlyPassword);
        }
      };
    }
    
  };
}
 
Example 12
Source File: ZkDynamicConfig.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a raw multi line config string with the full content of znode /zookeeper/config.
 * @param lines the multi line config string. If empty or null, this will return an empty list
 * @return an instance of ZkDynamicConfig
 */
public static ZkDynamicConfig parseLines(String lines) {
  ZkDynamicConfig zkDynamicConfig = new ZkDynamicConfig();
  if (!StringUtils.isEmpty(lines)) {
    lines.lines().forEach(l -> {
      if (l.startsWith("version=")) {
        zkDynamicConfig.version = l.split("=")[1];
      }
      if (l.startsWith("server.")) {
        zkDynamicConfig.servers.add(Server.parseLine(l));
      }
    });
  }
  return zkDynamicConfig;
}
 
Example 13
Source File: GraphBackedSearchIndexer.java    From atlas with Apache License 2.0 5 votes vote down vote up
private void createEdgeLabelUsingLabelName(final AtlasGraphManagement management, final String label) {
    if (StringUtils.isEmpty(label)) {
        return;
    }

    org.apache.atlas.repository.graphdb.AtlasEdgeLabel edgeLabel = management.getEdgeLabel(label);

    if (edgeLabel == null) {
        management.makeEdgeLabel(label);

        LOG.info("Created edge label {} ", label);
    }
}
 
Example 14
Source File: SSLConfigurations.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private boolean isEmpty(String str) {
  return StringUtils.isEmpty(str);
}
 
Example 15
Source File: ChronixQueryHandler.java    From chronix.server with Apache License 2.0 4 votes vote down vote up
private boolean contains(String field, String fields) {
    return !(StringUtils.isEmpty(field) || StringUtils.isEmpty(fields)) && fields.contains(field);
}
 
Example 16
Source File: ChangePasswordUtil.java    From ranger with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	logger.info("main()");
	try {
		ChangePasswordUtil loader = (ChangePasswordUtil) CLIUtil.getBean(ChangePasswordUtil.class);
		loader.init();
		userPwdArgs=args;
		if (args.length > 4) {
			if ("-default".equalsIgnoreCase(args[args.length-1])) {
				defaultPwdChangeRequest = true;
			}
			while (loader.isMoreToProcess()) {
				loader.load();
			}
			logger.info("Load complete. Exiting!!!");
			System.exit(0);
		} else if (args.length == 3 || args.length == 4) {
			userLoginId = args[0];
			currentPassword = args[1];
			newPassword = args[2];
			if (args.length == 4) {
				if ("-default".equalsIgnoreCase(args[3])) {
					defaultPwdChangeRequest = true;
				}
			}
			if (StringUtils.isEmpty(userLoginId)) {
				System.out.println("Invalid login ID. Exiting!!!");
				logger.info("Invalid login ID. Exiting!!!");
				System.exit(1);
			}
			if (StringUtils.isEmpty(currentPassword)) {
				System.out.println("Invalid current password. Exiting!!!");
				logger.info("Invalid current password. Exiting!!!");
				System.exit(1);
			}
			if (StringUtils.isEmpty(newPassword)) {
				System.out.println("Invalid new password. Exiting!!!");
				logger.info("Invalid new password. Exiting!!!");
				System.exit(1);
			}
			while (loader.isMoreToProcess()) {
				loader.load();
			}
			logger.info("Load complete. Exiting!!!");
			System.exit(0);
		} else {
			System.out.println(
					"ChangePasswordUtil: Incorrect Arguments \n Usage: \n <loginId> <current-password> <new-password>");
			logger.error(
					"ChangePasswordUtil: Incorrect Arguments \n Usage: \n <loginId> <current-password> <new-password>");
			System.exit(1);
		}
	} catch (Exception e) {
		logger.error("Error loading", e);
		System.exit(1);
	}
}
 
Example 17
Source File: JWTAuthPlugin.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void init(Map<String, Object> pluginConfig) {
  this.pluginConfig = pluginConfig;
  this.issuerConfigs = null;
  List<String> unknownKeys = pluginConfig.keySet().stream().filter(k -> !PROPS.contains(k)).collect(Collectors.toList());
  unknownKeys.remove("class");
  unknownKeys.remove("");
  if (!unknownKeys.isEmpty()) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Invalid JwtAuth configuration parameter " + unknownKeys); 
  }

  blockUnknown = Boolean.parseBoolean(String.valueOf(pluginConfig.getOrDefault(PARAM_BLOCK_UNKNOWN, false)));
  requireIssuer = Boolean.parseBoolean(String.valueOf(pluginConfig.getOrDefault(PARAM_REQUIRE_ISSUER, "true")));
  requireExpirationTime = Boolean.parseBoolean(String.valueOf(pluginConfig.getOrDefault(PARAM_REQUIRE_EXPIRATIONTIME, "true")));
  if (pluginConfig.get(PARAM_REQUIRE_SUBJECT) != null) {
    log.warn("Parameter {} is no longer used and may generate error in a later version. A subject claim is now always required",
        PARAM_REQUIRE_SUBJECT);
  }
  principalClaim = (String) pluginConfig.getOrDefault(PARAM_PRINCIPAL_CLAIM, "sub");

  rolesClaim = (String) pluginConfig.get(PARAM_ROLES_CLAIM);
  algWhitelist = (List<String>) pluginConfig.get(PARAM_ALG_WHITELIST);
  realm = (String) pluginConfig.getOrDefault(PARAM_REALM, DEFAULT_AUTH_REALM);

  Map<String, String> claimsMatch = (Map<String, String>) pluginConfig.get(PARAM_CLAIMS_MATCH);
  claimsMatchCompiled = new HashMap<>();
  if (claimsMatch != null) {
    for (Map.Entry<String, String> entry : claimsMatch.entrySet()) {
      claimsMatchCompiled.put(entry.getKey(), Pattern.compile(entry.getValue()));
    }
  }

  String requiredScopesStr = (String) pluginConfig.get(PARAM_SCOPE);
  if (!StringUtils.isEmpty(requiredScopesStr)) {
    requiredScopes = Arrays.asList(requiredScopesStr.split("\\s+"));
  }

  long jwkCacheDuration = Long.parseLong((String) pluginConfig.getOrDefault(PARAM_JWK_CACHE_DURATION, "3600"));
  JWTIssuerConfig.setHttpsJwksFactory(new JWTIssuerConfig.HttpsJwksFactory(jwkCacheDuration, DEFAULT_REFRESH_REPRIEVE_THRESHOLD));

  issuerConfigs = new ArrayList<>();

  // Try to parse an issuer from top level config, and add first (primary issuer)
  Optional<JWTIssuerConfig> topLevelIssuer = parseIssuerFromTopLevelConfig(pluginConfig);
  topLevelIssuer.ifPresent(ic -> {
    issuerConfigs.add(ic);
    log.warn("JWTAuthPlugin issuer is configured using top-level configuration keys. Please consider using the 'issuers' array instead.");
  });

  // Add issuers from 'issuers' key
  issuerConfigs.addAll(parseIssuers(pluginConfig));
  verificationKeyResolver = new JWTVerificationkeyResolver(issuerConfigs, requireIssuer);

  if (issuerConfigs.size() > 0 && getPrimaryIssuer().getAuthorizationEndpoint() != null) {
    adminUiScope = (String) pluginConfig.get(PARAM_ADMINUI_SCOPE);
    if (adminUiScope == null && requiredScopes.size() > 0) {
      adminUiScope = requiredScopes.get(0);
      log.warn("No adminUiScope given, using first scope in 'scope' list as required scope for accessing Admin UI");
    }

    if (adminUiScope == null) {
      adminUiScope = "solr";
      log.info("No adminUiScope provided, fallback to 'solr' as required scope for Admin UI login may not work");
    }

    Object redirectUrisObj = pluginConfig.get(PARAM_REDIRECT_URIS);
    redirectUris = Collections.emptyList();
    if (redirectUrisObj != null) {
      if (redirectUrisObj instanceof String) {
        redirectUris = Collections.singletonList((String) redirectUrisObj);
      } else if (redirectUrisObj instanceof List) {
        redirectUris = (List<String>) redirectUrisObj;
      }
    }
  }

  initConsumer();

  lastInitTime = Instant.now();
}
 
Example 18
Source File: Http2SolrClient.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private ContentType getContentType(Response response) {
  String contentType = response.getHeaders().get(HttpHeader.CONTENT_TYPE);
  return StringUtils.isEmpty(contentType)? null : ContentType.parse(contentType);
}
 
Example 19
Source File: MoreLikeThisHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public MoreLikeThisHelper( SolrParams params, SolrIndexSearcher searcher )
{
  this.searcher = searcher;
  this.reader = searcher.getIndexReader();
  this.uniqueKeyField = searcher.getSchema().getUniqueKeyField();
  this.needDocSet = params.getBool(FacetParams.FACET,false);
  
  SolrParams required = params.required();
  String[] fl = required.getParams(MoreLikeThisParams.SIMILARITY_FIELDS);
  List<String> list = new ArrayList<>();
  for (String f : fl) {
    if (!StringUtils.isEmpty(f))  {
      String[] strings = splitList.split(f);
      for (String string : strings) {
        if (!StringUtils.isEmpty(string)) {
          list.add(string);
        }
      }
    }
  }
  String[] fields = list.toArray(new String[list.size()]);
  if( fields.length < 1 ) {
    throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, 
        "MoreLikeThis requires at least one similarity field: "+MoreLikeThisParams.SIMILARITY_FIELDS );
  }
  
  this.mlt = new MoreLikeThis( reader ); // TODO -- after LUCENE-896, we can use , searcher.getSimilarity() );
  mlt.setFieldNames(fields);
  mlt.setAnalyzer( searcher.getSchema().getIndexAnalyzer() );
  
  // configurable params
  
  mlt.setMinTermFreq(       params.getInt(MoreLikeThisParams.MIN_TERM_FREQ,         MoreLikeThis.DEFAULT_MIN_TERM_FREQ));
  mlt.setMinDocFreq(        params.getInt(MoreLikeThisParams.MIN_DOC_FREQ,          MoreLikeThis.DEFAULT_MIN_DOC_FREQ));
  mlt.setMaxDocFreq(        params.getInt(MoreLikeThisParams.MAX_DOC_FREQ,          MoreLikeThis.DEFAULT_MAX_DOC_FREQ));
  mlt.setMinWordLen(        params.getInt(MoreLikeThisParams.MIN_WORD_LEN,          MoreLikeThis.DEFAULT_MIN_WORD_LENGTH));
  mlt.setMaxWordLen(        params.getInt(MoreLikeThisParams.MAX_WORD_LEN,          MoreLikeThis.DEFAULT_MAX_WORD_LENGTH));
  mlt.setMaxQueryTerms(     params.getInt(MoreLikeThisParams.MAX_QUERY_TERMS,       MoreLikeThis.DEFAULT_MAX_QUERY_TERMS));
  mlt.setMaxNumTokensParsed(params.getInt(MoreLikeThisParams.MAX_NUM_TOKENS_PARSED, MoreLikeThis.DEFAULT_MAX_NUM_TOKENS_PARSED));
  mlt.setBoost(            params.getBool(MoreLikeThisParams.BOOST, false ) );
  
  // There is no default for maxDocFreqPct. Also, it's a bit oddly expressed as an integer value 
  // (percentage of the collection's documents count). We keep Lucene's convention here. 
  if (params.getInt(MoreLikeThisParams.MAX_DOC_FREQ_PCT) != null) {
    mlt.setMaxDocFreqPct(params.getInt(MoreLikeThisParams.MAX_DOC_FREQ_PCT));
  }

  boostFields = SolrPluginUtils.parseFieldBoosts(params.getParams(MoreLikeThisParams.QF));
}
 
Example 20
Source File: SolrClient.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieves the SolrDocuments associated with the given identifiers and uses
 * the SolrParams to execute the request.
 *
 * If a document was not found, it will not be added to the SolrDocumentList.
 *
 * @param collection the Solr collection to query
 * @param ids the ids
 * @param params additional parameters to add to the query
 *
 * @return a SolrDocumentList, or null if no documents were found
 *
 * @throws IOException If there is a low-level I/O error.
 * @throws SolrServerException if there is an error on the server
 */
public SolrDocumentList getById(String collection, Collection<String> ids, SolrParams params)
    throws SolrServerException, IOException {
  if (ids == null || ids.isEmpty()) {
    throw new IllegalArgumentException("Must provide an identifier of a document to retrieve.");
  }

  ModifiableSolrParams reqParams = new ModifiableSolrParams(params);
  if (StringUtils.isEmpty(reqParams.get(CommonParams.QT))) {
    reqParams.set(CommonParams.QT, "/get");
  }
  reqParams.set("ids", ids.stream().map(id -> StrUtils.escapeTextWithSeparator(id, ',')).toArray(String[]::new));
  return query(collection, reqParams).getResults();
}