List of usage examples for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE
int SC_SERVICE_UNAVAILABLE
To view the source code for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE.
Click Source Link
From source file:org.energy_home.jemma.internal.shapi.M2MLocalService.java
private ContentInstancesBatchResponse postBatchRequest(ContentInstancesBatchRequest batchRequest) { ContentInstancesBatchResponse batchResponse = new ContentInstancesBatchResponse(); List<ContentInstanceItemsStatus> responseStatusList = batchResponse.getContentInstanceItemsStatuses(); List<ContentInstanceItems> itemsList = batchRequest.getContentInstanceItems(); for (Iterator iterator = itemsList.iterator(); iterator.hasNext();) { ContentInstanceItems contentInstanceItems = (ContentInstanceItems) iterator.next(); ContentInstanceItemsStatus itemsStatus = new ContentInstanceItemsStatus(); itemsStatus.setAddressedId(contentInstanceItems.getAddressedId()); responseStatusList.add(itemsStatus); for (Iterator iterator2 = contentInstanceItems.getContentInstances().iterator(); iterator2.hasNext();) { ContentInstance ci = (ContentInstance) iterator2.next(); ContentInstanceItemStatus itemStatus = new ContentInstanceItemStatus(); itemStatus.setResourceId(new Long(System.currentTimeMillis())); itemsStatus.getContentInstanceItemStatuses().add(itemStatus); try { AHContainerAddress itemContainerAddress = new AHM2MContainerAddress( contentInstanceItems.getAddressedId()); if (!isValidLocalHagId(itemContainerAddress.getHagId())) { itemStatus.setBatchStatus(HttpServletResponse.SC_NOT_FOUND); } else { ci = postContentInstance(itemContainerAddress, ci); if (ci == null) itemStatus.setBatchStatus(HttpServletResponse.SC_NOT_FOUND); else if (ServiceClusterProxy.isAnUnconfirmedCommand(itemContainerAddress)) itemStatus.setBatchStatus(HttpServletResponse.SC_ACCEPTED); else itemStatus.setBatchStatus(HttpServletResponse.SC_OK); }/*from w w w .j a v a 2 s .c o m*/ } catch (Exception e) { LOG.error("Exception on postBatchRequest", e); itemStatus.setBatchStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } } return batchResponse; }
From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java
/** * PAAA services/*from w ww.j a v a 2s. co m*/ */ private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String format, String patronid, String token, String service) throws IOException { String baseurl = httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort(); this.logger.info("[" + config.getProperty("service.name") + "] " + "baseurl = " + baseurl); ObjectMapper mapper = new ObjectMapper(); if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) { try { IntegratedLibrarySystem integratedLibrarySystem = Lookup.lookup(IntegratedLibrarySystem.class); // init ILS integratedLibrarySystem.init(this.config); switch (service) { case "signup": { Patron patron = null; // read Patron StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } Patron patron2create = mapper.readValue(jb.toString(), Patron.class); if (patron2create.getAccount() == null || patron2create.getAccount().equals("")) { if (!patronid.equals("")) { patron2create.setAccount(patronid); } else { patron2create.setAccount(UUID.randomUUID().toString()); } } patron = integratedLibrarySystem.signup(patron2create); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); if (patron != null) { Block block = new Block(); LocalDateTime timePoint = LocalDateTime.now(); block.setDate(timePoint.getYear() + "-" + (timePoint.getMonthValue() < 10 ? "0" + timePoint.getMonthValue() : timePoint.getMonthValue()) + "-" + (timePoint.getDayOfMonth() < 10 ? "0" + timePoint.getDayOfMonth() : timePoint.getDayOfMonth())); block.setKey("93"); integratedLibrarySystem.blockpatron(patron, block); StringWriter json = new StringWriter(); mapper.writeValue(json, patron); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } case "newpatron": { Patron patron = null; // read Patron StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } Patron patron2create = mapper.readValue(jb.toString(), Patron.class); patron2create.setAccount(patronid); patron = integratedLibrarySystem.newpatron(patron2create); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); if (patron != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, patron); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } case "updatepatron": { Patron patron = null; // read Patron StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } Patron patron2update = mapper.readValue(jb.toString(), Patron.class); patron2update.setAccount(patronid); // TODO Was tun bei nderung des 'status'? patron = integratedLibrarySystem.updatepatron(patron2update); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); if (patron != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, patron); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } case "blockpatron": { Patron patron = null; // read Patron StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } Patron patron2block = new Patron(); patron2block.setAccount(patronid); Block block = mapper.readValue(jb.toString(), Block.class); patron = integratedLibrarySystem.blockpatron(patron2block, block); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); if (patron != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, patron); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } case "unblockpatron": { Patron patron = null; // read Patron StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } Patron patron2unblock = new Patron(); patron2unblock.setAccount(patronid); Block block = mapper.readValue(jb.toString(), Block.class); patron = integratedLibrarySystem.unblockpatron(patron2unblock, block); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); if (patron != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, patron); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } case "deletepatron": { Patron patron = null; Patron patron2delete = new Patron(); patron2delete.setAccount(patronid); patron = integratedLibrarySystem.deletepatron(patron2delete); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); if (patron != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, patron); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } case "newfee": { Patron patron = null; Fee resultFee = null; patron = new Patron(); patron.setAccount(patronid); // read Fee StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } this.logger.debug("[" + config.getProperty("service.name") + "] " + "Fee = " + jb); Fee fee = mapper.readValue(jb.toString(), Fee.class); resultFee = integratedLibrarySystem.newfee(patron, fee); this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> success!"); StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, resultFee); this.logger.debug( "[" + config.getProperty("service.name") + "] " + "Fee: " + stringWriter.toString()); if (patron != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, resultFee); this.logger.debug(json); // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid if (httpServletRequest.getParameter("redirect_uri") != null) { this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? " + httpServletRequest.getParameter("redirect_uri")); httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri") + "&patron=" + patronid + "&token=" + token); } else { httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.getWriter().println(json); } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } break; } default: { // TODO: keine gltige Funktion } } } catch (ILSException e) { this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service + "' event for patron '" + patronid + "' >>> failed!"); this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": ILS Error! " + e.getMessage()); // TODO e.getMessage = 403 if (e.getMessage().equals("403")) { // TODO >> properties httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN))); requestError.setCode(HttpServletResponse.SC_FORBIDDEN); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } else { // Mail to Bib-IT wg. Socket-Error try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); mailer.postMail( "[" + this.config.getProperty("service.name") + "] ILS Error! " + e.getMessage(), sw.toString()); } catch (MessagingException | IOException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } // TODO >> properties httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } } } else { this.logger.error("[" + config.getProperty("service.name") + "] " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); StringWriter json = new StringWriter(); mapper.writeValue(json, requestError); this.logger.debug("[" + config.getProperty("service.name") + "] " + json); // send response httpServletResponse.getWriter().println(json); } }
From source file:org.energy_home.jemma.internal.shapi.M2MLocalService.java
protected void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String requestUri = servletRequest.getRequestURI(); String method = servletRequest.getParameter("method"); if (requestUri.endsWith(servletUri)) { writeStringObject(servletResponse, indexPage); return;// w w w.j ava 2 s. c o m } initResponse(servletResponse); if (requestUri.endsWith(M2MConstants.URL_SLASH)) requestUri = requestUri.substring(0, requestUri.length() - 1); if (requestUri.startsWith(M2MConstants.URL_SCL_BASE)) { if (networkScl == null) { servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } requestUri = replaceFilters(requestUri, true); HttpResponse proxyResponse = null; OutputStream out = null; try { String queryString = servletRequest.getQueryString(); proxyResponse = networkScl.httpGet(requestUri + "?" + queryString); int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { copyResponseEntity(proxyResponse, servletResponse); } else { // TODO check status code mapping servletResponse.sendError(statusCode); } } catch (Exception e) { LOG.error("service: error while sending request to hap service", e); servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) { requestUri = replaceFilters(requestUri, false); try { M2MXmlObject xmlObject = null; if (requestUri.startsWith(subscriptionItemsAddressedId)) { if (requestUri.endsWith(M2MContainerAddress.ALL_ID_FILTER)) { SubscriptionItems subscriptionItems = new SubscriptionItems(); for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) { SubscriptionInfo subscriptionInfo = (SubscriptionInfo) iterator.next(); subscriptionItems.getSubscriptions().add(subscriptionInfo.subscription); } writeXmlObject(servletResponse, subscriptionItems); } else { String subscriptionId = requestUri.substring(subscriptionItemsAddressedId.length() + 1, requestUri.length()); SubscriptionInfo subscriptionInfo = null; for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) { subscriptionInfo = (SubscriptionInfo) iterator.next(); if (subscriptionInfo.subscription.getId().equals(subscriptionId)) { break; } else subscriptionInfo = null; } if (subscriptionInfo != null) writeXmlObject(servletResponse, subscriptionInfo.subscription); else servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } else if (requestUri.endsWith(sclsListUri)) { scl.setOnLineStatus(hapService.isConnected() ? SclStatusEnumeration.ONLINE : SclStatusEnumeration.DISCONNECTED); if (sclItems != null) writeXmlObject(servletResponse, sclItems); else servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else if (scl != null && requestUri.endsWith(scl.getSclBaseId())) { writeXmlObject(servletResponse, scl); } else if (scl != null && requestUri.startsWith(scl.getSclBaseId() + M2MConstants.URL_SLASH)) { long startInstanceId = M2MNetworkScl.CONTENT_INSTANCE_OLDEST_ID; String startInstanceIdStr = servletRequest.getParameter(START_INSTANCE_ID_REQUEST_PARAM); if (startInstanceIdStr != null && startInstanceIdStr.length() > 0) { try { startInstanceId = Long.parseLong(startInstanceIdStr); } catch (Exception e) { LOG.error("Error while parsing stratInstanceId parameter", e); } } long endInstanceId = M2MNetworkScl.CONTENT_INSTANCE_LATEST_ID; String endInstanceIdStr = servletRequest.getParameter(END_INSTANCE_ID_REQUEST_PARAM); if (endInstanceIdStr != null && endInstanceIdStr.length() > 0) { try { endInstanceId = Long.parseLong(endInstanceIdStr); } catch (Exception e) { LOG.error("Error while parsing stratInstanceId parameter", e); } } String contentInstanceId = null; if (requestUri.endsWith(M2MConstants.URL_CIS_ID_LATEST_ALIAS)) { contentInstanceId = M2MConstants.URL_CIS_ID_LATEST_ALIAS; requestUri = requestUri.replace(M2MConstants.URL_CIS_ID_LATEST_ALIAS, ""); } if (requestUri.endsWith(M2MConstants.URL_CIS_ID_OLDEST_ALIAS)) { contentInstanceId = M2MConstants.URL_CIS_ID_OLDEST_ALIAS; requestUri = requestUri.replace(M2MConstants.URL_CIS_ID_OLDEST_ALIAS, ""); } // TODO:!!! manage uri with a specific timestamp used for content instance id AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri); if (!isValidLocalHagId(containerAddress.getHagId())) servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); boolean isFilter = containerAddress.isFilterAddress(); String containerName = containerAddress.getContainerName(); if (containerName != null && containerName.equals(AHContainers.attrId_ah_zigbee_network_status)) { xmlObject = getZigBeeNetworkContentInstance(); // If latest or oldest is specified a ContentInstance is returned, otherwise a ContentInstanceItems // with a single item is built if (xmlObject != null && contentInstanceId == null) { xmlObject = getSingleContentInstanceItems(requestUri, (ContentInstance) xmlObject, startInstanceId, endInstanceId); } } else if (!isFilter) { String[] clusterAndAttributeNames = ServiceClusterProxy .getClusterAndAttributeNamesForNotCachedAttributes(containerAddress); if (clusterAndAttributeNames == null) { xmlObject = hapService.getLocalContentInstance(containerAddress); } else { // A request is sent to the device ApplianceProxy applianceProxy = applianceProxyList .getApplianceProxy(containerAddress.getAppliancePid()); IServiceCluster serviceCluster = applianceProxy.getServiceCluster( new Integer(containerAddress.getEndPointId()).intValue(), clusterAndAttributeNames[0]); IAttributeValue av = serviceCluster.getAttributeValue(clusterAndAttributeNames[1], applianceProxy.getApplicationRequestContext()); ContentInstance ci = new ContentInstance(); ci.setId(av.getTimestamp()); ci.setContent(av.getValue()); xmlObject = ci; } if (xmlObject != null && contentInstanceId == null) { // If latest or oldest is specified a ContentInstance is returned, otherwise a ContentInstanceItems // with a single item is built xmlObject = getSingleContentInstanceItems(requestUri, (ContentInstance) xmlObject, startInstanceId, endInstanceId); } } else { xmlObject = hapService.getLocalContentInstanceItemsList(containerAddress, startInstanceId, endInstanceId); } if (xmlObject == null) { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { writeXmlObject(servletResponse, xmlObject); } } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { LOG.error("service: error while parsing local request", e); servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.apache.nifi.processors.standard.PostHTTP.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean(); final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger(); final String userAgent = context.getProperty(USER_AGENT).getValue(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectionRequestTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setConnectTimeout( context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setRedirectsEnabled(false); requestConfigBuilder/*from w w w . j a v a2 s .c o m*/ .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final RequestConfig requestConfig = requestConfigBuilder.build(); final StreamThrottler throttler = throttlerRef.get(); final ComponentLog logger = getLogger(); final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B); String lastUrl = null; long bytesToSend = 0L; final List<FlowFile> toSend = new ArrayList<>(); DestinationAccepts destinationAccepts = null; CloseableHttpClient client = null; final String transactionId = UUID.randomUUID().toString(); final AtomicReference<String> dnHolder = new AtomicReference<>("none"); while (true) { FlowFile flowFile = session.get(); if (flowFile == null) { break; } final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue(); try { new java.net.URL(url); } catch (final MalformedURLException e) { logger.error( "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure", new Object[] { flowFile, url }); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); continue; } // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles if (lastUrl != null && !lastUrl.equals(url)) { session.transfer(flowFile); break; } lastUrl = url; toSend.add(flowFile); if (client == null || destinationAccepts == null) { final Config config = getConfig(url, context); final HttpClientConnectionManager conMan = config.getConnectionManager(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(conMan); clientBuilder.setUserAgent(userAgent); clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException { final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext); final ManagedHttpClientConnection conn = coreContext .getConnection(ManagedHttpClientConnection.class); if (!conn.isOpen()) { return; } final SSLSession sslSession = conn.getSSLSession(); if (sslSession != null) { final Certificate[] certChain = sslSession.getPeerCertificates(); if (certChain == null || certChain.length == 0) { throw new SSLPeerUnverifiedException("No certificates found"); } try { final X509Certificate cert = CertificateUtils .convertAbstractX509Certificate(certChain[0]); dnHolder.set(cert.getSubjectDN().getName().trim()); } catch (CertificateException e) { final String msg = "Could not extract subject DN from SSL session peer certificate"; logger.warn(msg); throw new SSLPeerUnverifiedException(msg); } } } }); clientBuilder.disableAutomaticRetries(); clientBuilder.disableContentCompression(); final String username = context.getProperty(USERNAME).getValue(); final String password = context.getProperty(PASSWORD).getValue(); // set the credentials if appropriate if (username != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (password == null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username)); } else { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } // Set the proxy if specified if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) { final String host = context.getProperty(PROXY_HOST).getValue(); final int port = context.getProperty(PROXY_PORT).asInteger(); clientBuilder.setProxy(new HttpHost(host, port)); } client = clientBuilder.build(); // determine whether or not destination accepts flowfile/gzip destinationAccepts = config.getDestinationAccepts(); if (destinationAccepts == null) { try { destinationAccepts = getDestinationAcceptance(sendAsFlowFile, client, url, getLogger(), transactionId); config.setDestinationAccepts(destinationAccepts); } catch (final IOException e) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); logger.error( "Unable to communicate with destination {} to determine whether or not it can accept " + "flowfiles/gzip; routing {} to failure due to {}", new Object[] { url, flowFile, e }); context.yield(); return; } } } bytesToSend += flowFile.getSize(); if (bytesToSend > maxBatchBytes.longValue()) { break; } // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format, // then only use a single FlowFile if (!sendAsFlowFile || !destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted()) { break; } } if (toSend.isEmpty()) { return; } final String url = lastUrl; final HttpPost post = new HttpPost(url); final List<FlowFile> flowFileList = toSend; final DestinationAccepts accepts = destinationAccepts; final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null; final EntityTemplate entity = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream rawOut) throws IOException { final OutputStream throttled = throttler == null ? rawOut : throttler.newThrottledOutputStream(rawOut); OutputStream wrappedOut = new BufferedOutputStream(throttled); if (compressionLevel > 0 && accepts.isGzipAccepted()) { wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel); } try (final OutputStream out = wrappedOut) { for (final FlowFile flowFile : flowFileList) { session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { FlowFilePackager packager = null; if (!sendAsFlowFile) { packager = null; } else if (accepts.isFlowFileV3Accepted()) { packager = new FlowFilePackagerV3(); } else if (accepts.isFlowFileV2Accepted()) { packager = new FlowFilePackagerV2(); } else if (accepts.isFlowFileV1Accepted()) { packager = new FlowFilePackagerV1(); } // if none of the above conditions is met, we should never get here, because // we will have already verified that at least 1 of the FlowFile packaging // formats is acceptable if sending as FlowFile. if (packager == null) { StreamUtils.copy(in, out); } else { final Map<String, String> flowFileAttributes; if (isDestinationLegacyNiFi) { // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path; // in order to maintain backward compatibility, we copy the filename & path to those attribute keys. flowFileAttributes = new HashMap<>(flowFile.getAttributes()); flowFileAttributes.put("nf.file.name", flowFile.getAttribute(CoreAttributes.FILENAME.key())); flowFileAttributes.put("nf.file.path", flowFile.getAttribute(CoreAttributes.PATH.key())); } else { flowFileAttributes = flowFile.getAttributes(); } packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize()); } } } }); } out.flush(); } } }) { @Override public long getContentLength() { if (compressionLevel == 0 && !sendAsFlowFile && !context.getProperty(CHUNKED_ENCODING).asBoolean()) { return toSend.get(0).getSize(); } else { return -1; } } }; if (context.getProperty(CHUNKED_ENCODING).isSet()) { entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean()); } post.setEntity(entity); post.setConfig(requestConfig); final String contentType; if (sendAsFlowFile) { if (accepts.isFlowFileV3Accepted()) { contentType = APPLICATION_FLOW_FILE_V3; } else if (accepts.isFlowFileV2Accepted()) { contentType = APPLICATION_FLOW_FILE_V2; } else if (accepts.isFlowFileV1Accepted()) { contentType = APPLICATION_FLOW_FILE_V1; } else { logger.error( "Cannot send data to {} because the destination does not accept FlowFiles and this processor is " + "configured to deliver FlowFiles; rolling back session", new Object[] { url }); session.rollback(); context.yield(); IOUtils.closeQuietly(client); return; } } else { final String contentTypeValue = context.getProperty(CONTENT_TYPE) .evaluateAttributeExpressions(toSend.get(0)).getValue(); contentType = StringUtils.isBlank(contentTypeValue) ? DEFAULT_CONTENT_TYPE : contentTypeValue; } final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue(); if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) { final Pattern pattern = Pattern.compile(attributeHeaderRegex); final Map<String, String> attributes = flowFileList.get(0).getAttributes(); for (final Map.Entry<String, String> entry : attributes.entrySet()) { final String key = entry.getKey(); if (pattern.matcher(key).matches()) { post.setHeader(entry.getKey(), entry.getValue()); } } } post.setHeader(CONTENT_TYPE_HEADER, contentType); post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true"); post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION); post.setHeader(TRANSACTION_ID_HEADER, transactionId); if (compressionLevel > 0 && accepts.isGzipAccepted()) { if (sendAsFlowFile) { post.setHeader(GZIPPED_HEADER, "true"); } else { post.setHeader(CONTENT_ENCODING_HEADER, CONTENT_ENCODING_GZIP_VALUE); } } // Do the actual POST final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles"; final String uploadDataRate; final long uploadMillis; CloseableHttpResponse response = null; try { final StopWatch stopWatch = new StopWatch(true); response = client.execute(post); // consume input stream entirely, ignoring its contents. If we // don't do this, the Connection will not be returned to the pool EntityUtils.consume(response.getEntity()); stopWatch.stop(); uploadDataRate = stopWatch.calculateDataRate(bytesToSend); uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS); } catch (final IOException e) { logger.error("Failed to Post {} due to {}; transferring to failure", new Object[] { flowFileDescription, e }); context.yield(); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } finally { if (response != null) { try { response.close(); } catch (final IOException e) { getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e }); } } } // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us // from posting to some other webservice and then attempting to delete some resource to which // we are redirected final int responseCode = response.getStatusLine().getStatusCode(); final String responseReason = response.getStatusLine().getReasonPhrase(); String holdUri = null; if (responseCode == HttpServletResponse.SC_SEE_OTHER) { final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME); if (locationUriHeader != null) { if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) { final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME); if (holdUriHeader != null) { holdUri = holdUriHeader.getValue(); } } } if (holdUri == null) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } } if (holdUri == null) { if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: response code was {}:{}; will yield processing, " + "since the destination is temporarily unavailable", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } context.yield(); return; } if (responseCode >= 300) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error("Failed to Post {} to {}: response code was {}:{}", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription, url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis, true); session.transfer(flowFile, REL_SUCCESS); } return; } // // the response indicated a Hold URI; delete the Hold. // // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have // changed over the past, so we have to take into account a few different possibilities. String fullHoldUri = holdUri; if (holdUri.startsWith("/contentListener")) { // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener, // as this really indicates that it should be whatever we posted to -- if posting directly to the // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may // be posting to some other URL. fullHoldUri = url + holdUri.substring(16); } else if (holdUri.startsWith("/")) { // URL indicates the full path but not hostname or port; use the same hostname & port that we posted // to but use the full path indicated by the response. int firstSlash = url.indexOf("/", 8); if (firstSlash < 0) { firstSlash = url.length(); } final String beforeSlash = url.substring(0, firstSlash); fullHoldUri = beforeSlash + holdUri; } else if (!holdUri.startsWith("http")) { // Absolute URL fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri; } final HttpDelete delete = new HttpDelete(fullHoldUri); delete.setHeader(TRANSACTION_ID_HEADER, transactionId); while (true) { try { final HttpResponse holdResponse = client.execute(delete); EntityUtils.consume(holdResponse.getEntity()); final int holdStatusCode = holdResponse.getStatusLine().getStatusCode(); final String holdReason = holdResponse.getStatusLine().getReasonPhrase(); if (holdStatusCode >= 300) { logger.error( "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure", new Object[] { flowFileDescription, holdStatusCode, holdReason }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}", new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url); session.transfer(flowFile, REL_SUCCESS); } return; } catch (final IOException e) { logger.warn("Failed to delete Hold that destination placed on {} due to {}", new Object[] { flowFileDescription, e }); } if (!isScheduled()) { context.yield(); logger.warn( "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure", new Object[] { flowFileDescription }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } } }
From source file:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java
private void provideService(HttpServletRequest request, HttpServletResponse response, String format, HashMap<String, String> latinParameters, boolean isTUintern, boolean isUBintern, boolean is52bIBA) throws IOException { String openurl = ""; try {//from w w w . ja va 2 s. c o m // build openurl for (String k : latinParameters.keySet()) { // repeat input-openurl if (!k.equals("format") && !k.equals("system") && !latinParameters.get(k).equals("")) { if (latinParameters.get(k).contains("/>")) { latinParameters.put(k, latinParameters.get(k).replaceAll("/>", "")); } if (latinParameters.get(k).contains(">")) { latinParameters.put(k, latinParameters.get(k).replaceAll(">", "")); } String prefix = ""; if (!k.startsWith("rft")) { prefix = "rft."; } String value = ""; if (k.contains("title") || k.contains("au")) { value = latinParameters.get(k); } else if (k.contains("issn") && !latinParameters.get(k).equals("")) { if (latinParameters.get(k).contains("-")) { value = latinParameters.get(k); } else { value = latinParameters.get(k).subSequence(0, 4) + "-" + latinParameters.get(k).subSequence(4, 8); } } else { value = latinParameters.get(k); } openurl += "&" + prefix + k + "=" + URLEncoder.encode(value, "UTF-8"); } } this.logger.debug("\n" + "\tOpenURL-Parameter = " + this.config.getProperty("linkresolver.baseurl") + this.config.getProperty("linkresolver.parameters") + openurl); ArrayList<Document> daiaDocuments = new ArrayList<Document>(); // falls OpenURL contains isbn: Anfrage an "normalen DaiaService Endpoint String isbn = ""; if (latinParameters.get("rft.isbn") != null && !latinParameters.get("rft.isbn").equals("")) { isbn = latinParameters.get("rft.isbn"); } else if (latinParameters.get("isbn") != null && !latinParameters.get("isbn").equals("")) { isbn = latinParameters.get("isbn"); } else if (latinParameters.get("id") != null && latinParameters.get("id").contains("isbn:")) { isbn = latinParameters.get("id").split(":")[1]; } this.logger.debug("ISBN = " + isbn); if (!isbn.equals("")) { if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) { // erst DAIA isbn fragen if (isbn.contains("; ")) { isbn = isbn.replaceAll("; ", ","); } String daiaUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/daia/?id=isbn:" + isbn; this.logger.debug("daiaUrl = " + daiaUrl); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(daiaUrl); httpGet.addHeader("Accept", "application/xml"); CloseableHttpResponse httpResponse = httpclient.execute(httpGet); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { JAXBContext jaxbContext = JAXBContext.newInstance(Daia.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Daia daia = (Daia) unmarshaller.unmarshal(httpEntity.getContent()); if (daia.getDocument() != null) { daiaDocuments.addAll(daia.getDocument()); } break; } default: { // TODO Evaluieren: Das mssten die Flle sein, in denen E-Books in der Knowledgebase eingetragen sind if (Lookup.lookupAll(LinkResolver.class).size() > 0) { Document daiaDocument = null; LinkResolver linkResolver = Lookup.lookup(LinkResolver.class); // init Linkresolver linkResolver.init(this.config); // get items ArrayList<Document> linkresolverDocument = linkResolver.items("openurl", openurl); if (linkresolverDocument != null && linkresolverDocument.size() > 0) { daiaDocument = new Document(); daiaDocument.setId("urn:isbn:" + isbn); if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) { daiaDocument.setItem(linkresolverDocument.get(0).getItem()); } else { daiaDocument.getItem().addAll(linkresolverDocument.get(0).getItem()); } if (daiaDocument != null) { daiaDocuments.add(daiaDocument); } } } } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } } else { // Wenn JOP registriert ist if (Lookup.lookupAll(JournalOnlinePrintService.class).size() > 0) { // build OpenURL for JOP String issn = ""; if (latinParameters.get("rft.issn") != null && !latinParameters.get("rft.issn").equals("")) { issn = latinParameters.get("rft.issn"); } else if (latinParameters.get("issn") != null && !latinParameters.get("issn").equals("")) { issn = latinParameters.get("issn"); } if (latinParameters.get("rft.eissn") != null && !latinParameters.get("rft.eissn").equals("")) { issn = latinParameters.get("rft.eissn"); } else if (latinParameters.get("eissn") != null && !latinParameters.get("eissn").equals("")) { issn = latinParameters.get("eissn"); } else if (latinParameters.get("id") != null && latinParameters.get("id").contains("issn:")) { issn = latinParameters.get("id").split(":")[1]; } this.logger.debug("ISSN = " + issn); String jop_openurl = ""; for (String k : latinParameters.keySet()) { // mit rft if ((latinParameters.keySet().contains("rft.atitle") || latinParameters.keySet().contains("atitle")) && k.equals("rft.date") && !latinParameters.get(k).equals("")) { jop_openurl += "&date=" + latinParameters.get(k); } if (k.equals("rft.volume") && !latinParameters.get(k).equals("")) { jop_openurl += "&volume=" + latinParameters.get(k); } if (k.equals("rft.issue") && !latinParameters.get(k).equals("")) { jop_openurl += "&issue=" + latinParameters.get(k); } // ohne rft if ((latinParameters.keySet().contains("rft.atitle") || latinParameters.keySet().contains("atitle")) && k.equals("date") && !latinParameters.get(k).equals("")) { jop_openurl += "&date=" + latinParameters.get(k); } if (k.equals("volume") && !latinParameters.get(k).equals("")) { jop_openurl += "&volume=" + latinParameters.get(k); } if (k.equals("issue") && !latinParameters.get(k).equals("")) { jop_openurl += "&issue=" + latinParameters.get(k); } } if (!issn.equals("")) { if (issn.contains("-")) { jop_openurl += "&issn=" + issn; } else { jop_openurl += "&issn=" + issn.subSequence(0, 4) + "-" + issn.subSequence(4, 8); } } if (latinParameters.keySet().contains("rft.atitle") || latinParameters.keySet().contains("atitle")) { jop_openurl += "&genre=article"; } else { jop_openurl += "&genre=journal"; } this.logger.debug("\n" + jop_openurl + "\tOpenURL-Parameter (JOP) = " + this.config.getProperty("jop.url.openurl") + jop_openurl); if (!jop_openurl.equals("&genre=journal") && (jop_openurl.contains("&title=") || jop_openurl.contains("&issn="))) { // get data try { JournalOnlinePrintService journalOnlinePrintService = Lookup .lookup(JournalOnlinePrintService.class); // init JOP journalOnlinePrintService.init(this.config); // get items ArrayList<de.tu_dortmund.ub.api.daia.jop.model.Document> jopDocuments = journalOnlinePrintService .items("openurl", jop_openurl); if (jopDocuments != null && jopDocuments.size() > 0) { Document daiaDocument = new Document(); this.logger.debug("JOP hits: " + jopDocuments.size()); if (jopDocuments.get(0).getId() != null && jopDocuments.get(0).getHref() != null) { daiaDocument.setId(jopDocuments.get(0).getId()); daiaDocument.setHref(jopDocuments.get(0).getHref()); } else { daiaDocument.setId("urn:issn:" + issn); } // print if (jopDocuments.get(0).getItem() != null && jopDocuments.get(0).getItem().size() > 0) { daiaDocument.setItem(jopDocuments.get(0).getItem()); } // digital if (jopDocuments.get(0).isExistsDigitalItems() && Lookup.lookupAll(LinkResolver.class).size() > 0) { // TODO define a boolean variable for executing a linkresolver request // TODO auslagern! LinkResolver linkResolver = Lookup.lookup(LinkResolver.class); // init Linkresolver linkResolver.init(this.config); // get items ArrayList<Document> linkresolverDocument = linkResolver.items("openurl", openurl); if (linkresolverDocument != null && linkresolverDocument.size() > 0 && linkresolverDocument.get(0).getItem().size() >= jopDocuments.get(0) .getCountDigitlItems()) { if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) { daiaDocument.setItem(linkresolverDocument.get(0).getItem()); } else { daiaDocument.getItem().addAll(linkresolverDocument.get(0).getItem()); } } else { // TODO Ticket 11679 // E-Mail an katalogplus@ub.tu-dortmund.de mit Betreff-Prefix [Content] boolean isNatLic = true; if (isNatLic) { if (!issn.equals("")) { // request JOP again with only ISSN jopDocuments = journalOnlinePrintService.eonly("issn", issn); if (jopDocuments != null && jopDocuments.size() > 0) { this.logger.debug("JOP hits: " + jopDocuments.size()); if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) { daiaDocument.setItem(jopDocuments.get(0).getItem()); } else { if (jopDocuments.get(0).getItem() != null) { daiaDocument.getItem() .addAll(jopDocuments.get(0).getItem()); } else { // Error-E-Mail "JOP<>LinkResolver: Not an NatLic" Mailer mailer = new Mailer( this.config.getProperty("service.mailer.conf")); try { int cnt = 0; if (linkresolverDocument != null) { cnt = linkresolverDocument.get(0).getItem() .size(); } mailer.postMail( "[DAIAopenurl] JOP-Document ohne Items ", "JOP-Link " + jopDocuments.get(0) .getCountDigitlItems() + ": " + this.config.getProperty( "jop.url.openurl") + jop_openurl + ".\n"); } catch (MessagingException e) { this.logger.error(e.getMessage(), e.getCause()); this.logger.debug("[DAIAopenurl] CONTENT-ERROR"); this.logger.debug("OpenUrl: " + openurl + "\n\n\tJOP-URL: " + jop_openurl); } if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) { daiaDocument = null; } } } } } else { // Error-E-Mail "JOP<>LinkResolver: Not an NatLic" Mailer mailer = new Mailer( this.config.getProperty("service.mailer.conf")); try { int cnt = 0; if (linkresolverDocument != null) { cnt = linkresolverDocument.get(0).getItem().size(); } mailer.postMail( "[DAIAopenurl] JOP<>LinkResolver: NatLic without ISSN ", "Laut ZDB/EZB gibt es " + jopDocuments.get(0).getCountDigitlItems() + "-mal elektronischen Bestand (vgl. " + this.config.getProperty("jop.url.openurl") + jop_openurl + ").\n" + "Laut 360 Link aber " + cnt + "-mal (vgl. " + this.config .getProperty("linkresolver.baseurl") + this.config .getProperty("linkresolver.parameters") + openurl + ")."); } catch (MessagingException e) { this.logger.error(e.getMessage(), e.getCause()); this.logger.debug("[DAIAopenurl] CONTENT-ERROR"); this.logger.debug("OpenUrl: " + openurl + "\n\n\tJOP-URL: " + jop_openurl); } if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) { daiaDocument = null; } } } else { // Hier kann man nix machen! } } } if (daiaDocument != null) { daiaDocuments.add(daiaDocument); } } } catch (LinkResolverException e) { // daiaDocuments bleibt leer this.logger.error("[DaiaService OpenUrl Endpoint] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable (LinkResolver)."); this.logger.error(e.getMessage(), e.getCause()); for (StackTraceElement stackTraceElement : e.getStackTrace()) { this.logger.error("\t" + stackTraceElement.toString()); } Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { mailer.postMail( "[DaiaService OpenUrl Endpoint] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable (LinkResolver).", e.getMessage() + "\n" + this.config.getProperty("linkresolver.baseurl") + this.config.getProperty("linkresolver.parameters") + openurl); } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } } catch (JOPException e) { // daiaDocuments bleibt leer this.logger.error("[DaiaService OpenUrl Endpoint] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable (Journals Online & Print)."); this.logger.error(e.getMessage(), e.getCause()); for (StackTraceElement stackTraceElement : e.getStackTrace()) { this.logger.error("\t" + stackTraceElement.toString()); } Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { mailer.postMail( "[DaiaService OpenUrl Endpoint] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable (Journals Online & Print).", e.getMessage() + "\n" + this.config.getProperty("jop.url.openurl") + jop_openurl); } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } } } else { // tue nix: daiaDocuments bleibt leer } } } // Abschlusskorrektur fr ACM, IEEE und LNCS vor dem response // LNCS if (Lookup.lookupAll(LncsResolver.class).size() > 0 && Boolean.parseBoolean(this.config.getProperty("licenced.lncs"))) { if (daiaDocuments.size() > 0) { for (Document daiaDocument : daiaDocuments) { if (daiaDocument != null && daiaDocument.getId() != null && daiaDocument.getId().contains("urn:issn:03029743") && ((latinParameters.keySet().contains("id") && latinParameters.get("id").startsWith("doi:10.1007")) || (latinParameters.keySet().contains("rft.id") && latinParameters.get("rft.id").startsWith("doi:10.1145")))) { daiaDocument.setItem(null); LncsResolver lncsResolver = Lookup.lookup(LncsResolver.class); lncsResolver.init(this.config); Document lncsDocument = lncsResolver.items(latinParameters); daiaDocument.setId(lncsDocument.getId()); daiaDocument.setHref(lncsDocument.getHref()); daiaDocument.setItem(lncsDocument.getItem()); } } } } // ACM if (Lookup.lookupAll(AcmResolver.class).size() > 0 && Boolean.parseBoolean(this.config.getProperty("licenced.acm"))) { if ((latinParameters.keySet().contains("id") && latinParameters.get("id").contains("10.1145")) || (latinParameters.keySet().contains("rft.id") && latinParameters.get("rft.id").contains("10.1145"))) { if (daiaDocuments.size() > 0) { for (Document daiaDocument : daiaDocuments) { daiaDocument.setItem(null); AcmResolver acmResolver = Lookup.lookup(AcmResolver.class); acmResolver.init(this.config); Document acmDocument = acmResolver.items(latinParameters); daiaDocument.setId(acmDocument.getId()); daiaDocument.setHref(acmDocument.getHref()); if (daiaDocument.getItem() == null) { daiaDocument.setItem(acmDocument.getItem()); } else { daiaDocument.getItem().addAll(acmDocument.getItem()); } } } else { Document daiaDocument = new Document(); AcmResolver acmResolver = Lookup.lookup(AcmResolver.class); acmResolver.init(this.config); Document acmDocument = acmResolver.items(latinParameters); daiaDocument.setId(acmDocument.getId()); daiaDocument.setHref(acmDocument.getHref()); if (daiaDocument.getItem() == null) { daiaDocument.setItem(acmDocument.getItem()); } else { daiaDocument.getItem().addAll(acmDocument.getItem()); } daiaDocuments.add(daiaDocument); } } } // IEEE if (Lookup.lookupAll(IeeeResolver.class).size() > 0 && Boolean.parseBoolean(this.config.getProperty("licenced.ieee"))) { if ((latinParameters.keySet().contains("id") && latinParameters.get("id").contains("10.1109")) || (latinParameters.keySet().contains("rft.id") && latinParameters.get("rft.id").contains("10.1109"))) { if (daiaDocuments.size() > 0) { for (Document daiaDocument : daiaDocuments) { daiaDocument.setItem(null); IeeeResolver ieeeResolver = Lookup.lookup(IeeeResolver.class); ieeeResolver.init(this.config); Document ieeeDocument = ieeeResolver.items(latinParameters); daiaDocument.setId(ieeeDocument.getId()); daiaDocument.setHref(ieeeDocument.getHref()); if (daiaDocument.getItem() == null) { daiaDocument.setItem(ieeeDocument.getItem()); } else { daiaDocument.getItem().addAll(ieeeDocument.getItem()); } } } else { Document daiaDocument = new Document(); IeeeResolver ieeeResolver = Lookup.lookup(IeeeResolver.class); ieeeResolver.init(this.config); Document ieeeDocument = ieeeResolver.items(latinParameters); daiaDocument.setId(ieeeDocument.getId()); daiaDocument.setHref(ieeeDocument.getHref()); if (daiaDocument.getItem() == null) { daiaDocument.setItem(ieeeDocument.getItem()); } else { daiaDocument.getItem().addAll(ieeeDocument.getItem()); } daiaDocuments.add(daiaDocument); } } } if (daiaDocuments.size() > 0) { this.logger.debug("200 Document Found"); // TODO query footnotes from ils if configured // Ausgabe Daia daia = new Daia(); daia.setVersion(this.config.getProperty("daia.version")); daia.setSchema(this.config.getProperty("daia.schema")); GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(new Date().getTime()); try { DatatypeFactory df = DatatypeFactory.newInstance(); daia.setTimestamp(df.newXMLGregorianCalendar(gc).toString()); } catch (DatatypeConfigurationException dce) { this.logger.error("ERROR: Service unavailable.", dce.getCause()); } Institution institution = new Institution(); institution.setId(this.config.getProperty("daia.institution.id")); institution.setHref(this.config.getProperty("daia.institution.href")); institution.setContent(this.config.getProperty("daia.institution.content")); daia.setInstitution(institution); daia.setDocument(daiaDocuments); // Ausgabe if (daia.getDocument() == null || daia.getDocument().size() == 0) { // HTML-Ausgabe via XSLT if (format.equals("html")) { try { JAXBContext context = JAXBContext.newInstance(Daia.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse StringWriter stringWriter = new StringWriter(); m.marshal(daia, stringWriter); org.jdom2.Document doc = new org.jdom2.Document(); doc.setRootElement(new Element("daia")); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", "de"); parameters.put("isTUintern", Boolean.toString(isTUintern)); parameters.put("isUBintern", Boolean.toString(isUBintern)); parameters.put("is52bIBA", Boolean.toString(is52bIBA)); parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8")); ObjectMapper mapper = new ObjectMapper(); StringWriter json = new StringWriter(); mapper.writeValue(json, daia); parameters.put("json", json.toString()); String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"), parameters); response.setContentType("text/html;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(html); } catch (PropertyException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'."); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'."); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Document not found."); } } else { this.logger.debug("format = " + format); // HTML-Ausgabe via XSLT if (format.equals("html")) { try { JAXBContext context = JAXBContext.newInstance(Daia.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse StringWriter stringWriter = new StringWriter(); m.marshal(daia, stringWriter); org.jdom2.Document doc = new SAXBuilder() .build(new StringReader(this.cleanup(stringWriter.toString()))); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", "de"); parameters.put("isTUintern", Boolean.toString(isTUintern)); parameters.put("isUBintern", Boolean.toString(isUBintern)); parameters.put("is52bIBA", Boolean.toString(is52bIBA)); parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8")); ObjectMapper mapper = new ObjectMapper(); StringWriter json = new StringWriter(); mapper.writeValue(json, daia); parameters.put("json", json.toString()); String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"), parameters); response.setContentType("text/html;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(html); } catch (PropertyException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } catch (JDOMException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } catch (IOException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(Daia.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse response.setContentType("application/xml;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); m.marshal(daia, response.getWriter()); } catch (PropertyException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); mapper.writeValue(response.getWriter(), daia); } // RDF-Ausgabe mit XSLT auf XML-Ausgabe if (format.equals("rdf")) { try { JAXBContext context = JAXBContext.newInstance(Daia.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse response.setContentType("application/xml;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); StringWriter xml = new StringWriter(); m.marshal(daia, xml); XMLOutputter out = new XMLOutputter(); out.output( new SAXBuilder().build(new StringReader( xmlOutputter(new SAXBuilder().build(new StringReader(xml.toString())), config.getProperty("xslt_xml2rdf"), null))), response.getWriter()); } catch (JDOMException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } catch (PropertyException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } } } else { this.logger.debug("404 Document Not Found + (format=" + format + ")"); if (format.equals("html")) { try { JAXBContext context = JAXBContext.newInstance(Daia.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse org.jdom2.Document doc = new org.jdom2.Document(); doc.setRootElement(new Element("daia")); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", "de"); parameters.put("isTUintern", Boolean.toString(isTUintern)); parameters.put("isUBintern", Boolean.toString(isUBintern)); parameters.put("is52bIBA", Boolean.toString(is52bIBA)); parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8")); String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"), parameters); response.setContentType("text/html;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(html); } catch (PropertyException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'."); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'."); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Document not found."); } } } catch (Exception e) { this.logger.error("[DaiaService OpenUrl Endpoint] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable."); this.logger.error(e.getMessage(), e.getCause()); for (StackTraceElement stackTraceElement : e.getStackTrace()) { this.logger.error("\t" + stackTraceElement.toString()); } Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { mailer.postMail("[DaiaService OpenUrl Endpoint] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable.", e.getMessage() + "\n" + request.getRequestURL()); } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Service unavailable."); } }
From source file:org.springframework.extensions.webscripts.connector.RemoteClient.java
/** * Service a remote URL and write the the result into an output stream. * If an InputStream is provided then a POST will be performed with the content * pushed to the url. Otherwise a standard GET will be performed. * /*from w w w.j a v a 2 s.c o m*/ * @param url The URL to open and retrieve data from * @param in The optional InputStream - if set a POST or similar will be performed * @param out The OutputStream to write result to * @param res Optional HttpServletResponse - to which response headers will be copied - i.e. proxied * @param status The status object to apply the response code too * * @return encoding specified by the source URL - may be null * * @throws IOException */ private String service(URL url, InputStream in, OutputStream out, HttpServletRequest req, HttpServletResponse res, ResponseStatus status) throws IOException { final boolean trace = logger.isTraceEnabled(); final boolean debug = logger.isDebugEnabled(); if (debug) { logger.debug("Executing " + "(" + requestMethod + ") " + url.toString()); if (in != null) logger.debug(" - InputStream supplied - will push..."); if (out != null) logger.debug(" - OutputStream supplied - will stream response..."); if (req != null && res != null) logger.debug(" - Full Proxy mode between servlet request and response..."); } // aquire and configure the HttpClient HttpClient httpClient = createHttpClient(url); URL redirectURL = url; HttpResponse response; HttpRequestBase method = null; int retries = 0; // Only process redirects if we are not processing a 'push' int maxRetries = in == null ? this.maxRedirects : 1; try { do { // Release a previous method that we processed due to a redirect if (method != null) { method.reset(); method = null; } switch (this.requestMethod) { default: case GET: method = new HttpGet(redirectURL.toString()); break; case PUT: method = new HttpPut(redirectURL.toString()); break; case POST: method = new HttpPost(redirectURL.toString()); break; case DELETE: method = new HttpDelete(redirectURL.toString()); break; case HEAD: method = new HttpHead(redirectURL.toString()); break; case OPTIONS: method = new HttpOptions(redirectURL.toString()); break; } // proxy over any headers from the request stream to proxied request if (req != null) { Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String key = headers.nextElement(); if (key != null) { key = key.toLowerCase(); if (!this.removeRequestHeaders.contains(key) && !this.requestProperties.containsKey(key) && !this.requestHeaders.containsKey(key)) { method.setHeader(key, req.getHeader(key)); if (trace) logger.trace("Proxy request header: " + key + "=" + req.getHeader(key)); } } } } // apply request properties, allows for the assignment and override of specific header properties // firstly pre-configured headers are applied and overridden/augmented by runtime request properties final Map<String, String> headers = (Map<String, String>) this.requestHeaders.clone(); headers.putAll(this.requestProperties); if (headers.size() != 0) { for (Map.Entry<String, String> entry : headers.entrySet()) { String headerName = entry.getKey(); String headerValue = headers.get(headerName); if (headerValue != null) { method.setHeader(headerName, headerValue); } if (trace) logger.trace("Set request header: " + headerName + "=" + headerValue); } } // Apply cookies if (this.cookies != null && !this.cookies.isEmpty()) { StringBuilder builder = new StringBuilder(128); for (Map.Entry<String, String> entry : this.cookies.entrySet()) { if (builder.length() != 0) { builder.append(';'); } builder.append(entry.getKey()); builder.append('='); builder.append(entry.getValue()); } String cookieString = builder.toString(); if (debug) logger.debug("Setting Cookie header: " + cookieString); method.setHeader(HEADER_COOKIE, cookieString); } // HTTP basic auth support if (this.username != null && this.password != null) { String auth = this.username + ':' + this.password; method.addHeader("Authorization", "Basic " + Base64.encodeBytes(auth.getBytes(), Base64.DONT_BREAK_LINES)); if (debug) logger.debug("Applied HTTP Basic Authorization for user: " + this.username); } // prepare the POST/PUT entity data if input supplied if (in != null) { method.setHeader(HEADER_CONTENT_TYPE, getRequestContentType()); if (debug) logger.debug("Set Content-Type=" + getRequestContentType()); boolean urlencoded = getRequestContentType().startsWith(X_WWW_FORM_URLENCODED); if (!urlencoded) { // apply content-length here if known (i.e. from proxied req) // if this is not set, then the content will be buffered in memory long contentLength = -1L; if (req != null) { String contentLengthStr = req.getHeader(HEADER_CONTENT_LENGTH); if (contentLengthStr != null) { try { long actualContentLength = Long.parseLong(contentLengthStr); if (actualContentLength > 0) { contentLength = actualContentLength; } } catch (NumberFormatException e) { logger.warn("Can't parse 'Content-Length' header from '" + contentLengthStr + "'. The contentLength is set to -1"); } } } if (debug) logger.debug(requestMethod + " entity Content-Length=" + contentLength); // remove the Content-Length header as the setEntity() method will perform this explicitly method.removeHeaders(HEADER_CONTENT_LENGTH); try { // Apache doc for AbstractHttpEntity states: // HttpClient must use chunk coding if the entity content length is unknown (== -1). HttpEntity entity = new InputStreamEntity(in, contentLength); ((HttpEntityEnclosingRequest) method) .setEntity(contentLength == -1L || contentLength > 16384L ? entity : new BufferedHttpEntity(entity)); ((HttpEntityEnclosingRequest) method).setHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } catch (IOException e) { // During the creation of the BufferedHttpEntity the underlying stream can be closed by the client, // this happens if the request is discarded by the browser - we don't log this IOException as INFO // as that would fill the logs with unhelpful noise - enable DEBUG logging to see these messages. throw new RuntimeException(e.getMessage(), e); } } else { if (req != null) { // apply any supplied request parameters Map<String, String[]> postParams = req.getParameterMap(); if (postParams != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(postParams.size()); for (String key : postParams.keySet()) { String[] values = postParams.get(key); for (int i = 0; i < values.length; i++) { params.add(new BasicNameValuePair(key, values[i])); } } } // ensure that the Content-Length header is not directly proxied - as the underlying // HttpClient will encode the body as appropriate - cannot assume same as the original client sent method.removeHeaders(HEADER_CONTENT_LENGTH); } else { // Apache doc for AbstractHttpEntity states: // HttpClient must use chunk coding if the entity content length is unknown (== -1). HttpEntity entity = new InputStreamEntity(in, -1L); ((HttpEntityEnclosingRequest) method).setEntity(entity); ((HttpEntityEnclosingRequest) method).setHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Execute the method to get the response response = httpClient.execute(method); redirectURL = processResponse(redirectURL, response); } while (redirectURL != null && ++retries < maxRetries); // record the status code for the internal response object int responseCode = response.getStatusLine().getStatusCode(); if (responseCode >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR && this.exceptionOnError) { buildProxiedServerError(response); } else if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { // Occurs when server is down and likely an ELB response throw new ConnectException(response.toString()); } boolean allowResponseCommit = (responseCode != HttpServletResponse.SC_UNAUTHORIZED || commitResponseOnAuthenticationError); status.setCode(responseCode); if (debug) logger.debug("Response status code: " + responseCode); // walk over headers that are returned from the connection // if we have a servlet response, push the headers back to the existing response object // otherwise, store headers on status Header contentType = null; Header contentLength = null; for (Header header : response.getAllHeaders()) { // NOTE: Tomcat does not appear to be obeying the servlet spec here. // If you call setHeader() the spec says it will "clear existing values" - i.e. not // add additional values to existing headers - but for Server and Transfer-Encoding // if we set them, then two values are received in the response... // In addition handle the fact that the key can be null. final String key = header.getName(); if (key != null) { if (!key.equalsIgnoreCase(HEADER_SERVER) && !key.equalsIgnoreCase(HEADER_TRANSFER_ENCODING)) { if (res != null && allowResponseCommit && !this.removeResponseHeaders.contains(key.toLowerCase())) { res.setHeader(key, header.getValue()); } // store headers back onto status status.setHeader(key, header.getValue()); if (trace) logger.trace("Response header: " + key + "=" + header.getValue()); } // grab a reference to the the content-type header here if we find it if (contentType == null && key.equalsIgnoreCase(HEADER_CONTENT_TYPE)) { contentType = header; // additional optional processing based on the Content-Type header processContentType(url, res, contentType); } // grab a reference to the Content-Length header here if we find it else if (contentLength == null && key.equalsIgnoreCase(HEADER_CONTENT_LENGTH)) { contentLength = header; } } } // locate response encoding from the headers String encoding = null; String ct = null; if (contentType != null) { ct = contentType.getValue(); int csi = ct.indexOf(CHARSETEQUALS); if (csi != -1) { encoding = ct.substring(csi + CHARSETEQUALS.length()); if ((csi = encoding.lastIndexOf(';')) != -1) { encoding = encoding.substring(0, csi); } if (debug) logger.debug("Response charset: " + encoding); } } if (debug) logger.debug("Response encoding: " + contentType); // generate container driven error message response for specific response codes if (res != null && responseCode == HttpServletResponse.SC_UNAUTHORIZED && allowResponseCommit) { res.sendError(responseCode, response.getStatusLine().getReasonPhrase()); } else { // push status to existing response object if required if (res != null && allowResponseCommit) { res.setStatus(responseCode); } // perform the stream write from the response to the output int bufferSize = this.bufferSize; if (contentLength != null) { long length = Long.parseLong(contentLength.getValue()); if (length < bufferSize) { bufferSize = (int) length; } } copyResponseStreamOutput(url, res, out, response, ct, bufferSize); } // if we get here call was successful return encoding; } catch (ConnectTimeoutException | SocketTimeoutException timeErr) { // caught a socket timeout IO exception - apply internal error code logger.info("Exception calling (" + requestMethod + ") " + url.toString()); status.setCode(HttpServletResponse.SC_REQUEST_TIMEOUT); status.setException(timeErr); status.setMessage(timeErr.getMessage()); if (res != null) { //return a Request Timeout error res.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT, timeErr.getMessage()); } throw timeErr; } catch (UnknownHostException | ConnectException hostErr) { // caught an unknown host IO exception logger.info("Exception calling (" + requestMethod + ") " + url.toString()); status.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); status.setException(hostErr); status.setMessage(hostErr.getMessage()); if (res != null) { // return server error code res.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE, hostErr.getMessage()); } throw hostErr; } catch (IOException ioErr) { // caught a general IO exception - apply generic error code so one gets returned logger.info("Exception calling (" + requestMethod + ") " + url.toString()); status.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); status.setException(ioErr); status.setMessage(ioErr.getMessage()); if (res != null) { res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ioErr.getMessage()); } throw ioErr; } catch (RuntimeException e) { // caught an exception - apply generic error code so one gets returned logger.debug("Exception calling (" + requestMethod + ") " + url.toString()); status.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); status.setException(e); status.setMessage(e.getMessage()); if (res != null) { res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } throw e; } finally { // reset state values if (method != null) { method.releaseConnection(); } setRequestContentType(null); this.requestMethod = HttpMethod.GET; } }
From source file:org.energy_home.jemma.internal.shapi.HapProxy.java
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String requestUri = servletRequest.getRequestURI(); initResponse(servletResponse);//from www .j a va 2 s .c om requestUri = replaceFilters(requestUri, false); if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) { try { if (requestUri.equals(subscriptionItemsAddressedId)) { long now = System.currentTimeMillis(); Subscription subscription = (Subscription) readXmlObject(servletRequest); if (subscription.getId() != null || subscription.getContact() == null) { servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) { // Only one subscription for each contact uri is allowed (last subscription overwrite a previous existing one) if (subscription.getContact() .equals(((SubscriptionInfo) iterator.next()).subscription.getContact())) { iterator.remove(); break; } } subscription.setCreationTime(now); subscription.setLastModifiedTime(now); subscription.setId(UUID.randomUUID().toString()); writeXmlObject(servletResponse, subscription); subscriptionInfos.add(new SubscriptionInfo(subscription)); } } else if (requestUri.endsWith(M2MConstants.URL_CIS_BATCH_REQUEST)) { ContentInstancesBatchRequest batchRequest = (ContentInstancesBatchRequest) readXmlObject( servletRequest); ContentInstancesBatchResponse batchResponse = postBatchRequest(batchRequest); writeXmlObject(servletResponse, batchResponse); } else { AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri); if (!isValidLocalHagId(containerAddress.getHagId())) servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); String containerName = containerAddress.getContainerName(); if (containerName != null) { ContentInstance ci = (ContentInstance) readXmlObject(servletRequest); ci = postContentInstance(containerAddress, ci); if (ci == null) servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); else if (ServiceClusterProxy.isAnUnconfirmedCommand(containerAddress)) servletResponse.setStatus(HttpServletResponse.SC_ACCEPTED); else servletResponse.setStatus(HttpServletResponse.SC_OK); writeXmlObject(servletResponse, ci); } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } commitApplianceConfigurationUpdates(); } catch (Exception e) { log.error("service: error while parsing local request", e); servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.energy_home.jemma.internal.shapi.HapProxy.java
protected void doDelete(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String requestUri = servletRequest.getRequestURI(); initResponse(servletResponse);//w ww. ja va 2 s .c o m requestUri = replaceFilters(requestUri, false); if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) { try { if (requestUri.startsWith(subscriptionItemsAddressedId)) { if (requestUri.endsWith(M2MContainerAddress.ALL_ID_FILTER)) servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); else { String subscriptionId = requestUri.substring(subscriptionItemsAddressedId.length() + 1, requestUri.length()); SubscriptionInfo subscriptionInfo = null; synchronized (subscriptionInfos) { for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) { subscriptionInfo = (SubscriptionInfo) iterator.next(); if (subscriptionInfo.subscription.getId().equals(subscriptionId)) { iterator.remove(); break; } } } } } else { AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri); if (!isValidLocalHagId(containerAddress.getHagId())) servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); String appliancePid = containerAddress.getAppliancePid(); if (containerAddress.getAppliancePid() != null && containerAddress.getEndPointId() == null && containerAddress.getContainerName() == null) { ContentInstance ci = hapService.getM2MHapService() .getLocalContentInstance(containerAddress); boolean result = false; // Only existing resources are deleted if (ci != null) { result = appliancesProxy.deleteAppliance(appliancePid); if (!result) { servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { servletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } ContentInstance ci = new ContentInstance(); ci.setId(System.currentTimeMillis()); writeXmlObject(servletResponse, ci); } } catch (Exception e) { log.error("service: error while parsing local request", e); servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.energy_home.jemma.internal.shapi.M2MLocalService.java
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String requestUri = servletRequest.getRequestURI(); initResponse(servletResponse);/* w ww. ja v a 2s. c om*/ requestUri = replaceFilters(requestUri, false); if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) { try { if (requestUri.equals(subscriptionItemsAddressedId)) { long now = System.currentTimeMillis(); Subscription subscription = (Subscription) readXmlObject(servletRequest); if (subscription.getId() != null || subscription.getContact() == null) { servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) { // Only one subscription for each contact uri is allowed (last subscription overwrite a previous existing one) if (subscription.getContact() .equals(((SubscriptionInfo) iterator.next()).subscription.getContact())) { iterator.remove(); break; } } subscription.setCreationTime(now); subscription.setLastModifiedTime(now); subscription.setId(UUID.randomUUID().toString()); writeXmlObject(servletResponse, subscription); subscriptionInfos.add(new SubscriptionInfo(subscription)); } } else if (requestUri.endsWith(M2MConstants.URL_CIS_BATCH_REQUEST)) { ContentInstancesBatchRequest batchRequest = (ContentInstancesBatchRequest) readXmlObject( servletRequest); ContentInstancesBatchResponse batchResponse = postBatchRequest(batchRequest); writeXmlObject(servletResponse, batchResponse); } else { try { AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri); if (!isValidLocalHagId(containerAddress.getHagId())) servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); String containerName = containerAddress.getContainerName(); if (containerName != null) { ContentInstance ci = (ContentInstance) readXmlObject(servletRequest); ci = postContentInstance(containerAddress, ci); if (ci == null) servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); else if (ServiceClusterProxy.isAnUnconfirmedCommand(containerAddress)) servletResponse.setStatus(HttpServletResponse.SC_ACCEPTED); else servletResponse.setStatus(HttpServletResponse.SC_OK); writeXmlObject(servletResponse, ci); } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { LOG.error("Exception on doPost", e); servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } commitApplianceConfigurationUpdates(); } catch (Exception e) { LOG.error("service: error while parsing local request", e); servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else { servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } }