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.QueryServiceImpl.java

License:Apache License

@GET
@Path("graph/{top}/{doc}")
@Produces({ "application/xml", "application/xmi+xml", "application/xmi+binary", "application/graphml+xml" })
@Override/*from   ww  w  .ja  va  2 s  .  c o m*/
public SaltProject graph(@PathParam("top") String toplevelCorpusName, @PathParam("doc") String documentName,
        @QueryParam("filternodeanno") String filternodeanno) {

    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:subgraph:" + toplevelCorpusName);

    List<String> nodeAnnotationFilter = null;
    if (filternodeanno != null) {
        nodeAnnotationFilter = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(filternodeanno);
    }

    try {
        long start = new Date().getTime();
        SaltProject p = queryDao.retrieveAnnotationGraph(toplevelCorpusName, documentName,
                nodeAnnotationFilter);
        long end = new Date().getTime();
        logQuery("GRAPH", toplevelCorpusName, documentName, end - start);
        return p;
    } catch (Exception ex) {
        log.error("error when accessing graph " + toplevelCorpusName + "/" + documentName, ex);
        throw new WebApplicationException(ex, 500);
    }
}

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

License:Apache License

@GET
@Path("corpora")
@Produces("application/xml")
public List<AnnisCorpus> corpora() {
    List<AnnisCorpus> allCorpora = queryDao.listCorpora();

    List<AnnisCorpus> allowedCorpora = new LinkedList<>();

    // filter by which corpora the user is allowed to access
    Subject user = SecurityUtils.getSubject();
    for (AnnisCorpus c : allCorpora) {
        if (user.isPermitted("query:show:" + c.getName())) {
            allowedCorpora.add(c);/*  w w w. j av  a 2  s  .  c  o m*/
        }
    }

    return allowedCorpora;
}

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

License:Apache License

@GET
@Path("corpora/config")
@Produces("application/xml")
public CorpusConfigMap corpusConfigs() {
    CorpusConfigMap corpusConfigs = queryDao.getCorpusConfigurations();
    CorpusConfigMap result = new CorpusConfigMap();
    Subject user = SecurityUtils.getSubject();

    if (corpusConfigs != null) {
        for (String c : corpusConfigs.getCorpusConfigs().keySet()) {
            if (user.isPermitted("query:*:" + c)) {
                result.put(c, corpusConfigs.get(c));
            }/*from w  w w . j a  va  2 s  .c  o m*/
        }
    }

    return result;
}

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

License:Apache License

@GET
@Path("corpora/{top}")
@Produces("application/xml")
public List<AnnisCorpus> singleCorpus(@PathParam("top") String toplevelName) {
    List<AnnisCorpus> result = new ArrayList<>();

    Subject user = SecurityUtils.getSubject();

    LinkedList<String> originalCorpusNames = new LinkedList<>();
    originalCorpusNames.add(toplevelName);
    List<Long> ids = queryDao.mapCorpusNamesToIds(originalCorpusNames);

    // also add all corpora that match the alias name
    ids.addAll(queryDao.mapCorpusAliasToIds(toplevelName));
    if (!ids.isEmpty()) {
        List<AnnisCorpus> allCorpora = queryDao.listCorpora(ids);
        for (AnnisCorpus c : allCorpora) {
            if (user.isPermitted("query:show:" + c.getName())) {
                result.add(c);//w ww.j  ava  2s.  c o  m
            }
        }
    }

    return result;
}

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

License:Apache License

@GET
@Path("corpora/{top}/config")
@Produces("application/xml")
public CorpusConfig corpusConfig(@PathParam("top") String toplevelName) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:config:" + toplevelName);

    try {//from   w  ww .j  av a 2s  .  c  om
        Properties tmp = queryDao.getCorpusConfigurationSave(toplevelName);

        CorpusConfig corpusConfig = new CorpusConfig();
        corpusConfig.setConfig(tmp);

        return corpusConfig;
    } catch (Exception ex) {
        log.error("problems with reading config", ex);
        throw new WebApplicationException(ex, 500);
    }
}

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

License:Apache License

@GET
@Path("corpora/{top}/annotations")
@Produces("application/xml")
public List<AnnisAttribute> annotations(@PathParam("top") String toplevelCorpus,
        @DefaultValue("false") @QueryParam("fetchvalues") String fetchValues,
        @DefaultValue("false") @QueryParam("onlymostfrequentvalues") String onlyMostFrequentValues)
        throws WebApplicationException {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:annotations:" + toplevelCorpus);

    List<Long> corpusList = new ArrayList<>();
    corpusList.add(queryDao.mapCorpusNameToId(toplevelCorpus));

    return queryDao.listAnnotations(corpusList, Boolean.parseBoolean(fetchValues),
            Boolean.parseBoolean(onlyMostFrequentValues));

}

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

License:Apache License

@GET
@Path("corpora/{top}/segmentation-names")
@Produces("application/xml")
public SegmentationList segmentationNames(@PathParam("top") String toplevelCorpus)
        throws WebApplicationException {

    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:annotations:" + toplevelCorpus);

    List<Long> corpusList = new ArrayList<>();
    corpusList.add(queryDao.mapCorpusNameToId(toplevelCorpus));

    return new SegmentationList(queryDao.listSegmentationNames(corpusList));

}

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

License:Apache License

/**
 * Return true if this is a valid query or throw exception when invalid
 *
 * @param query Query to check for validity
 * @param rawCorpusNames// w w w .  j  a v  a 2  s .  co  m
 * @return Either "ok" or an error message.
 */
@GET
@Produces("text/plain")
@Path("check")
public String check(@QueryParam("q") String query,
        @DefaultValue("") @QueryParam("corpora") String rawCorpusNames) {
    Subject user = SecurityUtils.getSubject();
    List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames);
    for (String c : corpusNames) {
        user.checkPermission("query:parse:" + c);
    }
    Collections.sort(corpusNames);

    List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(corpusNames);

    queryDao.parseAQL(query, corpusIDs);
    return "ok";
}

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

License:Apache License

/**
 * Return the list of the query nodes if this is a valid query 
 * or throw exception when invalid//from  ww w .ja v  a  2 s  .c o m
 *
 * @param query Query to get the query nodes for
 * @param rawCorpusNames 
 * @return
 */
@GET
@Path("parse/nodes")
@Produces("application/xml")
public Response parseNodes(@QueryParam("q") String query,
        @DefaultValue("") @QueryParam("corpora") String rawCorpusNames) {
    Subject user = SecurityUtils.getSubject();
    List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames);
    for (String c : corpusNames) {
        user.checkPermission("query:parse:" + c);
    }
    Collections.sort(corpusNames);

    List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(corpusNames);

    QueryData data = queryDao.parseAQL(query, corpusIDs);
    List<QueryNode> nodes = new LinkedList<>();
    int i = 0;
    for (List<QueryNode> alternative : data.getAlternatives()) {
        for (QueryNode n : alternative) {
            n.setAlternativeNumber(i);
            nodes.add(n);
        }
        i++;
    }
    return Response.ok(new GenericEntity<List<QueryNode>>(nodes) {
    }).build();
}

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

License:Apache License

/**
 * Get an Annis Binary object identified by its id.
 *
 * @param id// w  ww.  j a  v a 2 s .c  o  m
 * @param rawOffset the part we want to start from, we start from 0
 * @param rawLength how many bytes we take
 * @return AnnisBinary
 */
@Override
public Response binary(String toplevelCorpusName, String corpusName, String rawOffset, String rawLength,
        String fileName) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:binary:" + toplevelCorpusName);

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

    List<AnnisBinaryMetaData> meta = queryDao.getBinaryMeta(toplevelCorpusName, corpusName);
    HashMap<String, AnnisBinaryMetaData> matchedMetaByType = new LinkedHashMap<>();

    for (AnnisBinaryMetaData m : meta) {
        if (fileName == null) {
            // just add all available media types
            if (!matchedMetaByType.containsKey(m.getMimeType())) {
                matchedMetaByType.put(m.getMimeType(), m);
            }
        } else {
            // check if this binary has the right title/file name
            if (fileName.equals(m.getFileName())) {
                matchedMetaByType.put(m.getMimeType(), m);
            }
        }
    }

    if (matchedMetaByType.isEmpty()) {
        return Response.status(Response.Status.NOT_FOUND).entity("Requested binary not found").build();
    }

    // find the best matching mime type
    String bestMediaTypeMatch = MIMEParse.bestMatch(matchedMetaByType.keySet(), acceptHeader);
    if (bestMediaTypeMatch.isEmpty()) {
        return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity("Client must accept one of the following media types: "
                        + StringUtils.join(matchedMetaByType.keySet(), ", "))
                .build();
    }
    MediaType mediaType = MediaType.valueOf(bestMediaTypeMatch);

    int offset = 0;
    int length = 0;

    if (rawLength == null || rawOffset == null) {
        // use matched binary meta data to get the complete file size
        AnnisBinaryMetaData matchedBinary = matchedMetaByType.get(mediaType.toString());
        if (matchedBinary != null) {
            length = matchedBinary.getLength();
        }
    } else {
        // use the provided information
        offset = Integer.parseInt(rawOffset);
        length = Integer.parseInt(rawLength);
    }

    log.debug("fetching  " + (length / 1024) + "kb (" + offset + "-" + (offset + length) + ") from binary "
            + toplevelCorpusName + "/" + corpusName + (fileName == null ? "" : fileName) + " "
            + mediaType.toString());

    final InputStream stream = queryDao.getBinary(toplevelCorpusName, corpusName, mediaType.toString(),
            fileName, offset, length);

    log.debug("fetch successfully");
    StreamingOutput result = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                ByteStreams.copy(stream, output);
                output.close();
            } finally {
                stream.close();
            }
        }
    };

    return Response.ok(result, mediaType).build();
}