List of usage examples for org.apache.solr.common.params ModifiableSolrParams ModifiableSolrParams
public ModifiableSolrParams(SolrParams params)
From source file:alba.components.FilteredShowFileRequestHandler.java
License:Apache License
private void showFromZooKeeper(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer coreContainer) throws KeeperException, InterruptedException, UnsupportedEncodingException { SolrZkClient zkClient = coreContainer.getZkController().getZkClient(); String adminFile = getAdminFileFromZooKeeper(req, rsp, zkClient, hiddenFiles); if (adminFile == null) { return;//from w w w . jav a2 s . com } // Show a directory listing List<String> children = zkClient.getChildren(adminFile, null, true); if (children.size() > 0) { NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>(); for (String f : children) { if (isHiddenFile(req, rsp, f, false, hiddenFiles)) { continue; } SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>(); files.add(f, fileInfo); List<String> fchildren = zkClient.getChildren(adminFile + "/" + f, null, true); if (fchildren.size() > 0) { fileInfo.add("directory", true); } else { // TODO? content type fileInfo.add("size", f.length()); } // TODO: ? // fileInfo.add( "modified", new Date( f.lastModified() ) ); } rsp.add("files", files); } else { // Include the file contents // The file logic depends on RawResponseWriter, so force its use. ModifiableSolrParams params = new ModifiableSolrParams(req.getParams()); params.set(CommonParams.WT, "raw"); req.setParams(params); ContentStreamBase content = new ContentStreamBase.ByteArrayStream( zkClient.getData(adminFile, null, null, true), adminFile); content.setContentType(req.getParams().get(USE_CONTENT_TYPE)); // Velocity parsing here! // http://velocity.apache.org/engine/devel/developer-guide.html#The_Context Velocity.init(); VelocityContext context = new VelocityContext(); //add some vars?? //context.put( "context", new String("Velocity") ); for (int i = 0; i < rsp.getValues().size(); i++) { context.put(rsp.getValues().getName(i), rsp.getValues().getVal(i)); } Template template = null; String fname = req.getParams().get("file", null); try { //TODO what if fname is null? template = Velocity.getTemplate(fname); } catch (ResourceNotFoundException rnfe) { // couldn't find the template, try to load it // TODO it should be fired only for SOME mimetypes (..through an annotation??) StringBuilder sb = this.getTemplate(content); RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(sb.toString()); SimpleNode node = null; try { node = runtimeServices.parse(reader, fname); } catch (ParseException e) { // TODO Auto-generated catch block logger.error("error while parsing new template", e); } template = new Template(); template.setRuntimeServices(runtimeServices); if (node != null) { template.setData(node); } else { logger.error("node null, can't set on template"); } template.initDocument(); } catch (ParseErrorException pee) { // syntax error: problem parsing the template logger.error("error while parsing template: ", pee); } catch (MethodInvocationException mie) { // something invoked in the template // threw an exception logger.error("error while parsing temaplate: ", mie); } catch (Exception e) { logger.error("error while parsing temaplate: ", e); } StringWriter sw = new StringWriter(); template.merge(context, sw); // http://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte content = new ContentStreamBase.ByteArrayStream( sw.getBuffer().toString().getBytes(Charset.forName("UTF-8")), adminFile); content.setContentType(req.getParams().get(USE_CONTENT_TYPE)); rsp.add(RawResponseWriter.CONTENT, content); } rsp.setHttpCaching(false); }
From source file:alba.components.FilteredShowFileRequestHandler.java
License:Apache License
private void showFromFileSystem(SolrQueryRequest req, SolrQueryResponse rsp) { File adminFile = getAdminFileFromFileSystem(req, rsp, hiddenFiles); if (adminFile == null) { // exception already recorded return;/*ww w.ja v a 2 s. c o m*/ } // Make sure the file exists, is readable and is not a hidden file if (!adminFile.exists()) { log.error("Can not find: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]"); rsp.setException(new SolrException(ErrorCode.NOT_FOUND, "Can not find: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]")); return; } if (!adminFile.canRead() || adminFile.isHidden()) { log.error("Can not show: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]"); rsp.setException(new SolrException(ErrorCode.NOT_FOUND, "Can not show: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]")); return; } // Show a directory listing if (adminFile.isDirectory()) { // it's really a directory, just go for it. int basePath = adminFile.getAbsolutePath().length() + 1; NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>(); for (File f : adminFile.listFiles()) { String path = f.getAbsolutePath().substring(basePath); path = path.replace('\\', '/'); // normalize slashes if (isHiddenFile(req, rsp, f.getName().replace('\\', '/'), false, hiddenFiles)) { continue; } SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>(); files.add(path, fileInfo); if (f.isDirectory()) { fileInfo.add("directory", true); } else { // TODO? content type fileInfo.add("size", f.length()); } fileInfo.add("modified", new Date(f.lastModified())); } rsp.add("files", files); } else { // Include the file contents //The file logic depends on RawResponseWriter, so force its use. ModifiableSolrParams params = new ModifiableSolrParams(req.getParams()); params.set(CommonParams.WT, "raw"); req.setParams(params); ContentStreamBase content = new ContentStreamBase.FileStream(adminFile); content.setContentType(req.getParams().get(USE_CONTENT_TYPE)); rsp.add(RawResponseWriter.CONTENT, content); } rsp.setHttpCaching(false); }
From source file:alba.solr.searchcomponents.AlbaRequestHandler.java
License:Apache License
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { // TODO Auto-generated method stub /* List<SearchComponent> components = new ArrayList<SearchComponent>(); /*from w w w. j a va 2s . c o m*/ MySearchComponent msc = new MySearchComponent(); ResponseBuilder rb = new ResponseBuilder(req, rsp, components); msc.process(rb);*/ //rsp.add("hello", rb.rsp.getValues()); req.getContext().put(Loader.FUNCTIONS, functions); Object params[] = new Object[2]; params[0] = req; params[1] = rsp; // what if this method calls rsp.add( .. ) ???? Object result = this.function.getMethod().invoke(this.function.getInstance(), params); if (Map.class.isAssignableFrom(result.getClass())) { // if we got a Map, just return it as-is rsp.add(this.sectionName, result); } else // if we got anything else, try to serialize it! if (List.class.isAssignableFrom(result.getClass())) { for (Object o : (List) result) { DocumentObjectBinder dob = new DocumentObjectBinder(); SolrInputDocument sd = dob.toSolrInputDocument(o); SolrDocument dest = ClientUtils.toSolrDocument(sd); HashMap<Object, Object> nl = (HashMap<Object, Object>) dest.get("functionDescriptor"); //rsp.add(nl.get("name").toString(), dest2); rsp.add(null, dest); } } if (StaticResource.class.isAssignableFrom(result.getClass())) { FilteredShowFileRequestHandler file = new FilteredShowFileRequestHandler(); file.init(new NamedList()); //to initialize internal variables - but in this way it will NOT get the proper configuration from SolrConfig! ModifiableSolrParams solrParams = new ModifiableSolrParams(req.getParams()); StaticResource resource = ((StaticResource) result); solrParams.set("file", resource.getName()); //TODO Proper mapping here!! //solrParams.set("contentType", "text/xml;charset=utf-8"); solrParams.set("contentType", resource.getContentType()); req.setParams(solrParams); file.handleRequest(req, rsp); // logger.error("returning the content of " + ); } else { // unable to do any kind of serialization.. just add the result and let the ResponseWriter handle it rsp.add(null, result); } }
From source file:com.adr.bigdata.search.product.fe.BaseSuggestionHandler.java
@Override public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) { String cacheKey = SolrParamUtils.transform(req.getParams()); try {//from w w w. j a v a 2 s. c o m String cacheResponse = this.rdModel.get(cacheKey); if (cacheResponse == null) { //cacheMiss try { final Object[] terms = new Object[1]; suggestionLogic.execute(req, rsp, new Callable() { @Override public void call(Object... args) { terms[0] = args[0]; } }); SolrQueryResponse _rsp = new SolrQueryResponse(); super.handleRequest(req, _rsp); suggestionLogic.writeRsp(req, _rsp, terms[0]); String result = outerString(req, _rsp); if (!zeroResult(_rsp)) { this.rdModel.put(cacheKey, result); } ModifiableSolrParams params = new ModifiableSolrParams(req.getParams()); params.set("vincache", true); SolrParams _params = SolrParams.wrapDefaults(params, defaults); _params = SolrParams.wrapAppended(_params, appends); req.setParams(_params); rsp.add("vincache", result); } catch (Exception e) { error(req, rsp); getLogger().error("", e); } } else { //cache hit ModifiableSolrParams solrParam = new ModifiableSolrParams(req.getParams()); solrParam.set("vincache", true); SolrParams params = SolrParams.wrapAppended(solrParam, appends); params = SolrParams.wrapDefaults(params, defaults); req.setParams(params); rsp.add("vincache", cacheResponse); } } catch (Exception cacheEx) { getLogger().error("fail to get from redis cache.....{}", cacheEx.getMessage()); try { final Object[] terms = new Object[1]; suggestionLogic.execute(req, rsp, new Callable() { @Override public void call(Object... args) { terms[0] = args[0]; } }); super.handleRequest(req, rsp); suggestionLogic.writeRsp(req, rsp, terms[0]); } catch (Exception e) { error(req, rsp); getLogger().error("", e); } } }
From source file:com.doculibre.constellio.solr.handler.component.ManifoldCFAuthorizationComponent.java
License:Open Source License
@Override public void prepare(ResponseBuilder rb) throws IOException { SolrQueryRequest req = rb.req;/*from w w w . j a v a 2 s .c om*/ SolrParams params = req.getParams(); // A runtime param can skip if (!params.getBool(ENABLE, true)) { return; } boolean hasManifoldConnector = false; String collectioName = params.get(ConstellioSolrQueryParams.COLLECTION_NAME); RecordCollectionServices recordCollectionServices = ConstellioSpringUtils.getRecordCollectionServices(); RecordCollection recordCollection = recordCollectionServices.get(collectioName); if (recordCollection != null) { for (ConnectorInstance connector : recordCollection.getConnectorInstances()) { if (connector.getConnectorType().getName().equals(ManifoldCFConnectorType.CONNECTOR_TYPE_NAME)) { hasManifoldConnector = true; break; } else if (connector.getConnectorType().getName() .equals(IntelliGIDConnectorType.CONNECTOR_TYPE_NAME)) { hasManifoldConnector = true; break; } } } //skip calling the component if we don't use the service (the manifoldcf server could not be up) if (hasManifoldConnector) { ConstellioUser user; String userIdStr = params.get(ConstellioSolrQueryParams.USER_ID); if (userIdStr != null) { UserServices userServices = ConstellioSpringUtils.getUserServices(); try { user = userServices.get(new Long(userIdStr)); } catch (NumberFormatException e) { user = null; } } else { user = null; } if (user != null) { ModifiableSolrParams newParams = new ModifiableSolrParams(params); newParams.add(AUTHENTICATED_USER_NAME, user.getUsername() + "@" + user.getDomain()); req.setParams(newParams); } else { ModifiableSolrParams newParams = new ModifiableSolrParams(params); newParams.add(AUTHENTICATED_USER_NAME, "guest@guest"); req.setParams(newParams); } super.prepare(rb); } }
From source file:com.doculibre.constellio.wicket.servlet.SolrServletEmulator.java
License:Open Source License
@SuppressWarnings("deprecation") public void writeResponse(String solrQuery, RecordCollection collection, ConstellioUser user, HttpServletRequest request, HttpServletResponse response) { OutputStream outputStream;/* w ww. j av a2 s . c o m*/ try { outputStream = response.getOutputStream(); } catch (IOException e) { throw new RuntimeException(e); } if (user != null && !user.hasSearchPermission(collection)) { throw new RuntimeException("The user doesn't have search permission on the collection"); } else if (user == null && collection.hasSearchPermission()) { throw new RuntimeException("The collection requires a user with search permission"); } else { SimpleSearch simpleSearch = new SimpleSearch(); simpleSearch.setCollectionName(collection.getName()); if (solrQuery.contains("facet=constellio")) { solrQuery = solrQuery.replace("facet=constellio", "facet=on"); solrQuery = addConstellioFacets(simpleSearch, solrQuery, collection, user); LOGGER.info("Using constellio facets, new query is " + solrQuery); } ModifiableSolrParams solrParams = new ModifiableSolrParams( SolrRequestParsers.parseQueryString(solrQuery)); String queryType = solrParams.get("qt"); if (queryType != null && (queryType.toLowerCase().equals("spellchecker") || queryType.toLowerCase().equals("spellcheck"))) { writeSpellCheckerResponse(simpleSearch, solrParams, collection, user, outputStream); } else { String cdf = solrParams.get("cdf"); if (cdf != null && cdf.equals("true")) { SearchResultFieldServices searchResultFieldServices = ConstellioSpringUtils .getSearchResultFieldServices(); List<SearchResultField> fields = searchResultFieldServices.list(); List<String> fieldNames = new ArrayList<String>(); for (SearchResultField field : fields) { if (field.getRecordCollection().equals(collection)) { fieldNames.add(field.getIndexField().getName()); } } solrParams.add("fl", StringUtils.join(fieldNames.toArray(), ",")); solrParams.remove("cdf"); } try { SolrServer solrServer = SolrCoreContext.getSolrServer(collection); QueryResponse queryResponse = solrServer.query(solrParams); if (queryResponse.getStatus() == 0) { String ipAddress = request.getRemoteAddr(); simpleSearch.setQuery(solrParams.get("q")); StatsServices statsServices = ConstellioSpringUtils.getStatsServices(); statsServices.logSearch(simpleSearch, queryResponse, ipAddress); XMLResponseWriter xmlWriter = new XMLResponseWriter(); SolrQueryResponse sResponse = new SolrQueryResponse(); sResponse.setAllValues(queryResponse.getResponse()); try (OutputStreamWriter out = new OutputStreamWriter(outputStream)) { xmlWriter.write(out, new LocalSolrQueryRequest(null, solrParams), sResponse); out.flush(); } catch (IOException e) { throw new RuntimeException("Unable to convert Solr response into XML", e); } } } catch (SolrException e) { // if (!e.logged) LOGGER.log(Level.SEVERE, SolrException.toStr(e), e); // try { // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes()); // } catch (IOException e1) { // throw new RuntimeException(e1); // } // if (!e.logged) SolrException.log(log,e); sendErr(e.code(), SolrException.toStr(e), response, outputStream); } catch (Throwable e) { LOGGER.log(Level.SEVERE, SolrException.toStr(e), e); // try { // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes()); // } catch (IOException e1) { // throw new RuntimeException(e1); // } // SolrException.log(log,e); sendErr(500, SolrException.toStr(e), response, outputStream); } // final SolrCore core = // SolrCoreContext.getCores().getCore(collection.getName()); // // SolrServletRequest solrReq = new SolrServletRequest(core, // request); // SolrQueryRequest solrReq = new LocalSolrQueryRequest(core, // solrParams); // SolrQueryResponse solrRsp = new SolrQueryResponse(); // try { // // SolrRequestHandler handler = // core.getRequestHandler(solrReq.getParams().get(CommonParams.QT)); // if (handler==null) { // LOGGER.log(Level.WARNING, "Unknown Request Handler '" + // solrReq.getParams().get(CommonParams.QT) // + "' :" + solrReq); // // log.warn("Unknown Request Handler '" + // solrReq.getQueryType() +"' :" + solrReq); // throw new // SolrException(SolrException.ErrorCode.BAD_REQUEST,"Unknown Request Handler '" // + solrReq.getParams().get(CommonParams.QT) + "'"); // } // core.execute(handler, solrReq, solrRsp ); // if (solrRsp.getException() == null) { // String ipAddress = request.getRemoteAddr(); // // simpleSearch.setQuery(solrParams.get("q")); // QueryResponse qrsp = new QueryResponse(); // qrsp.setResponse(getParsedResponse(solrReq, solrRsp)); // // StatsServices statsServices = // ConstellioSpringUtils.getStatsServices(); // statsServices.logSearch(simpleSearch, qrsp, ipAddress); // // QueryResponseWriter responseWriter = // core.getQueryResponseWriter(solrReq); // // Now write it out // final String ct = responseWriter.getContentType(solrReq, // solrRsp); // // don't call setContentType on null // if (null != ct) response.setContentType(ct); // if (responseWriter instanceof BinaryQueryResponseWriter) { // BinaryQueryResponseWriter binWriter = // (BinaryQueryResponseWriter) responseWriter; // binWriter.write(outputStream, solrReq, solrRsp); // } else { // String charset = // ContentStreamBase.getCharsetFromContentType(ct); // Writer out = (charset == null || // charset.equalsIgnoreCase("UTF-8")) // ? new OutputStreamWriter(outputStream, UTF8) // : new OutputStreamWriter(outputStream, charset); // out = new FastWriter(out); // responseWriter.write(out, solrReq, solrRsp); // out.flush(); // } // } else { // Exception e = solrRsp.getException(); // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e); // // // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes()); // int rc=500; // if (e instanceof SolrException) { // rc=((SolrException)e).code(); // } // sendErr(rc, SolrException.toStr(e), response, outputStream); // } // } catch (SolrException e) { // // if (!e.logged) // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e); // // try { // // // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes()); // // } catch (IOException e1) { // // throw new RuntimeException(e1); // // } // // if (!e.logged) SolrException.log(log,e); // sendErr(e.code(), SolrException.toStr(e), response, // outputStream); // } catch (Throwable e) { // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e); // // try { // // // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes()); // // } catch (IOException e1) { // // throw new RuntimeException(e1); // // } // // SolrException.log(log,e); // sendErr(500, SolrException.toStr(e), response, outputStream); // } finally { // // This releases the IndexReader associated with the request // solrReq.close(); // } } } }
From source file:com.hurence.logisland.service.solr.api.SolrClientService.java
License:Apache License
@Override public List<MultiGetResponseRecord> multiGet(List<MultiGetQueryRecord> multiGetQueryRecords) throws DatastoreClientServiceException { try {//from ww w.j a v a 2 s.co m List<MultiGetResponseRecord> multiGetResponseRecords = new ArrayList<>(); for (MultiGetQueryRecord multiGetQueryRecord : multiGetQueryRecords) { String index = multiGetQueryRecord.getIndexName(); String uniqueKeyName = getUniqueKey(index); String[] fieldsToInclude = multiGetQueryRecord.getFieldsToInclude(); Map<String, String[]> params = new HashMap<>(); if (fieldsToInclude != null && fieldsToInclude.length > 0) { ArrayList<String> fields = new ArrayList<>(); fields.addAll(Arrays.asList(fieldsToInclude)); if (!fields.contains(uniqueKeyName)) { fields.add(uniqueKeyName); } params.put("fl", fields.toArray(new String[fields.size()])); } SolrParams solrParams = new ModifiableSolrParams(params); SolrDocumentList documents = getClient().getById(index, multiGetQueryRecord.getDocumentIds(), solrParams); for (SolrDocument document : documents) { Map<String, Map<String, String>> map = getConverter().toMap(document, uniqueKeyName); Map.Entry<String, Map<String, String>> mapDocument = map.entrySet().iterator().next(); multiGetResponseRecords.add( new MultiGetResponseRecord(index, "", mapDocument.getKey(), mapDocument.getValue())); } } return multiGetResponseRecords; } catch (Exception e) { throw new DatastoreClientServiceException(e); } }
From source file:com.nkang.kxmoment.util.SolrUtils.HttpSolrServer.java
License:Apache License
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;//from w w w.j a va2 s .c o m InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // client already has this set, is this needed method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); // add jauth information //String username = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_USERNAME).toString(); //String password = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_PASSWORD).toString(); ResourceBundle bundle = ResourceBundle.getBundle("solrconfig"); String username; String password; username = bundle.getString("wsUsername.url"); password = bundle.getString("wsPassword.url"); method.addHeader("username", username); method.addHeader("password", password); InputStream respBody = null; boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList<?> err = (NamedList<?>) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (IOException e) { //log.error("", e); } finally { if (!success) { method.abort(); } } } } }
From source file:com.s24.search.solr.util.SolrParamsUtil.java
License:Apache License
/** * Returns a modifiable version of the given parameters. If {@code params}already is an instance of * {@code ModifiableSolrParams}, the same instance is returned, otherwise, a modifiable copy of the parameters is * created and returned.//from w ww . jav a 2 s . c o m * * @param params the parameters. If {@code null}, an empty {@code ModifiableSolrParams} instance will be returned. */ public static ModifiableSolrParams modifiable(SolrParams params) { if (params instanceof ModifiableSolrParams) { return (ModifiableSolrParams) params; } return new ModifiableSolrParams(params); }
From source file:com.sitewhere.connectors.solr.search.SolrSearchProvider.java
License:Open Source License
/** * Create Solr parameters from an arbitrary query string. * /*from w ww. j ava 2 s .co m*/ * @param queryString * @return */ protected SolrParams createParamsFromQueryString(String queryString) { MultiValueMap<String, String> parsed = UriComponentsBuilder.fromHttpUrl("http://localhost?" + queryString) .build().getQueryParams(); Map<String, String[]> params = new HashMap<String, String[]>(); for (String key : parsed.keySet()) { params.put(key, parsed.get(key).toArray(new String[0])); } return new ModifiableSolrParams(params); }