Search in sources :

Example 51 with PrivilegedActionException

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();
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) SolrCore(org.apache.solr.core.SolrCore) IndexReader(org.apache.lucene.index.IndexReader) TaggerFstCorpus(org.opensextant.solrtexttagger.TaggerFstCorpus) SolrIndexSearcher(org.apache.solr.search.SolrIndexSearcher) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException)

Example 52 with PrivilegedActionException

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();
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) HttpPost(org.apache.http.client.methods.HttpPost) Blob(org.apache.stanbol.enhancer.servicesapi.Blob) PrivilegedActionException(java.security.PrivilegedActionException) PlainLiteralImpl(org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) URISyntaxException(java.net.URISyntaxException) ConfigurationException(org.osgi.service.cm.ConfigurationException) HttpException(org.apache.http.HttpException) ClientProtocolException(org.apache.http.client.ClientProtocolException) PrivilegedActionException(java.security.PrivilegedActionException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) ClientProtocolException(org.apache.http.client.ClientProtocolException) Graph(org.apache.clerezza.commons.rdf.Graph) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) Map(java.util.Map) HashMap(java.util.HashMap)

Example 53 with PrivilegedActionException

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);
        }
    }
}
Also used : Chain(org.apache.stanbol.enhancer.servicesapi.Chain) PrivilegedActionException(java.security.PrivilegedActionException) VelocityContext(org.apache.velocity.VelocityContext) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamespaceException(org.osgi.service.http.NamespaceException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Template(org.apache.velocity.Template) ServletException(javax.servlet.ServletException) StringReader(java.io.StringReader) Benchmark(org.apache.stanbol.enhancer.benchmark.Benchmark) PrintWriter(java.io.PrintWriter)

Example 54 with PrivilegedActionException

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);
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) SolrServerException(org.apache.solr.client.solrj.SolrServerException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) SolrQuery(org.apache.solr.client.solrj.SolrQuery) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SolrException(org.apache.solr.common.SolrException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException)

Example 55 with PrivilegedActionException

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;
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) PrivilegedActionException(java.security.PrivilegedActionException) StreamQueryRequest(org.apache.stanbol.commons.solr.utils.StreamQueryRequest) SolrServerException(org.apache.solr.client.solrj.SolrServerException) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) SolrQuery(org.apache.solr.client.solrj.SolrQuery) SolrServerException(org.apache.solr.client.solrj.SolrServerException) YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) NoConverterException(org.apache.stanbol.entityhub.yard.solr.model.NoConverterException) YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) SolrDocument(org.apache.solr.common.SolrDocument) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) QueryResultListImpl(org.apache.stanbol.entityhub.core.query.QueryResultListImpl)

Aggregations

PrivilegedActionException (java.security.PrivilegedActionException)135 IOException (java.io.IOException)58 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)56 Subject (javax.security.auth.Subject)23 LoginContext (javax.security.auth.login.LoginContext)14 LoginException (javax.security.auth.login.LoginException)12 InvocationTargetException (java.lang.reflect.InvocationTargetException)11 Method (java.lang.reflect.Method)11 URISyntaxException (java.net.URISyntaxException)11 HashSet (java.util.HashSet)11 ServletException (javax.servlet.ServletException)11 AccessControlContext (java.security.AccessControlContext)10 Principal (java.security.Principal)9 GSSException (org.ietf.jgss.GSSException)9 Field (java.lang.reflect.Field)8 SolrServerException (org.apache.solr.client.solrj.SolrServerException)7 GSSManager (org.ietf.jgss.GSSManager)7 MalformedURLException (java.net.MalformedURLException)6 ArrayList (java.util.ArrayList)6 YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)6