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

The following examples show how to use org.apache.solr.common.SolrException.ErrorCode. These examples are extracted from open source projects. 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 Project: lucene-solr   Source File: FieldTypeXmlAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected static Element transformSimilarity(Document doc, Map<String,?> json, String jsonFieldName) {
  Object jsonField = json.get(jsonFieldName);
  if (jsonField == null)
    return null; // it's ok for this field to not exist in the JSON map

  if (!(jsonField instanceof Map))
    throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid fieldType definition! Expected JSON object for "+
        jsonFieldName+" not a "+jsonField.getClass().getName());

  Element similarity = doc.createElement("similarity");
  Map<String,?> config = (Map<String,?>)jsonField;
  similarity.setAttribute(SimilarityFactory.CLASS_NAME, (String)config.remove(SimilarityFactory.CLASS_NAME));
  for (Map.Entry<String,?> entry : config.entrySet()) {
    Object val = entry.getValue();
    if (val != null) {
      Element child = doc.createElement(classToXmlTag(val.getClass()));
      child.setAttribute(CommonParams.NAME, entry.getKey());
      child.setTextContent(entry.getValue().toString());
      similarity.appendChild(child);
    }
  }
  return similarity;
}
 
Example 2
Source Project: lucene-solr   Source File: RepositoryManager.java    License: Apache License 2.0 6 votes vote down vote up
private List<Path> downloadPackageArtifacts(String packageName, String version) throws SolrException {
  try {
    SolrPackageRelease release = getPackageRelease(packageName, version);
    List<Path> downloadedPaths = new ArrayList<Path>(release.artifacts.size());

    for (PackageRepository repo: getRepositories()) {
      if (repo.hasPackage(packageName)) {
        for (Artifact art: release.artifacts) {
          downloadedPaths.add(repo.download(art.url));
        }
        return downloadedPaths;
      }
    }
  } catch (IOException e) {
    throw new SolrException(ErrorCode.SERVER_ERROR, "Error during download of package " + packageName, e);
  }
  throw new SolrException(ErrorCode.NOT_FOUND, "Package not found in any repository.");
}
 
Example 3
@SuppressWarnings("rawtypes")
@Override
public void init( NamedList args ) {

  Object maxErrorsObj = args.get(MAX_ERRORS_PARAM); 
  if (maxErrorsObj != null) {
    try {
      defaultMaxErrors = Integer.parseInt(maxErrorsObj.toString());
    } catch (Exception e) {
      throw new SolrException(ErrorCode.SERVER_ERROR, "Unnable to parse maxErrors parameter: " + maxErrorsObj, e);
    }
    if (defaultMaxErrors < -1) {
      throw new SolrException(ErrorCode.SERVER_ERROR, "Config option '"+MAX_ERRORS_PARAM + "' must either be non-negative, or -1 to indicate 'unlimiited': " + maxErrorsObj.toString());
    }
  }
}
 
Example 4
Source Project: lucene-solr   Source File: ZkStateReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get shard leader properties, with retry if none exist.
 */
public Replica getLeaderRetry(String collection, String shard, int timeout) throws InterruptedException {

  AtomicReference<Replica> leader = new AtomicReference<>();
  try {
    waitForState(collection, timeout, TimeUnit.MILLISECONDS, (n, c) -> {
      if (c == null)
        return false;
      Replica l = getLeader(n, c, shard);
      if (l != null) {
        leader.set(l);
        return true;
      }
      return false;
    });
  } catch (TimeoutException e) {
    throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "No registered leader was found after waiting for "
        + timeout + "ms " + ", collection: " + collection + " slice: " + shard + " saw state=" + clusterState.getCollectionOrNull(collection)
        + " with live_nodes=" + clusterState.getLiveNodes());
  }
  return leader.get();
}
 
Example 5
Source Project: lucene-solr   Source File: SplitShardCmd.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean lockForSplit(SolrCloudManager cloudManager, String collection, String shard) throws Exception {
  String path = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection + "/" + shard + "-splitting";
  final DistribStateManager stateManager = cloudManager.getDistribStateManager();
  synchronized (stateManager) {
    if (stateManager.hasData(path)) {
      VersionedData vd = stateManager.getData(path);
      return false;
    }
    Map<String, Object> map = new HashMap<>();
    map.put(ZkStateReader.STATE_TIMESTAMP_PROP, String.valueOf(cloudManager.getTimeSource().getEpochTimeNs()));
    byte[] data = Utils.toJSON(map);
    try {
      cloudManager.getDistribStateManager().makePath(path, data, CreateMode.EPHEMERAL, true);
    } catch (Exception e) {
      throw new SolrException(SolrException.ErrorCode.INVALID_STATE, "Can't lock parent slice for splitting (another split operation running?): " +
          collection + "/" + shard, e);
    }
    return true;
  }
}
 
Example 6
Source Project: lucene-solr   Source File: ManagedWordSetResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Implements the GET request to provide the list of words to the client.
 * Alternatively, if a specific word is requested, then it is returned
 * or a 404 is raised, indicating that the requested word does not exist.
 */
@Override
public void doGet(BaseSolrResource endpoint, String childId) {
  SolrQueryResponse response = endpoint.getSolrResponse();
  if (childId != null) {
    // downcase arg if we're configured to ignoreCase
    String key = getIgnoreCase() ? childId.toLowerCase(Locale.ROOT) : childId;       
    if (!managedWords.contains(key))
      throw new SolrException(ErrorCode.NOT_FOUND, 
          String.format(Locale.ROOT, "%s not found in %s", childId, getResourceId()));
      
    response.add(childId, key);
  } else {
    response.add(WORD_SET_JSON_FIELD, buildMapToStore(managedWords));      
  }
}
 
Example 7
private boolean invokeFunctionUnsafe(String name, Object... cmd) {

      for (EngineInfo engine : engines) {
        try {
          Object result = engine.getEngine().invokeFunction(name, cmd);
          if (null != result && result instanceof Boolean) {
            if (! ((Boolean)result).booleanValue() ) {
              return false;
            }
          }

        } catch (ScriptException | NoSuchMethodException e) {
          throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, 
                                  "Unable to invoke function " + name + 
                                  " in script: " + 
                                  engine.getScriptFile().getFileName() + 
                                  ": " + e.getMessage(), e);
        }
      }

      return true;
    }
 
Example 8
Source Project: lucene-solr   Source File: IndexSchemaFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an index schema created from a local resource.  The input is usually from the core descriptor.
 */
public IndexSchema create(String resourceName, SolrConfig config) {
  SolrResourceLoader loader = config.getResourceLoader();
  InputStream schemaInputStream = null;

  if (null == resourceName) {
    resourceName = IndexSchema.DEFAULT_SCHEMA_FILE;
  }

  try {
    schemaInputStream = loader.openResource(resourceName);
  } catch (Exception e) {
    final String msg = "Error loading schema resource " + resourceName;
    log.error(msg, e);
    throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);
  }
  InputSource inputSource = new InputSource(schemaInputStream);
  inputSource.setSystemId(SystemIdResolver.createSystemIdFromResourceName(resourceName));
  IndexSchema schema = new IndexSchema(resourceName, inputSource, config.luceneMatchVersion, loader, config.getSubstituteProperties());
  return schema;
}
 
Example 9
Source Project: lucene-solr   Source File: AbstractFullDistribZkTestBase.java    License: Apache License 2.0 6 votes vote down vote up
public static String getUrlFromZk(ClusterState clusterState, String collection) {
  Map<String,Slice> slices = clusterState.getCollection(collection).getSlicesMap();

  if (slices == null) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Could not find collection:" + collection);
  }

  for (Map.Entry<String,Slice> entry : slices.entrySet()) {
    Slice slice = entry.getValue();
    Map<String,Replica> shards = slice.getReplicasMap();
    Set<Map.Entry<String,Replica>> shardEntries = shards.entrySet();
    for (Map.Entry<String,Replica> shardEntry : shardEntries) {
      final ZkNodeProps node = shardEntry.getValue();
      if (clusterState.liveNodesContain(node.getStr(ZkStateReader.NODE_NAME_PROP))) {
        return ZkCoreNodeProps.getCoreUrl(node.getStr(ZkStateReader.BASE_URL_PROP), collection); //new ZkCoreNodeProps(node).getCoreUrl();
      }
    }
  }

  throw new RuntimeException("Could not find a live node for collection:" + collection);
}
 
Example 10
Source Project: lucene-solr   Source File: ZkController.java    License: 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 11
/** 
 * In case of a null query a {@link QueryParseException} must be raised.
 */
@Test
@Ignore
public void nullOrEmptyQuery() {
	final String [] invalidQueries = {"", "   "};
	for (final String invalidQuery : invalidQueries) {
		parameters.set(CommonParams.Q, invalidQuery);
		try {
			cut.load(request, response, stream, processor);
			fail();
		} catch (final Exception expected) {
			assertTrue(expected instanceof SolrException);
			assertEquals(ErrorCode.BAD_REQUEST.code, ((SolrException)expected).code());
		}
	}
}
 
Example 12
Source Project: lucene-solr   Source File: PackageManager.java    License: 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 13
Source Project: lucene-solr   Source File: RestManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Overrides the parent impl to handle FileNotFoundException better
 */
@Override
protected synchronized void reloadFromStorage() throws SolrException {
  String resourceId = getResourceId();
  Object data = null;
  try {
    data = storage.load(resourceId);
  } catch (FileNotFoundException fnf) {
    // this is ok - simply means there are no managed components added yet
  } catch (IOException ioExc) {
    throw new SolrException(ErrorCode.SERVER_ERROR,
        "Failed to load stored data for "+resourceId+" due to: "+ioExc, ioExc);
  }

  Object managedData = processStoredData(data);

  if (managedInitArgs == null)
    managedInitArgs = new NamedList<>();

  if (managedData != null)
    onManagedDataLoadedFromStorage(managedInitArgs, managedData);
}
 
Example 14
Source Project: lucene-solr   Source File: StatsField.java    License: Apache License 2.0 6 votes vote down vote up
/** special for percentiles **/
boolean parseParams(StatsField sf) {
  String percentileParas = sf.localParams.get(this.name());
  if (percentileParas != null) {
    List<Double> percentiles = new ArrayList<Double>();
    try {
      for (String percentile : StrUtils.splitSmart(percentileParas, ',')) {
        percentiles.add(Double.parseDouble(percentile));
      }
      if (!percentiles.isEmpty()) {
        sf.percentilesList.addAll(percentiles);
        sf.tdigestCompression = sf.localParams.getDouble("tdigestCompression", 
                                                         sf.tdigestCompression);
        return true;
      }
    } catch (NumberFormatException e) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to parse "
          + StatsParams.STATS_FIELD + " local params: " + sf.localParams + " due to: "
          + e.getMessage(), e);
    }

  }
  return false;
}
 
Example 15
Source Project: lucene-solr   Source File: SolrConfig.java    License: Apache License 2.0 6 votes vote down vote up
public static final Version parseLuceneVersionString(final String matchVersion) {
  final Version version;
  try {
    version = Version.parseLeniently(matchVersion);
  } catch (ParseException pe) {
    throw new SolrException(ErrorCode.SERVER_ERROR,
        "Invalid luceneMatchVersion.  Should be of the form 'V.V.V' (e.g. 4.8.0)", pe);
  }

  if (version == Version.LATEST && !versionWarningAlreadyLogged.getAndSet(true)) {
    log.warn("You should not use LATEST as luceneMatchVersion property: "
        + "if you use this setting, and then Solr upgrades to a newer release of Lucene, "
        + "sizable changes may happen. If precise back compatibility is important "
        + "then you should instead explicitly specify an actual Lucene version.");
  }

  return version;
}
 
Example 16
Source Project: lucene-solr   Source File: SubQueryAugmenterFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void transform(SolrDocument doc, int docid) {

  final SolrParams docWithDeprefixed = SolrParams.wrapDefaults(
      new DocRowParams(doc, prefix, separator), baseSubParams);
  try {
    QueryResponse rsp = server.query(coreName, docWithDeprefixed);
    SolrDocumentList docList = rsp.getResults();
    doc.setField(getName(), new Result(docList));
  } catch (Exception e) {
    String docString = doc.toString();
    throw new SolrException(ErrorCode.BAD_REQUEST, "while invoking " +
        name + ":[subquery"+ (coreName!=null ? "fromIndex="+coreName : "") +"] on doc=" +
          docString.substring(0, Math.min(100, docString.length())), e.getCause());
  }
}
 
Example 17
Source Project: lucene-solr   Source File: DefaultPackageRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Path download(String artifactName) throws SolrException, IOException {
  Path tmpDirectory = Files.createTempDirectory("solr-packages");
  tmpDirectory.toFile().deleteOnExit();
  URL url = new URL(new URL(repositoryURL.endsWith("/")? repositoryURL: repositoryURL+"/"), artifactName);
  String fileName = FilenameUtils.getName(url.getPath());
  Path destination = tmpDirectory.resolve(fileName);

  switch (url.getProtocol()) {
    case "http":
    case "https":
    case "ftp":
      FileUtils.copyURLToFile(url, destination.toFile());
      break;
    default:
      throw new SolrException(ErrorCode.BAD_REQUEST, "URL protocol " + url.getProtocol() + " not supported");
  }
  
  return destination;
}
 
Example 18
Source Project: lucene-solr   Source File: AnalyticsRequestParser.java    License: Apache License 2.0 6 votes vote down vote up
private static EnumSet<FacetRangeOther> constructOthers(List<String> othersRequest, String facetName) throws SolrException {
  EnumSet<FacetRangeOther> others = EnumSet.noneOf(FacetRangeOther.class);
  for (String rawOther : othersRequest) {
    if (!others.add(FacetRangeOther.get(rawOther))) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Duplicate include value '" + rawOther + "' found in range facet '" + facetName + "'");
    }
  }
  if (others.contains(FacetRangeOther.NONE)) {
    if (others.size() > 1) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Include value 'NONE' is used with other includes in a range facet '" + facetName + "'. "
          + "If 'NONE' is used, it must be the only include.");
    }
    return EnumSet.noneOf(FacetRangeOther.class);
  }
  if (others.contains(FacetRangeOther.ALL)) {
    if (others.size() > 1) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Include value 'ALL' is used with other includes in a range facet '" + facetName + "'. "
          + "If 'ALL' is used, it must be the only include.");
    }
    return EnumSet.of(FacetRangeOther.BEFORE, FacetRangeOther.BETWEEN, FacetRangeOther.AFTER);
  }
  return others;
}
 
Example 19
Source Project: lucene-solr   Source File: FieldTypeXmlAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Node toNode(Map<String,?> json) {
  DocumentBuilder docBuilder;
  try {
    docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  } catch (ParserConfigurationException e) {
    throw new SolrException(ErrorCode.SERVER_ERROR, e);
  }
  
  Document doc = docBuilder.newDocument();    
  Element fieldType = doc.createElement(IndexSchema.FIELD_TYPE);
  appendAttrs(fieldType, json);
  
  // transform the analyzer definitions into XML elements
  Element analyzer = transformAnalyzer(doc, json, "analyzer", null);
  if (analyzer != null)
    fieldType.appendChild(analyzer);

  analyzer = transformAnalyzer(doc, json, "indexAnalyzer", "index");
  if (analyzer != null)
    fieldType.appendChild(analyzer);

  analyzer = transformAnalyzer(doc, json, "queryAnalyzer", "query");
  if (analyzer != null)
    fieldType.appendChild(analyzer);

  analyzer = transformAnalyzer(doc, json, "multiTermAnalyzer", "multiterm");
  if (analyzer != null)
    fieldType.appendChild(analyzer);

  Element similarity = transformSimilarity(doc, json, "similarity");
  if (similarity != null)
    fieldType.appendChild(similarity);
      
  return fieldType;
}
 
Example 20
Source Project: BioSolr   Source File: OntologyUpdateProcessorFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void processAdd(AddUpdateCommand cmd) throws IOException {
	if (isEnabled()) {
		try {
			// Look up ontology data for document
			OntologyHelper helper = initialiseHelper();
			String iri = (String)cmd.getSolrInputDocument().getFieldValue(getAnnotationField());

			if (StringUtils.isNotBlank(iri)) {
				OntologyData data = findOntologyData(helper, iri);

				if (data == null) {
					LOGGER.debug("Cannot find OWL class for IRI {}", iri);
				} else {
					addDataToSolrDoc(cmd.getSolrInputDocument(), data);
				}
			}
		} catch (OntologyHelperException e) {
			throw new SolrException(ErrorCode.SERVER_ERROR,
					"Cannot load ontology: " + e.getMessage());
		}
	}

	// Run the next processor in the chain
	if (next != null) {
		next.processAdd(cmd);
	}
}
 
Example 21
Source Project: lucene-solr   Source File: TestDelegationWithHadoopAuth.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test HttpSolrServer's delegation token support
 */
@Test
public void testDelegationTokenSolrClient() throws Exception {
  // Get token
  String token = getDelegationToken(null, USER_1, primarySolrClient);
  assertNotNull(token);

  @SuppressWarnings({"rawtypes"})
  SolrRequest request = getAdminRequest(new ModifiableSolrParams());

  // test without token
  HttpSolrClient ss =
      new HttpSolrClient.Builder(primarySolrClient.getBaseURL().toString())
          .withResponseParser(primarySolrClient.getParser())
          .build();
  try {
    doSolrRequest(ss, request, ErrorCode.UNAUTHORIZED.code);
  } finally {
    ss.close();
  }

  try (HttpSolrClient client = new HttpSolrClient.Builder(primarySolrClient.getBaseURL())
           .withKerberosDelegationToken(token)
           .withResponseParser(primarySolrClient.getParser())
           .build()) {
    // test with token via property
    doSolrRequest(client, request, HttpStatus.SC_OK);

    // test with param -- should throw an exception
    ModifiableSolrParams tokenParam = new ModifiableSolrParams();
    tokenParam.set("delegation", "invalidToken");
    expectThrows(IllegalArgumentException.class, () -> doSolrRequest(client, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code));
  }
}
 
Example 22
Source Project: lucene-solr   Source File: MockExchangeRateProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
  public double getExchangeRate(String sourceCurrencyCode, String targetCurrencyCode) {
//    System.out.println("***** getExchangeRate("+sourceCurrencyCode+targetCurrencyCode+")");
    if(sourceCurrencyCode.equals(targetCurrencyCode)) return 1.0;

    Double result = map.get(sourceCurrencyCode+","+targetCurrencyCode);
    if(result == null) {
      throw new SolrException(ErrorCode.NOT_FOUND, "No exchange rate found for the pair "+sourceCurrencyCode+","+targetCurrencyCode);
    }
    return result;
  }
 
Example 23
Source Project: lucene-solr   Source File: SolrResponse.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressForbidden(reason = "XXX: security hole")
@Deprecated
public static SolrResponse deserialize(byte[] bytes) {
  try {
    ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
    ObjectInputStream inputStream = new ObjectInputStream(byteStream);
    return (SolrResponse) inputStream.readObject();
  } catch (Exception e) {
    throw new SolrException(ErrorCode.SERVER_ERROR, e);
  }
}
 
Example 24
Source Project: lucene-solr   Source File: CoreContainer.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void initializeAuditloggerPlugin(Map<String, Object> auditConf) {
  auditConf = Utils.getDeepCopy(auditConf, 4);
  int newVersion = readVersion(auditConf);
  //Initialize the Auditlog module
  SecurityPluginHolder<AuditLoggerPlugin> old = auditloggerPlugin;
  SecurityPluginHolder<AuditLoggerPlugin> newAuditloggerPlugin = null;
  if (auditConf != null) {
    String klas = (String) auditConf.get("class");
    if (klas == null) {
      throw new SolrException(ErrorCode.SERVER_ERROR, "class is required for auditlogger plugin");
    }
    if (old != null && old.getZnodeVersion() == newVersion && newVersion > 0) {
      log.debug("Auditlogger config not modified");
      return;
    }
    log.info("Initializing auditlogger plugin: {}", klas);
    newAuditloggerPlugin = new SecurityPluginHolder<>(newVersion,
        getResourceLoader().newInstance(klas, AuditLoggerPlugin.class));

    newAuditloggerPlugin.plugin.init(auditConf);
    newAuditloggerPlugin.plugin.initializeMetrics(solrMetricsContext, "/auditlogging");
  } else {
    log.debug("Security conf doesn't exist. Skipping setup for audit logging module.");
  }
  this.auditloggerPlugin = newAuditloggerPlugin;
  if (old != null) {
    try {
      old.plugin.close();
    } catch (Exception e) {
      log.error("Exception while attempting to close old auditlogger plugin", e);
    }
  }
}
 
Example 25
Source Project: lucene-solr   Source File: ConfigSetsHandler.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void handleResponse(String operation, ZkNodeProps m,
                            SolrQueryResponse rsp, long timeout) throws KeeperException, InterruptedException {
  long time = System.nanoTime();

  QueueEvent event = coreContainer.getZkController()
      .getOverseerConfigSetQueue()
      .offer(Utils.toJSON(m), timeout);
  if (event.getBytes() != null) {
    SolrResponse response = OverseerSolrResponseSerializer.deserialize(event.getBytes());
    rsp.getValues().addAll(response.getResponse());
    @SuppressWarnings({"rawtypes"})
    SimpleOrderedMap exp = (SimpleOrderedMap) response.getResponse().get("exception");
    if (exp != null) {
      Integer code = (Integer) exp.get("rspCode");
      rsp.setException(new SolrException(code != null && code != -1 ? ErrorCode.getErrorCode(code) : ErrorCode.SERVER_ERROR, (String) exp.get("msg")));
    }
  } else {
    if (System.nanoTime() - time >= TimeUnit.NANOSECONDS.convert(timeout, TimeUnit.MILLISECONDS)) {
      throw new SolrException(ErrorCode.SERVER_ERROR, operation
          + " the configset time out:" + timeout / 1000 + "s");
    } else if (event.getWatchedEvent() != null) {
      throw new SolrException(ErrorCode.SERVER_ERROR, operation
          + " the configset 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 configset unknown case");
    }
  }
}
 
Example 26
@Test(expected = SolrException.class)
public void testAdd_SolrExceptionCausedByIOException() throws SolrServerException, IOException {
    SolrInputDocument inputDoc = mock(SolrInputDocument.class);
    Map<String,SolrInputDocument> inputDocMap = ImmutableMap.of("idA", inputDoc);

    when(solrServer.add(inputDocMap.values()))
        .thenThrow(new SolrException(ErrorCode.SERVER_ERROR, new IOException()));

    solrWriter.add(-1, inputDocMap);
}
 
Example 27
Source Project: lucene-solr   Source File: BasicHttpSolrClientTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * test that SolrExceptions thrown by HttpSolrClient can
 * correctly encapsulate http status codes even when not on the list of
 * ErrorCodes solr may return.
 */
public void testSolrExceptionCodeNotFromSolr() throws IOException, SolrServerException {
  final int status = 527;
  assertEquals(status + " didn't generate an UNKNOWN error code, someone modified the list of valid ErrorCode's w/o changing this test to work a different way",
      ErrorCode.UNKNOWN, ErrorCode.getErrorCode(status));

  try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) {
    DebugServlet.setErrorCode(status);
    SolrQuery q = new SolrQuery("foo");
    SolrException e = expectThrows(SolrException.class, () -> client.query(q, METHOD.GET));
    assertEquals("Unexpected exception status code", status, e.code());
  } finally {
    DebugServlet.clear();
  }
}
 
Example 28
Source Project: lucene-solr   Source File: CoreAdminOperationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testListSnapshotMissingCoreParamResultsIn400SolrException() {
  whenCoreAdminOpHasParams(Maps.newHashMap());

  Exception ex = expectThrows(Exception.class, () ->  CoreAdminOperation.LISTSNAPSHOTS_OP.execute(callInfo));
  assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
}
 
Example 29
Source Project: lucene-solr   Source File: CurrencyFieldType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Query getSpecializedRangeQuery(QParser parser, SchemaField field, String part1, String part2, final boolean minInclusive, final boolean maxInclusive) {
  final CurrencyValue p1 = CurrencyValue.parse(part1, defaultCurrency);
  final CurrencyValue p2 = CurrencyValue.parse(part2, defaultCurrency);

  if (p1 != null && p2 != null && !p1.getCurrencyCode().equals(p2.getCurrencyCode())) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Cannot parse range query " + part1 + " to " + part2 +
            ": range queries only supported when upper and lower bound have same currency.");
  }

  return getRangeQueryInternal(parser, field, p1, p2, minInclusive, maxInclusive);
}
 
Example 30
Source Project: lucene-solr   Source File: SolrCore.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
<T> Map<String, T> createInstances(Map<String, Class<? extends T>> map) {
  Map<String, T> result = new LinkedHashMap<>(map.size(), 1);
  for (Map.Entry<String, Class<? extends T>> e : map.entrySet()) {
    try {
      Object o = getResourceLoader().newInstance(e.getValue().getName(), e.getValue());
      result.put(e.getKey(), (T) o);
    } catch (Exception exp) {
      //should never happen
      throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to instantiate class", exp);
    }
  }
  return result;
}