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

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

Introduction

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

Prototype

protected SolrException(int code, String msg, Throwable th) 

Source Link

Document

Constructor that can set arbitrary http status code.

Usage

From source file:alba.components.FilteredShowFileRequestHandler.java

License:Apache License

public static File getAdminFileFromFileSystem(SolrQueryRequest req, SolrQueryResponse rsp,
        Set<String> hiddenFiles) {
    File adminFile = null;//from w  w  w .  j ava2s. com
    final SolrResourceLoader loader = req.getCore().getResourceLoader();
    File configdir = new File(loader.getConfigDir());
    if (!configdir.exists()) {
        // TODO: maybe we should just open it this way to start with?
        try {
            configdir = new File(loader.getClassLoader().getResource(loader.getConfigDir()).toURI());
        } catch (URISyntaxException e) {
            log.error("Can not access configuration directory!");
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN,
                    "Can not access configuration directory!", e));
            return null;
        }
    }
    String fname = req.getParams().get("file", null);
    if (fname == null) {
        adminFile = configdir;
    } else {
        fname = fname.replace('\\', '/'); // normalize slashes
        if (hiddenFiles.contains(fname.toUpperCase(Locale.ROOT))) {
            log.error("Can not access: " + fname);
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN, "Can not access: " + fname));
            return null;
        }
        if (fname.indexOf("..") >= 0) {
            log.error("Invalid path: " + fname);
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN, "Invalid path: " + fname));
            return null;
        }
        adminFile = new File(configdir, fname);
    }
    return adminFile;
}

From source file:com.appleframework.solr.util.DateFormatUtil.java

License:Apache License

/**
 * Parses a String which may be a date (in the standard format) followed by
 * an optional math expression.//from  w  w w  .jav  a 2  s  .  co  m
 * 
 * @param now
 *            an optional fixed date to use as "NOW" in the DateMathParser
 * @param val
 *            the string to parse
 */
public static Date parseMath(Date now, String val) {
    String math;
    final DateMathParser p = new DateMathParser();

    if (null != now)
        p.setNow(now);

    if (val.startsWith(NOW)) {
        math = val.substring(NOW.length());
    } else {
        final int zz = val.indexOf(Z);
        if (0 < zz) {
            math = val.substring(zz + 1);
            try {
                // p.setNow(toObject(val.substring(0,zz)));
                p.setNow(parseDate(val.substring(0, zz + 1)));
            } catch (ParseException e) {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "Invalid Date in Date Math String:'" + val + '\'', e);
            }
        } else {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date String:'" + val + '\'');
        }
    }

    if (null == math || math.equals("")) {
        return p.getNow();
    }

    try {
        return p.parseMath(math);
    } catch (ParseException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date Math String:'" + val + '\'',
                e);
    }
}

From source file:com.appleframework.solr.util.DateFormatUtil.java

License:Apache License

/**
 * Parses a String which may be a date followed by an optional math
 * expression./*w ww .  j a v a  2  s  .  c  o  m*/
 * 
 * @param now
 *            an optional fixed date to use as "NOW" in the DateMathParser
 * @param val
 *            the string to parse
 */
public static Date parseMathLenient(Date now, String val, SolrQueryRequest req) {
    String math;
    final DateMathParser p = new DateMathParser();

    if (null != now)
        p.setNow(now);

    if (val.startsWith(DateFormatUtil.NOW)) {
        math = val.substring(DateFormatUtil.NOW.length());
    } else {
        final int zz = val.indexOf(DateFormatUtil.Z);
        if (0 < zz) {
            math = val.substring(zz + 1);
            try {
                // p.setNow(toObject(val.substring(0,zz)));
                p.setNow(parseDateLenient(val.substring(0, zz + 1), req));
            } catch (ParseException e) {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "Invalid Date in Date Math String: '" + val + '\'', e);
            }
        } else {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date String: '" + val + '\'');
        }
    }

    if (null == math || math.equals("")) {
        return p.getNow();
    }

    try {
        return p.parseMath(math);
    } catch (ParseException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date Math String: '" + val + '\'',
                e);
    }
}

From source file:com.billiger.solr.handler.component.QLTBComponent.java

License:Apache License

/**
 * Add boost terms to the query if it matches a know query.
 *
 * The query string is analyzed and compared to the known query strings
 * from the XML file. If a matching (i.e. equal) query string is found,
 * the associated terms (ConstantScoreQuery) are added: the original
 * query (object, not string) is added as a MUST term in a newly created
 * BooleanQuery, whereas the new terms are added either as Occur.SHOULD
 * for positive boost, or Occur.MUST_NOT for zero or negative boost.
 *
 * prepare() might trigger a reload of the XML file if it resides in
 * the data/ directory and the reader is new.
 *
 *//*w ww. j  ava2s  .  c  o m*/
@Override
public final void prepare(final ResponseBuilder rb) {
    if (disabled(rb)) {
        return;
    }
    Query query = rb.getQuery();
    String queryStr = rb.getQueryString();
    if (query == null || queryStr == null) {
        return;
    }
    IndexReader reader = rb.req.getSearcher().getIndexReader();
    List<Query> boostTerms = null;
    try {
        queryStr = getAnalyzedQuery(queryStr);
        boostTerms = getQLTBMap(reader, rb.req.getCore()).get(queryStr);
        if (boostTerms == null || boostTerms.isEmpty()) {
            return;
        }
        log.debug("QLTBComponent.prepare() query: \"" + queryStr + "\" with " + boostTerms.size()
                + " boost terms");
    } catch (Exception ex) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "error loading QLTB", ex);
    }
    BooleanQuery newq = new BooleanQuery(true);
    newq.add(query, BooleanClause.Occur.MUST);
    for (Query term : boostTerms) {
        if (term.getBoost() > 0.0) {
            newq.add(new BooleanClause(term, BooleanClause.Occur.SHOULD));
        } else {
            newq.add(new BooleanClause(term, BooleanClause.Occur.MUST_NOT));
        }
    }
    rb.setQuery(newq);
}

From source file:com.cloudlbs.core.utils.DateParser.java

License:Apache License

/**
 * Parses a String which may be a date (in the standard format) followed by
 * an optional math expression./*from   w ww .j a va2  s . c o  m*/
 * 
 * @param now
 *            an optional fixed date to use as "NOW" in the DateMathParser
 * @param val
 *            the string to parse
 */
public Date parseMath(Date now, String val) throws ParseException {
    String math = null;
    final DateMathParser p = new DateMathParser(MATH_TZ, MATH_LOCALE);

    if (null != now)
        p.setNow(now);

    if (val.startsWith(NOW)) {
        math = val.substring(NOW.length());
    } else {
        final int zz = val.indexOf(Z);
        if (0 < zz) {
            math = val.substring(zz + 1);
            try {
                // p.setNow(toObject(val.substring(0,zz)));
                p.setNow(parseDate(val.substring(0, zz + 1)));
            } catch (ParseException e) {
                throw new ParseException("Invalid Date in Date Math String:'" + val + '\'', e.getErrorOffset());
            }
        } else {
            throw new ParseException("Invalid Date String:'" + val + '\'', 0);
        }
    }

    if (null == math || math.equals("")) {
        return p.getNow();
    }

    try {
        return p.parseMath(math);
    } catch (ParseException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date Math String:'" + val + '\'',
                e);
    }
}

From source file:com.cloudlbs.core.utils.DateParser.java

License:Apache License

/**
 * Parses a String which may be a date followed by an optional math
 * expression.//from w  ww  .j av a  2  s . c  o  m
 * 
 * @param now
 *            an optional fixed date to use as "NOW" in the DateMathParser
 * @param val
 *            the string to parse
 */
public Date parseMathLenient(Date now, String val) {
    String math = null;
    final DateMathParser p = new DateMathParser(MATH_TZ, MATH_LOCALE);

    if (null != now)
        p.setNow(now);

    if (val.startsWith(NOW)) {
        math = val.substring(NOW.length());
    } else {
        final int zz = val.indexOf(Z);
        if (0 < zz) {
            math = val.substring(zz + 1);
            try {
                // p.setNow(toObject(val.substring(0,zz)));
                p.setNow(parseDateLenient(val.substring(0, zz + 1)));
            } catch (ParseException e) {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "Invalid Date in Date Math String:'" + val + '\'', e);
            }
        } else {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date String:'" + val + '\'');
        }
    }

    if (null == math || math.equals("")) {
        return p.getNow();
    }

    try {
        return p.parseMath(math);
    } catch (ParseException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Date Math String:'" + val + '\'',
                e);
    }
}

From source file:com.github.le11.nls.solr.UIMAAsyncUpdateRequestProcessor.java

License:Apache License

@Override
public void processAdd(AddUpdateCommand cmd) throws IOException {
    String text = null;/*  ww w . jav a2  s. com*/
    try {
        /* get Solr document */
        SolrInputDocument solrInputDocument = cmd.getSolrInputDocument();

        /* get the fields to analyze */
        String[] texts = getTextsToAnalyze(solrInputDocument);
        for (int i = 0; i < texts.length; i++) {
            text = texts[i];
            if (text != null && text.length() > 0) {
                /* process the text value */
                JCas jcas = UIMAAnalyzersUtils.getInstance()
                        .analyzeAsynchronously(new StringReader(text), solrUIMAConfiguration.getAePath())
                        .getJCas();

                UIMAToSolrMapper uimaToSolrMapper = new UIMAToSolrMapper(solrInputDocument, jcas);
                /* get field mapping from config */
                /* map type features on fields */
                for (String typeFQN : solrUIMAConfiguration.getTypesFeaturesFieldsMapping().keySet()) {
                    uimaToSolrMapper.map(typeFQN,
                            solrUIMAConfiguration.getTypesFeaturesFieldsMapping().get(typeFQN));
                }
            }
        }
    } catch (Exception e) {
        String logField = solrUIMAConfiguration.getLogField();
        if (logField == null) {
            SchemaField uniqueKeyField = solrCore.getSchema().getUniqueKeyField();
            if (uniqueKeyField != null) {
                logField = uniqueKeyField.getName();
            }
        }
        String optionalFieldInfo = logField == null ? "."
                : new StringBuilder(". ").append(logField).append("=")
                        .append((String) cmd.getSolrInputDocument().getField(logField).getValue()).append(", ")
                        .toString();
        int len = Math.min(text.length(), 100);
        if (solrUIMAConfiguration.isIgnoreErrors()) {
            log.warn(new StringBuilder("skip the text processing due to ").append(e.getLocalizedMessage())
                    .append(optionalFieldInfo).append(" text=\"").append(text.substring(0, len)).append("...\"")
                    .toString());
        } else {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    new StringBuilder("processing error: ").append(e.getLocalizedMessage())
                            .append(optionalFieldInfo).append(" text=\"").append(text.substring(0, len))
                            .append("...\"").toString(),
                    e);
        }
    }
    super.processAdd(cmd);
}

From source file:com.grantingersoll.intell.clustering.KMeansClusteringEngine.java

License:Apache License

@Override
public String init(NamedList config, SolrCore core) {
    String result = super.init(config, core);
    SolrParams params = SolrParams.toSolrParams(config);
    this.core = core;
    String dirStr = params.get("dir");
    clusterBaseDir = new File(dirStr);
    if (clusterBaseDir.isAbsolute() == false) {
        clusterBaseDir = new File(core.getDataDir(), dirStr);
    }//from www  .  j a  v  a2  s  .c o m
    clusterBaseDir.mkdirs();
    inputField = params.get("inputField");
    String distMeas = params.get("distanceMeasure");
    Class distClass = core.getResourceLoader().findClass(distMeas);

    try {
        measure = (DistanceMeasure) distClass.newInstance();
    } catch (InstantiationException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to load measure class", e);
    } catch (IllegalAccessException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to load measure class", e);
    }
    convergence = params.getDouble("convergence", 0.001);
    maxIters = params.getInt("maxIterations", 20);
    cacheClusters = params.getBool("cacheClusters", true);
    cachePoints = params.getBool("cachePoints", true);
    this.k = params.getInt("k");
    //See if we have clusters already
    File nowFile = new File(clusterBaseDir, "lastJob");
    if (nowFile.exists()) {
        lastSuccessful = readJobDetails(nowFile);

    }
    return result;
}

From source file:com.grantingersoll.intell.clustering.KMeansClusteringEngine.java

License:Apache License

private ClusterJob readJobDetails(File jobFile) {
    log.info("Reading job from: {} ", jobFile);
    ClusterJob result = null;//from   w  w w.  ja va  2  s.com
    try {
        FileReader fReader = new FileReader(jobFile);
        Properties props = new Properties();
        props.load(fReader);
        result = new ClusterJob(Integer.parseInt(props.get("k").toString()), props.get("jobDir").toString(),
                new Path(props.get("input").toString()), new Path(props.get("clustersIn").toString()),
                new Path(props.get("output").toString()), new Path(props.get("dictionary").toString()));
    } catch (FileNotFoundException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to load: " + jobFile, e);
    } catch (IOException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to read: " + jobFile, e);
    }
    log.info("Read job: {}", result);
    return result;
}

From source file:com.sindicetech.siren.solr.qparser.SirenQParserPlugin.java

License:Open Source License

/**
 * Load QNames mapping from the properties file
 * <p>//w  w  w.ja  v  a2 s.c om
 * The mapping file contains lines such as:
 * <ul>
 * <li> foaf=http://xmlns.com/foaf/0.1/
 * </ul>
 * which means that the qname <code>foaf:name</code> will be expanded to
 * <code>http://xmlns.com/foaf/0.1/name</code>.
 */
protected void loadQNamesFile(final ResourceLoader loader) {
    try {
        logger.info("Loading of the QNames mapping file: {}", qnamesFile);
        qnames = new Properties();
        qnames.load(loader.openResource(qnamesFile));
    } catch (final IOException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Loading of the QNames mapping file failed: [" + qnamesFile + "]", e);
    }
}