List of usage examples for org.apache.commons.lang.text StrTokenizer getContent
public String getContent()
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetPdfAction.java
/************************************************************************************ * validate all parameters of request for pdf handling, throws IllegalArgumentException if one request parameter is not valid * /*from w ww. j a v a2s .co m*/ * @param request {@link HttpServletRequest} of ServletRequest * @throws IllegalArgumentException ************************************************************************************/ @Override public void validateParameters(HttpServletRequest request) throws IllegalArgumentException { /* call super.validation for main parameters of image and pdf actions */ super.validateParameters(request); /* * -------------------------------- validate images -------------------------------- */ /* validate if parameter images is used */ if (request.getParameter("images") == null) { throw new IllegalArgumentException("no images defined to use for pdf generation (images)"); } /* check if every file has a file extension */ String images = request.getParameter("images"); StrTokenizer imagetokenizer = new StrTokenizer(images, "$"); for (String image : imagetokenizer.getTokenArray()) { int dotPos = image.lastIndexOf("."); if (dotPos == -1) { throw new IllegalArgumentException("no file extension for image: " + image); } } /* validate if parameter imageNames is used and valid */ if (request.getParameter("imageNames") != null) { String imageNames = request.getParameter("imageNames"); StrTokenizer imageNametokenizer = new StrTokenizer(imageNames, "$"); if (imageNametokenizer.getTokenArray().length != imagetokenizer.getTokenArray().length) { throw new IllegalArgumentException( "list of image names (elements: " + imageNametokenizer.getTokenArray().length + ") must have same size as list of images (elements: " + imagetokenizer.getTokenArray().length + "): " + imageNametokenizer.getContent()); } } /* * -------------------------------- validate bookmarks -------------------------------- */ /* validate if parameter bookmarks is used and valid */ if (request.getParameter("bookmarks") != null) { String bookmarks = request.getParameter("bookmarks"); ArrayList<String> allIDs = new ArrayList<String>(); allIDs.add("0"); /* run through all bookmark defnitions */ StrTokenizer bookmarkDefTokenizer = new StrTokenizer(bookmarks, "$"); for (String bookmarkDef : bookmarkDefTokenizer.getTokenArray()) { /* * each BookmarkDefinition contains of 4 values: id, parentId, imagenumber, title */ StrTokenizer bookmarkDefValues = new StrTokenizer(bookmarkDef, ","); if (bookmarkDefValues.getTokenArray().length != 4) { throw new IllegalArgumentException( "bookmark definition does not contain the 4 values id, parentId, imageNumber and title: " + bookmarkDefValues.getContent()); } /* get all bookmark definition values as strings from tokenizer */ String defID = bookmarkDefValues.getTokenArray()[0].trim(); String defParentID = bookmarkDefValues.getTokenArray()[1].trim(); String defImageNumber = bookmarkDefValues.getTokenArray()[2].trim(); String defTitle = bookmarkDefValues.getTokenArray()[3].trim(); /* id, parentId and image number have to be numeric */ if (!StringUtils.isNumeric(defID) || !StringUtils.isNumeric(defParentID) || !StringUtils.isNumeric(defImageNumber)) { throw new IllegalArgumentException( "id, parentId and image number of bookmark definition have to be numeric: " + bookmarkDefValues.getContent()); } /* title must not be whitespace or empty */ if (StringUtils.isBlank(defTitle)) { throw new IllegalArgumentException( "title of bookmark definition must not be empty: " + bookmarkDefValues.getContent()); } /* image index number must exist */ int imageNumber = Integer.parseInt(defImageNumber); int allImagesSize = imagetokenizer.getTokenArray().length; if (imageNumber < 0 || imageNumber >= allImagesSize) { throw new IllegalArgumentException("image number is greater than defined list of images: " + bookmarkDefValues.getContent()); } /* id have to be unique */ if (allIDs.contains(defID)) { throw new IllegalArgumentException("id of bookmark have to be unique: " + defID); } else { allIDs.add(defID); } /* parentId must not be the same as id */ if (defID.equals(defParentID)) { throw new IllegalArgumentException( "parentId of bookmark can not be the same as id: " + bookmarkDefValues.getContent()); } /* parentIds have to exist */ if (!allIDs.contains(defParentID)) { throw new IllegalArgumentException("parentId of bookmark have to exist: " + defID); } else { allIDs.add(defID); } } } }
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java
/************************************************************************************ * validate all parameters of request for image handling, throws IllegalArgumentException if one request parameter is not valid * /*www .j a va2s.c o m*/ * @param request {@link HttpServletRequest} of ServletRequest * @throws IllegalArgumentException ************************************************************************************/ @Override public void validateParameters(HttpServletRequest request) throws IllegalArgumentException { /* call super.validation for main parameters of image and pdf actions */ super.validateParameters(request); /* validate path of source image */ if (request.getParameter("sourcepath") == null && request.getAttribute("sourcepath") == null) { throw new IllegalArgumentException("no source path defined (sourcepath)"); } /* validate rotation agle is a number */ if (request.getParameterMap().containsKey("rotate") && !StringUtils.isNumeric(request.getParameter("rotate"))) { throw new IllegalArgumentException("rotation angle is not numeric"); } /* validate percent scaling is a number */ if (request.getParameterMap().containsKey("scale") && !StringUtils.isNumeric(request.getParameter("scale"))) { throw new IllegalArgumentException("scale is not numeric"); } /* validate width scaling is a number */ if (request.getParameterMap().containsKey("width") && !StringUtils.isNumeric(request.getParameter("width"))) { throw new IllegalArgumentException("width is not numeric"); } /* validate height scaling is a number */ if (request.getParameterMap().containsKey("height") && !StringUtils.isNumeric(request.getParameter("height"))) { throw new IllegalArgumentException("height is not numeric"); } /* validate resolution */ if (request.getParameter("resolution") != null && !StringUtils.isNumeric(request.getParameter("resolution"))) { throw new IllegalArgumentException("resolution is not numeric"); } /* validate highlighting coordinates */ if (request.getParameter("highlight") != null) { String highlight = request.getParameter("highlight"); StrTokenizer areas = new StrTokenizer(highlight, "$"); for (String area : areas.getTokenArray()) { /* currently only 4 coordinates are supported per area */ StrTokenizer coordinates = new StrTokenizer(area, ","); if (coordinates.getTokenArray().length != 4) { throw new IllegalArgumentException( "highlight area does not have 4 coordinates: " + coordinates.getContent()); } /* only numbers are permitted */ for (String coordinate : coordinates.getTokenArray()) { if (!StringUtils.isNumeric(coordinate)) { throw new IllegalArgumentException( "highlight coordinate is not numeric: " + coordinates.getContent()); } } } // end for (String area ... } // end if (request.getParameter("highlight") ... }
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java
public ImageHolder getImageHolder(Map<String, String[]> params) throws URISyntaxException, IOException, ImageManagerException { /*// w ww . ja va2 s .c o m * -------------------------------- get central configuration -------------------------------- */ URI sourceImageUrl = null; ContentServerConfiguration config = ContentServerConfiguration.getInstance(); if (!params.get("sourcepath")[0].startsWith("file:") && !params.get("sourcepath")[0].startsWith("http:")) { String path = params.get("sourcepath")[0].replace(" ", "+"); sourceImageUrl = new URI(config.getRepositoryPathImages() + path); } else { String path = params.get("sourcepath")[0].replace(" ", "+"); sourceImageUrl = new URI(path); } try { Cache cc = null; // ServletOutputStream output = response.getOutputStream(); if (params.get("thumbnail") != null) { cc = ContentServer.getThumbnailCache(); } else { cc = ContentServer.getContentCache(); } String myUniqueID = getContentCacheIdForParamMap(params, config); LOGGER.trace("myUniqueId: " + myUniqueID); String targetExtension = params.get("format")[0]; boolean ignoreCache = false; /* check if cache should be ignored */ if (params.get("ignoreCache") != null) { String ignore = params.get("ignoreCache")[0].trim(); ignoreCache = Boolean.parseBoolean(ignore); } boolean useCache = false; if (params.get("thumbnail") != null) { useCache = config.getThumbnailCacheUse(); } else { useCache = config.getContentCacheUse(); } if (params.get("highlight") != null) { useCache = false; } if (cc == null || !useCache || params.get("highlight") != null) { ignoreCache = true; cc = null; LOGGER.debug("cache deactivated via configuration"); } // Image found in cache if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension); try { CacheObject co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getValue(); return new ImageHolder(co.getData()); } catch (NullPointerException e) { LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension); } // if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { // LOGGER.debug("get file from cache: " + myUniqueID); // // RenderedImage ri = (RenderedImage) cc.get(myUniqueID + "." + targetExtension).getObjectValue(); // JpegInterpreter ii = new JpegInterpreter(ri); // ii.writeToStream(null, baos); // return baos.toByteArray(); } else if (!ignoreCache) { LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension); } /* * -------------------------------- retrieve source image from url -------------------------------- */ ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL()); LOGGER.trace("imageManager initialized"); /* * -------------------------------- set the defaults -------------------------------- */ int angle = 0; int scaleX = 100; int scaleY = 100; int scaleType = ImageManager.SCALE_BY_PERCENT; LinkedList<String> highlightCoordinateList = null; Color highlightColor = null; Watermark myWatermark = null; LOGGER.trace("Variables set"); /* * -------------------------------- rotate -------------------------------- */ if (params.get("rotate") != null) { angle = Integer.parseInt(params.get("rotate")[0]); LOGGER.trace("rotate image:" + angle); } /* * -------------------------------- scale: scale the image to some percent value -------------------------------- */ if (params.get("scale") != null) { scaleX = Integer.parseInt(params.get("scale")[0]); scaleY = scaleX; scaleType = ImageManager.SCALE_BY_PERCENT; LOGGER.trace("scale image to percent:" + scaleX); } if (params.get("width") != null && params.get("height") != null) { scaleX = Integer.parseInt(params.get("width")[0]); scaleY = Integer.parseInt(params.get("height")[0]); scaleType = ImageManager.SCALE_TO_BOX; } /* * -------------------------------- width: scale image to fixed width -------------------------------- */ else if (params.get("width") != null) { scaleX = Integer.parseInt(params.get("width")[0]); scaleY = 0; scaleType = ImageManager.SCALE_BY_WIDTH; LOGGER.trace("scale image to width:" + scaleX); } /* * -------------------------------- height: scale image to fixed height -------------------------------- */ else if (params.get("height") != null) { scaleY = Integer.parseInt(params.get("height")[0]); scaleX = 0; scaleType = ImageManager.SCALE_BY_HEIGHT; LOGGER.trace("scale image to height:" + scaleY); } /* * -------------------------------- highlight -------------------------------- */ if (params.get("highlight") != null) { highlightCoordinateList = new LinkedList<String>(); String highlight = params.get("highlight")[0]; StrTokenizer areas = new StrTokenizer(highlight, "$"); for (String area : areas.getTokenArray()) { StrTokenizer coordinates = new StrTokenizer(area, ","); highlightCoordinateList.add(coordinates.getContent()); } highlightColor = config.getDefaultHighlightColor(); } /* * -------------------------------- insert watermark, if it should be used -------------------------------- */ if (params.get("ignoreWatermark") == null) { if (config.getWatermarkUse()) { File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath())); myWatermark = Watermark.generateWatermark(params, watermarkfile); } } /* * -------------------------------- prepare target -------------------------------- */ // change to true if watermark should scale boolean scaleWatermark = false; if (config.getScaleWatermark()) { scaleWatermark = true; } RenderedImage targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, scaleWatermark, ImageManager.BOTTOM); LOGGER.trace("Creating ImageInterpreter"); ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension); ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file LOGGER.trace("Image stored in " + wi.getClass().getCanonicalName()); /* * -------------------------------- set file name and attachment header from parameter or from configuration * -------------------------------- */ // StringBuilder targetFileName = new StringBuilder(); // if (config.getSendImageAsAttachment()) { // targetFileName.append("attachment; "); // } // targetFileName.append("filename="); // // if (params.get("targetFileName") != null) { // targetFileName.append(params.get("targetFileName")); // } else { // String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(), "." + // targetFormat.getFileExtension()); // targetFileName.append(filename); // } /* * -------------------------------- resolution -------------------------------- */ LOGGER.trace("Setting image resolution"); if (params.get("resolution") != null) { wi.setXResolution(Float.parseFloat(params.get("resolution")[0])); wi.setYResolution(Float.parseFloat(params.get("resolution")[0])); // TODO Is this correct? } else { wi.setXResolution(config.getDefaultResolution()); wi.setYResolution(config.getDefaultResolution()); } LOGGER.trace("Finished setting image resolution"); /* * -------------------------------- write target image to stream -------------------------------- */ byte[] data = wi.writeToStreamAndByteArray(new ByteArrayOutputStream()); ImageHolder returnImage = new ImageHolder(data, wi.getWidth(), wi.getHeight()); if (cc != null && highlightColor == null) { cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data))); } LOGGER.trace("Done writing image to stream"); return returnImage; } catch (CacheException e) { LOGGER.error("CacheException", e); } catch (MalformedURLException e) { LOGGER.error(e.getMessage(), e); } catch (ImageManipulatorException e) { LOGGER.error(e.getMessage(), e); } catch (WatermarkException e) { LOGGER.error(e.getMessage(), e); } return null; }
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java
/************************************************************************************ * exectute all image actions (rotation, scaling etc.) and send image back to output stream of the servlet, after setting correct mime type * //w w w . ja v a2s . c om * @param request {@link HttpServletRequest} of ServletRequest * @param response {@link HttpServletResponse} for writing to response output stream * @throws IOException * @throws ImageInterpreterException * @throws ServletException * @throws ContentLibException * @throws URISyntaxException * @throws ContentLibPdfException ************************************************************************************/ @Override public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException, ContentLibException { long startTime = System.currentTimeMillis(); super.run(servletContext, request, response); /* * -------------------------------- get central configuration -------------------------------- */ URI sourceImageUrl = null; ContentServerConfiguration config = ContentServerConfiguration.getInstance(); if (!request.getParameter("sourcepath").startsWith("file:") && !request.getParameter("sourcepath").startsWith("http:")) { sourceImageUrl = new URI(config.getRepositoryPathImages() + request.getParameter("sourcepath")); } else { sourceImageUrl = new URI(request.getParameter("sourcepath")); } try { Cache cc = null; ServletOutputStream output = response.getOutputStream(); if (request.getParameter("thumbnail") != null) { cc = ContentServer.getThumbnailCache(); } else { cc = ContentServer.getContentCache(); } // String myUniqueID = getContentCacheIdForRequest(request, config); String myUniqueID = getContentCacheIdForParamMap(request.getParameterMap(), config); String targetExtension = request.getParameter("format"); boolean ignoreCache = false; /* check if cache should be ignored */ if (request.getParameter("ignoreCache") != null) { String ignore = request.getParameter("ignoreCache").trim(); ignoreCache = Boolean.parseBoolean(ignore); } boolean useCache = false; if (request.getParameter("thumbnail") != null) { useCache = config.getThumbnailCacheUse(); } else { useCache = config.getContentCacheUse(); } if (request.getParameterMap().containsKey("highlight")) { useCache = false; } if (cc == null || !useCache) { ignoreCache = true; cc = null; LOGGER.debug("cache deactivated via configuration"); } if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension); CacheObject co; try { co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getObjectValue(); ByteArrayInputStream in = new ByteArrayInputStream(co.getData()); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { output.write(buf, 0, len); } in.close(); output.flush(); output.close(); return; } catch (NullPointerException e) { LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension); } } else if (!ignoreCache) { LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension); } // if (!ignoreCache && cc.cacheContains(myUniqueID, targetExtension)) { // LOGGER.debug("get file from cache: " + myUniqueID); // cc.writeToStream(output, myUniqueID, targetExtension); // output.flush(); // output.close(); // return; // } else if (ignoreCache == false) { // LOGGER.debug("file not found in cache: " + myUniqueID); // } // /* // * -------------------------------- if there is an internal request from goobiContentServer, you have to overwrite the // sourcepath with // * given attribute for image url -------------------------------- // */ // if (request.getAttribute("sourcepath") != null) { // sourceImageUrl = new URI((String) request.getAttribute("sourcepath")); // } LOGGER.debug("source image:" + sourceImageUrl); /* * -------------------------------- retrieve source image from url -------------------------------- */ ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL()); LOGGER.trace("imageManager initialized"); /* * -------------------------------- set the defaults -------------------------------- */ int angle = 0; int scaleX = 100; int scaleY = 100; int scaleType = ImageManager.SCALE_BY_PERCENT; LinkedList<String> highlightCoordinateList = null; Color highlightColor = null; Watermark myWatermark = null; LOGGER.trace("Variables set"); /* * -------------------------------- rotate -------------------------------- */ if (request.getParameterMap().containsKey("rotate")) { angle = Integer.parseInt(request.getParameter("rotate")); LOGGER.trace("rotate image:" + angle); } /* * -------------------------------- scale: scale the image to some percent value -------------------------------- */ if (request.getParameterMap().containsKey("scale")) { scaleX = Integer.parseInt(request.getParameter("scale")); scaleY = scaleX; scaleType = ImageManager.SCALE_BY_PERCENT; LOGGER.trace("scale image to percent:" + scaleX); } if (request.getParameterMap().containsKey("width") && request.getParameterMap().containsKey("height")) { scaleX = Integer.parseInt(request.getParameter("width")); scaleY = Integer.parseInt(request.getParameter("height")); scaleType = ImageManager.SCALE_TO_BOX; } /* * -------------------------------- width: scale image to fixed width -------------------------------- */ else if (request.getParameterMap().containsKey("width")) { scaleX = Integer.parseInt(request.getParameter("width")); scaleY = 0; scaleType = ImageManager.SCALE_BY_WIDTH; LOGGER.trace("scale image to width:" + scaleX); } /* * -------------------------------- height: scale image to fixed height -------------------------------- */ else if (request.getParameterMap().containsKey("height")) { scaleY = Integer.parseInt(request.getParameter("height")); scaleX = 0; scaleType = ImageManager.SCALE_BY_HEIGHT; LOGGER.trace("scale image to height:" + scaleY); } /* * -------------------------------- highlight -------------------------------- */ if (request.getParameterMap().containsKey("highlight")) { highlightCoordinateList = new LinkedList<String>(); String highlight = request.getParameter("highlight"); StrTokenizer areas = new StrTokenizer(highlight, "$"); for (String area : areas.getTokenArray()) { StrTokenizer coordinates = new StrTokenizer(area, ","); highlightCoordinateList.add(coordinates.getContent()); } highlightColor = config.getDefaultHighlightColor(); } /* * -------------------------------- insert watermark, if it should be used -------------------------------- */ if (!request.getParameterMap().containsKey("ignoreWatermark") && config.getWatermarkUse()) { File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath())); myWatermark = Watermark.generateWatermark(request, watermarkfile); } /* * -------------------------------- prepare target -------------------------------- */ // change to true if watermark should scale RenderedImage targetImage = null; if (config.getScaleWatermark()) { targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, true, ImageManager.BOTTOM); } else { targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, false, ImageManager.BOTTOM); } LOGGER.trace("Creating ImageInterpreter"); ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension); ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file LOGGER.trace("Image stored in " + wi.getClass().toString()); /* * -------------------------------- set file name and attachment header from parameter or from configuration * -------------------------------- */ LOGGER.trace("Creating target file"); StringBuilder targetFileName = new StringBuilder(); if (config.getSendImageAsAttachment()) { targetFileName.append("attachment; "); } targetFileName.append("filename="); if (request.getParameter("targetFileName") != null) { targetFileName.append(request.getParameter("targetFileName")); } else { String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(), "." + targetFormat.getFileExtension()); targetFileName.append(filename); } LOGGER.trace("Adding targetFile " + targetFileName.toString() + " to response"); response.setHeader("Content-Disposition", targetFileName.toString()); response.setContentType(targetFormat.getMimeType()); /* * -------------------------------- resolution -------------------------------- */ LOGGER.trace("Setting image resolution values"); if (request.getParameter("resolution") != null) { wi.setXResolution(Float.parseFloat(request.getParameter("resolution"))); wi.setYResolution(Float.parseFloat(request.getParameter("resolution"))); } else { wi.setXResolution(config.getDefaultResolution()); wi.setYResolution(config.getDefaultResolution()); } LOGGER.trace("Setting image compression"); if (request.getParameter("compression") != null) { String value = request.getParameter("compression"); try { int intvalue = Integer.parseInt(value); wi.setWriterCompressionValue(intvalue); } catch (Exception e) { LOGGER.trace("value is not a number, use default value"); } } /* * -------------------------------- write target image to stream -------------------------------- */ // cc.put(new Element(myUniqueID + "." + targetExtension, wi.getRenderedImage())); if (cc != null) { byte[] data = wi.writeToStreamAndByteArray(output); cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data))); } else { LOGGER.trace("writing file to servlet response"); wi.writeToStream(null, output); } LOGGER.trace("Done writing ImageInterpreter to stream"); wi.clear(); LOGGER.trace("Done clearing ImageInterpreter"); } catch (Exception e) { LOGGER.error("CacheException", e); } long endTime = System.currentTimeMillis(); LOGGER.trace("Content server time to process request: " + (endTime - startTime) + " ms"); // try { // CommonUtils.appendTextFile("Image request for file " + new File(sourceImageUrl).getAbsolutePath() + "; Time to process: " + (endTime - // startTime) // + " ms\n", new File(de.unigoettingen.sub.commons.contentlib.servlet.Util.getBaseFolderAsFile(), "timeConsumptionLog.txt")); // // } catch (IOException e) { // LOGGER.info("Unable to write time log file due to IOException " + e.toString()); // } }