List of usage examples for java.io ByteArrayInputStream read
public int read(byte b[]) throws IOException
b
. From source file:org.dspace.app.xmlui.aspect.discovery.json.JSONSolrSearcher.java
public void generate() throws IOException, SAXException, ProcessingException { if (solrServerUrl == null) { return;//w ww .jav a2 s .c o m } Map<String, String> params = new HashMap<String, String>(); String solrRequestUrl = solrServerUrl + "/select"; //Add our default parameters params.put(CommonParams.ROWS, "0"); params.put(CommonParams.WT, "json"); //We uwe json as out output type params.put("json.nl", "map"); params.put("json.wrf", jsonWrf); params.put(FacetParams.FACET, Boolean.TRUE.toString()); //Generate our json out of the given params try { params.put(CommonParams.Q, URLEncoder.encode(query, Constants.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException uee) { //Should never occur return; } params.put(FacetParams.FACET_LIMIT, String.valueOf(facetLimit)); if (facetSort != null) { params.put(FacetParams.FACET_SORT, facetSort); } params.put(FacetParams.FACET_MINCOUNT, String.valueOf(facetMinCount)); solrRequestUrl = AbstractDSpaceTransformer.generateURL(solrRequestUrl, params); if (facetFields != null || filterQueries != null) { StringBuilder urlBuilder = new StringBuilder(solrRequestUrl); if (facetFields != null) { //Add our facet fields for (String facetField : facetFields) { urlBuilder.append("&").append(FacetParams.FACET_FIELD).append("="); //This class can only be used for autocomplete facet fields if (!facetField.endsWith(".year") && !facetField.endsWith("_ac")) { urlBuilder.append(URLEncoder.encode(facetField + "_ac", Constants.DEFAULT_ENCODING)); } else { urlBuilder.append(URLEncoder.encode(facetField, Constants.DEFAULT_ENCODING)); } } } if (filterQueries != null) { for (String filterQuery : filterQueries) { urlBuilder.append("&").append(CommonParams.FQ).append("=") .append(URLEncoder.encode(filterQuery, Constants.DEFAULT_ENCODING)); } } solrRequestUrl = urlBuilder.toString(); } try { GetMethod get = new GetMethod(solrRequestUrl); new HttpClient().executeMethod(get); String result = get.getResponseBodyAsString(); if (result != null) { ByteArrayInputStream inputStream = new ByteArrayInputStream(result.getBytes("UTF-8")); byte[] buffer = new byte[8192]; response.setHeader("Content-Length", String.valueOf(result.length())); int length; while ((length = inputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } } catch (Exception e) { log.error("Error while getting json solr result for discovery search recommendation", e); e.printStackTrace(); } }
From source file:com.jing.common.controller.CommonController.java
/** * ??//from ww w. ja v a2 s . com * @param session * @param response */ @RequestMapping("/common/securityCodeImageAction") public void securityCodeImageAction(HttpSession session, HttpServletResponse response) { String securityCode = SecurityCode.getSecurityCode(); ByteArrayInputStream imageStream = SecurityImage.getImageAsInputStream(securityCode); //session session.setAttribute("SESSION_SECURITY_CODE", securityCode); response.setContentType("image/jpeg"); OutputStream stream; try { stream = response.getOutputStream(); byte[] tmp = new byte[1]; while (imageStream.read(tmp) != -1) { stream.write(tmp); } stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.reydentx.core.common.PhotoUtils.java
public static byte[] resizeImage(ByteArrayInputStream data, int img_width, int img_height, boolean isPNG) { BufferedImage originalImage;/*from w ww . ja va 2 s. c o m*/ try { originalImage = ImageIO.read(data); Dimension origDimentsion = new Dimension(originalImage.getWidth(), originalImage.getHeight()); Dimension fitDimentsion = new Dimension(img_width, img_height); // Dimension dimentsion = getScaledDimension(origDimentsion, fitDimentsion); Dimension dimentsion = fitDimentsion; if (origDimentsion.width != dimentsion.width || origDimentsion.height != dimentsion.height) { ByteArrayOutputStream outstream = new ByteArrayOutputStream(); BufferedImage resizedImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, dimentsion.width, dimentsion.height, Scalr.OP_ANTIALIAS); if (isPNG) { ImageIO.write(resizedImage, "png", outstream); } else { ImageIO.write(resizedImage, "jpg", outstream); } return outstream.toByteArray(); } else { data.reset(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] read = new byte[2048]; int i = 0; while ((i = data.read(read)) > 0) { byteArray.write(read, 0, i); } data.close(); return byteArray.toByteArray(); } } catch (Exception ex) { } return null; }
From source file:org.ngrinder.script.controller.FileEntryController.java
/** * Download file entry of given path./*from w ww . j av a 2 s. com*/ * * @param user current user * @param path user * @param response response */ @RequestMapping("/download/**") public void download(User user, @RemainedPath String path, HttpServletResponse response) { FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); return; } response.reset(); try { response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8")); } catch (UnsupportedEncodingException e1) { LOG.error(e1.getMessage(), e1); } response.setContentType("application/octet-stream; charset=UTF-8"); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); byte[] buffer = new byte[4096]; ByteArrayInputStream fis = null; OutputStream toClient = null; try { fis = new ByteArrayInputStream(fileEntry.getContentBytes()); toClient = new BufferedOutputStream(response.getOutputStream()); int readLength; while (((readLength = fis.read(buffer)) != -1)) { toClient.write(buffer, 0, readLength); } } catch (IOException e) { throw processException("error while download file", e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(toClient); } }
From source file:org.jboss.dashboard.ui.resources.GraphicElement.java
/** * Zipped file content//ww w.j a v a 2 s . c o m * * @param zipFile Zipped file content * @throws Exception */ public void setZipFile(byte[] zipFile) throws Exception { //Else don't touch, as it is being set by hibernate... if (tmpZipFile != null) tmpZipFile.delete(); tmpZipFile = File.createTempFile("graphicElement", ".tmp"); tmpZipFile.deleteOnExit(); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(tmpZipFile)); ByteArrayInputStream is = new ByteArrayInputStream(zipFile); int bytesIn; byte[] readBuffer = new byte[2048]; while ((bytesIn = is.read(readBuffer)) != -1) { os.write(readBuffer, 0, bytesIn); } } finally { if (os != null) os.close(); } deploy(); }
From source file:com.iyonger.apm.web.controller.FileEntryController.java
/** * Download file entry of given path./*from w w w .j a va 2s. c o m*/ * * @param user current user * @param path user * @param response response */ @RequestMapping("/download/**") public void download(User user, String path, HttpServletResponse response) { FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); return; } response.reset(); try { response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8")); } catch (UnsupportedEncodingException e1) { LOG.error(e1.getMessage(), e1); } response.setContentType("application/octet-stream; charset=UTF-8"); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); byte[] buffer = new byte[4096]; ByteArrayInputStream fis = null; OutputStream toClient = null; try { fis = new ByteArrayInputStream(fileEntry.getContentBytes()); toClient = new BufferedOutputStream(response.getOutputStream()); int readLength; while (((readLength = fis.read(buffer)) != -1)) { toClient.write(buffer, 0, readLength); } } catch (IOException e) { throw processException("error while download file", e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(toClient); } }
From source file:com.photon.phresco.framework.impl.CIManagerImpl.java
private void validate() throws IOException, InterruptedException { S_LOGGER.debug("Entering Method CIManagerImpl.validate()"); CLI validateCLI = new CLI(new URL("http://localhost:3579/ci/")); List<String> argList = new ArrayList<String>(); argList.add("build"); argList.add("NewJob"); Gson gson = new Gson(); JsonParser parser = new JsonParser(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] data = new byte[4]; ByteArrayInputStream inputStream = new ByteArrayInputStream(data); BufferedInputStream stream = new BufferedInputStream(System.in); int execute = validateCLI.execute(argList, inputStream, baos, baos); validateCLI.close();/* www.ja v a2 s . co m*/ byte[] outData = new byte[2]; int read; while ((read = inputStream.read(outData)) != -1) { System.out.print(new String(outData)); } inputStream.close(); // byte[] byteArray = baos.toByteArray(); // baos.flush(); // baos.close(); }
From source file:com.ezdi.rtf.testRTFParser.RTFObjDataParser.java
/** * can return null if there is a linked object instead of an embedded file *//*from w ww. ja v a2 s . co m*/ private byte[] handlePackage(byte[] pkgBytes, Metadata metadata) throws IOException { // now parse the package header ByteArrayInputStream is = new ByteArrayInputStream(pkgBytes); readUShort(is); String displayName = readAnsiString(is); // should we add this to the metadata? readAnsiString(is); // iconFilePath readUShort(is); // iconIndex int type = readUShort(is); // type // 1 is link, 3 is embedded object // this only handles embedded objects if (type != 3) { return null; } // should we really be ignoring this filePathLen? readUInt(is); // filePathLen String ansiFilePath = readAnsiString(is); // filePath long bytesLen = readUInt(is); byte[] objBytes = initByteArray(bytesLen); is.read(objBytes); StringBuilder unicodeFilePath = new StringBuilder(); try { long unicodeLen = readUInt(is); for (int i = 0; i < unicodeLen; i++) { int lo = is.read(); int hi = is.read(); int sum = lo + 256 * hi; if (hi == -1 || lo == -1) { // stream ran out; empty SB and stop unicodeFilePath.setLength(0); break; } unicodeFilePath.append((char) sum); } } catch (IOException e) { // swallow; the unicode file path is optional and might not happen unicodeFilePath.setLength(0); } String fileNameToUse = ""; String pathToUse = ""; if (unicodeFilePath.length() > 0) { String p = unicodeFilePath.toString(); fileNameToUse = p; pathToUse = p; } else { fileNameToUse = displayName == null ? "" : displayName; pathToUse = ansiFilePath == null ? "" : ansiFilePath; } metadata.set(Metadata.RESOURCE_NAME_KEY, FilenameUtils.getName(fileNameToUse)); metadata.set(Metadata.EMBEDDED_RELATIONSHIP_ID, pathToUse); return objBytes; }
From source file:org.bibalex.gallery.model.BAGImage.java
public BAGImage(BAGGalleryAbstract gallery, BAGAlbum album, String name, long viewPaneWidth, long viewPaneHeight) throws BAGException { super();/*from w w w .j a v a2 s . co m*/ this.gallery = gallery; this.album = album; this.name = name; HttpGet djatokaReq = null; try { this.highResUrlStr = this.gallery.getImageDirectAccUrlStr(album.getName(), name, EnumResolutions.high); // this.highResUrlEncoded = this.highResUrlStr.replaceAll(" ", "%20"); // new URLCodec("US-ASCII").encode(this.highResUrlStr); this.thumbLocalUrl = this.gallery.getThumbLocalUrl(this.album.getName(), this.name); Integer tempFullWidth = null; Integer tempFullHeight = null; Integer tempZoomLevels = null; // Execute HTTP request this.httpclient = new DefaultHttpClient(); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("url_ver", "Z39.88-2004")); qparams.add(new BasicNameValuePair("rft_id", this.highResUrlStr)); // "http://memory.loc.gov/gmd/gmd433/g4330/g4330/np000066.jp2")); qparams.add(new BasicNameValuePair("svc_id", "info:lanl-repo/svc/getMetadata")); URI serverUri = new URI(gallery.getDjatokaServerUrlStr()); URI reqUri = URIUtils.createURI(serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(), serverUri.getPath(), URLEncodedUtils.format(qparams, "US-ASCII"), null); djatokaReq = new HttpGet(reqUri); if (LOG.isDebugEnabled()) { LOG.debug("Getting metadata of image via URL: " + djatokaReq.getURI()); } HttpResponse response = this.httpclient.execute(djatokaReq); if (response.getStatusLine().getStatusCode() / 100 != 2) { throw new BAGException("Connection error: " + response.getStatusLine().toString()); } if (LOG.isDebugEnabled()) { LOG.debug("Response from URL: " + djatokaReq.getURI() + " => " + response.getStatusLine()); } // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if ((entity != null)) { entity = new BufferedHttpEntity(entity); if ("application/json".equalsIgnoreCase(entity.getContentType().getValue())) { // Since the djatoka returned JSON is not properly escaped and I cannot find // any library that escapes JSON while parsing it I had to do this: String jsonString = EntityUtils.toString(entity); // remove the braces: jsonString = jsonString.substring(1); jsonString = jsonString.substring(0, jsonString.length() - 1); StringTokenizer pairTokens = new StringTokenizer(jsonString, ",", false); while (pairTokens.hasMoreElements()) { String pair = pairTokens.nextToken().trim(); int colonIx = pair.indexOf(':'); String memberName = pair.substring(0, colonIx); memberName = memberName.substring(1); memberName = memberName.substring(0, memberName.length() - 1); String memberValue = pair.substring(colonIx + 1).trim(); memberValue = memberValue.substring(memberValue.indexOf('"') + 1); memberValue = memberValue.substring(0, memberValue.lastIndexOf('"')); if ("width".equals(memberName)) { tempFullWidth = Integer.valueOf(memberValue); } else if ("height".equals(memberName)) { tempFullHeight = Integer.valueOf(memberValue); } else if ("levels".equals(memberName)) { // FIXME replace "dwtLevels" by "levels" according to // http://sourceforge.net/apps/mediawiki/djatoka/index.php?title=Djatoka_Level_Logic // "dwtLevels" are the native JP2 DWT levels tempZoomLevels = Integer.valueOf(memberValue); } } } } if ((tempFullWidth == null) || (tempFullHeight == null) || (tempZoomLevels == null)) { throw new BAGException("Cannot retrieve metadata!"); } else { this.fullWidth = tempFullWidth; this.fullHeight = tempFullHeight; this.zoomLevels = tempZoomLevels; } } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw new BAGException(ex); } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. djatokaReq.abort(); throw ex; } catch (URISyntaxException e) { throw new BAGException(e); // } catch (EncoderException e) { // throw new BAGException(e); } finally { // connection kept alive and closed in finalize } this.djatokaParams = new ArrayList<NameValuePair>(); this.djatokaParams.add(new BasicNameValuePair("url_ver", "Z39.88-2004")); this.djatokaParams.add(new BasicNameValuePair("rft_id", this.highResUrlStr)); // "http://memory.loc.gov/gmd/gmd433/g4330/g4330/np000066.jp2")); this.djatokaParams.add(new BasicNameValuePair("svc_id", "info:lanl-repo/svc/getRegion")); this.djatokaParams.add(new BasicNameValuePair("svc_val_fmt", "info:ofi/fmt:kev:mtx:jpeg2000")); this.djatokaParams.add(new BasicNameValuePair("svc.format", "image/jpeg")); this.zoomedX = 0; this.zoomedY = 0; this.zoomedWidth = this.fullWidth; this.zoomedHeight = this.fullHeight; this.zoomedRotate = 0; this.viewPaneHeight = viewPaneHeight; this.viewPaneWidth = viewPaneWidth; this.calculateDjatokaLevel(); this.updateZoomedBytes(); String lowResCache = URLPathStrUtils.appendParts(this.gallery.cacheLocalPath, "low"); File tempJpg = new File(URLPathStrUtils.appendParts(lowResCache, name + ".jpg")); try { if (!tempJpg.exists()) { synchronized (BAGImage.class) { new File(lowResCache).mkdirs(); tempJpg.createNewFile(); FileOutputStream tempJpgOs = new FileOutputStream(tempJpg); ByteArrayInputStream temlJpgIS = new ByteArrayInputStream(this.zoomedBytes); try { byte buffer[] = new byte[10240]; int bytesRead = 0; do { bytesRead = temlJpgIS.read(buffer); if (bytesRead > 0) { tempJpgOs.write(buffer, 0, bytesRead); } else { break; } } while (true); } finally { tempJpgOs.flush(); tempJpgOs.close(); } } } } catch (IOException e) { LOG.error("Couldn't create local cached version of low resolution version of: " + name); tempJpg = null; } if (tempJpg != null) { String ctxRootURL = new File(this.gallery.contextRootPath).toURI().toString(); this.lowResLocalUrl = tempJpg.toURI().toString().substring(ctxRootURL.length()); } else { this.lowResLocalUrl = this.thumbLocalUrl; } }
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 * //from w w w . ja v a2s . c o m * @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()); // } }