Search in sources :

Example 1 with ActionNotAllowed

use of cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed in project kramerius by ceskaexpedice.

the class PDFResource method selection.

/**
 * Generate pdf from selection
 * @param pidsParam List of pids
 * @param pageType First page type. Possible values TEXT, IMAGE
 * @param format Page format. Possible values : A0,...A5, B0,...B5, LETTER, POSTCARD
 * @return
 * @throws OutOfRangeException
 */
@GET
@Path("selection")
@Produces({ "application/pdf", "application/json" })
public Response selection(@QueryParam("pids") String pidsParam, @QueryParam("firstPageType") @DefaultValue("TEXT") String pageType, @QueryParam("format") String format) throws OutOfRangeException {
    boolean acquired = false;
    try {
        acquired = PDFExlusiveGenerateSupport.PDF_SEMAPHORE.tryAcquire();
        if (acquired) {
            try {
                AbstractPDFResource.FirstPage fp = pageType != null ? AbstractPDFResource.FirstPage.valueOf(pageType) : AbstractPDFResource.FirstPage.TEXT;
                if (StringUtils.isAnyString(pidsParam)) {
                    String[] pids = pidsParam.split(",");
                    // max number test
                    ConfigurationUtils.checkNumber(pids);
                    Rectangle formatRect = formatRect(format);
                    final File generatedPDF = super.selection(pids, formatRect, fp);
                    final InputStream fis = new FileInputStream(generatedPDF);
                    StreamingOutput stream = new StreamingOutput() {

                        public void write(OutputStream output) throws IOException, WebApplicationException {
                            try {
                                IOUtils.copyStreams(fis, output);
                            } catch (Exception e) {
                                throw new WebApplicationException(e);
                            } finally {
                                if (generatedPDF != null)
                                    generatedPDF.delete();
                            }
                        }
                    };
                    SimpleDateFormat sdate = new SimpleDateFormat("yyyyMMdd_mmhhss");
                    return Response.ok().header("Content-disposition", "attachment; filename=" + sdate.format(new Date()) + ".pdf").entity(stream).type("application/pdf").build();
                } else {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }
            } catch (MalformedURLException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (ProcessSubtreeException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (DocumentException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (SecurityException e) {
                LOGGER.log(Level.INFO, e.getMessage());
                throw new ActionNotAllowed(e.getMessage());
            }
        } else {
            throw new PDFResourceNotReadyException("not ready");
        }
    } finally {
        if (acquired)
            PDFExlusiveGenerateSupport.PDF_SEMAPHORE.release();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) WebApplicationException(javax.ws.rs.WebApplicationException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Rectangle(com.lowagie.text.Rectangle) StreamingOutput(javax.ws.rs.core.StreamingOutput) SecurityException(cz.incad.kramerius.security.SecurityException) IOException(java.io.IOException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) FileInputStream(java.io.FileInputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) JSONException(org.json.JSONException) SecurityException(cz.incad.kramerius.security.SecurityException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) FileNotFoundException(java.io.FileNotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException) MalformedURLException(java.net.MalformedURLException) BadRequestException(cz.incad.kramerius.rest.api.exceptions.BadRequestException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) Date(java.util.Date) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) DocumentException(com.lowagie.text.DocumentException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with ActionNotAllowed

use of cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed in project kramerius by ceskaexpedice.

the class PDFResource method parent.

/**
 * Generate whole document
 * @param pid PID of generating document
 * @param number Number of pages (whole document or maximum number of pages)
 * @param pageType Type of firt page. Possible values: TEXT,IMAGE
 * @param format Page format. Possible values : A0,...A5, B0,...B5, LETTER, POSTCARD
 * @return
 */
@GET
@Path("parent")
@Produces({ "application/pdf", "application/json" })
public Response parent(@QueryParam("pid") String pid, @QueryParam("number") String number, @QueryParam("firstPageType") @DefaultValue("TEXT") String pageType, @QueryParam("format") String format) {
    boolean acquired = false;
    try {
        acquired = PDFExlusiveGenerateSupport.PDF_SEMAPHORE.tryAcquire();
        if (acquired) {
            try {
                AbstractPDFResource.FirstPage fp = pageType != null ? AbstractPDFResource.FirstPage.valueOf(pageType) : AbstractPDFResource.FirstPage.TEXT;
                // max number test
                int n = ConfigurationUtils.checkNumber(number);
                Rectangle formatRect = formatRect(format);
                final File generatedPdf = super.parent(pid, n, formatRect, fp);
                final InputStream fis = new FileInputStream(generatedPdf);
                StreamingOutput stream = new StreamingOutput() {

                    public void write(OutputStream output) throws IOException, WebApplicationException {
                        try {
                            IOUtils.copyStreams(fis, output);
                        } catch (Exception e) {
                            throw new WebApplicationException(e);
                        } finally {
                            if (generatedPdf != null)
                                generatedPdf.delete();
                        }
                    }
                };
                SimpleDateFormat sdate = new SimpleDateFormat("yyyyMMdd_mmhhss");
                return Response.ok().header("Content-disposition", "attachment; filename=" + sdate.format(new Date()) + ".pdf").entity(stream).type("application/pdf").build();
            } catch (NumberFormatException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (FileNotFoundException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (DocumentException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (ProcessSubtreeException e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                throw new GenericApplicationException(e.getMessage());
            } catch (OutOfRangeException e1) {
                LOGGER.log(Level.WARNING, "too much pages for pdf generating - consider changing config attribute (generatePdfMaxRange)");
                throw new PDFResourceBadRequestException(e1.getMessage());
            } catch (SecurityException e1) {
                LOGGER.log(Level.INFO, e1.getMessage());
                throw new ActionNotAllowed(e1.getMessage());
            }
        } else {
            throw new PDFResourceNotReadyException("not ready");
        }
    } finally {
        if (acquired)
            PDFExlusiveGenerateSupport.PDF_SEMAPHORE.release();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Rectangle(com.lowagie.text.Rectangle) FileNotFoundException(java.io.FileNotFoundException) StreamingOutput(javax.ws.rs.core.StreamingOutput) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) DocumentException(com.lowagie.text.DocumentException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SecurityException(cz.incad.kramerius.security.SecurityException) IOException(java.io.IOException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) FileInputStream(java.io.FileInputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) JSONException(org.json.JSONException) SecurityException(cz.incad.kramerius.security.SecurityException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) FileNotFoundException(java.io.FileNotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException) MalformedURLException(java.net.MalformedURLException) BadRequestException(cz.incad.kramerius.rest.api.exceptions.BadRequestException) IOException(java.io.IOException) DocumentException(com.lowagie.text.DocumentException) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) Date(java.util.Date) ProcessSubtreeException(cz.incad.kramerius.ProcessSubtreeException) OutOfRangeException(cz.incad.kramerius.pdf.OutOfRangeException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 3 with ActionNotAllowed

use of cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed in project kramerius by ceskaexpedice.

the class ItemResource method stream.

@GET
@Path("{pid}/streams/{dsid}")
public Response stream(@PathParam("pid") String pid, @PathParam("dsid") String dsid) {
    try {
        checkPid(pid);
        if (!FedoraUtils.FEDORA_INTERNAL_STREAMS.contains(dsid)) {
            if (!PIDSupport.isComposedPID(pid)) {
                // audio streams - bacause of support rage in headers
                if (FedoraUtils.AUDIO_STREAMS.contains(dsid)) {
                    String mimeTypeForStream = this.fedoraAccess.getMimeTypeForStream(pid, dsid);
                    ResponseBuilder responseBuilder = Response.ok();
                    responseBuilder = responseBuilder.type(mimeTypeForStream);
                    HttpServletRequest request = this.requestProvider.get();
                    User user = this.userProvider.get();
                    AudioStreamId audioStreamId = new AudioStreamId(pid, AudioFormat.valueOf(dsid));
                    ResponseBuilder builder = AudioStreamForwardUtils.GET(audioStreamId, request, responseBuilder, solrAccess, user, this.rightsResolver, urlManager);
                    return builder.build();
                } else {
                    final InputStream is = this.fedoraAccess.getDataStream(pid, dsid);
                    String mimeTypeForStream = this.fedoraAccess.getMimeTypeForStream(pid, dsid);
                    StreamingOutput stream = new StreamingOutput() {

                        public void write(OutputStream output) throws IOException, WebApplicationException {
                            try {
                                IOUtils.copyStreams(is, output);
                            } catch (Exception e) {
                                throw new WebApplicationException(e);
                            }
                        }
                    };
                    return Response.ok().entity(stream).type(mimeTypeForStream).build();
                }
            } else
                throw new PIDNotFound("cannot find stream " + dsid);
        } else {
            throw new PIDNotFound("cannot find stream " + dsid);
        }
    } catch (IOException e) {
        throw new PIDNotFound(e.getMessage());
    } catch (SecurityException e) {
        throw new ActionNotAllowed(e.getMessage());
    }
}
Also used : AudioStreamId(cz.incad.kramerius.audio.AudioStreamId) User(cz.incad.kramerius.security.User) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) SecurityException(cz.incad.kramerius.security.SecurityException) IOException(java.io.IOException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) URISyntaxException(java.net.URISyntaxException) LexerException(cz.incad.kramerius.utils.pid.LexerException) JSONException(org.json.JSONException) SecurityException(cz.incad.kramerius.security.SecurityException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) ResourceIndexException(cz.incad.kramerius.resourceindex.ResourceIndexException) ReplicateException(cz.incad.kramerius.service.ReplicateException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) PIDNotFound(cz.incad.kramerius.rest.api.k5.client.item.exceptions.PIDNotFound)

Example 4 with ActionNotAllowed

use of cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed in project kramerius by ceskaexpedice.

the class ItemResource method foxml.

@GET
@Path("{pid}/foxml")
@Produces({ MediaType.APPLICATION_XML + ";charset=utf-8" })
public Response foxml(@PathParam("pid") String pid) {
    boolean access = false;
    try {
        ObjectPidsPath[] paths = this.solrAccess.getPidPaths(pid);
        if (paths.length == 0) {
            paths = this.resourceIndex.getPaths(pid);
        }
        for (ObjectPidsPath path : paths) {
            if (this.rightsResolver.isActionAllowed(SecuredActions.READ.getFormalName(), pid, null, path).flag()) {
                access = true;
                break;
            }
        }
        if (access) {
            checkPid(pid);
            byte[] bytes = replicationService.getExportedFOXML(pid, FormatType.IDENTITY);
            final ByteArrayInputStream is = new ByteArrayInputStream(bytes);
            StreamingOutput stream = new StreamingOutput() {

                public void write(OutputStream output) throws IOException, WebApplicationException {
                    try {
                        IOUtils.copyStreams(is, output);
                    } catch (Exception e) {
                        throw new WebApplicationException(e);
                    }
                }
            };
            return Response.ok().entity(stream).build();
        } else
            throw new ActionNotAllowed("access denied");
    } catch (IOException e) {
        throw new PIDNotFound("cannot parse foxml for  " + pid);
    } catch (ReplicateException e) {
        throw new PIDNotFound("cannot parse foxml for  " + pid);
    } catch (ResourceIndexException e) {
        throw new PIDNotFound("cannot parse foxml for  " + pid);
    }
}
Also used : OutputStream(java.io.OutputStream) IOException(java.io.IOException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) ResourceIndexException(cz.incad.kramerius.resourceindex.ResourceIndexException) URISyntaxException(java.net.URISyntaxException) LexerException(cz.incad.kramerius.utils.pid.LexerException) JSONException(org.json.JSONException) SecurityException(cz.incad.kramerius.security.SecurityException) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) ResourceIndexException(cz.incad.kramerius.resourceindex.ResourceIndexException) ReplicateException(cz.incad.kramerius.service.ReplicateException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) ReplicateException(cz.incad.kramerius.service.ReplicateException) PIDNotFound(cz.incad.kramerius.rest.api.k5.client.item.exceptions.PIDNotFound)

Example 5 with ActionNotAllowed

use of cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed in project kramerius by ceskaexpedice.

the class LRResource method getProcessDescription.

/**
 * Returns process description
 * @param uuid Process identification
 * @return JSON process description
 */
@GET
@Path("{uuid}")
@Produces({ MediaType.APPLICATION_JSON + ";charset=utf-8" })
public Response getProcessDescription(@PathParam("uuid") String uuid) {
    LRProcess lrPRocess = lrProcessManager.getLongRunningProcess(uuid);
    String loggedUserKey = findLoggedUserKey();
    User user = this.loggedUsersSingleton.getUser(loggedUserKey);
    if (user == null) {
        // throw new SecurityException("access denided");
        throw new ActionNotAllowed("action is not allowed");
    }
    SecuredActions actionFromDef = securedAction(lrPRocess.getDefinitionId(), processDefinition(lrPRocess.getDefinitionId()));
    boolean permitted = permit(rightsResolver, actionFromDef, user);
    if (permitted) {
        LRProcess lrProc = this.lrProcessManager.getLongRunningProcess(uuid);
        if (lrProc != null) {
            try {
                JSONObject jsonObject = lrPRocessToJSONObject(lrProc);
                if (lrProc.isMasterProcess()) {
                    JSONArray array = new JSONArray();
                    List<LRProcess> childSubprecesses = this.lrProcessManager.getLongRunningProcessesByGroupToken(lrProc.getGroupToken());
                    for (LRProcess child : childSubprecesses) {
                        array.put(lrPRocessToJSONObject(child));
                    }
                    jsonObject.put("children", array);
                }
                return Response.ok().entity(jsonObject.toString()).build();
            } catch (JSONException e) {
                throw new GenericApplicationException(e.getMessage());
            }
        } else
            throw new NoProcessFound("cannot find process '" + uuid + "'");
    } else {
        throw new ActionNotAllowed("action is not allowed");
    }
}
Also used : User(cz.incad.kramerius.security.User) JSONObject(org.json.JSONObject) SecuredActions(cz.incad.kramerius.security.SecuredActions) JSONArray(org.json.JSONArray) NoProcessFound(cz.incad.kramerius.rest.api.processes.exceptions.NoProcessFound) JSONException(org.json.JSONException) ActionNotAllowed(cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) LRProcess(cz.incad.kramerius.processes.LRProcess) Path(javax.ws.rs.Path) ObjectPidsPath(cz.incad.kramerius.ObjectPidsPath) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

ActionNotAllowed (cz.incad.kramerius.rest.api.exceptions.ActionNotAllowed)47 JSONException (org.json.JSONException)42 GenericApplicationException (cz.incad.kramerius.rest.api.exceptions.GenericApplicationException)37 Produces (javax.ws.rs.Produces)30 ObjectPidsPath (cz.incad.kramerius.ObjectPidsPath)27 Path (javax.ws.rs.Path)21 JSONObject (org.json.JSONObject)21 ObjectNotFound (cz.incad.kramerius.rest.api.replication.exceptions.ObjectNotFound)16 GET (javax.ws.rs.GET)15 User (cz.incad.kramerius.security.User)14 IOException (java.io.IOException)14 JSONArray (org.json.JSONArray)13 SQLException (java.sql.SQLException)10 BadRequestException (cz.incad.kramerius.rest.api.exceptions.BadRequestException)9 ReplicateException (cz.incad.kramerius.service.ReplicateException)9 Consumes (javax.ws.rs.Consumes)9 LRProcess (cz.incad.kramerius.processes.LRProcess)8 SecurityException (cz.incad.kramerius.security.SecurityException)8 NoProcessFound (cz.incad.kramerius.rest.api.processes.exceptions.NoProcessFound)6 SecuredActions (cz.incad.kramerius.security.SecuredActions)6