Example usage for org.apache.solr.common SolrException code

List of usage examples for org.apache.solr.common SolrException code

Introduction

In this page you can find the example usage for org.apache.solr.common SolrException code.

Prototype

int code

To view the source code for org.apache.solr.common SolrException code.

Click Source Link

Usage

From source file:com.frank.search.solr.core.SolrExceptionTranslator.java

License:Apache License

@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
    if (ex.getCause() instanceof SolrServerException) {
        SolrServerException solrServerException = (SolrServerException) ex.getCause();
        if (solrServerException.getCause() instanceof SolrException) {
            SolrException solrException = (SolrException) solrServerException.getCause();
            // solr 4.x moved ParseExecption from
            // org.apache.lucene.queryParser to
            // org.apache.lucene.queryparser.classic
            // therefore compare ShortClassName instead of using instanceof
            // expression
            if (solrException.getCause() != null && ClassUtils.getShortName(solrException.getCause().getClass())
                    .equalsIgnoreCase("ParseException")) {
                return new InvalidDataAccessApiUsageException((solrException.getCause()).getMessage(),
                        solrException.getCause());
            } else {
                ErrorCode errorCode = ErrorCode.getErrorCode(solrException.code());
                switch (errorCode) {
                case NOT_FOUND:
                case SERVICE_UNAVAILABLE:
                case SERVER_ERROR:
                    return new DataAccessResourceFailureException(solrException.getMessage(), solrException);
                case FORBIDDEN:
                case UNAUTHORIZED:
                    return new PermissionDeniedDataAccessException(solrException.getMessage(), solrException);
                case BAD_REQUEST:
                    return new InvalidDataAccessApiUsageException(solrException.getMessage(), solrException);
                case UNKNOWN:
                    return new UncategorizedSolrException(solrException.getMessage(), solrException);
                default:
                    break;
                }//from   w w w .j  av  a  2  s . c o  m
            }
        } else if (solrServerException.getCause() instanceof ConnectException) {
            return new DataAccessResourceFailureException(solrServerException.getCause().getMessage(),
                    solrServerException.getCause());
        }
    }
    return null;
}

From source file:com.mustardgrain.solr.SolrClient.java

License:Apache License

/**
 * Tries to query a live server from the list provided in Req. Servers in
 * the dead pool are skipped. If a request fails due to an IOException, the
 * server is moved to the dead pool for a certain period of time, or until a
 * test request on that server succeeds. Servers are queried in the exact
 * order given (except servers currently in the dead pool are skipped). If
 * no live servers from the provided list remain to be tried, a number of
 * previously skipped dead servers will be tried.
 * Req.getNumDeadServersToTry() controls how many dead servers will be
 * tried. If no live servers are found a SolrServerException is thrown.
 * /*from  www  .j a v a2 s. co  m*/
 * @param req contains both the request as well as the list of servers to
 *        query
 * @return the result of the request
 * @throws IOException If there is a low-level I/O error.
 */
public Rsp request(Req req) throws SolrServerException, IOException {
    Rsp rsp = new Rsp();
    Exception ex = null;

    List<ServerWrapper> skipped = new ArrayList<ServerWrapper>(req.getNumDeadServersToTry());

    for (String serverStr : req.getServers()) {
        serverStr = normalize(serverStr);
        // if the server is currently a zombie, just skip to the next one
        ServerWrapper wrapper = zombieServers.get(serverStr);
        if (wrapper != null) {
            // System.out.println("ZOMBIE SERVER QUERIED: " + serverStr);
            if (skipped.size() < req.getNumDeadServersToTry())
                skipped.add(wrapper);
            continue;
        }
        rsp.server = serverStr;
        HttpSolrServer server = makeServer(serverStr);

        try {
            long start = System.currentTimeMillis();
            rsp.rsp = server.request(req.getRequest());
            long end = System.currentTimeMillis();
            updateStatsSuccess(server, end - start);
            return rsp; // SUCCESS
        } catch (SolrException e) {
            updateStatsException(server, e);
            // we retry on 404 or 403 or 503 - you can see this on solr
            // shutdown
            if (e.code() == 404 || e.code() == 403 || e.code() == 503 || e.code() == 500) {
                ex = addZombie(server, e);
            } else {
                // Server is alive but the request was likely malformed or
                // invalid
                throw e;
            }

            // TODO: consider using below above - currently does cause a
            // problem with distrib updates:
            // seems to match up against a failed forward to leader
            // exception as well...
            // || e.getMessage().contains("java.net.SocketException")
            // || e.getMessage().contains("java.net.ConnectException")
        } catch (SocketException e) {
            updateStatsException(server, e);
            ex = addZombie(server, e);
        } catch (SocketTimeoutException e) {
            updateStatsException(server, e);
            ex = addZombie(server, e);
        } catch (SolrServerException e) {
            Throwable rootCause = e.getRootCause();
            updateStatsException(server, rootCause);
            if (rootCause instanceof IOException) {
                ex = addZombie(server, e);
            } else {
                throw e;
            }
        } catch (Exception e) {
            updateStatsException(server, e);
            throw new SolrServerException(e);
        }
    }

    // try the servers we previously skipped
    for (ServerWrapper wrapper : skipped) {
        try {
            long start = System.currentTimeMillis();
            rsp.rsp = wrapper.solrServer.request(req.getRequest());
            long end = System.currentTimeMillis();
            updateStatsSuccess(wrapper.solrServer, end - start);
            zombieServers.remove(wrapper.getKey());
            return rsp; // SUCCESS
        } catch (SolrException e) {
            updateStatsException(wrapper.solrServer, e);
            // we retry on 404 or 403 or 503 - you can see this on solr
            // shutdown
            if (e.code() == 404 || e.code() == 403 || e.code() == 503 || e.code() == 500) {
                ex = e;
                // already a zombie, no need to re-add
            } else {
                // Server is alive but the request was malformed or invalid
                zombieServers.remove(wrapper.getKey());
                throw e;
            }

        } catch (SocketException e) {
            updateStatsException(wrapper.solrServer, e);
            ex = e;
        } catch (SocketTimeoutException e) {
            updateStatsException(wrapper.solrServer, e);
            ex = e;
        } catch (SolrServerException e) {
            Throwable rootCause = e.getRootCause();
            updateStatsException(wrapper.solrServer, rootCause);
            if (rootCause instanceof IOException) {
                ex = e;
                // already a zombie, no need to re-add
            } else {
                throw e;
            }
        } catch (Exception e) {
            updateStatsException(wrapper.solrServer, e);
            throw new SolrServerException(e);
        }
    }

    if (ex == null) {
        throw new SolrServerException("No live SolrServers available to handle this request");
    } else {
        throw new SolrServerException(
                "No live SolrServers available to handle this request:" + zombieServers.keySet(), ex);
    }

}

From source file:com.ngdata.hbaseindexer.indexer.DirectSolrClassicInputDocumentWriter.java

License:Apache License

private boolean isDocumentIssue(SolrException e) {
    return e.code() == ErrorCode.BAD_REQUEST.code;
}

From source file:io.logspace.hq.core.solr.report.SolrReportService.java

License:Open Source License

@Override
public void deleteReport(String reportId) {
    this.logger.debug("Deleting report with ID '{}'.", reportId);

    try {/*w ww.  j  a v  a 2 s  .co  m*/
        SolrInputDocument solrInputDocument = new SolrInputDocument();
        solrInputDocument.setField(FIELD_ID, reportId);

        // make this a field update to an existing document
        solrInputDocument.setField(FIELD_DELETED, asFieldUpdate(Boolean.TRUE));
        documentMustExist(solrInputDocument);

        this.solrClient.add(solrInputDocument);

        this.makeChangesVisible();
    } catch (SolrException e) {
        if (HttpStatusCode.CONFLICT.matches(e.code())) {
            // this means that the ID does not exist -> throw appropriate exception
            throw ReportNotFoundException.forReportId(reportId);
        }
    } catch (SolrServerException | IOException e) {
        throw new DataDeletionException("Could not delete report.", e);
    }
}

From source file:io.logspace.hq.core.solr.report.SolrReportService.java

License:Open Source License

@Override
public void saveReport(Report report) {
    this.validateReportCanBeSaved(report);

    this.logger.debug("Storing report with ID '{}'.", report.getId());

    for (String id : new EscalatingIdGenerator("report_", 3)) {
        String branch = report.getBranch() != null ? report.getBranch() : id;
        Date timestamp = new Date();

        try {/*  w w  w  . j a  va  2 s. c o  m*/
            SolrInputDocument solrInputDocument = new SolrInputDocument();
            solrInputDocument.setField(FIELD_ID, id);
            solrInputDocument.setField(FIELD_BRANCH, branch);
            solrInputDocument.setField(FIELD_PARENT_ID, report.getParentId());
            solrInputDocument.setField(FIELD_TYPE, CONFIG_TYPE);
            solrInputDocument.setField(FIELD_NAME, report.getName());
            solrInputDocument.setField(FIELD_TIMESTAMP, timestamp);
            solrInputDocument.setField(FIELD_CONTENT, serializeDefinitions(report.getTimeSeriesDefinitions()));

            // fail with HTTP CONFLICT if the ID is already in use
            documentMustNotExist(solrInputDocument);
            this.solrClient.add(solrInputDocument);

            this.makeChangesVisible();

            // the add was successful -> update the report and stop here
            report.setId(id);
            report.setBranch(branch);
            report.setTimestamp(timestamp);
            break;
        } catch (SolrException e) {
            if (HttpStatusCode.CONFLICT.matches(e.code())) {
                // this means that our generated ID is already in use -> try the next ID
                continue;
            }

            throw new DataStorageException("Could not store report.", e);
        } catch (SolrServerException | IOException e) {
            throw new DataStorageException("Could not store report.", e);
        }
    }
}

From source file:io.logspace.hq.core.solr.report.SolrReportService.java

License:Open Source License

@Override
public void undeleteReport(String reportId) {
    this.logger.debug("Un-deleting report with ID '{}'.", reportId);

    try {//from ww  w  . j  a va 2  s.  c om
        SolrInputDocument solrInputDocument = new SolrInputDocument();
        solrInputDocument.setField(FIELD_ID, reportId);

        // make this a field update to an existing document
        solrInputDocument.setField(FIELD_DELETED, asFieldUpdate(null));
        documentMustExist(solrInputDocument);

        this.solrClient.add(solrInputDocument);

        this.makeChangesVisible();
    } catch (SolrException e) {
        if (HttpStatusCode.CONFLICT.matches(e.code())) {
            // this means that the id does not exist -> throw appropriate exception
            throw ReportNotFoundException.forReportId(reportId);
        }
    } catch (SolrServerException | IOException e) {
        throw new DataDeletionException("Could not un-delete report.", e);
    }
}

From source file:org.alfresco.solr.CoresCreateUpdateDistributedTest.java

License:Open Source License

@Test
public void newCoreWithUpdateSharedProperties() throws Exception {
    CoreContainer coreContainer = jettyContainers.get(JETTY_SERVER_ID).getCoreContainer();

    //Now create the new core with
    AlfrescoCoreAdminHandler coreAdminHandler = (AlfrescoCoreAdminHandler) coreContainer.getMultiCoreHandler();
    assertNotNull(coreAdminHandler);/*from  ww w.  ja  va 2 s  .  co  m*/
    String coreName = "alfSharedCore";

    //First, we have no cores so we can update the shared properties, including disallowed
    updateShared(coreAdminHandler, "property.solr.host", "myhost", "property.my.property", "chocolate",
            "property.alfresco.identifier.property.0", "http://www.alfresco.org/model/content/1.0}userName");
    Properties props = AlfrescoSolrDataModel.getCommonConfig();
    assertEquals(props.getProperty("my.property"), "chocolate");
    assertEquals(props.getProperty("alfresco.identifier.property.0"),
            "http://www.alfresco.org/model/content/1.0}userName");

    createSimpleCore(coreAdminHandler, coreName, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.toString(), null);
    //Get a reference to the new core
    SolrCore defaultCore = getCore(coreContainer, coreName);

    TimeUnit.SECONDS.sleep(3); //Wait a little for background threads to catchup
    assertNotNull(defaultCore);

    String solrHost = props.getProperty("solr.host");
    assertFalse(props.containsKey("new.property"));
    try {
        updateShared(coreAdminHandler, "property.solr.host", "superhost", "property.new.property", "catchup",
                "property.alfresco.identifier.property.0", "not_this_time");
        assertFalse(true); //Should not get here
    } catch (SolrException se) {
        assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, se.code());
    }
    updateShared(coreAdminHandler, "property.solr.host", "superhost", "property.new.property", "catchup");
    props = AlfrescoSolrDataModel.getCommonConfig();
    assertEquals(props.getProperty("new.property"), "catchup");
    assertNotEquals(props.getProperty("solr.host"), solrHost);
}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

License:Apache License

/** Handle a SolrException.
* These exceptions are mainly Http errors having to do with actual responses from Solr.
* If this method doesn't throw an exception, it means that the exception should be interpreted
* as meaning that the document or action is illegal and should not be repeated.
*///from w w  w.  j  a va2s  .c  om
protected static void handleSolrException(SolrException e, String context)
        throws ManifoldCFException, ServiceInterruption {
    int code = e.code();
    if (code == 0) {
        try {
            // Solrj doesn't always set the code properly.  If it doesn't, we have to parse it out of the exception string.  Ugh.
            Pattern p = Pattern.compile("non ok status:([0-9]*),");
            Matcher m = p.matcher(e.getMessage());
            if (m.find())
                code = Integer.parseInt(m.group(1));
        } catch (PatternSyntaxException e2) {
            throw new ManifoldCFException("Unexpected error: " + e2.getMessage());
        } catch (NumberFormatException e2) {
            throw new ManifoldCFException("Unexpected error: " + e2.getMessage());
        }
    }

    // Use the exception text to determine the proper result.
    if (code == 500 && e.getMessage().indexOf("org.apache.tika.exception.TikaException") != -1)
        // Can't process the document, so don't keep trying.
        return;

    // If the code is in the 400 range, the document will never be accepted, so indicate that.
    if (code >= 400 && code < 500)
        return;

    // The only other kind of return code we know how to handle is 50x.
    // For these, we should retry for a while.
    if (code == 500) {
        long currentTime = System.currentTimeMillis();

        // Log the error
        String message = "Solr exception during " + context + " (" + e.code() + "): " + e.getMessage();
        Logging.ingest.warn(message, e);
        throw new ServiceInterruption(message, e, currentTime + interruptionRetryTime,
                currentTime + 2L * 60L * 60000L, -1, true);
    }

    // Unknown code: end the job.
    throw new ManifoldCFException(
            "Unhandled Solr exception during " + context + " (" + e.code() + "): " + e.getMessage());
}

From source file:org.springframework.data.search.solr.SolrExceptionTranslator.java

License:Apache License

/**
 * {@inheritDoc}/*from ww w . j a v a  2s .co m*/
 */
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
    if (ex.getCause() instanceof SolrServerException) {
        SolrServerException solrServerException = (SolrServerException) ex.getCause();
        if (solrServerException.getCause() instanceof SolrException) {
            SolrException solrException = (SolrException) solrServerException.getCause();
            if (solrException.getCause() instanceof ParseException) {
                return new InvalidQueryException(((ParseException) solrException.getCause()).getMessage(),
                        solrException.getCause());
            } else {
                ErrorCode errorCode = SolrException.ErrorCode.getErrorCode(solrException.code());
                switch (errorCode) {
                case NOT_FOUND:
                case FORBIDDEN:
                case SERVICE_UNAVAILABLE:
                case SERVER_ERROR:
                    return new SearchServerException(solrException.getMessage(), solrException);
                case BAD_REQUEST:
                    return new InvalidQueryException(solrException.getMessage(), solrException);
                case UNAUTHORIZED:
                case UNKNOWN:
                    return new UncategorizedSearchException(solrException.getMessage(), solrException);
                default:
                    break;
                }
            }
        }
    }

    return super.translateExceptionIfPossible(ex);
}

From source file:org.springframework.data.solr.core.SolrExceptionTranslator.java

License:Apache License

@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
    if (ex.getCause() instanceof SolrServerException) {
        SolrServerException solrServerException = (SolrServerException) ex.getCause();
        if (solrServerException.getCause() instanceof SolrException) {
            SolrException solrException = (SolrException) solrServerException.getCause();
            // solr 4.x moved ParseExecption from org.apache.lucene.queryParser to org.apache.lucene.queryparser.classic
            // therefore compare ShortClassName instead of using instanceof expression
            if (solrException.getCause() != null && ClassUtils.getShortName(solrException.getCause().getClass())
                    .equalsIgnoreCase("ParseException")) {
                return new InvalidDataAccessApiUsageException((solrException.getCause()).getMessage(),
                        solrException.getCause());
            } else {
                ErrorCode errorCode = SolrException.ErrorCode.getErrorCode(solrException.code());
                switch (errorCode) {
                case NOT_FOUND:
                case SERVICE_UNAVAILABLE:
                case SERVER_ERROR:
                    return new DataAccessResourceFailureException(solrException.getMessage(), solrException);
                case FORBIDDEN:
                case UNAUTHORIZED:
                    return new PermissionDeniedDataAccessException(solrException.getMessage(), solrException);
                case BAD_REQUEST:
                    return new InvalidDataAccessApiUsageException(solrException.getMessage(), solrException);
                case UNKNOWN:
                    return new UncategorizedSolrException(solrException.getMessage(), solrException);
                default:
                    break;
                }//from  w  w w  .j ava2  s  . c  om
            }
        } else if (solrServerException.getCause() instanceof ConnectException) {
            return new DataAccessResourceFailureException(solrServerException.getCause().getMessage(),
                    solrServerException.getCause());
        }
    }
    return null;
}