String djatokaCacheFile = null;
String responseFormat = null;
String format = "image/jpeg";
int status = HttpServletResponse.SC_OK;
final HashMap<String, String> kev = setServiceValues(contextObject);
final DjatokaDecodeParam params = new DjatokaDecodeParam();
String id = null;
if (kev.containsKey("region")) {
params.setRegion(kev.get("region"));
}
if (kev.containsKey("format")) {
format = kev.get("format");
if (!format.startsWith("image")) {
// ignoring invalid format identifier
format = "image/jpeg";
}
}
if (kev.containsKey("level")) {
params.setLevel(Integer.parseInt(kev.get("level")));
}
if (kev.containsKey("rotate")) {
params.setRotationDegree(Integer.parseInt(kev.get("rotate")));
}
if (kev.containsKey("scale")) {
final String[] v = kev.get("scale").split(",");
if (v.length == 1) {
if (v[0].contains(".")) {
params.setScalingFactor(Double.parseDouble(v[0]));
} else {
final int[] dims = new int[] { -1, Integer.parseInt(v[0]) };
params.setScalingDimensions(dims);
}
} else if (v.length == 2) {
final int[] dims = new int[] { Integer.parseInt(v[0]), Integer.parseInt(v[1]) };
params.setScalingDimensions(dims);
}
}
if (kev.containsKey("clayer") && kev.get("clayer") != null) {
final int clayer = Integer.parseInt(kev.get("clayer"));
if (clayer > 0) {
params.setCompositingLayer(clayer);
}
}
responseFormat = format;
byte[] bytes = null;
if (params.getRegion() != null && params.getRegion().contains("-")) {
try {
bytes = ("Negative Region Arguments are not supported.").getBytes("UTF-8");
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
} else {
final String region = params.getRegion();
if (LOGGER.isDebugEnabled() && region != null) {
LOGGER.debug("Service has a valid region request: {}", region);
}
try {
final Referent referent = contextObject.getReferent();
final ImageRecord r = ReferentManager.getImageRecord(referent);
if (r != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Retrieving ImageRecord for: {}", r.getIdentifier());
}
if (transformCheck && transform != null) {
final HashMap<String, String> instProps = new HashMap<String, String>();
if (r.getInstProps() != null) {
instProps.putAll(r.getInstProps());
}
int l = contextObject.getRequesters().length;
final Requester[] req = contextObject.getRequesters();
if (l > 0 && req[0].getDescriptors().length > 0) {
final String rs = req[0].getDescriptors()[0].toString();
instProps.put(PROPS_REQUESTER, rs);
}
l = contextObject.getReferringEntities().length;
ReferringEntity[] rea;
rea = contextObject.getReferringEntities();
if (l > 0 && rea[0].getDescriptors().length > 0) {
instProps.put(PROPS_REFERRING_ENTITY, contextObject.getReferringEntities()[0]
.getDescriptors()[0].toString());
}
if (instProps.size() > 0) {
transform.setInstanceProps(instProps);
}
params.setTransform(transform);
}
if (!cacheTiles || !isCacheable(params)) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Not using the OpenURL layer cache");
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
extractor.extractImage(r.getImageFile(), baos, params, format);
bytes = baos.toByteArray();
baos.close();
} else {
final String ext = getExtension(format);
final String hash = getTileHash(r, params);
String file = tileCache.get(hash + ext);
File f;
id = r.getIdentifier();
if (file == null || !(f = new File(file)).exists() && f.length() > 0) {
if (cacheDir != null) {
final File cacheDirFile = new File(cacheDir);
// If our cache dir doesn't exist, create it
if (!cacheDirFile.exists()) {
if (!cacheDirFile.mkdirs() && LOGGER.isWarnEnabled()) {
LOGGER.warn("Dirs not created: {}", cacheDirFile);
}
}
f = File.createTempFile("cache" + hash.hashCode() + "-", "." + ext, cacheDirFile);
} else {
f = File.createTempFile("cache" + hash.hashCode() + "-", "." + ext);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Temp file created: {}", f);
}
f.deleteOnExit();
file = f.getAbsolutePath();
djatokaCacheFile = file;
extractor.extractImage(r.getImageFile(), file, params, format);
if (tileCache.get(hash + ext) == null) {
tileCache.put(hash + ext, file);
bytes = IOUtils.getBytesFromFile(f);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("makingTile: " + file + " " + bytes.length + " params: " + params);
}
} else {
// Handles simultaneous request on separate
// thread, ignores cache.
bytes = IOUtils.getBytesFromFile(f);
if (!f.delete() && LOGGER.isWarnEnabled()) {
LOGGER.warn("File not deleted: {}", f);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("tempTile: " + file + " " + bytes.length + " params: " + params);
}
}
} else {
bytes = IOUtils.getBytesFromFile(new File(file));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("tileCache: {} {}", file, bytes.length);
}
djatokaCacheFile = file;
}
}
} else if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Unable to retrieve ImageRecord");
}
} catch (final ResolverException e) {
LOGGER.error(e.getMessage(), e);
bytes = e.getMessage().getBytes();
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
} catch (final DjatokaException e) {
LOGGER.error(e.getMessage(), e);
bytes = e.getMessage().getBytes();
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
bytes = e.getMessage().getBytes();
responseFormat = "text/plain";
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
}
if (bytes == null || bytes.length == 0) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No bytes found!");
}
bytes = "".getBytes();
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
}
final HashMap<String, String> header_map = new HashMap<String, String>();
header_map.put("Content-Length", bytes.length + "");
header_map.put("Date", HttpDate.getHttpDate());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Getting OpenURLResponse...");
}
final OpenURLResponse response = new OpenURLResponse(status, responseFormat, bytes, header_map);
// Record where our cache file was (if we had/created one)
if (djatokaCacheFile != null) {
final StringBuilder dimBuilder = new StringBuilder();
final int[] dims = params.getScalingDimensions();
final String level = Integer.toString(params.getLevel());
final String region = params.getRegion();
final int rotation = params.getRotationDegree();
final String ext = getExtension(format);
String scale;
String hash;
if (dims != null) {