Java Code Examples for org.apache.solr.common.SolrException.ErrorCode#BAD_REQUEST

The following examples show how to use org.apache.solr.common.SolrException.ErrorCode#BAD_REQUEST . 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: AnalyticsRequestParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private static ValueFacet constructValueFacet(String name, AnalyticsValueFacetRequest facetRequest, ExpressionFactory expressionFactory, Map<String, AnalyticsExpression> expressions) throws SolrException {
  if (facetRequest.expression == null) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Value Facets must contain a mapping expression to facet over, '" + name + "' has none.");
  }

  // The second parameter must be a mapping expression
  AnalyticsValueStream expr = expressionFactory.createExpression(facetRequest.expression);
  if (!expr.getExpressionType().isUnreduced()) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Value Facet expressions must be mapping expressions, "
        + "the following expression in value facet '" + name + "' contains a reduction: " + facetRequest.expression);
  }
  if (!(expr instanceof StringValueStream)) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Value Facet expressions must be castable to string expressions, "
        + "the following expression in value facet '" + name + "' is not: " + facetRequest.expression);
  }

  ValueFacet facet = new ValueFacet(name, (StringValueStream)expr);

  // Check if the value facet is sorted
  if (facetRequest.sort != null) {
    facet.setSort(constructSort(facetRequest.sort, expressions));
  }
  return facet;
}
 
Example 2
Source File: PivotFacetProcessor.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * returns the {@link StatsField} instances that should be computed for a pivot
 * based on the 'stats' local params used.
 *
 * @return A list of StatsFields to compute for this pivot, or the empty list if none
 */
private static List<StatsField> getTaggedStatsFields(StatsInfo statsInfo,
                                                     String statsLocalParam) {
  if (null == statsLocalParam || null == statsInfo) {
    return Collections.emptyList();
  }
  
  List<StatsField> fields = new ArrayList<>(7);
  List<String> statsAr = StrUtils.splitSmart(statsLocalParam, ',');

  // TODO: for now, we only support a single tag name - we reserve using 
  // ',' as a possible delimiter for logic related to only computing stats
  // at certain levels -- see SOLR-6663
  if (1 < statsAr.size()) {
    String msg = StatsParams.STATS + " local param of " + FacetParams.FACET_PIVOT + 
      "may not include tags separated by a comma - please use a common tag on all " + 
      StatsParams.STATS_FIELD + " params you wish to compute under this pivot";
    throw new SolrException(ErrorCode.BAD_REQUEST, msg);
  }

  for(String stat : statsAr) {
    fields.addAll(statsInfo.getStatsFieldsByTag(stat));
  }
  return fields;
}
 
Example 3
Source File: CreateCollectionCmd.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static List<String> populateShardNames(ZkNodeProps message, String router) {
  List<String> shardNames = new ArrayList<>();
  Integer numSlices = message.getInt(OverseerCollectionMessageHandler.NUM_SLICES, null);
  if (ImplicitDocRouter.NAME.equals(router)) {
    ClusterStateMutator.getShardNames(shardNames, message.getStr("shards", null));
    numSlices = shardNames.size();
  } else {
    if (numSlices == null) {
      throw new SolrException(ErrorCode.BAD_REQUEST, OverseerCollectionMessageHandler.NUM_SLICES + " is a required param (when using CompositeId router).");
    }
    if (numSlices <= 0) {
      throw new SolrException(ErrorCode.BAD_REQUEST, OverseerCollectionMessageHandler.NUM_SLICES + " must be > 0");
    }
    ClusterStateMutator.getShardNames(numSlices, shardNames);
  }
  return shardNames;
}
 
Example 4
Source File: SolrSnapshotMetaDataManager.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * This method creates a new snapshot meta-data entry.
 *
 * @param name The name of the snapshot.
 * @param indexDirPath The directory path where the index files are stored.
 * @param gen The generation number for the {@linkplain IndexCommit} being snapshotted.
 * @throws IOException in case of I/O errors.
 */
public synchronized void snapshot(String name, String indexDirPath, long gen) throws IOException {
  Objects.requireNonNull(name);

  if (log.isInfoEnabled()) {
    log.info("Creating the snapshot named {} for core {} associated with index commit with generation {} in directory {}"
        , name, solrCore.getName(), gen, indexDirPath);
  }

  if(nameToDetailsMapping.containsKey(name)) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "A snapshot with name " + name + " already exists");
  }

  SnapshotMetaData d = new SnapshotMetaData(name, indexDirPath, gen);
  nameToDetailsMapping.put(name, d);

  boolean success = false;
  try {
    persist();
    success = true;
  } finally {
    if (!success) {
      try {
        release(name);
      } catch (Exception e) {
        // Suppress so we keep throwing original exception
      }
    }
  }
}
 
Example 5
Source File: AnalyticsRequestParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static QueryFacet constructQueryFacet(String name, AnalyticsQueryFacetRequest facetRequest) throws SolrException {
  if (facetRequest.queries == null || facetRequest.queries.size() == 0) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Query Facets must be contain at least 1 query to facet over, '" + name + "' does not.");
  }

  // The first param must be the facet name
  return new QueryFacet(name, facetRequest.queries);
}
 
Example 6
Source File: ChildDocTransformerFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static Query parseQuery(String qstr, SolrQueryRequest req, String param) {
  try {
    return QParser.getParser(qstr, req).getQuery();
  } catch (SyntaxError syntaxError) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Failed to parse '" + param + "' param.");
  }
}
 
Example 7
Source File: SolrRequestParsers.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Given a url-encoded query string (UTF-8), map it into the given map
 * @param queryString as given from URL
 * @param map place all parameters in this map
 */
static void parseQueryString(final String queryString, final Map<String,String[]> map) {
  if (queryString != null && queryString.length() > 0) {
    try {
      final int len = queryString.length();
      // this input stream emulates to get the raw bytes from the URL as passed to servlet container, it disallows any byte > 127 and enforces to %-escape them:
      final InputStream in = new InputStream() {
        int pos = 0;
        @Override
        public int read() {
          if (pos < len) {
            final char ch = queryString.charAt(pos);
            if (ch > 127) {
              throw new SolrException(ErrorCode.BAD_REQUEST, "URLDecoder: The query string contains a not-%-escaped byte > 127 at position " + pos);
            }
            pos++;
            return ch;
          } else {
            return -1;
          }
        }
      };
      parseFormDataContent(in, Long.MAX_VALUE, StandardCharsets.UTF_8, map, true);
    } catch (IOException ioe) {
      throw new SolrException(ErrorCode.BAD_REQUEST, ioe);
    }
  }
}
 
Example 8
Source File: TreeFacetComponent.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare(ResponseBuilder rb) throws IOException {
	super.prepare(rb);
	
	// Do we need to create a facet tree?
	if (rb.doFacets && rb.req.getParams().getBool(FACET_TREE, false)) {
		try {
			LOGGER.debug("{} set to true - adding tree fields to facets", FACET_TREE);
			// Make sure the facet tree field is in the facet field list
			addTreeFieldsToFacets(rb);
		} catch (SyntaxError e) {
			throw new SolrException(ErrorCode.BAD_REQUEST, e);
		}
	}
}
 
Example 9
Source File: ConfigSetsHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
  if (coreContainer == null) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Core container instance missing");
  }

  // Make sure that the core is ZKAware
  if (!coreContainer.isZooKeeperAware()) {
    throw new SolrException(ErrorCode.BAD_REQUEST,
        "Solr instance is not running in SolrCloud mode.");
  }

  // Pick the action
  SolrParams params = req.getParams();
  String a = params.get(ConfigSetParams.ACTION);
  if (a != null) {
    ConfigSetAction action = ConfigSetAction.get(a);
    if (action == null)
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unknown action: " + a);
    if (action == ConfigSetAction.UPLOAD) {
      handleConfigUploadRequest(req, rsp);
      return;
    }
    invokeAction(req, rsp, action);
  } else {
    throw new SolrException(ErrorCode.BAD_REQUEST, "action is a required param");
  }

  rsp.setHttpCaching(false);
}
 
Example 10
Source File: LukeRequestHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static ShowStyle get(String v) {
  if(v==null) return null;
  if("schema".equalsIgnoreCase(v)) return SCHEMA;
  if("index".equalsIgnoreCase(v))  return INDEX;
  if("doc".equalsIgnoreCase(v))    return DOC;
  if("all".equalsIgnoreCase(v))    return ALL;
  throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown Show Style: "+v);
}
 
Example 11
Source File: SolrRequestParsers.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static String decodeChars(byte[] bytes, long position, CharsetDecoder charsetDecoder) {
  try {
    return charsetDecoder.decode(ByteBuffer.wrap(bytes)).toString();
  } catch (CharacterCodingException cce) {
    throw new SolrException(ErrorCode.BAD_REQUEST,
      "URLDecoder: Invalid character encoding detected after position " + position +
      " of query string / form data (while parsing as " + charsetDecoder.charset().name() + ")"
    );
  }
}
 
Example 12
Source File: AnalyticsRequestParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private static PivotNode<?> constructPivot(AnalyticsPivotRequest pivotRequest,
                                    PivotNode<?> childPivot,
                                    ExpressionFactory expressionFactory,
                                    Map<String, AnalyticsExpression> expressions) throws SolrException {
  if (pivotRequest.name == null || pivotRequest.name.length() == 0) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Pivots must have a name.");
  }
  if (pivotRequest.expression == null) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Pivots must have an expression to facet over, '" + pivotRequest.name + "' does not.");
  }

  // The second parameter must be a mapping expression
  AnalyticsValueStream expr = expressionFactory.createExpression(pivotRequest.expression);
  if (!expr.getExpressionType().isUnreduced()) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Pivot expressions must be mapping expressions, "
        + "the following expression in pivot '" + pivotRequest.name + "' contains a reduction: " + pivotRequest.expression);
  }
  if (!(expr instanceof StringValueStream)) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "Pivot expressions must be castable to string expressions, "
        + "the following expression in pivot '" + pivotRequest.name + "' is not: '" + pivotRequest.expression);
  }

  PivotNode<?> pivot;
  if (childPivot == null) {
    pivot = new PivotNode.PivotLeaf(pivotRequest.name, (StringValueStream)expr);
  } else {
    pivot = new PivotNode.PivotBranch(pivotRequest.name, (StringValueStream)expr, childPivot);
  }

  // Check if the pivot is sorted
  if (pivotRequest.sort != null) {
    pivot.setSort(constructSort(pivotRequest.sort, expressions));
  }
  return pivot;
}
 
Example 13
Source File: OverseerCollectionMessageHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
void checkRequired(ZkNodeProps message, String... props) {
  for (String prop : props) {
    if(message.get(prop) == null){
      throw new SolrException(ErrorCode.BAD_REQUEST, StrUtils.join(Arrays.asList(props),',') +" are required params" );
    }
  }

}
 
Example 14
Source File: IndexSchema.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** 
 * Loads fields and dynamic fields.
 * 
 * @return a map from field name to explicit required value  
 */ 
protected synchronized Map<String,Boolean> loadFields(Document document, XPath xpath) throws XPathExpressionException {
  // Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key
  Map<String,Boolean> explicitRequiredProp = new HashMap<>();
  
  ArrayList<DynamicField> dFields = new ArrayList<>();

  //                  /schema/field | /schema/dynamicField | /schema/fields/field | /schema/fields/dynamicField
  String expression = stepsToPath(SCHEMA, FIELD)
      + XPATH_OR + stepsToPath(SCHEMA, DYNAMIC_FIELD)
      + XPATH_OR + stepsToPath(SCHEMA, FIELDS, FIELD)
      + XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD);

  NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET);

  for (int i=0; i<nodes.getLength(); i++) {
    Node node = nodes.item(i);

    NamedNodeMap attrs = node.getAttributes();

    String name = DOMUtil.getAttr(attrs, NAME, "field definition");
    log.trace("reading field def {}", name);
    String type = DOMUtil.getAttr(attrs, TYPE, "field " + name);

    FieldType ft = fieldTypes.get(type);
    if (ft==null) {
      throw new SolrException
          (ErrorCode.BAD_REQUEST, "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name);
    }

    Map<String,String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE);
    if (null != args.get(REQUIRED)) {
      explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED)));
    }

    SchemaField f = SchemaField.create(name,ft,args);

    if (node.getNodeName().equals(FIELD)) {
      SchemaField old = fields.put(f.getName(),f);
      if( old != null ) {
        String msg = "[schema.xml] Duplicate field definition for '"
          + f.getName() + "' [[["+old.toString()+"]]] and [[["+f.toString()+"]]]";
        throw new SolrException(ErrorCode.SERVER_ERROR, msg );
      }
      log.debug("field defined: {}", f);
      if( f.getDefaultValue() != null ) {
        if (log.isDebugEnabled()) {
          log.debug("{} contains default value {}", name, f.getDefaultValue());
        }
        fieldsWithDefaultValue.add( f );
      }
      if (f.isRequired()) {
        log.debug("{} is required in this schema", name);
        requiredFields.add(f);
      }
    } else if (node.getNodeName().equals(DYNAMIC_FIELD)) {
      if (isValidDynamicField(dFields, f)) {
        addDynamicFieldNoDupCheck(dFields, f);
      }
    } else {
      // we should never get here
      throw new RuntimeException("Unknown field type");
    }
  }

  //fields with default values are by definition required
  //add them to required fields, and we only have to loop once
  // in DocumentBuilder.getDoc()
  requiredFields.addAll(fieldsWithDefaultValue);

  dynamicFields = dynamicFieldListToSortedArray(dFields);
                                                                 
  return explicitRequiredProp;
}
 
Example 15
Source File: SolrRequestParsers.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** Returns the parameter map if a different content type was auto-detected */
private static SolrParams autodetect(HttpServletRequest req, ArrayList<ContentStream> streams, FastInputStream in) throws IOException {
  String detectedContentType = null;
  boolean shouldClose = true;

  try {
    in.peek();  // should cause some bytes to be read
    byte[] arr = in.getBuffer();
    int pos = in.getPositionInBuffer();
    int end = in.getEndInBuffer();

    for (int i = pos; i < end - 1; i++) {  // we do "end-1" because we check "arr[i+1]" sometimes in the loop body
      int ch = arr[i];
      boolean isWhitespace = ((WS_MASK >> ch) & 0x01) != 0 && (ch <= ' ' || ch == 0xa0);
      if (!isWhitespace) {
        // first non-whitespace chars
        if (ch == '#'                         // single line comment
            || (ch == '/' && (arr[i + 1] == '/' || arr[i + 1] == '*'))  // single line or multi-line comment
            || (ch == '{' || ch == '[')       // start of JSON object
            )
        {
          detectedContentType = "application/json";
        }
        if (ch == '<') {
          detectedContentType = "text/xml";
        }
        break;
      }
    }

    if (detectedContentType == null) {
      shouldClose = false;
      return null;
    }

    Long size = null;
    String v = req.getHeader("Content-Length");
    if (v != null) {
      size = Long.valueOf(v);
    }
    streams.add(new InputStreamContentStream(in, detectedContentType, size));


    final Map<String, String[]> map = new HashMap<>();
    // also add possible URL parameters and include into the map (parsed using UTF-8):
    final String qs = req.getQueryString();
    if (qs != null) {
      parseQueryString(qs, map);
    }

    return new MultiMapSolrParams(map);

  } catch (IOException ioe) {
    throw new SolrException(ErrorCode.BAD_REQUEST, ioe);
  } catch (IllegalStateException ise) {
    throw (SolrException) FormDataRequestParser.getParameterIncompatibilityException().initCause(ise);
  } finally {
    if (shouldClose) {
      IOUtils.closeWhileHandlingException(in);
    }
  }
}
 
Example 16
Source File: RequestReplicaListTransformerGenerator.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void transform(List<?> choices) {
  if (choices.size() > 1) {
    if (log.isDebugEnabled()) {
      log.debug("Applying the following sorting preferences to replicas: {}",
          Arrays.toString(replicaComp.getPreferenceRules().toArray()));
    }

    // First, sort according to comparator rules.
    try {
      choices.sort(replicaComp);
    } catch (IllegalArgumentException iae) {
      throw new SolrException(
          ErrorCode.BAD_REQUEST,
          iae.getMessage()
      );
    }

    // Next determine all boundaries between replicas ranked as "equivalent" by the comparator
    Iterator<?> iter = choices.iterator();
    Object prev = iter.next();
    Object current;
    int idx = 1;
    int boundaryCount = 0;
    int[] boundaries = new int[choices.size()];
    do {
      current = iter.next();
      if (replicaComp.compare(prev, current) != 0) {
        boundaries[boundaryCount++] = idx;
      }
      prev = current;
      idx++;
    } while (iter.hasNext());
    boundaries[boundaryCount++] = idx;

    // Finally inspect boundaries to apply base transformation, where necessary (separate phase to avoid ConcurrentModificationException)
    int startIdx = 0;
    int endIdx;
    for (int i = 0; i < boundaryCount; i++) {
      endIdx = boundaries[i];
      if (endIdx - startIdx > 1) {
        baseReplicaListTransformer.transform(choices.subList(startIdx, endIdx));
      }
      startIdx = endIdx;
    }

    if (log.isDebugEnabled()) {
      log.debug("Applied sorting preferences to replica list: {}", Arrays.toString(choices.toArray()));
    }
  }
}
 
Example 17
Source File: CollectionsHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public SolrResponse sendToOCPQueue(ZkNodeProps m, long timeout) throws KeeperException, InterruptedException {
  String operation = m.getStr(QUEUE_OPERATION);
  if (operation == null) {
    throw new SolrException(ErrorCode.BAD_REQUEST, "missing key " + QUEUE_OPERATION);
  }
  if (m.get(ASYNC) != null) {

    String asyncId = m.getStr(ASYNC);

    if (asyncId.equals("-1")) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "requestid can not be -1. It is reserved for cleanup purposes.");
    }

    NamedList<String> r = new NamedList<>();


    if (coreContainer.getZkController().claimAsyncId(asyncId)) {
      boolean success = false;
      try {
        coreContainer.getZkController().getOverseerCollectionQueue()
            .offer(Utils.toJSON(m));
        success = true;
      } finally {
        if (!success) {
          try {
            coreContainer.getZkController().clearAsyncId(asyncId);
          } catch (Exception e) {
            // let the original exception bubble up
            log.error("Unable to release async ID={}", asyncId, e);
            SolrZkClient.checkInterrupted(e);
          }
        }
      }
    } else {
      r.add("error", "Task with the same requestid already exists.");
    }
    r.add(CoreAdminParams.REQUESTID, (String) m.get(ASYNC));

    return new OverseerSolrResponse(r);
  }

  long time = System.nanoTime();
  QueueEvent event = coreContainer.getZkController()
      .getOverseerCollectionQueue()
      .offer(Utils.toJSON(m), timeout);
  if (event.getBytes() != null) {
    return OverseerSolrResponseSerializer.deserialize(event.getBytes());
  } else {
    if (System.nanoTime() - time >= TimeUnit.NANOSECONDS.convert(timeout, TimeUnit.MILLISECONDS)) {
      throw new SolrException(ErrorCode.SERVER_ERROR, operation
          + " the collection time out:" + timeout / 1000 + "s");
    } else if (event.getWatchedEvent() != null) {
      throw new SolrException(ErrorCode.SERVER_ERROR, operation
          + " the collection error [Watcher fired on path: "
          + event.getWatchedEvent().getPath() + " state: "
          + event.getWatchedEvent().getState() + " type "
          + event.getWatchedEvent().getType() + "]");
    } else {
      throw new SolrException(ErrorCode.SERVER_ERROR, operation
          + " the collection unknown case");
    }
  }
}
 
Example 18
Source File: ManagedIndexSchema.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public ManagedIndexSchema addFieldTypes(List<FieldType> fieldTypeList, boolean persist) {
  if (!isMutable) {
    String msg = "This ManagedIndexSchema is not mutable.";
    log.error(msg);
    throw new SolrException(ErrorCode.SERVER_ERROR, msg);    
  }

  ManagedIndexSchema newSchema = shallowCopy(true);

  // we shallow copied fieldTypes, but since we're changing them, we need to do a true
  // deep copy before adding the new field types
  @SuppressWarnings({"unchecked"})
  HashMap<String,FieldType> clone =
      (HashMap<String,FieldType>)((HashMap<String,FieldType>)newSchema.fieldTypes).clone();
  newSchema.fieldTypes = clone;

  // do a first pass to validate the field types don't exist already
  for (FieldType fieldType : fieldTypeList) {    
    String typeName = fieldType.getTypeName();
    if (newSchema.getFieldTypeByName(typeName) != null) {
      throw new FieldExistsException(ErrorCode.BAD_REQUEST,
          "Field type '" + typeName + "' already exists!");
    }
    
    newSchema.fieldTypes.put(typeName, fieldType);
  }

  newSchema.postReadInform();
  
  newSchema.refreshAnalyzers();

  if (persist) {
    boolean success = newSchema.persistManagedSchema(false);
    if (success) {
      if (log.isDebugEnabled()) {
        StringBuilder fieldTypeNames = new StringBuilder();
        for (int i=0; i < fieldTypeList.size(); i++) {
          if (i > 0) fieldTypeNames.append(", ");
          fieldTypeNames.append(fieldTypeList.get(i).typeName);
        }
        log.debug("Added field types: {}", fieldTypeNames);
      }
    } else {
      // this is unlikely to happen as most errors are handled as exceptions in the persist code
      log.error("Failed to add field types: {}", fieldTypeList);
      throw new SolrException(ErrorCode.SERVER_ERROR,
          "Failed to persist updated schema due to underlying storage issue; check log for more details!");
    }
  }

  return newSchema;
}
 
Example 19
Source File: LambdaFunction.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a function that maps two booleans to a single boolean.
 * This can take the following shapes:
 * <ul>
 * <li> Taking in two single-valued expressions and returning a single-valued expression which represents the lambda combination of the inputs.
 * <li> Taking in a single-valued expression and a multi-valued expression and returning a multi-valued expression which
 * represents the lambda combination of the single-value input with each of the values of the multi-value input.
 * <br>
 * The inputs can be either {@code func(single,multi)} or {@code func(multi,single)}.
 * </ul>
 * <p>
 *
 * @param name name for the function
 * @param lambda the function to be applied to every value: {@code (boolean,boolean) -> boolean}
 * @param param1 the first parameter in the lambda
 * @param param2 the second parameter in the lambda
 * @return a single or multi valued expression combining the two parameters with the given lambda
 * @throws SolrException if neither parameter is single-valued
 */
public static BooleanValueStream createBooleanLambdaFunction(String name, TwoBoolInBoolOutLambda lambda, BooleanValueStream param1, BooleanValueStream param2) throws SolrException {
  if (param1 instanceof BooleanValue && param2 instanceof BooleanValue) {
    return new TwoBooleanValueInBooleanValueOutFunction(name,lambda,(BooleanValue)param1,(BooleanValue)param2);
  } else if (param1 instanceof BooleanValue) {
    return new BooleanValueBooleanStreamInBooleanStreamOutFunction(name,lambda,(BooleanValue)param1,param2);
  } else if (param2 instanceof BooleanValue) {
    return new BooleanStreamBooleanValueInBooleanStreamOutFunction(name,lambda,param1,(BooleanValue)param2);
  } else {
    throw new SolrException(ErrorCode.BAD_REQUEST,"The "+name+" function requires at least 1 single-valued parameter.");
  }
}
 
Example 20
Source File: LambdaFunction.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a function that maps two dates to a single date.
 * This can take the following shapes:
 * <ul>
 * <li> Taking in two single-valued expressions and returning a single-valued expression which represents the lambda combination of the inputs.
 * <li> Taking in a single-valued expression and a multi-valued expression and returning a multi-valued expression which
 * represents the lambda combination of the single-value input with each of the values of the multi-value input.
 * <br>
 * The inputs can be either {@code func(single,multi)} or {@code func(multi,single)}.
 * </ul>
 *
 * <p>
 * NOTE: The lambda must work on longs, not Date objects
 *
 * @param name name for the function
 * @param lambda the function to be applied to every value: {@code (long,long) -> long}
 * @param param1 the first parameter in the lambda
 * @param param2 the second parameter in the lambda
 * @return a single or multi valued expression combining the two parameters with the given lambda
 * @throws SolrException if neither parameter is single-valued
 */
public static DateValueStream createDateLambdaFunction(String name, TwoLongInLongOutLambda lambda, DateValueStream param1, DateValueStream param2) throws SolrException {
  if (param1 instanceof DateValue && param2 instanceof DateValue) {
    return new TwoDateValueInDateValueOutFunction(name,lambda,(DateValue)param1,(DateValue)param2);
  } else if (param1 instanceof DateValue) {
    return new DateValueDateStreamInDateStreamOutFunction(name,lambda,(DateValue)param1,param2);
  } else if (param2 instanceof DateValue) {
    return new DateStreamDateValueInDateStreamOutFunction(name,lambda,param1,(DateValue)param2);
  } else {
    throw new SolrException(ErrorCode.BAD_REQUEST,"The "+name+" function requires at least 1 single-valued parameter.");
  }
}