Search in sources :

Example 11 with JsonGenerator

use of javax.json.stream.JsonGenerator in project sling by apache.

the class MDCStateServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter pw = resp.getWriter();
    if (req.getParameter("createTestConfig") != null) {
        createTestConfig();
        pw.print("created");
        return;
    }
    Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
    JsonGenerator json = Json.createGenerator(pw);
    json.writeStartObject();
    if (copyOfContextMap != null) {
        for (Entry<String, String> entry : copyOfContextMap.entrySet()) {
            json.write(entry.getKey(), entry.getValue());
        }
    }
    json.writeEnd();
    json.flush();
}
Also used : JsonGenerator(javax.json.stream.JsonGenerator) PrintWriter(java.io.PrintWriter)

Example 12 with JsonGenerator

use of javax.json.stream.JsonGenerator in project digilib by robcast.

the class ServletOps method sendIiifInfo.

/**
 * Returns IIIF compatible image information as application/json response.
 *
 * @param dlReq
 * @param response
 * @param logger
 * @throws FileOpException
 * @throws ServletException
 * @see <a href="http://www-sul.stanford.edu/iiif/image-api/1.1/#info">IIIF Image Information Request</a>
 */
public static void sendIiifInfo(DigilibServletRequest dlReq, HttpServletResponse response, Logger logger) throws ServletException {
    if (response == null) {
        logger.error("No response!");
        return;
    }
    /*
         * get image size
         */
    ImageSize size = null;
    ImageSet imageSet = null;
    try {
        // get original image size
        imageSet = dlReq.getJobDescription().getImageSet();
        ImageInput img = imageSet.getBiggest();
        size = img.getSize();
    } catch (FileOpException e) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (IOException e1) {
            throw new ServletException("Unable to write error response!", e);
        }
    }
    /*
         * get resource URL
         */
    String url = dlReq.getServletRequest().getRequestURL().toString();
    if (url.endsWith("/info.json")) {
        url = url.substring(0, url.lastIndexOf("/info.json"));
    } else if (url.endsWith("/")) {
        url = url.substring(0, url.lastIndexOf("/"));
    }
    /*
         * send response
         */
    response.setCharacterEncoding("UTF-8");
    logger.debug("sending info.json");
    try {
        /*
             * set CORS header ACAO "*" for info response as per IIIF spec
             */
        if (corsForInfoRequests) {
            String origin = dlReq.getServletRequest().getHeader("Origin");
            if (origin != null) {
                response.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
        if (dlConfig.getAsString("iiif-api-version").startsWith("2.")) {
            /*
                 * IIIF Image API version 2 image information
                 */
            // use JSON-LD content type only when asked
            String accept = dlReq.getServletRequest().getHeader("Accept");
            if (accept != null && accept.contains("application/ld+json")) {
                response.setContentType("application/ld+json");
            } else {
                response.setContentType("application/json");
            }
            // write info.json
            ServletOutputStream out = response.getOutputStream();
            JsonGenerator info = Json.createGenerator(out);
            // top level object
            info.writeStartObject().write("@context", "http://iiif.io/api/image/2/context.json").write("@id", url).write("protocol", "http://iiif.io/api/image").write("width", size.width).write("height", size.height);
            // profile[ array
            info.writeStartArray("profile").write("http://iiif.io/api/image/2/level2.json");
            // profile[{ object
            info.writeStartObject();
            // profile[{formats[
            info.writeStartArray("formats").write("jpg").write("png").writeEnd();
            // profile[{qualities[
            info.writeStartArray("qualities").write("color").write("gray").writeEnd();
            // profile[{maxArea
            if (dlConfig.getAsInt("max-image-size") > 0) {
                info.write("maxArea", dlConfig.getAsInt("max-image-size"));
            }
            // profile[{supports[
            info.writeStartArray("supports").write("mirroring").write("rotationArbitrary").write("sizeAboveFull").write("regionSquare").writeEnd();
            // profile[{}
            info.writeEnd();
            // profile[]
            info.writeEnd();
            // add size of original and prescaled images
            int numImgs = imageSet.size();
            if (numImgs > 0) {
                // sizes[
                info.writeStartArray("sizes");
                for (int i = numImgs - 1; i >= 0; --i) {
                    ImageInput ii = imageSet.get(i);
                    ImageSize is = ii.getSize();
                    // sizes[{
                    info.writeStartObject().write("width", is.getWidth()).write("height", is.getHeight()).writeEnd();
                }
                // sizes[]
                info.writeEnd();
            }
            // end info.json
            info.writeEnd();
            info.close();
        } else {
            /*
                 * IIIF Image API version 1 image information
                 */
            response.setContentType("application/json,application/ld+json");
            // write info.json
            ServletOutputStream out = response.getOutputStream();
            JsonGenerator info = Json.createGenerator(out);
            // top level object
            info.writeStartObject().write("@context", "http://library.stanford.edu/iiif/image-api/1.1/context.json").write("@id", url).write("width", size.width).write("height", size.height);
            // formats[
            info.writeStartArray("formats").write("jpg").write("png").writeEnd();
            // qualities[
            info.writeStartArray("qualities").write("native").write("color").write("gray").writeEnd();
            // profile
            info.write("profile", "http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2");
            // end info.json
            info.writeEnd();
            info.close();
        }
    } catch (IOException e) {
        throw new ServletException("Unable to write response!", e);
    }
}
Also used : ServletException(javax.servlet.ServletException) ImageSize(digilib.util.ImageSize) ImageInput(digilib.io.ImageInput) ServletOutputStream(javax.servlet.ServletOutputStream) FileOpException(digilib.io.FileOpException) JsonGenerator(javax.json.stream.JsonGenerator) ImageSet(digilib.io.ImageSet) IOException(java.io.IOException)

Example 13 with JsonGenerator

use of javax.json.stream.JsonGenerator in project digilib by robcast.

the class Manifester method processRequest.

protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
    try {
        // create DigilibRequest from ServletRequest, omit IIIF Image API parsing
        DigilibServletRequest dlRequest = new DigilibServletRequest(request, dlConfig, EnumSet.of(ParsingOption.omitIiifImageApi));
        // get list of IIIF parameters
        @SuppressWarnings("unchecked") List<String> iiifParams = (List<String>) dlRequest.getValue("request.iiif.elements");
        if (iiifParams == null) {
            logger.error("Invalid IIIF request.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid IIIF request.");
            return;
        }
        // get identifier (first parameter)
        // allow empty identifier for image root dir
        String identifier = "";
        if (iiifParams.size() > 0) {
            identifier = iiifParams.get(0);
        }
        // decode identifier to file path
        dlRequest.setValueFromString("fn", dlRequest.decodeIiifIdentifier(identifier));
        // get directory path
        String dlFn = dlRequest.getFilePath();
        // get information about the directory
        DocuDirectory dlDir = dirCache.getDirectory(dlFn);
        if (dlDir == null) {
            logger.error("Directory for manifest not found: " + dlFn);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // check for existing manifest file
        File mfFile = new File(dlDir.getDir(), "manifest.json");
        // check for image files
        if ((dlDir.size() == 0) && !mfFile.canRead()) {
            logger.debug("Directory has no files: " + dlFn);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ManifestParams params = new ManifestParams();
        /*
			 * set CORS header ACAO "*" for info response as per IIIF spec
			 */
        if (corsForInfoRequests) {
            String origin = request.getHeader("Origin");
            if (origin != null) {
                response.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
        /*
             * check permissions
             */
        if (useAuthorization) {
            // is the current request/user authorized?
            if (!authzOp.isAuthorized(dlRequest)) {
                // send deny answer and abort
                throw new AuthOpException("Access denied!");
            }
        }
        // use JSON-LD content type only when asked
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/ld+json")) {
            response.setContentType("application/ld+json");
        } else {
            response.setContentType("application/json");
        }
        if (mfFile.canRead()) {
            // send manifest file
            ServletOps.sendFile(mfFile, "", "", response);
            return;
        }
        // check for manifest-meta.json file with additional metadata
        File mfMetaFile = new File(dlDir.getDir(), "manifest-meta.json");
        if (mfMetaFile.canRead()) {
            params.mfMetaFile = mfMetaFile;
        }
        /*
			 * configure base URLs for manifest
			 */
        params.imgApiUrl = dlConfig.getAsString("iiif-image-base-url");
        String manifestBaseUrl = dlConfig.getAsString("iiif-manifest-base-url");
        if ("".equals(params.imgApiUrl) || "".equals(manifestBaseUrl)) {
            // try to figure out base URLs
            String servletBaseUrl = dlConfig.getAsString("webapp-base-url");
            if ("".equals(servletBaseUrl)) {
                String url = request.getRequestURL().toString();
                // get base URL for web application by last occurrence of Servlet path
                int srvPathLen = url.lastIndexOf(request.getServletPath());
                servletBaseUrl = url.substring(0, srvPathLen);
            }
            // manifest base URL
            manifestBaseUrl = servletBaseUrl + request.getServletPath() + "/" + dlConfig.getAsString("iiif-prefix");
            // Image API base URL
            params.imgApiUrl = servletBaseUrl + "/" + this.scalerServletPath + "/" + dlConfig.getAsString("iiif-prefix");
        }
        // full manifest URL with identifier
        params.manifestUrl = manifestBaseUrl + "/" + identifier;
        params.identifier = identifier;
        params.docuDir = dlDir;
        /*
			 * start json representation
			 */
        ServletOutputStream out = response.getOutputStream();
        JsonGenerator manifest = Json.createGenerator(out).writeStartObject();
        /*
			 * manifest metadata
			 */
        writeManifestMeta(manifest, dlFn, params);
        /*
			 * sequences
			 */
        writeSequences(manifest, params);
        // manifest
        manifest.writeEnd();
        manifest.close();
    } catch (IOException e) {
        logger.error("ERROR sending manifest: ", e);
    } catch (ImageOpException e) {
        logger.error("ERROR sending manifest: ", e);
    } catch (AuthOpException e) {
        logger.debug("Permission denied.");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            logger.error("Error sending error: ", e);
        }
    }
}
Also used : ImageOpException(digilib.image.ImageOpException) DigilibServletRequest(digilib.conf.DigilibServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) IOException(java.io.IOException) AuthOpException(digilib.auth.AuthOpException) DocuDirectory(digilib.io.DocuDirectory) JsonGenerator(javax.json.stream.JsonGenerator) List(java.util.List) File(java.io.File)

Example 14 with JsonGenerator

use of javax.json.stream.JsonGenerator in project javaee7-samples by javaee-samples.

the class MyWriter method writeTo.

@Override
public void writeTo(MyObject t, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    JsonGenerator gen = Json.createGenerator(out);
    gen.writeStartObject().write("name", t.getName()).write("age", t.getAge()).writeEnd();
    gen.flush();
}
Also used : JsonGenerator(javax.json.stream.JsonGenerator)

Example 15 with JsonGenerator

use of javax.json.stream.JsonGenerator in project javaee7-samples by javaee-samples.

the class StreamingGeneratorTest method testEmptyObject.

@Test
public void testEmptyObject() throws JSONException {
    JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
    StringWriter w = new StringWriter();
    JsonGenerator gen = factory.createGenerator(w);
    gen.writeStartObject().writeEnd();
    gen.flush();
    JSONAssert.assertEquals("{}", w.toString(), JSONCompareMode.STRICT);
}
Also used : StringWriter(java.io.StringWriter) JsonGenerator(javax.json.stream.JsonGenerator) JsonGeneratorFactory(javax.json.stream.JsonGeneratorFactory) Test(org.junit.Test)

Aggregations

JsonGenerator (javax.json.stream.JsonGenerator)18 StringWriter (java.io.StringWriter)9 HashMap (java.util.HashMap)4 JsonGeneratorFactory (javax.json.stream.JsonGeneratorFactory)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 File (java.io.File)2 PrintWriter (java.io.PrintWriter)2 Map (java.util.Map)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 AuthOpException (digilib.auth.AuthOpException)1 DigilibServletRequest (digilib.conf.DigilibServletRequest)1 ImageOpException (digilib.image.ImageOpException)1 DocuDirectory (digilib.io.DocuDirectory)1 FileOpException (digilib.io.FileOpException)1 ImageInput (digilib.io.ImageInput)1 ImageSet (digilib.io.ImageSet)1 ImageSize (digilib.util.ImageSize)1 FileOutputStream (java.io.FileOutputStream)1 Writer (java.io.Writer)1