List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:de.innovationgate.wgpublisher.WGPDispatcher.java
public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { if (!isServePages()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Website is currently updating configuration. Please try again later."); return;//from w w w . j av a 2 s. c o m } Date startDate = new Date(); if (this._contextPath == null) { this._contextPath = request.getContextPath(); this._listenPort = request.getServerPort(); } WGARequestInformation reqInfo = (WGARequestInformation) request .getAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME); try { // Parse request WGPRequestPath path = WGPRequestPath.parseRequest(this, request, response); request.setAttribute(WGACore.ATTRIB_REQUESTPATH, path); // If database login failed or access was denied exit immediately if (!path.isProceedRequest()) { return; } // Set access logging for this request if (path.getDatabase() != null) { String accessLoggingEnabled = (String) path.getDatabase() .getAttribute(WGACore.DBATTRIB_ENABLE_ACCESSLOGGING); if (accessLoggingEnabled != null) { if (reqInfo != null) { reqInfo.setLoggingEnabled(Boolean.parseBoolean(accessLoggingEnabled)); } } } int iPathType = path.getPathType(); // Treatment of special URL types String dbKey = path.getDatabaseKey(); if (iPathType == WGPRequestPath.TYPE_INVALID) { throw new HttpErrorException(404, "Invalid path: " + path.getBasePath(), dbKey); } if (iPathType == WGPRequestPath.TYPE_INVALID_DB) { throw new HttpErrorException(404, "Specified application '" + dbKey + "' is unknown", null); } if (iPathType == WGPRequestPath.TYPE_UNKNOWN_CONTENT) { sendNoContentNotification(path, request, response, path.getDatabase()); return; } if (iPathType == WGPRequestPath.TYPE_GOTO_HOMEPAGE) { iPathType = determineHomepage(request, path, iPathType); } if (iPathType == WGPRequestPath.TYPE_UNAVAILABLE_DB) { throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The website is currently unavailable", path.getDatabaseKey()); } if (iPathType == WGPRequestPath.TYPE_UNDEFINED_HOMEPAGE) { throw new HttpErrorException( HttpServletResponse.SC_NOT_FOUND, "No home page was defined for app '" + path.getDatabaseKey() + "'. Please specify an explicit content path.", path.getDatabaseKey()); } if (iPathType == WGPRequestPath.TYPE_TMLDEBUG) { _tmlDebugger.performDebugMode(request, response, request.getSession()); return; } if (iPathType == WGPRequestPath.TYPE_JOBLOG) { sendJobLog(request, response, request.getSession()); return; } if (iPathType == WGPRequestPath.TYPE_LOGOUT) { WGDatabase db = (WGDatabase) _core.getContentdbs().get(dbKey); String domain = (String) db.getAttribute(WGACore.DBATTRIB_DOMAIN); _core.logout(domain, request.getSession(), request, response, true); removeSessionCookie(response, request.getSession(), db); iPathType = WGPRequestPath.TYPE_REDIRECT; } if (iPathType == WGPRequestPath.TYPE_FAVICON) { String faviconPath = determineFavicon(request); if (faviconPath != null) { iPathType = WGPRequestPath.TYPE_REDIRECT; path.setResourcePath(faviconPath); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Favicon not defined"); return; } } if (iPathType == WGPRequestPath.TYPE_TMLFORM) { dispatchTmlFormRequest(path, request, response); return; } // Treatment of base URL Types if (iPathType == WGPRequestPath.TYPE_REDIRECT) { String url = path.getResourcePath(); if (path.appendQueryString() == true && request.getQueryString() != null && !request.getQueryString().equals("")) { if (url.indexOf("?") != -1) { url += "&" + request.getQueryString(); } else { url += "?" + request.getQueryString(); } } if (path.isPermanentRedirect()) { sendPermanentRedirect(response, url); } else { sendRedirect(request, response, url); } } else if (iPathType != WGPRequestPath.TYPE_RESOURCE && iPathType != WGPRequestPath.TYPE_STATICTML && !_core.getContentdbs().containsKey(path.getDatabaseKey())) { throw new HttpErrorException(404, "Database '" + dbKey + "' is unknown", null); } else { String requestMethod = request.getMethod().toLowerCase(); switch (iPathType) { case (WGPRequestPath.TYPE_TML): case (WGPRequestPath.TYPE_TITLE_PATH): // Fetch the redirect cookie Cookie lastRedirectCookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_LASTREDIRECT)) { lastRedirectCookie = cookie; break; } } } // If path is not complete redirect it to the complete path, if possible. Set redirect cookie to prevent endless redirections if (!path.isCompletePath()) { String redirectPath = path.expandToCompletePath(request); if (isRedirectable(request, redirectPath, lastRedirectCookie)) { lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT, Hex.encodeHexString(redirectPath.getBytes("UTF-8"))); lastRedirectCookie.setMaxAge(-1); lastRedirectCookie.setPath("/"); ((WGCookie) lastRedirectCookie).addCookieHeader(response); sendRedirect(request, response, redirectPath); break; } } // Delete redirect cookie when exists on normal dispatching if (lastRedirectCookie != null) { lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT, ""); lastRedirectCookie.setMaxAge(0); lastRedirectCookie.setPath("/"); ((WGCookie) lastRedirectCookie).addCookieHeader(response); } // Dispatch dispatchTmlRequest(path, request, response, startDate); break; case (WGPRequestPath.TYPE_FILE): dispatchFileRequest(path, request, response); break; case (WGPRequestPath.TYPE_CSS): case (WGPRequestPath.TYPE_JS): dispatchCssjsRequest(path, request, response); break; case (WGPRequestPath.TYPE_RESOURCE): dispatchResourceRequest(path, request, response); break; case (WGPRequestPath.TYPE_STATICTML): dispatchStaticTmlRequest(path, request, response); break; default: throw new HttpErrorException(500, "Invalid url format", dbKey); } } // moved from finally block to ensure errorpage can be displayed commitResponse(response); } catch (ClientAccessException exc) { response.sendError(403, exc.getMessage()); } catch (AjaxFailureException exc) { handleAjaxFailure(exc, request, response); } catch (HttpErrorException exc) { request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc); ProblemOccasion occ = new PathDispatchingOccasion(request, exc.getDbHint()); _core.getProblemRegistry().addProblem( Problem.create(occ, "dispatching.http404#" + request.getRequestURL(), ProblemSeverity.LOW)); if (!response.isCommitted()) { // throw exception to display errorpage - with senderror() the // applicationserver use the buildin errorpage if (exc.getCode() == HttpServletResponse.SC_NOT_FOUND || exc.getCode() == HttpServletResponse.SC_FORBIDDEN || exc.getCode() == HttpServletResponse.SC_PRECONDITION_FAILED) { response.sendError(exc.getCode(), exc.getMessage()); } else { _log.error("Exception in processing request from " + request.getRemoteAddr() + " to URL " + String.valueOf(request.getRequestURL())); throw new ServletException(exc); } } } catch (SocketException exc) { _log.warn("Socket Exception: " + exc.getMessage()); } catch (Exception exc) { _log.error("Exception in processing of request URL " + String.valueOf(request.getRequestURL()), exc); request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc); throw new ServletException(exc); } catch (Error err) { _log.error("Error in processing of request URL " + String.valueOf(request.getRequestURL()), err); request.setAttribute(WGACore.ATTRIB_EXCEPTION, err); throw new ServletException(err); } finally { if (reqInfo != null) { reqInfo.setCommited(true); } } }
From source file:org.jahia.modules.userregistration.actions.NewReservation.java
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, final Resource resource, JCRSessionWrapper session, final Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception { final HttpServletRequest requ = req; final String nom = getParameter(parameters, "nom"); final String prenom = getParameter(parameters, "prenom"); final String adresse = getParameter(parameters, "adresse"); final String codePostal = getParameter(parameters, "codePostal"); final String ville = getParameter(parameters, "ville"); final String telephone = getParameter(parameters, "telephone"); final String email = getParameter(parameters, "email"); final String places = getParameter(parameters, "places"); if (StringUtils.isEmpty(nom) || StringUtils.isEmpty(prenom) || StringUtils.isEmpty(adresse) || StringUtils.isEmpty(email)) { return ActionResult.BAD_REQUEST; }/*from ww w .ja v a2s.co m*/ /* * final Properties properties = new Properties(); * properties.put("j:email",parameters.get("desired_email").get(0)); * properties.put("j:firstName",parameters.get("desired_firstname").get( * 0)); * properties.put("j:lastName",parameters.get("desired_lastname").get(0) * ); for (Map.Entry<String, List<String>> param : * parameters.entrySet()) { if (param.getKey().startsWith("j:")) { * String value = getParameter(parameters, param.getKey()); if (value != * null) { properties.put(param.getKey(), value); } } } */ JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Boolean>() { @Override public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { // final JCRUserNode user = // userManagerService.createUser(username, password, properties, // session); // session.save(); JCRNodeWrapper reservationFolder = session.getNode("/sites/LARBRE/contents/reservations"); JCRNodeWrapper emailFolder; if (reservationFolder.hasNode(email)) emailFolder = reservationFolder.getNode(email); else emailFolder = reservationFolder.addNode(email, "jnt:contentFolder"); session.save(); String key = generateKey(email); JCRNodeWrapper uneReservation = emailFolder.addNode(key, "jnt:uneReservation"); uneReservation.setProperty("nom", nom); uneReservation.setProperty("prenom", prenom); uneReservation.setProperty("adresse", adresse); uneReservation.setProperty("codePostal", codePostal); uneReservation.setProperty("ville", ville); uneReservation.setProperty("telephone", telephone); uneReservation.setProperty("email", email); uneReservation.setProperty("places", places); session.save(); if (mailService.isEnabled()) { // Prepare mail to be sent : boolean toAdministratorMail = Boolean .valueOf(getParameter(parameters, "toAdministrator", "false")); String cc = toAdministratorMail ? mailService.getSettings().getTo() : getParameter(parameters, "cc"); String from = cc; logger.info("send copie to :" + cc); //String cc = parameters.get("cc") == null ? null : getParameter(parameters, "cc"); String bcc = parameters.get("bcc") == null ? null : getParameter(parameters, "bcc"); Map<String, Object> bindings = new HashMap<String, Object>(); final JCRNodeWrapper node = resource.getNode(); logger.info("********Node :" + node.getName()); logger.info("Template path:" + templatePath); bindings.put("reservation", uneReservation); bindings.put("confirmationlink", requ.getScheme() + "://" + requ.getServerName() + ":" + requ.getServerPort() + Jahia.getContextPath() + Render.getRenderServletPath() + "/live/" + node.getLanguage() + node.getPath() + ".confirmationReservation.do?email=" + email + "&key=" + key + "&copie=" + cc + "&confirmationPage=" + parameters.get("confirmationReservationPage").get(0)); try { mailService.sendMessageWithTemplate(templatePath, bindings, email, from, cc, bcc, resource.getLocale(), "Jahia User Registration"); } catch (ScriptException e) { logger.error("Error sending e-mail notification for user creation", e); } } return true; } }); return new ActionResult(HttpServletResponse.SC_ACCEPTED, parameters.get("newReservationPage").get(0), new JSONObject()); }
From source file:org.apache.jsp.fileUploader_jsp.java
private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId, Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request, HttpServletResponse response) {/*from w ww. j a va2 s . c om*/ String charset = "UTF-8"; String url = ""; try { if (isJson) { //first check if bytes are actually json try { new JsonParser().parse(new String(bytes)); } catch (Exception ex) { return "Failed, file was not valid JSON"; } if (newShare) url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } else { if (newShare) url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/binary/" + prevId + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } if (localCookie) CookieHandler.setDefault(cm); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); } if (mimeType != null && mimeType.length() > 0) connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset); DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(bytes); DataInputStream responseStream = new DataInputStream(connection.getInputStream()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = responseStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } String json = buffer.toString(); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } buffer.flush(); buffer.close(); output.close(); responseStream.close(); if (isJson) { jsonResponse jr = new Gson().fromJson(json, jsonResponse.class); if (jr == null) { return "Failed: " + json; } if (jr.response.success == true) { if (jr.data != null && jr.data._id != null) { addRemoveCommunities(jr.data._id, communities, request, response); return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload } } return "Upload Failed: " + jr.response.message; } else { modResponse mr = new Gson().fromJson(json, modResponse.class); if (mr == null) { return "Failed: " + json; } if (mr.response.success == true) { if (prevId != null && mr.data == null) { addRemoveCommunities(prevId, communities, request, response); return prevId; } else { addRemoveCommunities(mr.data, communities, request, response); return mr.data; //When a new upload, mr.data contains the ShareID for the upload } } else { return "Upload Failed: " + mr.response.message; } } } catch (IOException e) { e.printStackTrace(); return "Upload Failed: " + e.getMessage(); } }
From source file:com.iisigroup.cap.base.handler.CheckTimeoutHandler.java
@SuppressWarnings({ "unchecked", "unused" }) public Result checkTO(Request request) throws CapException { AjaxFormResult result = new AjaxFormResult(); HttpServletRequest sreq = (HttpServletRequest) request.getServletRequest(); String refPath = sreq.getHeader("referer"); refPath = StringEscapeUtils.unescapeHtml(refPath); String path = sreq.getPathInfo(); boolean isNewSes = sreq.getSession(false).isNew(); String isFresh = request.get("REFSH_TO", ""); HttpSession session = sreq.getSession(false); Map<String, String> map = (Map<String, String>) session.getAttribute(TOCM); String curPage = request.get(CCPAGE_NO); if (curPage.lastIndexOf("ap") >= 0) { if (map != null && map.containsKey(curPage)) { // DO NOT THING } else {/* w w w.j a v a2 s . c o m*/ map = new HashMap<String, String>(); session.setAttribute(TOCM, map); } } if (map == null) { map = new HashMap<String, String>(); } if (!CapString.isEmpty(curPage)) { if (map.containsKey(curPage) && !"Y".equals(isFresh)) { String openTime = map.get(curPage); // ??db?? sysProp.remove(TIME_OUT); String stout = sysProp.get(TIME_OUT); if (CapString.isEmpty(stout)) { stout = "10"; // default 10mins } // ?? String lastPageNo = getLastRcordTOMC(map); if (lastPageNo.compareTo(curPage) != 0) { /* * ??timeout? ??? */ if (map.get(lastPageNo) != null) { long lastOpenTime = Long.parseLong(map.get(lastPageNo)); // Calculate difference in milliseconds long curTime = CapDate.getCurrentTimestamp().getTime(); long diff = curTime - lastOpenTime; // Difference in seconds long diffSec = diff / 1000; long propTimeout = (Long.parseLong(stout) + 1) * 60; if (diffSec > propTimeout) { map.remove(lastPageNo); session.setAttribute(TOCM, map); } } // ?????? return result; } long time = Long.parseLong(openTime); Timestamp ts1 = new Timestamp(time); String d12str = CapDate.convertTimestampToString(ts1, "HH:mm:ss.sss"); long curTime = CapDate.getCurrentTimestamp().getTime(); long propTimeOut = sreq.getSession(false).getMaxInactiveInterval(); if (!CapString.isEmpty(stout)) { propTimeOut = Long.parseLong(stout); long remindTime = (propTimeOut - 1) * 60; propTimeOut = propTimeOut * 60; // Calculate difference in milliseconds long diff = curTime - time; // Difference in seconds long diffSec = diff / 1000; String isContinues = request.get("isCntnu"); if ("true".equals(isContinues)) { map.put(curPage, String.valueOf(curTime)); session.setAttribute(TOCM, map); } else if (CapString.isEmpty(isContinues) && diffSec >= remindTime) { result.set("SHOW_REMIND", "true"); } // ?falsetimeout(user??,1??) else if ("false".equals(isContinues) || diffSec > propTimeOut) { String webApUrl = sysProp.get("WEB_AP_URL"); String st1 = sreq.getScheme(); String st2 = sreq.getServerName(); int port = sreq.getServerPort(); String st4 = sreq.getContextPath(); webApUrl = st1 + "://" + st2 + ":" + port + st4; result.set("errorPage", st4 + "/page/timeout"); map.remove(curPage); session.setAttribute(TOCM, map); } } } else { long curTime = CapDate.getCurrentTimestamp().getTime(); map.put(curPage, String.valueOf(curTime)); session.setAttribute(TOCM, map); } } return result; }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
protected Map systemInfo(HttpServletRequest req) { String baseURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();//from w w w. j a v a2s . co m Map info = new LinkedHashMap(); info.put("sampleObject", sampleObject); info.put("adminEmail", adminEmail); info.put("fedoraCompat", fedoraCompat); info.put("baseURL", baseURL); return info; }
From source file:com.devnexus.ting.web.controller.RegisterController.java
@RequestMapping(value = "/s/registerPageTwo", method = RequestMethod.POST) public String validateDetailsForm(HttpServletRequest request, Model model, @Valid RegistrationDetails registerForm, BindingResult result) { Event currentEvent = businessService.getCurrentEvent(); EventSignup eventSignup = businessService.getEventSignup(); PaymentMethod paymentMethod = PaymentMethod.PAYPAL; prepareHeader(currentEvent, model);/*w ww .j av a 2 s . co m*/ model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup)); model.addAttribute("registrationDetails", registerForm); registerForm.setFinalCost(getTotal(registerForm)); registerForm.setEvent(currentEvent); if (result.hasErrors()) { return "register2"; } for (int index = 0; index < registerForm.getOrderDetails().size(); index++) { TicketOrderDetail orderDetails = registerForm.getOrderDetails().get(index); TicketGroup ticketGroup = businessService.getTicketGroup(orderDetails.getTicketGroup()); if (!com.google.common.base.Strings.isNullOrEmpty(orderDetails.getCouponCode()) && ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0) { if (!hasCode(ticketGroup.getCouponCodes(), orderDetails.getCouponCode())) { result.addError(new FieldError("registrationDetails", "orderDetails[" + index + "].couponCode", "Invalid Coupon Code.")); } } if (StringUtils.isEmpty(orderDetails.getFirstName())) { result.rejectValue("orderDetails[" + index + "].firstName", "firstName.isRequired", "First Name is required."); } if (StringUtils.isEmpty(orderDetails.getLastName())) { result.rejectValue("orderDetails[" + index + "].lastName", "lastName.isRequired", "Last Name is required."); } if (StringUtils.isEmpty(orderDetails.getEmailAddress())) { result.rejectValue("orderDetails[" + index + "].emailAddress", "emailAddress.isReq uired", "Email Address is required."); } if (StringUtils.isEmpty(orderDetails.getCity())) { result.rejectValue("orderDetails[" + index + "].city", "city.isRequired", "City is required."); } if (StringUtils.isEmpty(orderDetails.getState())) { result.rejectValue("orderDetails[" + index + "].state", "state.isRequired", "State is required."); } if (StringUtils.isEmpty(orderDetails.getCountry())) { result.rejectValue("orderDetails[" + index + "].country", "country.isRequired", "Country is required."); } if (StringUtils.isEmpty(orderDetails.getJobTitle())) { result.rejectValue("orderDetails[" + index + "].jobTitle", "jobTitle.isRequired", "Job Title is required."); } if (StringUtils.isEmpty(orderDetails.getCompany())) { result.rejectValue("orderDetails[" + index + "].company", "company.isRequired", "Company is required."); } } if (result.hasErrors()) { return "register2"; } for (TicketOrderDetail detail : registerForm.getOrderDetails()) { detail.setRegistration(registerForm); } switch (paymentMethod) { case INVOICE: registerForm.setPaymentState(RegistrationDetails.PaymentState.REQUIRES_INVOICE); registerForm.setFinalCost(getTotal(registerForm)); businessService.createPendingRegistrationForm(registerForm); return "index"; case PAYPAL: registerForm.setPaymentState(RegistrationDetails.PaymentState.PAYPAL_CREATED); registerForm.setFinalCost(getTotal(registerForm)); registerForm = businessService.createPendingRegistrationForm(registerForm); String baseUrl = String.format("%s://%s:%d/", request.getScheme(), request.getServerName(), request.getServerPort()); Payment createdPayment = runPayPal(registerForm, baseUrl); return "redirect:" + createdPayment.getLinks().stream().filter(link -> { return link.getRel().equals("approval_url"); }).findFirst().get().getHref(); default: throw new IllegalStateException("The system did not understand the payment type."); } }
From source file:org.openmrs.module.feedback.web.AddFeedbackFormController.java
@Override protected Boolean formBackingObject(HttpServletRequest request) throws Exception { /* To check wheather or not the subject , severity and feedback is empty or not */ Boolean feedbackMessage = false; String text = ""; String subject = request.getParameter("subject"); String severity = request.getParameter("severity"); String feedback = request.getParameter("feedback"); if (StringUtils.hasLength(subject) && StringUtils.hasLength(severity) && StringUtils.hasLength(severity)) { Object o = Context.getService(FeedbackService.class); FeedbackService service = (FeedbackService) o; Feedback s = new Feedback(); s.setSubject(request.getParameter("subject")); s.setSeverity(request.getParameter("severity")); /* To get the Stacktrace of the page from which the feedback is submitted */ StackTraceElement[] c = Thread.currentThread().getStackTrace(); if ("Yes".equals(request.getParameter("pagecontext"))) { for (int i = 0; i < c.length; i++) { feedback = feedback + System.getProperty("line.separator") + c[i].getFileName() + c[i].getMethodName() + c[i].getClass() + c[i].getLineNumber(); }// w ww . j a va 2s . c om } s.setContent(feedback); /* file upload in multiplerequest */ if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = (MultipartFile) multipartRequest.getFile("file"); if (!file.isEmpty()) { if (file.getSize() <= 5242880) { if (file.getOriginalFilename().endsWith(".jpeg") || file.getOriginalFilename().endsWith(".jpg") || file.getOriginalFilename().endsWith(".gif") || file.getOriginalFilename().endsWith(".png")) { s.setMessage(file.getBytes()); } else { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "feedback.notification.feedback.error"); return false; } } else { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "feedback.notification.feedback.error"); return false; } } } /* Save the Feedback */ service.saveFeedback(s); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, Context.getAdministrationService().getGlobalProperty("feedback.ui.notification")); if ("Yes".equals(Context.getUserContext().getAuthenticatedUser() .getUserProperty("feedback_notificationReceipt"))) { try { // Create Message Message message = new Message(); message.setSender( Context.getAdministrationService().getGlobalProperty("feedback.notification.email")); message.setRecipients( Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email")); message.setSubject("Feedback submission confirmation mail"); message.setContent(Context.getAdministrationService().getGlobalProperty("feedback.notification") + "Ticket Number: " + s.getFeedbackId() + " Subject :" + s.getSubject()); message.setSentDate(new Date()); // Send message Context.getMessageService().send(message); } catch (Exception e) { log.error("Unable to sent the email to the Email : " + Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email")); } } try { // Create Message Message message = new Message(); message.setSender( Context.getAdministrationService().getGlobalProperty("feedback.notification.email")); message.setRecipients( Context.getAdministrationService().getGlobalProperty("feedback.admin.notification.email")); message.setSubject("New feedback submitted"); message.setContent( Context.getAdministrationService().getGlobalProperty("feedback.admin.notification") + "Ticket Number: " + s.getFeedbackId() + " Subject : " + s.getSubject() + " Take Action :" + request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/module/feedback/feedback.form?feedbackId=" + s.getFeedbackId() + "#command"); message.setSentDate(new Date()); // Send message Context.getMessageService().send(message); } catch (Exception e) { log.error("Unable to sent the email to the Email : " + Context.getUserContext() .getAuthenticatedUser().getUserProperty("feedback.admin.notification.email")); } feedbackMessage = true; } /* Reserved for future use for showing that the data is saved and the feedback is submitted */ log.debug("Returning hello world text: " + text); return feedbackMessage; }
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 ww.ja v a 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:com.groupdocs.ui.servlets.ViewDocument.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.addHeader("Content-Type", "application/json"); ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(), ViewDocumentParameters.class); ViewDocumentResponse result = new ViewDocumentResponse(); FileData fileData = ViewerUtils.factoryFileData(params.getPath()); DocumentInfoContainer docInfo = null; try {/* w ww . j av a 2s. c om*/ result.setDocumentDescription( (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false)); } catch (ParseException x) { throw new ServletException(x); } if (params.getUseHtmlBasedEngine()) { try { docInfo = ViewerUtils.getViewerHtmlHandler() .getDocumentInfo(new DocumentInfoOptions(params.getPath())); } catch (Exception x) { throw new ServletException(x); } result.setPageCss(new String[0]); result.setLic(true); result.setPdfDownloadUrl(GetPdfDownloadUrl(params)); result.setPdfPrintUrl(GetPdfPrintUrl(params)); result.setUrl(GetFileUrl(params)); result.setPath(params.getPath()); result.setName(params.getPath()); result.setDocType(docInfo.getDocumentType()); result.setFileType(docInfo.getFileType()); HtmlOptions htmlOptions = new HtmlOptions(); htmlOptions.setResourcesEmbedded(true); htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath() + "&pageNumber={page-number}&resourceName="); if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString()) && params.getPreloadPagesCount().intValue() > 0) { htmlOptions.setPageNumber(1); htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue()); } String[] cssList = null; RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList); List<PageHtml> htmlPages = GetHtmlPages(params.getPath(), htmlOptions); cssList = tempRef_cssList.argValue; ArrayList<String> pagesContent = new ArrayList<String>(); for (PageHtml page : htmlPages) { pagesContent.add(page.getHtmlContent()); } String[] htmlContent = pagesContent.toArray(new String[0]); result.setPageHtml(htmlContent); result.setPageCss(new String[] { String.join(" ", temp_cssList) }); for (int i = 0; i < result.getPageHtml().length; i++) { String html = result.getPageHtml()[i]; int indexOfScript = html.indexOf("script"); if (indexOfScript > 0) { result.getPageHtml()[i] = html.substring(0, indexOfScript); } } } else { try { docInfo = ViewerUtils.getViewerImageHandler() .getDocumentInfo(new DocumentInfoOptions(params.getPath())); } catch (Exception x) { throw new ServletException(x); } int maxWidth = 0; int maxHeight = 0; for (PageData pageData : docInfo.getPages()) { if (pageData.getHeight() > maxHeight) { maxHeight = pageData.getHeight(); maxWidth = pageData.getWidth(); } } fileData.setDateCreated(new Date()); fileData.setDateModified(docInfo.getLastModificationDate()); fileData.setPageCount(docInfo.getPages().size()); fileData.setPages(docInfo.getPages()); fileData.setMaxWidth(maxWidth); fileData.setMaxHeight(maxHeight); result.setPageCss(new String[0]); result.setLic(true); result.setPdfDownloadUrl(GetPdfDownloadUrl(params)); result.setPdfPrintUrl(GetPdfPrintUrl(params)); result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(), params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(), params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(), params.getSupportPageRotation())); result.setPath(params.getPath()); result.setName(params.getPath()); result.setDocType(docInfo.getDocumentType()); result.setFileType(docInfo.getFileType()); int[] pageNumbers = new int[docInfo.getPages().size()]; int count = 0; for (PageData page : docInfo.getPages()) { pageNumbers[count] = page.getNumber(); count++; } String applicationHost = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params); result.setImageUrls(imageUrls); } new ObjectMapper().writeValue(response.getOutputStream(), result); }
From source file:at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser.java
public static void parse(AuthenticationSession moasession, String target, String oaURL, String bkuURL, String templateURL, String useMandate, String ccc, String module, String action, HttpServletRequest req) throws WrongParametersException, MOAIDException { String targetFriendlyName = null; // String sso = req.getParameter(PARAM_SSO); // escape parameter strings target = StringEscapeUtils.escapeHtml(target); //oaURL = StringEscapeUtils.escapeHtml(oaURL); bkuURL = StringEscapeUtils.escapeHtml(bkuURL); templateURL = StringEscapeUtils.escapeHtml(templateURL); useMandate = StringEscapeUtils.escapeHtml(useMandate); ccc = StringEscapeUtils.escapeHtml(ccc); // sso = StringEscapeUtils.escapeHtml(sso); // check parameter //pvp2.x can use general identifier (equals oaURL in SAML1) // if (!ParamValidatorUtils.isValidOA(oaURL)) // throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); if (!ParamValidatorUtils.isValidUseMandate(useMandate)) throw new WrongParametersException("StartAuthentication", PARAM_USEMANDATE, "auth.12"); if (!ParamValidatorUtils.isValidCCC(ccc)) throw new WrongParametersException("StartAuthentication", PARAM_CCC, "auth.12"); // if (!ParamValidatorUtils.isValidUseMandate(sso)) // throw new WrongParametersException("StartAuthentication", PARAM_SSO, "auth.12"); //check UseMandate flag String useMandateString = null; boolean useMandateBoolean = false; if ((useMandate != null) && (useMandate.compareTo("") != 0)) { useMandateString = useMandate;/*from w ww .j a v a 2s . c o m*/ } else { useMandateString = "false"; } if (useMandateString.compareToIgnoreCase("true") == 0) useMandateBoolean = true; else useMandateBoolean = false; moasession.setUseMandate(useMandateString); //load OnlineApplication configuration OAAuthParameter oaParam; if (moasession.getPublicOAURLPrefix() != null) { Logger.debug("Loading OA parameters for PublicURLPrefix: " + moasession.getPublicOAURLPrefix()); oaParam = AuthConfigurationProvider.getInstance() .getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); if (oaParam == null) throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() }); } else { oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oaURL); if (oaParam == null) throw new AuthenticationException("auth.00", new Object[] { oaURL }); // get target and target friendly name from config String targetConfig = oaParam.getTarget(); String targetFriendlyNameConfig = oaParam.getTargetFriendlyName(); if (StringUtils.isEmpty(targetConfig) || (module.equals(SAML1Protocol.PATH) && !StringUtils.isEmpty(target))) { //INFO: ONLY SAML1 legacy mode // if SAML1 is used and target attribute is given in request // use requested target // check target parameter if (!ParamValidatorUtils.isValidTarget(target)) { Logger.error("Selected target is invalid. Using target: " + target); throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); } } else { // use target from config target = targetConfig; targetFriendlyName = targetFriendlyNameConfig; } // //check useSSO flag // String useSSOString = null; // boolean useSSOBoolean = false; // if ((sso != null) && (sso.compareTo("") != 0)) { // useSSOString = sso; // } else { // useSSOString = "false"; // } // // if (useSSOString.compareToIgnoreCase("true") == 0) // useSSOBoolean = true; // else // useSSOBoolean = false; //moasession.setSsoRequested(useSSOBoolean); moasession.setSsoRequested(true && oaParam.useSSO()); //make always SSO if OA requested it!!!! //Validate BKU URI List<String> allowedbkus = oaParam.getBKUURL(); allowedbkus.addAll(AuthConfigurationProvider.getInstance().getDefaultBKUURLs()); if (!ParamValidatorUtils.isValidBKUURI(bkuURL, allowedbkus)) throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12"); moasession.setBkuURL(bkuURL); if ((!oaParam.getBusinessService())) { if (isEmpty(target)) throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.05"); } else { if (useMandateBoolean) { Logger.error("Online-Mandate Mode for business application not supported."); throw new AuthenticationException("auth.17", null); } target = null; targetFriendlyName = null; } moasession.setPublicOAURLPrefix(oaParam.getPublicURLPrefix()); moasession.setTarget(target); moasession.setBusinessService(oaParam.getBusinessService()); //moasession.setStorkService(oaParam.getStorkService()); Logger.debug( "Business: " + moasession.getBusinessService() + " stork: " + moasession.getStorkService()); moasession.setTargetFriendlyName(targetFriendlyName); moasession.setDomainIdentifier(oaParam.getIdentityLinkDomainIdentifier()); } //check OnlineApplicationURL if (isEmpty(oaURL)) throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.05"); moasession.setOAURLRequested(oaURL); //check AuthURL String authURL = req.getScheme() + "://" + req.getServerName(); if ((req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443) || (req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)) { authURL = authURL.concat(":" + req.getServerPort()); } authURL = authURL.concat(req.getContextPath() + "/"); if (!authURL.startsWith("https:")) throw new AuthenticationException("auth.07", new Object[] { authURL + "*" }); //set Auth URL from configuration moasession.setAuthURL(AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/"); //check and set SourceID if (oaParam.getSAML1Parameter() != null) { String sourceID = oaParam.getSAML1Parameter().getSourceID(); if (MiscUtil.isNotEmpty(sourceID)) moasession.setSourceID(sourceID); } if (MiscUtil.isEmpty(templateURL)) { List<TemplateType> templateURLList = oaParam.getTemplateURL(); List<String> defaulTemplateURLList = AuthConfigurationProvider.getInstance().getSLRequestTemplates(); if (templateURLList != null && templateURLList.size() > 0 && MiscUtil.isNotEmpty(templateURLList.get(0).getURL())) { templateURL = FileUtils.makeAbsoluteURL(oaParam.getTemplateURL().get(0).getURL(), AuthConfigurationProvider.getInstance().getRootConfigFileDir()); Logger.info("No SL-Template in request, load SL-Template from OA configuration (URL: " + templateURL + ")"); } else if ((defaulTemplateURLList.size() > 0) && MiscUtil.isNotEmpty(defaulTemplateURLList.get(0))) { templateURL = FileUtils.makeAbsoluteURL(defaulTemplateURLList.get(0), AuthConfigurationProvider.getInstance().getRootConfigFileDir()); Logger.info("No SL-Template in request, load SL-Template from general configuration (URL: " + templateURL + ")"); } else { Logger.error("NO SL-Tempalte found in OA config"); throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); } } if (!ParamValidatorUtils.isValidTemplate(req, templateURL, oaParam.getTemplateURL())) throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); moasession.setTemplateURL(templateURL); moasession.setCcc(ccc); }