Example usage for org.apache.shiro SecurityUtils getSubject

List of usage examples for org.apache.shiro SecurityUtils getSubject

Introduction

In this page you can find the example usage for org.apache.shiro SecurityUtils getSubject.

Prototype

public static Subject getSubject() 

Source Link

Document

Returns the currently accessible Subject available to the calling code depending on runtime environment.

Usage

From source file:annis.service.internal.QueryService.java

License:Apache License

@GET
@Path("corpora/{top}/allmetadata")
@Produces("application/xml")
public List<Annotation> getAllMetadata(@PathParam("top") String toplevelCorpusName) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:meta:" + toplevelCorpusName);
    return annisDao.listDocumentsAnnotations(toplevelCorpusName, true);
}

From source file:annis.service.internal.QueryService.java

License:Apache License

@GET
@Path("corpora/{top}/docmetadata")
@Produces("application/xml")
public List<Annotation> getDocMetadata(@PathParam("top") String toplevelCorpusName) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:meta:" + toplevelCorpusName);
    return annisDao.listDocumentsAnnotations(toplevelCorpusName, false);
}

From source file:annis.service.internal.QueryService.java

License:Apache License

/**
* Get an Annis Binary object identified by its id.
*
* @param id/*w  w w .  j  av a  2  s .  co  m*/
* @param rawOffset the part we want to start from, we start from 0
* @param rawLength how many bytes we take
* @return AnnisBinary
*/
@GET
@Path("corpora/{top}/{document}/binary/{offset}/{length}")
@Produces("application/xml")
public AnnisBinary binary(@PathParam("top") String toplevelCorpusName, @PathParam("document") String corpusName,
        @PathParam("offset") String rawOffset, @PathParam("length") String rawLength,
        @QueryParam("mime") String mimeType, @QueryParam("title") String title) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:binary:" + toplevelCorpusName);

    int offset = Integer.parseInt(rawOffset);
    int length = Integer.parseInt(rawLength);

    AnnisBinary bin;
    log.debug("fetching " + (length / 1024) + "kb (" + offset + "-" + (offset + length) + ") from binary "
            + toplevelCorpusName + "/" + corpusName + (title == null ? "" : title) + " "
            + (mimeType == null ? "" : mimeType));

    bin = annisDao.getBinary(toplevelCorpusName, corpusName, mimeType, title, offset + 1, length);

    log.debug("fetch successfully");
    return bin;
}

From source file:annis.service.internal.QueryService.java

License:Apache License

/**
* Fetches the example queries for a specific corpus.
*
* @param rawCorpusNames specifies the corpora the examples are fetched from.
*
*///w  w w .  java 2  s .  c o  m
@GET
@Path("corpora/example-queries/")
@Produces(MediaType.APPLICATION_XML)
public List<ExampleQuery> getExampleQueries(@QueryParam("corpora") String rawCorpusNames)
        throws WebApplicationException {

    try {
        String[] corpusNames;
        if (rawCorpusNames != null) {
            corpusNames = rawCorpusNames.split(",");
        } else {
            List<AnnisCorpus> allCorpora = annisDao.listCorpora();
            corpusNames = new String[allCorpora.size()];
            for (int i = 0; i < corpusNames.length; i++) {
                corpusNames[i] = allCorpora.get(i).getName();
            }
        }

        List<String> allowedCorpora = new ArrayList<String>();

        // filter by which corpora the user is allowed to access
        Subject user = SecurityUtils.getSubject();
        for (String c : corpusNames) {
            if (user.isPermitted("query:*:" + c)) {
                allowedCorpora.add(c);
            }
        }

        List<Long> corpusIDs = annisDao.mapCorpusNamesToIds(allowedCorpora);
        return annisDao.getExampleQueries(corpusIDs);
    } catch (Exception ex) {
        throw new WebApplicationException(400);
    }
}

From source file:annis.service.internal.QueryService.java

License:Apache License

/**
* Get the Metadata of an Annis Binary object identified by its id. This
* function calls getBinary(long id, 1, 1), so this function does not work, if
* the specs of getBinary(long id, int offset,int length) changed.
*
* @param id//from   w ww  .  ja v  a 2s  .  c  o m
* @return AnnisBinaryMetaData
*/
@GET
@Path("corpora/{top}/{document}/binary/meta")
@Produces("application/xml")
public List<AnnisBinaryMetaData> binaryMeta(@PathParam("top") String toplevelCorpusName,
        @PathParam("document") String documentName) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:binary:" + toplevelCorpusName);

    return annisDao.getBinaryMeta(toplevelCorpusName, documentName);

}

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

@GET
@Path("search/count")
@Produces("application/xml")
@Override/*from  w  w w. j  av a2 s  .co  m*/
public Response count(@QueryParam("q") String query, @QueryParam("corpora") String rawCorpusNames) {

    requiredParameter(query, "q", "AnnisQL query");
    requiredParameter(rawCorpusNames, "corpora", "comma separated list of corpus names");

    Subject user = SecurityUtils.getSubject();
    List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames);
    for (String c : corpusNames) {
        user.checkPermission("query:count:" + c);
    }

    QueryData data = queryDataFromParameters(query, rawCorpusNames);
    long start = new Date().getTime();
    MatchAndDocumentCount count = queryDao.countMatchesAndDocuments(data);
    long end = new Date().getTime();

    logQuery("COUNT", query, splitCorpusNamesFromRaw(rawCorpusNames), end - start);

    return Response.ok(count).type(MediaType.APPLICATION_XML_TYPE).build();
}

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

@GET
@Path("search/find")
@Produces({ "application/xml", "text/plain" })
@Override/*from   w  w  w .  j  ava  2  s.c o m*/
public Response find(@QueryParam("q") String query, @QueryParam("corpora") String rawCorpusNames,
        @DefaultValue("0") @QueryParam("offset") String offsetRaw,
        @DefaultValue("-1") @QueryParam("limit") String limitRaw,
        @DefaultValue("ascending") @QueryParam("order") String orderRaw) throws IOException {
    requiredParameter(query, "q", "AnnisQL query");
    requiredParameter(rawCorpusNames, "corpora", "comma separated list of corpus names");

    Subject user = SecurityUtils.getSubject();
    List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames);
    for (String c : corpusNames) {
        user.checkPermission("query:find:" + c);
    }

    int offset = Integer.parseInt(offsetRaw);
    int limit = Integer.parseInt(limitRaw);

    OrderType order;
    try {
        order = OrderType.valueOf(orderRaw.toLowerCase());
    } catch (IllegalArgumentException ex) {
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
                .type(MediaType.TEXT_PLAIN).entity("parameter 'order' has the invalid value '" + orderRaw
                        + "'. It should be one of" + " 'ascending', 'random' or 'descending")
                .build());
    }

    final QueryData data = queryDataFromParameters(query, rawCorpusNames);
    data.setCorpusConfiguration(queryDao.getCorpusConfiguration());
    data.addExtension(new LimitOffsetQueryData(offset, limit, order));

    String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);
    if (acceptHeader == null || acceptHeader.trim().isEmpty()) {
        acceptHeader = "*/*";
    }

    List<String> knownTypes = Lists.newArrayList("text/plain", "application/xml");

    // find the best matching mime type
    String bestMediaTypeMatch = MIMEParse.bestMatch(knownTypes, acceptHeader);

    if ("text/plain".equals(bestMediaTypeMatch)) {
        return Response.ok(findRaw(data, rawCorpusNames, query), "text/plain").build();
    } else {
        List<Match> result = findXml(data, rawCorpusNames, query);
        return Response.ok().type("application/xml")
                .entity(new GenericEntity<MatchGroup>(new MatchGroup(result)) {
                }).build();
    }

}

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

/**
 * Get result as matrix in WEKA (ARFF) format.
 * @param query//from  w  ww.  j  a v a2  s. co  m
 * @param rawCorpusNames
 * @param rawMetaKeys
 * @param rawCsv
 * @return 
 */
@GET
@Path("search/matrix")
@Produces("text/plain")
public StreamingOutput matrix(final @QueryParam("q") String query,
        final @QueryParam("corpora") String rawCorpusNames, @QueryParam("metakeys") String rawMetaKeys,
        @DefaultValue("false") @QueryParam("csv") String rawCsv) {
    requiredParameter(query, "q", "AnnisQL query");
    requiredParameter(rawCorpusNames, "corpora", "comma separated list of corpus names");

    final boolean outputCsv = Boolean.parseBoolean(rawCsv);

    Subject user = SecurityUtils.getSubject();
    List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames);
    for (String c : corpusNames) {
        user.checkPermission("query:matrix:" + c);
    }

    final QueryData data = queryDataFromParameters(query, rawCorpusNames);

    MatrixQueryData ext = new MatrixQueryData();
    if (rawMetaKeys != null) {
        ext.setMetaKeys(splitMatrixKeysFromRaw(rawMetaKeys));
    }
    if (ext.getMetaKeys() != null && ext.getMetaKeys().isEmpty()) {
        ext.setMetaKeys(null);
    }

    data.addExtension(ext);

    StreamingOutput result = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            long start = new Date().getTime();
            queryDao.matrix(data, outputCsv, output);
            long end = new Date().getTime();
            logQuery("MATRIX", query, splitCorpusNamesFromRaw(rawCorpusNames), end - start);
        }
    };

    return result;
}

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

/**
 * Frequency analysis./* w w  w .jav a 2  s  .  c  o m*/
 * 
 * @param  rawFields Comma seperated list of result vector elements. 
 *                   Each element has the form <node-nr>:<anno-name>. The
 *                   annotation name can be set to "tok" to indicate that the
 *                   span should be used instead of an annotation.
 */
@GET
@Path("search/frequency")
@Produces("application/xml")
public FrequencyTable frequency(@QueryParam("q") String query, @QueryParam("corpora") String rawCorpusNames,
        @QueryParam("fields") String rawFields) {
    requiredParameter(query, "q", "AnnisQL query");
    requiredParameter(rawCorpusNames, "corpora", "comma separated list of corpus names");
    requiredParameter(rawFields, "fields", "Comma seperated list of result vector elements.");

    Subject user = SecurityUtils.getSubject();
    List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames);
    for (String c : corpusNames) {
        user.checkPermission("query:matrix:" + c);
    }

    QueryData data = queryDataFromParameters(query, rawCorpusNames);
    FrequencyTableQuery ext = FrequencyTableQuery.parse(rawFields);
    data.addExtension(ext);

    long start = new Date().getTime();
    FrequencyTable freqTable = queryDao.frequency(data);
    long end = new Date().getTime();
    logQuery("FREQUENCY", query, splitCorpusNamesFromRaw(rawCorpusNames), end - start);

    return freqTable;
}

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

protected SaltProject basicSubgraph(MatchGroup matches, @QueryParam("segmentation") String segmentation,
        @DefaultValue("0") @QueryParam("left") String leftRaw,
        @DefaultValue("0") @QueryParam("right") String rightRaw,
        @DefaultValue("all") @QueryParam("filter") String filterRaw) {

    Subject user = SecurityUtils.getSubject();

    int left = Integer.parseInt(leftRaw);
    int right = Integer.parseInt(rightRaw);
    SubgraphFilter filter = SubgraphFilter.valueOf(filterRaw);

    QueryData data = GraphHelper.createQueryData(matches, queryDao);

    data.addExtension(new AnnotateQueryData(left, right, segmentation, filter));

    Set<String> corpusNames = new TreeSet<>();

    for (Match singleMatch : matches.getMatches()) {
        // collect list of used corpora
        for (java.net.URI u : singleMatch.getSaltIDs()) {
            corpusNames.add(CommonHelper.getCorpusPath(u).get(0));
        }/* w ww. j  ava 2s .c o m*/
    }

    for (String c : corpusNames) {
        user.checkPermission("query:subgraph:" + c);
    }

    List<String> corpusNamesList = new LinkedList<>(corpusNames);

    if (data.getCorpusList() == null || data.getCorpusList().isEmpty()) {
        throw new WebApplicationException(Response.Status.BAD_REQUEST.getStatusCode());
    }

    long start = new Date().getTime();
    SaltProject p = queryDao.graph(data);
    long end = new Date().getTime();
    String options = "matches: " + matches.toString() + ", seg: " + segmentation + ", left: " + left
            + ", right: " + right + ", filter: " + filter;
    logQuery("SUBGRAPH", "", corpusNamesList, end - start, options);

    return p;
}