org.apache.solr.common.SolrException Java Examples

The following examples show how to use org.apache.solr.common.SolrException. 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: DeleteReplicaCmd.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Validate if there is less replicas than requested to remove. Also error out if there is
 * only one replica available
 */
private void validateReplicaAvailability(Slice slice, String shard, String collectionName, int count) {
  //If there is a specific shard passed, validate if there any or just 1 replica left
  if (slice != null) {
    Collection<Replica> allReplicasForShard = slice.getReplicas();
    if (allReplicasForShard == null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No replicas found  in shard/collection: " +
              shard + "/"  + collectionName);
    }


    if (allReplicasForShard.size() == 1) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "There is only one replica available in shard/collection: " +
              shard + "/" + collectionName + ". Cannot delete that.");
    }

    if (allReplicasForShard.size() <= count) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "There are lesser num replicas requested to be deleted than are available in shard/collection : " +
              shard + "/"  + collectionName  + " Requested: "  + count + " Available: " + allReplicasForShard.size() + ".");
    }
  }
}
 
Example #2
Source File: ClusterStateUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static boolean waitForLiveAndActiveReplicaCount(ZkStateReader zkStateReader,
    String collection, int replicaCount, int timeoutInMs) {
  long timeout = System.nanoTime()
      + TimeUnit.NANOSECONDS.convert(timeoutInMs, TimeUnit.MILLISECONDS);
  boolean success = false;
  while (!success && System.nanoTime() < timeout) {
    success = getLiveAndActiveReplicaCount(zkStateReader, collection) == replicaCount;
    
    if (!success) {
      try {
        Thread.sleep(TIMEOUT_POLL_MS);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new SolrException(ErrorCode.SERVER_ERROR, "Interrupted");
      }
    }
    
  }
  
  return success;
}
 
Example #3
Source File: SolrRrdBackendFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a database.
 * @param path database path.
 * @throws IOException on Solr exception
 */
public void remove(String path) throws IOException {
  SolrRrdBackend backend = backends.remove(path);
  if (backend != null) {
    IOUtils.closeQuietly(backend);
  }
  if (!persistent) {
    return;
  }
  // remove Solr doc
  try {
    solrClient.deleteByQuery(collection, "{!term f=id}" + ID_PREFIX + ID_SEP + path);
  } catch (SolrServerException | SolrException e) {
    log.warn("Error deleting RRD for path {}", path, e);
  }
}
 
Example #4
Source File: IndexFetcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void downloadConfFiles(List<Map<String, Object>> confFilesToDownload, long latestGeneration) throws Exception {
  log.info("Starting download of configuration files from master: {}", confFilesToDownload);
  confFilesDownloaded = Collections.synchronizedList(new ArrayList<>());
  File tmpconfDir = new File(solrCore.getResourceLoader().getConfigDir(), "conf." + getDateAsStr(new Date()));
  try {
    boolean status = tmpconfDir.mkdirs();
    if (!status) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
              "Failed to create temporary config folder: " + tmpconfDir.getName());
    }
    for (Map<String, Object> file : confFilesToDownload) {
      String saveAs = (String) (file.get(ALIAS) == null ? file.get(NAME) : file.get(ALIAS));
      localFileFetcher = new LocalFsFileFetcher(tmpconfDir, file, saveAs, CONF_FILE_SHORT, latestGeneration);
      currentFile = file;
      localFileFetcher.fetchFile();
      confFilesDownloaded.add(new HashMap<>(file));
    }
    // this is called before copying the files to the original conf dir
    // so that if there is an exception avoid corrupting the original files.
    terminateAndWaitFsyncService();
    copyTmpConfFiles2Conf(tmpconfDir);
  } finally {
    delTree(tmpconfDir);
  }
}
 
Example #5
Source File: TestSolrQueryParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testManyClauses_Solr() throws Exception {
  final String a = "1 a 2 b 3 c 10 d 11 12 "; // 10 terms
  
  // this should exceed our solrconfig.xml level (solr specific) maxBooleanClauses limit
  // even though it's not long enough to trip the Lucene level (global) limit
  final String too_long = "id:(" + a + a + a + a + a + ")";

  final String expectedMsg = "Too many clauses";
  ignoreException(expectedMsg);
  SolrException e = expectThrows(SolrException.class, "expected SolrException",
                                 () -> assertJQ(req("q", too_long), "/response/numFound==6"));
  assertThat(e.getMessage(), containsString(expectedMsg));
  
  // but should still work as a filter query since TermsQuery can be used...
  assertJQ(req("q","*:*", "fq", too_long)
           ,"/response/numFound==6");
  assertJQ(req("q","*:*", "fq", too_long, "sow", "false")
           ,"/response/numFound==6");
  assertJQ(req("q","*:*", "fq", too_long, "sow", "true")
           ,"/response/numFound==6");
}
 
Example #6
Source File: TrieField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** expert internal use, subject to change.
 * Returns null if no prefix or prefix not needed, or the prefix of the main value of a trie field
 * that indexes multiple precisions per value.
 */
public static String getMainValuePrefix(org.apache.solr.schema.FieldType ft) {
  if (ft instanceof TrieField) {
    final TrieField trie = (TrieField)ft;
    if (trie.precisionStep  == Integer.MAX_VALUE)
      return null;
    switch (trie.type) {
      case INTEGER:
      case FLOAT:
        return INT_PREFIX;
      case LONG:
      case DOUBLE:
      case DATE:
        return LONG_PREFIX;
      default:
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown type for trie field: " + trie.type);
    }
  }
  return null;
}
 
Example #7
Source File: HttpPartitionOnCommitTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected void sendCommitWithRetry(Replica replica) throws Exception {
  String replicaCoreUrl = replica.getCoreUrl();
  log.info("Sending commit request to: {}", replicaCoreUrl);
  final RTimer timer = new RTimer();
  try (HttpSolrClient client = getHttpSolrClient(replicaCoreUrl)) {
    try {
      client.commit();

      if (log.isInfoEnabled()) {
        log.info("Sent commit request to {} OK, took {}ms", replicaCoreUrl, timer.getTime());
      }
    } catch (Exception exc) {
      Throwable rootCause = SolrException.getRootCause(exc);
      if (rootCause instanceof NoHttpResponseException) {
        log.warn("No HTTP response from sending commit request to {}; will re-try after waiting 3 seconds", replicaCoreUrl);
        Thread.sleep(3000);
        client.commit();
        log.info("Second attempt at sending commit to {} succeeded", replicaCoreUrl);
      } else {
        throw exc;
      }
    }
  }
}
 
Example #8
Source File: CurrencyValue.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public int compareTo(CurrencyValue o) {
  if(o == null) {
    throw new NullPointerException("Cannot compare CurrencyValue to a null values");
  }
  if(!getCurrencyCode().equals(o.getCurrencyCode())) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Cannot compare CurrencyValues when their currencies are not equal");
  }
  if(o.getAmount() < getAmount()) {
    return 1;
  }
  if(o.getAmount() == getAmount()) {
    return 0;
  }
  return -1;
}
 
Example #9
Source File: PlainTextIndexer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public IndexDocument getIndexedDocument(File2Index fileData) throws SolrException,
           RegistryException {
			
	IndexDocument indexDoc = new IndexDocument(fileData.path, RegistryUtils.decodeBytes(fileData.data), null);
			
	Map<String, List<String>> fields = new HashMap<String, List<String>>();
	fields.put("path", Arrays.asList(fileData.path));
			
	if (fileData.mediaType != null) {
		fields.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList(fileData.mediaType));
	} else {
		fields.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList("text/(.)"));
	}
	
	indexDoc.setFields(fields);
	
	return indexDoc;
}
 
Example #10
Source File: DocExpirationUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void processAdd(AddUpdateCommand cmd) throws IOException {
  final SolrInputDocument doc = cmd.getSolrInputDocument();

  final String math = doc.containsKey(ttlField) 
    ? doc.getFieldValue(ttlField).toString() : defaultTtl;

  if (null != math) {
    try {
      final DateMathParser dmp = new DateMathParser();
      // TODO: should we try to accept things like "1DAY" as well as "+1DAY" ?
      // How? 
      // 'startsWith("+")' is a bad idea because it would cause problems with
      // things like "/DAY+1YEAR"
      // Maybe catch ParseException and retry with "+" prepended?
      doc.addField(expireField, dmp.parseMath(math));
    } catch (ParseException pe) {
      throw new SolrException(BAD_REQUEST, "Can't parse ttl as date math: " + math, pe);
    }
  }

  super.processAdd(cmd);
}
 
Example #11
Source File: DeleteCollectionCmd.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private List<String> checkAliasReference(ZkStateReader zkStateReader, String extCollection, boolean followAliases) throws Exception {
  Aliases aliases = zkStateReader.getAliases();
  List<String> aliasesRefs = referencedByAlias(extCollection, aliases, followAliases);
  List<String> aliasesToDelete = new ArrayList<>();
  if (aliasesRefs.size() > 0) {
    zkStateReader.aliasesManager.update(); // aliases may have been stale; get latest from ZK
    aliases = zkStateReader.getAliases();
    aliasesRefs = referencedByAlias(extCollection, aliases, followAliases);
    String collection = followAliases ? aliases.resolveSimpleAlias(extCollection) : extCollection;
    if (aliasesRefs.size() > 0) {
      for (String alias : aliasesRefs) {
        // for back-compat in 8.x we don't automatically remove other
        // aliases that point only to this collection
        if (!extCollection.equals(alias)) {
          throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
              "Collection : " + collection + " is part of aliases: " + aliasesRefs + ", remove or modify the aliases before removing this collection.");
        } else {
          aliasesToDelete.add(alias);
        }
      }
    }
  }
  return aliasesToDelete;
}
 
Example #12
Source File: ClassificationUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {
  String trainingFilterQueryString = (params.get(KNN_FILTER_QUERY));
  try {
    if (trainingFilterQueryString != null && !trainingFilterQueryString.isEmpty()) {
      Query trainingFilterQuery = this.parseFilterQuery(trainingFilterQueryString, params, req);
      classificationParams.setTrainingFilterQuery(trainingFilterQuery);
    }
  } catch (SyntaxError | RuntimeException syntaxError) {
    throw new SolrException
        (SolrException.ErrorCode.SERVER_ERROR,
            "Classification UpdateProcessor Training Filter Query: '" + trainingFilterQueryString + "' is not supported", syntaxError);
  }

  IndexSchema schema = req.getSchema();
  IndexReader indexReader = req.getSearcher().getIndexReader();

  return new ClassificationUpdateProcessor(classificationParams, next, indexReader, schema);
}
 
Example #13
Source File: ZkController.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void waitForShardId(CoreDescriptor cd) {
  if (log.isDebugEnabled()) {
    log.debug("waiting to find shard id in clusterstate for {}", cd.getName());
  }
  int retryCount = 320;
  while (retryCount-- > 0) {
    final String shardId = zkStateReader.getClusterState().getShardId(cd.getCollectionName(), getNodeName(), cd.getName());
    if (shardId != null) {
      cd.getCloudDescriptor().setShardId(shardId);
      return;
    }
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }

  throw new SolrException(ErrorCode.SERVER_ERROR,
      "Could not get shard id for core: " + cd.getName());
}
 
Example #14
Source File: ExtendedDismaxQParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected DynamicField(String wildcard) {
  this.wildcard = wildcard;
  if (wildcard.equals("*")) {
    type=CATCHALL;
    str=null;
  }
  else if (wildcard.startsWith("*")) {
    type=ENDS_WITH;
    str=wildcard.substring(1);
  }
  else if (wildcard.endsWith("*")) {
    type=STARTS_WITH;
    str=wildcard.substring(0,wildcard.length()-1);
  }
  else {
    throw new SolrException(ErrorCode.BAD_REQUEST, "dynamic field name must start or end with *");
  }
}
 
Example #15
Source File: PackageManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Given a package, return a map of collections where this package is
 * installed to the installed version (which can be {@link PackagePluginHolder#LATEST})
 */
public Map<String, String> getDeployedCollections(String packageName) {
  List<String> allCollections;
  try {
    allCollections = zkClient.getChildren(ZkStateReader.COLLECTIONS_ZKNODE, null, true);
  } catch (KeeperException | InterruptedException e) {
    throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, e);
  }
  Map<String, String> deployed = new HashMap<String, String>();
  for (String collection: allCollections) {
    // Check package version installed
    String paramsJson = PackageUtils.getJsonStringFromUrl(solrClient.getHttpClient(), solrBaseUrl + PackageUtils.getCollectionParamsPath(collection) + "/PKG_VERSIONS?omitHeader=true");
    String version = null;
    try {
      version = JsonPath.parse(paramsJson, PackageUtils.jsonPathConfiguration())
          .read("$['response'].['params'].['PKG_VERSIONS'].['"+packageName+"'])");
    } catch (PathNotFoundException ex) {
      // Don't worry if PKG_VERSION wasn't found. It just means this collection was never touched by the package manager.
    }
    if (version != null) {
      deployed.put(collection, version);
    }
  }
  return deployed;
}
 
Example #16
Source File: FieldMutatingUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Handles common initialization related to source fields for 
 * constructing the FieldNameSelector to be used.
 *
 * Will error if any unexpected init args are found, so subclasses should
 * remove any subclass-specific init args before calling this method.
 */
@SuppressWarnings("unchecked")
@Override
public void init(@SuppressWarnings({"rawtypes"})NamedList args) {

  inclusions = parseSelectorParams(args);
  exclusions = parseSelectorExclusionParams(args);

  if (0 < args.size()) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
        "Unexpected init param(s): '" + args.getName(0) + "'");
  }

}
 
Example #17
Source File: SumsqAgg.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public SlotAcc createSlotAcc(FacetContext fcontext, long numDocs, int numSlots) throws IOException {
  ValueSource vs = getArg();

  if (vs instanceof FieldNameValueSource) {
    String field = ((FieldNameValueSource)vs).getFieldName();
    SchemaField sf = fcontext.qcontext.searcher().getSchema().getField(field);
    if (sf.getType().getNumberType() == null) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
          name() + " aggregation not supported for " + sf.getType().getTypeName());
    }
    if (sf.multiValued() || sf.getType().multiValuedFieldCache()) {
      if (sf.hasDocValues()) {
        if (sf.getType().isPointField()) {
          return new SumSqSortedNumericAcc(fcontext, sf, numSlots);
        }
        return new SumSqSortedSetAcc(fcontext, sf, numSlots);
      }
      if (sf.getType().isPointField()) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
            name() + " aggregation not supported for PointField w/o docValues");
      }
      return new SumSqUnInvertedFieldAcc(fcontext, sf, numSlots);
    }
    vs = sf.getType().getValueSource(sf, null);
  }
  return new SlotAcc.SumsqSlotAcc(vs, fcontext, numSlots);
}
 
Example #18
Source File: FacetHeatmap.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void process() throws IOException {
  super.process(); // handles domain changes

  //Compute!
  final HeatmapFacetCounter.Heatmap heatmap;
  try {
    heatmap = HeatmapFacetCounter.calcFacets(
        strategy,
        fcontext.searcher.getTopReaderContext(),
        getTopAcceptDocs(fcontext.base, fcontext.searcher), // turn DocSet into Bits
        boundsShape,
        gridLevel,
        maxCells);
  } catch (IllegalArgumentException e) {//e.g. too many cells
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.toString(), e);
  }

  //Populate response
  response = new SimpleOrderedMap<>();
  response.add("gridLevel", gridLevel);
  response.add("columns", heatmap.columns);
  response.add("rows", heatmap.rows);
  response.add("minX", heatmap.region.getMinX());
  response.add("maxX", heatmap.region.getMaxX());
  response.add("minY", heatmap.region.getMinY());
  response.add("maxY", heatmap.region.getMaxY());

  //A shard request will always be a PNG
  String format = fcontext.isShard() ? FORMAT_PNG : FacetHeatmap.this.format;

  response.add("counts_" + format, formatCountsVal(format, heatmap.columns, heatmap.rows, heatmap.counts, fcontext.getDebugInfo()));

  // note: we do not call processStats or processSubs as it's not supported yet
}
 
Example #19
Source File: Assign.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static List<String> checkLiveNodes(List<String> createNodeList, ClusterState clusterState) {
  Set<String> liveNodes = clusterState.getLiveNodes();
  if (createNodeList != null) {
    if (!liveNodes.containsAll(createNodeList)) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
          "At least one of the node(s) specified " + createNodeList + " are not currently active in "
              + createNodeList + ", no action taken.");
    }
    // the logic that was extracted to this method used to create a defensive copy but no code
    // was modifying the copy, if this method is made protected or public we want to go back to that
  }
  return createNodeList; // unmodified, but return for inline use
}
 
Example #20
Source File: CdcrUpdateLog.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * If called after {@link #next()}, it resets the reader to its last position.
 */
public void resetToLastPosition() {
  try {
    if (tlogReader != null) {
      tlogReader.fis.seek(lastPositionInTLog);
      numRecordsReadInCurrentTlog--;
      lastVersion = nextToLastVersion;
    }
  } catch (IOException e) {
    log.error("Failed to seek last position in tlog", e);
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Failed to seek last position in tlog", e);
  }
}
 
Example #21
Source File: IfFunction.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public DateIfFunction(BooleanValue ifExpr, DateValue thenExpr, DateValue elseExpr) throws SolrException {
  this.ifExpr = ifExpr;
  this.thenExpr = thenExpr;
  this.elseExpr = elseExpr;
  this.exprStr = AnalyticsValueStream.createExpressionString(name,ifExpr,thenExpr,elseExpr);
  this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,ifExpr,thenExpr,elseExpr);
}
 
Example #22
Source File: RdfBulkUpdateRequestHandler.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void load( 
		final SolrQueryRequest request, 
		final SolrQueryResponse response,
		final ContentStream stream, 
		final UpdateRequestProcessor processor) throws Exception {
	
	final PipedRDFIterator<Quad> iterator = new PipedRDFIterator<Quad>();
	final StreamRDF inputStream = new PipedQuadsStream(iterator);
	
	executor.submit(new Runnable() {
		@Override
		public void run() {
			try {
				RDFDataMgr.parse(
						inputStream, 
						stream.getStream(), 
						RDFLanguages.contentTypeToLang(stream.getContentType()));
			} catch (final IOException exception) {
				throw new SolrException(ErrorCode.SERVER_ERROR, exception);
			}					
		}
	});
	
	final DatasetGraph dataset = new LocalDatasetGraph(request, response);
	while (iterator.hasNext()) {
		dataset.add(iterator.next());
	}									
}
 
Example #23
Source File: FacetFieldProcessorByArrayUIF.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
FacetFieldProcessorByArrayUIF(FacetContext fcontext, FacetField freq, SchemaField sf) {
  super(fcontext, freq, sf);
  if (! sf.isUninvertible()) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                            getClass()+" can not be used on fields where uninvertible='false'");
  }
}
 
Example #24
Source File: ReplaceFunction.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public ValueReplaceFunction(AnalyticsValue baseExpr, AnalyticsValue compExpr, AnalyticsValue fillExpr) throws SolrException {
  this.baseExpr = baseExpr;
  this.compExpr = compExpr;
  this.fillExpr = fillExpr;
  this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,compExpr,fillExpr);
  this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,compExpr,fillExpr);
}
 
Example #25
Source File: DateRangeField.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public NRShape parseShape(String str) {
  if (str.contains(" TO ")) {
    //TODO parsing range syntax doesn't support DateMath on either side or exclusive/inclusive
    try {
      return tree.parseShape(str);
    } catch (ParseException e) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
          "Couldn't parse date because: "+ e.getMessage(), e);
    }
  } else {
    return tree.toShape(parseCalendar(str));
  }
}
 
Example #26
Source File: CloudDatasetGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean _containsGraph(final Node graphNode) {
	final SolrQuery query = new SolrQuery("*:*")
		.addFilterQuery(fq(Field.C, asNtURI(graphNode)))
		.setRows(0);
	try {
		return cloud.query(query).getResults().getNumFound() > 0;
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new SolrException(ErrorCode.SERVER_ERROR, exception);
	}			    
}
 
Example #27
Source File: SolrQueryRequestBase.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public List<CommandOperation> getCommands(boolean validateInput) {
  if (parsedCommands == null) {
    Iterable<ContentStream> contentStreams = getContentStreams();
    if (contentStreams == null) throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No content stream");
    for (ContentStream contentStream : contentStreams) {
      parsedCommands = ApiBag.getCommandOperations(contentStream, getValidators(), validateInput);
    }

  }
  return CommandOperation.clone(parsedCommands);

}
 
Example #28
Source File: TestJaegerConfigurator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked"})
public void testIncorrectFormat() {
  JaegerTracerConfigurator configurator = new JaegerTracerConfigurator();
  @SuppressWarnings({"rawtypes"})
  NamedList initArgs = new NamedList();
  initArgs.add(AGENT_HOST, 100);
  initArgs.add(AGENT_PORT, 5775);

  IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> configurator.init(initArgs));
  assertTrue(exc.getMessage().contains(AGENT_HOST));

  initArgs.clear();
  initArgs.add(AGENT_HOST, "localhost");
  initArgs.add(AGENT_PORT, "5775");
  exc = expectThrows(IllegalArgumentException.class, () -> configurator.init(initArgs));
  assertTrue(exc.getMessage().contains(AGENT_PORT));

  initArgs.clear();
  initArgs.add(AGENT_HOST, "localhost");
  initArgs.add(AGENT_PORT, 5775);
  initArgs.add(LOG_SPANS, 10);
  SolrException solrExc = expectThrows(SolrException.class, () -> configurator.init(initArgs));
  assertTrue(solrExc.getMessage().contains(LOG_SPANS));

  initArgs.clear();
  initArgs.add(AGENT_HOST, "localhost");
  initArgs.add(AGENT_PORT, 5775);
  initArgs.add(FLUSH_INTERVAL, "10");
  exc = expectThrows(IllegalArgumentException.class, () -> configurator.init(initArgs));
  assertTrue(exc.getMessage().contains(FLUSH_INTERVAL));

  initArgs.clear();
  initArgs.add(AGENT_HOST, "localhost");
  initArgs.add(AGENT_PORT, 5775);
  initArgs.add(MAX_QUEUE_SIZE, "10");
  exc = expectThrows(IllegalArgumentException.class, () -> configurator.init(initArgs));
  assertTrue(exc.getMessage().contains(MAX_QUEUE_SIZE));

}
 
Example #29
Source File: PackageTool.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Parses package name and version in the format "name:version" or "name"
 * @return A pair of package name (first) and version (second)
 */
private Pair<String, String> parsePackageVersion(String arg) {
  String[] splits = arg.split(":");
  if (splits.length > 2) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid package name: " + arg +
        ". Didn't match the pattern: <packagename>:<version> or <packagename>");
  }

  String packageName = splits[0];
  String version = splits.length == 2? splits[1]: null;
  return new Pair<>(packageName, version);
}
 
Example #30
Source File: FieldMutatingUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Collection<SelectorParams> parseSelectorExclusionParams(
        @SuppressWarnings({"rawtypes"})NamedList args) {
  Collection<SelectorParams> exclusions = new ArrayList<>();
  @SuppressWarnings({"unchecked"})
  List<Object> excList = args.getAll("exclude");
  for (Object excObj : excList) {
    if (null == excObj) {
      throw new SolrException (SolrException.ErrorCode.SERVER_ERROR,
          "'exclude' init param can not be null");
    }
    if (! (excObj instanceof NamedList) ) {
      throw new SolrException (SolrException.ErrorCode.SERVER_ERROR,
          "'exclude' init param must be <lst/>");
    }
    @SuppressWarnings({"rawtypes"})
    NamedList exc = (NamedList) excObj;
    exclusions.add(parseSelectorParams(exc));
    if (0 < exc.size()) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
          "Unexpected 'exclude' init sub-param(s): '" +
              args.getName(0) + "'");
    }
    // call once per instance
    args.remove("exclude");
  }
  return exclusions;
}