use of java.security.PrivilegedActionException in project stanbol by apache.
the class CorpusCreationTask method call.
@Override
public TaggerFstCorpus call() {
if (!indexConfig.isActive()) {
String msg = "Index Configuration already deactivated";
fstInfo.setError(msg);
throw new IllegalStateException(msg);
}
SolrCore core = indexConfig.getIndex();
if (core.isClosed()) {
String msg = "Unable to build " + fstInfo + " becuase SolrCore " + core.getName() + " is closed!";
fstInfo.setError(msg);
throw new IllegalStateException(msg);
}
final TaggerFstCorpus corpus;
RefCounted<SolrIndexSearcher> searcherRef = core.getSearcher();
try {
//STANBOL-1177: create FST models in AccessController.doPrivileged(..)
final SolrIndexSearcher searcher = searcherRef.get();
//we do get the AtomicReader, because TaggerFstCorpus will need it
//anyways. This prevents to create another SlowCompositeReaderWrapper.
final IndexReader reader = searcher.getAtomicReader();
log.info(" ... build FST corpus for {}", fstInfo);
corpus = AccessController.doPrivileged(new PrivilegedExceptionAction<TaggerFstCorpus>() {
public TaggerFstCorpus run() throws IOException {
return new TaggerFstCorpus(reader, searcher.getIndexReader().getVersion(), null, fstInfo.indexedField, fstInfo.storedField, fstInfo.analyzer, fstInfo.partialMatches, 1, 100);
}
});
if (indexConfig.isActive()) {
//set the created corpus to the FST Info
fstInfo.setCorpus(corpus);
} else {
//index configuration no longer active ... ignore the built FST
log.warn("Index Config for " + fstInfo + "was deactivated while building FST. " + "Built FST will be ignored.");
}
return corpus;
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof IOException) {
//IO Exception while loading the file
throw new IllegalStateException("Unable to read Information to build " + fstInfo + " from SolrIndex '" + core.getName() + "'!", e);
} else {
//Runtime exception
throw RuntimeException.class.cast(e);
}
} finally {
//ensure that we dereference the searcher
searcherRef.decref();
}
}
use of java.security.PrivilegedActionException in project stanbol by apache.
the class RestfulLangidentEngine method computeEnhancements.
/**
* Compute enhancements for supplied ContentItem. The results of the process
* are expected to be stored in the metadata of the content item.
* <p/>
* The client (usually an {@link org.apache.stanbol.enhancer.servicesapi.EnhancementJobManager}) should take care of
* persistent storage of the enhanced {@link org.apache.stanbol.enhancer.servicesapi.ContentItem}.
* <p/>
* This method creates a new POSContentPart using {@link org.apache.stanbol.enhancer.engines.pos.api.POSTaggerHelper#createContentPart} from a text/plain part and
* stores it as a new part in the content item. The metadata is not changed.
*
* @throws org.apache.stanbol.enhancer.servicesapi.EngineException
* if the underlying process failed to work as
* expected
*/
@Override
public void computeEnhancements(final ContentItem ci) throws EngineException {
//get the plain text Blob
Map.Entry<IRI, Blob> textBlob = getPlainText(this, ci, false);
Blob blob = textBlob.getValue();
//send the text to the server
final HttpPost request = new HttpPost(serviceUrl);
request.setEntity(new InputStreamEntity(blob.getStream(), blob.getContentLength(), ContentType.create(blob.getMimeType(), blob.getParameter().get("charset"))));
//execute the request
List<LangSuggestion> detected;
try {
detected = AccessController.doPrivileged(new PrivilegedExceptionAction<List<LangSuggestion>>() {
public List<LangSuggestion> run() throws ClientProtocolException, IOException {
return httpClient.execute(request, new LangIdentResponseHandler(ci, objectMapper));
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof ClientProtocolException) {
throw new EngineException(this, ci, "Exception while executing Request " + "on RESTful Language Identification Service at " + serviceUrl, e);
} else if (e instanceof IOException) {
throw new EngineException(this, ci, "Exception while executing Request " + "on RESTful Language Identification Service at " + serviceUrl, e);
} else {
throw RuntimeException.class.cast(e);
}
}
Graph metadata = ci.getMetadata();
log.debug("Detected Languages for ContentItem {} and Blob {}");
ci.getLock().writeLock().lock();
try {
//write TextAnnotations for the detected languages
for (LangSuggestion suggestion : detected) {
// add a hypothesis
log.debug(" > {}@{}", suggestion.getLanguage(), suggestion.hasProbability() ? suggestion.getProbability() : "-,--");
IRI textEnhancement = EnhancementEngineHelper.createTextEnhancement(ci, this);
metadata.add(new TripleImpl(textEnhancement, DC_LANGUAGE, new PlainLiteralImpl(suggestion.getLanguage())));
metadata.add(new TripleImpl(textEnhancement, DC_TYPE, DCTERMS_LINGUISTIC_SYSTEM));
if (suggestion.hasProbability()) {
metadata.add(new TripleImpl(textEnhancement, ENHANCER_CONFIDENCE, literalFactory.createTypedLiteral(suggestion.getProbability())));
}
}
} finally {
ci.getLock().writeLock().unlock();
}
}
use of java.security.PrivilegedActionException in project stanbol by apache.
the class BenchmarkServlet method doPost.
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final String content = request.getParameter(PARAM_CONTENT);
if (content == null) {
throw new ServletException("Missing " + PARAM_CONTENT + " parameter");
}
String chainName = request.getParameter(PARAM_CHAIN);
final Template t = AccessController.doPrivileged(new PrivilegedAction<Template>() {
@Override
public Template run() {
return getTemplate("/velocity/benchmark-results.html");
}
});
final VelocityContext ctx = getVelocityContext(request, "Benchmark Results");
ctx.put("contentItemFactory", ciFactory);
ctx.put("jobManager", jobManager);
List<? extends Benchmark> benchmarks = parser.parse(new StringReader(content));
if (chainName != null && !chainName.isEmpty()) {
Chain chain = chainManager.getChain(chainName);
if (chain == null) {
response.setStatus(404);
PrintWriter w = response.getWriter();
w.println("Unable to perform benchmark on EnhancementChain '" + StringEscapeUtils.escapeHtml(chainName) + "' because no chain with that name is active!");
IOUtils.closeQuietly(w);
return;
}
for (Benchmark benchmark : benchmarks) {
benchmark.setChain(chain);
}
}
ctx.put("benchmarks", benchmarks);
ctx.put("graphFormatter", new GraphFormatter(graphSerializer));
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws IOException {
t.merge(ctx, response.getWriter());
return null;
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof IOException) {
throw (IOException) e;
} else {
throw RuntimeException.class.cast(e);
}
}
}
use of java.security.PrivilegedActionException in project stanbol by apache.
the class SolrFieldMapper method getSolrDocument.
/**
* Getter for a SolrDocument based on the ID. Used to load the config from the index.
*
* @param inputDoc
* the document to store
*/
protected SolrDocument getSolrDocument(String uri) throws SolrServerException, IOException {
if (server == null) {
return null;
}
final SolrQuery solrQuery = new SolrQuery();
// select all fields
solrQuery.addField("*");
// we query for the id, there is only one result
solrQuery.setRows(1);
String queryString = String.format("%s:%s", this.getDocumentIdField(), SolrUtil.escapeSolrSpecialChars(uri));
solrQuery.setQuery(queryString);
QueryResponse queryResponse;
try {
queryResponse = AccessController.doPrivileged(new PrivilegedExceptionAction<QueryResponse>() {
public QueryResponse run() throws IOException, SolrServerException {
return server.query(solrQuery);
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof SolrServerException) {
throw (SolrServerException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
} else {
throw RuntimeException.class.cast(e);
}
}
if (queryResponse.getResults().isEmpty()) {
return null;
} else {
return queryResponse.getResults().get(0);
}
}
use of java.security.PrivilegedActionException in project stanbol by apache.
the class SolrYard method find.
private QueryResultList<Representation> find(final FieldQuery parsedQuery, SELECT select) throws YardException {
//create a clone of the query, because we need to refine it because the
//query (as executed) needs to be included in the result set
FieldQuery fieldQuery = parsedQuery.clone();
log.debug("find " + fieldQuery);
long start = System.currentTimeMillis();
final Set<String> selected;
if (select == SELECT.QUERY) {
// if query set the fields to add to the result Representations
selected = new HashSet<String>(fieldQuery.getSelectedFields());
// add the score to query results!
selected.add(RdfResourceEnum.resultScore.getUri());
} else {
// otherwise add all fields
selected = null;
}
final SolrQuery query = solrQueryFactoy.parseFieldQuery(fieldQuery, select);
long queryGeneration = System.currentTimeMillis();
if (closed) {
log.warn("The SolrYard '{}' was already closed!", config.getName());
}
QueryResponse response;
try {
response = AccessController.doPrivileged(new PrivilegedExceptionAction<QueryResponse>() {
public QueryResponse run() throws IOException, SolrServerException {
StreamQueryRequest request = new StreamQueryRequest(query);
return request.process(server);
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof SolrServerException) {
if ("unknown handler: /mlt".equals(e.getCause().getMessage())) {
throw new YardException("Solr is missing '<requestHandler name=\"/mlt\"" + " class=\"solr.MoreLikeThisHandler\" startup=\"lazy\" />'" + " in 'solrconfig.xml'", e);
}
throw new YardException("Error while performing Query on SolrServer: " + query.getQuery(), e);
} else if (e instanceof IOException) {
throw new YardException("Unable to access SolrServer", e);
} else {
throw RuntimeException.class.cast(e);
}
}
if (SolrQueryFactory.MLT_QUERY_TYPE.equals(query.getRequestHandler())) {
log.debug("{}", response);
}
long queryTime = System.currentTimeMillis();
// return a queryResultList
QueryResultListImpl<Representation> resultList = new QueryResultListImpl<Representation>(fieldQuery, // by adapting SolrDocuments to Representations
new AdaptingIterator<SolrDocument, Representation>(response.getResults().iterator(), // inline Adapter Implementation
new AdaptingIterator.Adapter<SolrDocument, Representation>() {
@Override
public Representation adapt(SolrDocument doc, Class<Representation> type) {
// use this method for the conversion!
return createRepresentation(doc, selected);
}
}, Representation.class), Representation.class);
long resultProcessing = System.currentTimeMillis();
log.debug(String.format(" ... done [queryGeneration=%dms|queryTime=%dms|resultProcessing=%dms|sum=%dms]", (queryGeneration - start), (queryTime - queryGeneration), (resultProcessing - queryTime), (resultProcessing - start)));
return resultList;
}
Aggregations