List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:com.occamlab.te.web.TestServlet.java
public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {//from w w w.j av a2 s . c o m FileItemFactory ffactory; ServletFileUpload upload; List /* FileItem */ items = null; HashMap<String, String> params = new HashMap<String, String>(); boolean multipart = ServletFileUpload.isMultipartContent(request); if (multipart) { ffactory = new DiskFileItemFactory(); upload = new ServletFileUpload(ffactory); items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } } } else { Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = (String) paramNames.nextElement(); params.put(name, request.getParameter(name)); } } HttpSession session = request.getSession(); ServletOutputStream out = response.getOutputStream(); String operation = params.get("te-operation"); if (operation.equals("Test")) { TestSession s = new TestSession(); String user = request.getRemoteUser(); File logdir = new File(conf.getUsersDir(), user); String mode = params.get("mode"); RuntimeOptions opts = new RuntimeOptions(); opts.setWorkDir(conf.getWorkDir()); opts.setLogDir(logdir); if (mode.equals("retest")) { opts.setMode(Test.RETEST_MODE); String sessionid = params.get("session"); String test = params.get("test"); if (sessionid == null) { int i = test.indexOf("/"); sessionid = i > 0 ? test.substring(0, i) : test; } opts.setSessionId(sessionid); if (test == null) { opts.addTestPath(sessionid); } else { opts.addTestPath(test); } for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { String profileId = entry.getValue(); int i = profileId.indexOf("}"); opts.addTestPath(sessionid + "/" + profileId.substring(i + 1)); } } s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else if (mode.equals("resume")) { opts.setMode(Test.RESUME_MODE); String sessionid = params.get("session"); opts.setSessionId(sessionid); s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else { opts.setMode(Test.TEST_MODE); String sessionid = LogUtils.generateSessionId(logdir); s.setSessionId(sessionid); String sources = params.get("sources"); s.setSourcesName(sources); SuiteEntry suite = conf.getSuites().get(sources); s.setSuiteName(suite.getId()); // String suite = params.get("suite"); // s.setSuiteName(suite); String description = params.get("description"); s.setDescription(description); opts.setSessionId(sessionid); opts.setSourcesName(sources); opts.setSuiteName(suite.getId()); ArrayList<String> profiles = new ArrayList<String>(); for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { profiles.add(entry.getValue()); opts.addProfile(entry.getValue()); } } s.setProfiles(profiles); s.save(logdir); } String webdir = conf.getWebDirs().get(s.getSourcesName()); // String requestURI = request.getRequestURI(); // String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1); // URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null); URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), request.getRequestURI(), null, null); opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString()); // URI baseURI = new URL(contextURI.toURL(), webdir).toURI(); // String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/"; // opts.setBaseURI(base); //System.out.println(opts.getSourcesName()); TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts); //System.out.println(indexes.get(opts.getSourcesName()).toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); core.setOut(ps); core.setWeb(true); Thread thread = new Thread(core); session.setAttribute("testsession", core); thread.start(); response.setContentType("text/xml"); out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>"); } else if (operation.equals("Stop")) { response.setContentType("text/xml"); TECore core = (TECore) session.getAttribute("testsession"); if (core != null) { core.stopThread(); session.removeAttribute("testsession"); out.println("<stopped/>"); } else { out.println("<message>Could not retrieve core object</message>"); } } else if (operation.equals("GetStatus")) { TECore core = (TECore) session.getAttribute("testsession"); response.setContentType("text/xml"); out.print("<status"); if (core.getFormHtml() != null) { out.print(" form=\"true\""); } if (core.isThreadComplete()) { out.print(" complete=\"true\""); session.removeAttribute("testsession"); } out.println(">"); out.print("<![CDATA["); // out.print(core.getOutput()); out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' ')); out.println("]]>"); out.println("</status>"); } else if (operation.equals("GetForm")) { TECore core = (TECore) session.getAttribute("testsession"); String html = core.getFormHtml(); core.setFormHtml(null); response.setContentType("text/html"); out.print(html); } else if (operation.equals("SubmitForm")) { TECore core = (TECore) session.getAttribute("testsession"); Document doc = DB.newDocument(); Element root = doc.createElement("values"); doc.appendChild(root); for (String key : params.keySet()) { if (!key.startsWith("te-")) { Element valueElement = doc.createElement("value"); valueElement.setAttribute("key", key); valueElement.appendChild(doc.createTextNode(params.get(key))); root.appendChild(valueElement); } } if (multipart) { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField() && !item.getName().equals("")) { File uploadedFile = new File(core.getLogDir(), StringUtils.getFilenameFromString(item.getName())); item.write(uploadedFile); Element valueElement = doc.createElement("value"); String key = item.getFieldName(); valueElement.setAttribute("key", key); if (core.getFormParsers().containsKey(key)) { Element parser = core.getFormParsers().get(key); URL url = uploadedFile.toURI().toURL(); Element resp = core.parse(url.openConnection(), parser, doc); Element content = DomUtils.getElementByTagName(resp, "content"); if (content != null) { Element child = DomUtils.getChildElement(content); if (child != null) { valueElement.appendChild(child); } } } else { Element fileEntry = doc.createElementNS(CTL_NS, "file-entry"); fileEntry.setAttribute("full-path", uploadedFile.getAbsolutePath().replace('\\', '/')); fileEntry.setAttribute("media-type", item.getContentType()); fileEntry.setAttribute("size", String.valueOf(item.getSize())); valueElement.appendChild(fileEntry); } root.appendChild(valueElement); } } } core.setFormResults(doc); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Form Submitted</title></head>"); out.print("<body onload=\"window.parent.update()\"></body>"); out.println("</html>"); } } catch (Throwable t) { throw new ServletException(t); } }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
public String harvestStudy_action() { String link = null;/*from w w w . jav a2s . c o m*/ HarvestingDataverse hd = null; try { hd = harvestingDataverseService.find(harvestDVId); Long studyId = harvesterService.getRecord(hd, harvestIdentifier, hd.getHarvestFormatType().getMetadataPrefix()); if (studyId != null) { indexService.updateStudy(studyId); // create link String HttpServletRequest req = (HttpServletRequest) getExternalContext().getRequest(); link = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/dv/" + hd.getVdc().getAlias() + "/faces/study/StudyPage.xhtml?studyId=" + studyId; } addMessage("harvestMessage", "Harvest succeeded" + (link == null ? "." : ": " + link)); } catch (Exception e) { e.printStackTrace(); addMessage("harvestMessage", "Harvest failed: An unexpected error occurred trying to get this record."); addMessage("harvestMessage", "Exception message: " + e.getMessage()); addMessage("harvestMessage", "Harvest URL: " + hd.getServerUrl() + "?verb=GetRecord&identifier=" + harvestIdentifier + "&metadataPrefix=" + hd.getHarvestFormatType().getMetadataPrefix()); } return null; }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
public String importSingleFile_action() { //L.A.if(inputFile==null) return null; //L.A.File originalFile = inputFile.getFile(); //File originalFile = null; if (uploadedDdiFile != null) { try {//from w ww.j ava 2 s .co m Study study = studyService.importStudy(uploadedDdiFile, getImportFileFormat(), getImportDVId(), getVDCSessionBean().getLoginBean().getUser().getId()); indexService.updateStudy(study.getId()); // create result message HttpServletRequest req = (HttpServletRequest) getExternalContext().getRequest(); String studyURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/dv/" + study.getOwner().getAlias() + "/faces/study/StudyPage.xhtml?globalId=" + study.getGlobalId(); addMessage("importMessage", "Import succeeded."); addMessage("importMessage", "Study URL: " + studyURL); } catch (Exception e) { e.printStackTrace(); addMessage("harvestMessage", "Import failed: An unexpected error occurred trying to import this study."); addMessage("harvestMessage", "Exception message: " + e.getMessage()); } } return null; }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.FormAuthenticator.java
/** Perform form authentication. * Called from SecurityHandler./*w ww .j av a2 s . c o m*/ * @return UserPrincipal if authenticated else null. */ public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest httpRequest, HttpResponse httpResponse) throws IOException { HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper(); HttpServletResponse response = httpResponse == null ? null : (HttpServletResponse) httpResponse.getWrapper(); // Handle paths String uri = pathInContext; // Setup session HttpSession session = request.getSession(response != null); if (session == null) return null; // Handle a request for authentication. if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) { // Check the session object for login info. FormCredential form_cred = new FormCredential(); form_cred.authenticate(realm, request.getParameter(__J_USERNAME), request.getParameter(__J_PASSWORD), httpRequest); String nuri = (String) session.getAttribute(__J_URI); if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = "/"; } if (form_cred._userPrincipal != null) { // Authenticated OK if (log.isDebugEnabled()) log.debug("Form authentication OK for " + form_cred._jUserName); session.removeAttribute(__J_URI); // Remove popped return URI. httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH); httpRequest.setAuthUser(form_cred._jUserName); httpRequest.setUserPrincipal(form_cred._userPrincipal); session.setAttribute(__J_AUTHENTICATED, form_cred); // Sign-on to SSO mechanism if (realm instanceof SSORealm) { ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal, new Password(form_cred._jPassword)); } // Redirect to original request if (response != null) { response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); } } else if (response != null) { if (log.isDebugEnabled()) log.debug("Form authentication FAILED for " + form_cred._jUserName); if (_formErrorPage != null) { response.setContentLength(0); response.sendRedirect( response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage))); } else { response.sendError(HttpResponse.__403_Forbidden); } } // Security check is always false, only true after final redirection. return null; } // Check if the session is already authenticated. FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED); if (form_cred != null) { // We have a form credential. Has it been distributed? if (form_cred._userPrincipal == null) { // This form_cred appears to have been distributed. Need to reauth form_cred.authenticate(realm, httpRequest); // Sign-on to SSO mechanism if (form_cred._userPrincipal != null && realm instanceof SSORealm) { ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal, new Password(form_cred._jPassword)); } } else if (!realm.reauthenticate(form_cred._userPrincipal)) // Else check that it is still authenticated. form_cred._userPrincipal = null; // If this credential is still authenticated if (form_cred._userPrincipal != null) { if (log.isDebugEnabled()) log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName()); httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH); httpRequest.setAuthUser(form_cred._userPrincipal.getName()); httpRequest.setUserPrincipal(form_cred._userPrincipal); return form_cred._userPrincipal; } else session.setAttribute(__J_AUTHENTICATED, null); } else if (realm instanceof SSORealm) { // Try a single sign on. Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse); if (httpRequest.hasUserPrincipal()) { form_cred = new FormCredential(); form_cred._userPrincipal = request.getUserPrincipal(); form_cred._jUserName = form_cred._userPrincipal.getName(); if (cred != null) form_cred._jPassword = cred.toString(); if (log.isDebugEnabled()) log.debug("SSO for " + form_cred._userPrincipal); httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH); session.setAttribute(__J_AUTHENTICATED, form_cred); return form_cred._userPrincipal; } } // Don't authenticate authform or errorpage if (isLoginOrErrorPage(pathInContext)) return SecurityConstraint.__NOBODY; // redirect to login page if (response != null) { if (httpRequest.getQuery() != null) uri += "?" + httpRequest.getQuery(); session.setAttribute(__J_URI, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URI.addPaths(request.getContextPath(), uri)); response.setContentLength(0); response.sendRedirect( response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage))); } return null; }
From source file:MyServlet.UserController.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); Object message;/*from ww w .j a va 2 s.c o m*/ Object userResetToken; String url = "/main.jsp"; action = request.getParameter("action"); System.out.println("action" + action); PrintWriter writer = response.getWriter(); HttpSession session = request.getSession(); User theUser = (User) session.getAttribute("theUser"); writer.println("Inside get" + action); if (theUser != null) { //writer.println("Inside user"); if (action.equals("about")) { url = "/aboutl.jsp"; } if (action.equals("how")) { url = "/main.jsp"; } if (action.equals("home")) { url = "/main.jsp"; } if (action.equals("main")) { url = "/main.jsp"; } if (action.equals("login")) { url = "/login.jsp"; } if (action.equals("create")) { try { String currentTime = sdf.format(dt); String token = request.getParameter("token"); String expiryTime = UserDB.getTime(token); Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { request.setAttribute("token", token); url = "/signup.jsp"; } } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (action.equals("activation")) { String currentTime = sdf.format(dt); String value; String userToken; String password; userToken = request.getParameter("activationcode"); System.out.println("userToken if" + userToken); String expiryTime = UserDB.getTime(userToken); try { Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(userToken); if (user != null) { value = userPassword.get(user.getEmail()); session.setAttribute("theUser", user); try { password = hashAndSalt(value); userDB.addUser(user, password, salt); userDB.addUser(user); userDB.deleteTemp(userToken); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } url = "/login.jsp"; } else { url = "/signup.jsp"; } } } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (action.equals("resetpassword")) { try { String token; String currentTime = sdf.format(dt); token = request.getParameter("token"); System.out.println("userToken else" + token); String expiryTime = UserDB.getTime(token); Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(token); if (user != null) { request.setAttribute("user", user); request.setAttribute("userResetToken", token); url = "/resetpassword.jsp"; } else { url = "/signup.jsp"; } } else { message = "Token is expired!!"; request.setAttribute("message", message); url = "/signup.jsp"; } //url="/login.jsp"; } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } } else { if (action.equals("about")) { url = "/about.jsp"; } if (action.equals("how")) { url = "/how.jsp"; } if (action.equals("home")) { if (flag == 0) { int i = request.getServerPort(); String port = String.valueOf(i); Cookie myCookie = new Cookie("HostName", request.getServerName()); myCookie.setMaxAge(60 * 60 * 24 * 365); myCookie.setPath("/"); response.addCookie(myCookie); Cookie cookiePort = new Cookie("Port", port); myCookie.setMaxAge(60 * 60 * 24 * 365); myCookie.setPath("/"); response.addCookie(cookiePort); } url = "/home.jsp"; flag++; } if (action.equals("main")) { url = "/login.jsp"; } if (action.equals("login")) { url = "/login.jsp"; } if (action.equals("activation")) { String currentTime = sdf.format(dt); String value; String userToken; String password; userToken = request.getParameter("activationcode"); System.out.println("userToken else" + userToken); String expiryTime = UserDB.getTime(userToken); try { Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(userToken); if (user != null) { value = userPassword.get(user.getEmail()); session.setAttribute("theUser", user); try { password = hashAndSalt(value); userDB.addUser(user, password, salt); userDB.addUser(user); userDB.deleteTemp(userToken); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } url = "/login.jsp"; } else { url = "/signup.jsp"; } } } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (action.equals("resetpassword")) { try { String token; String currentTime = sdf.format(dt); token = request.getParameter("token"); System.out.println("userToken else" + token); String expiryTime = UserDB.getTime(token); Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(token); if (user != null) { request.setAttribute("user", user); request.setAttribute("userResetToken", token); url = "/resetpassword.jsp"; } else { url = "/signup.jsp"; } } else { message = "Token is expired!!"; request.setAttribute("message", message); url = "/signup.jsp"; } //url="/login.jsp"; } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } } getServletContext().getRequestDispatcher(url).forward(request, response); }
From source file:com.viewer.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 {//from w w w . j a v a 2 s .co m 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()); try { result.setDocumentDescription( (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false)); } catch (ParseException x) { throw new ServletException(x); } 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; try { 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); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } 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:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java
/** * Processes the request made from the HTML visual interface of Strabon Endpoint. * //from w ww . j ava 2 s . c o m * @param request * @param response * @throws ServletException * @throws IOException */ private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher; // check whether Update submit button was fired String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit"); if (reqFuncionality.equals("Update")) { // get the dispatcher for forwarding the rendering of the response dispatcher = request.getRequestDispatcher("/Update"); dispatcher.forward(request, response); } else { String query = URLDecoder.decode(request.getParameter("query"), "UTF-8"); String format = request.getParameter("format"); String handle = request.getParameter("handle"); String maxLimit = request.getParameter("maxLimit"); // get stSPARQLQueryResultFormat from given format name TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format); if (query == null || format == null || queryResultFormat == null) { dispatcher = request.getRequestDispatcher("query.jsp"); request.setAttribute(ERROR, PARAM_ERROR); dispatcher.forward(request, response); } else { query = strabonWrapper.addLimit(query, maxLimit); if ("download".equals(handle)) { // download as attachment ServletOutputStream out = response.getOutputStream(); response.setContentType(queryResultFormat.getDefaultMIMEType()); response.setHeader("Content-Disposition", "attachment; filename=results." + queryResultFormat.getDefaultFileExtension() + "; " + queryResultFormat.getCharset()); try { strabonWrapper.query(query, format, out); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.print(ResponseMessages.getXMLHeader()); out.print(ResponseMessages.getXMLException(e.getMessage())); out.print(ResponseMessages.getXMLFooter()); } out.flush(); } else if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle)) && (queryResultFormat == stSPARQLQueryResultFormat.KML || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) { // show map (only valid for KML/KMZ) // get dispatcher dispatcher = request.getRequestDispatcher("query.jsp"); // re-assign handle request.setAttribute("handle", handle); SecureRandom random = new SecureRandom(); String temp = new BigInteger(130, random).toString(32); // the temporary KML/KMZ file to create in the server String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension(); ; try { Date date = new Date(); // get the absolute path of the temporary directory if (!request.getParameter("handle").toString().contains("timemap")) { tempDirectory = appName + "-temp"; basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/"; // fix the temporary directory for this web application FileUtils.forceMkdir(new File(basePath)); @SuppressWarnings("unchecked") Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false); while (it.hasNext()) { File tbd = new File((it.next()).getAbsolutePath()); if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) { FileUtils.forceDelete(new File(tbd.getAbsolutePath())); } } } else { //timemap case tempDirectory = "js/timemap"; basePath = context.getRealPath("/") + tempDirectory + "/"; // fix the temporary directory for this web application } // fix the temporary directory for this web application // create temporary KML/KMZ file File file = new File(basePath + tempKMLFile); // if file does not exist, then create it if (!file.exists()) { file.createNewFile(); } try { // query and write the result in the temporary KML/KMZ file FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile); strabonWrapper.query(query, format, fos); fos.close(); if (request.getParameter("handle").toString().contains("timemap")) { request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile); } else { request.setAttribute("pathToKML", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + tempDirectory + "/" + tempKMLFile); } } catch (MalformedQueryException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage()); request.setAttribute(ERROR, e.getMessage()); } catch (Exception e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); request.setAttribute(ERROR, e.getMessage()); } dispatcher.forward(request, response); } catch (IOException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); } } else { // "plain" is assumed as the default dispatcher = request.getRequestDispatcher("query.jsp"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { strabonWrapper.query(query, format, bos); if (format.equals(Common.getHTMLFormat())) { request.setAttribute(RESPONSE, bos.toString()); } else if (format.equals(Format.PIECHART.toString()) || format.equals(Format.AREACHART.toString()) || format.equals(Format.COLUMNCHART.toString())) { request.setAttribute("format", "CHART"); request.setAttribute(RESPONSE, strabonWrapper.getgChartString()); } else { request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString())); } } catch (MalformedQueryException e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage()); request.setAttribute(ERROR, e.getMessage()); } catch (Exception e) { logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e); request.setAttribute(ERROR, e.getMessage()); } finally { dispatcher.forward(request, response); } } } } }
From source file:jp.or.openid.eiwg.scim.operation.Operation.java
/** * ?/*from ww w.j av a 2 s . c om*/ * * @param context * @param request * @param attributes * @param requestJson */ public LinkedHashMap<String, Object> createUserInfo(ServletContext context, HttpServletRequest request, String attributes, String requestJson) { LinkedHashMap<String, Object> result = null; Set<String> returnAttributeNameSet = new HashSet<>(); // ? setError(0, null, null); // ?? if (attributes != null && !attributes.isEmpty()) { // String[] tempList = attributes.split(","); for (int i = 0; i < tempList.length; i++) { String attributeName = tempList[i].trim(); // ??????? LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName, true); if (attributeSchema != null && !attributeSchema.isEmpty()) { returnAttributeNameSet.add(attributeName); } else { // ??????? String message = String.format(MessageConstants.ERROR_INVALID_ATTRIBUTES, attributeName); setError(HttpServletResponse.SC_BAD_REQUEST, null, message); return result; } } } // ? if (requestJson == null || requestJson.isEmpty()) { // setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST); return result; } // (JSON)? ObjectMapper mapper = new ObjectMapper(); LinkedHashMap<String, Object> requestObject = null; try { requestObject = mapper.readValue(requestJson, new TypeReference<LinkedHashMap<String, Object>>() { }); } catch (JsonParseException e) { String datailMessage = e.getMessage(); datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n')); setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")"); return result; } catch (JsonMappingException e) { String datailMessage = e.getMessage(); datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n')); setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")"); return result; } catch (IOException e) { setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN); return result; } // ? if (requestObject != null && !requestObject.isEmpty()) { Iterator<String> attributeIt = requestObject.keySet().iterator(); while (attributeIt.hasNext()) { // ??? String attributeName = attributeIt.next(); // ? LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName, true); if (attributeSchema != null) { // ???? Object mutability = attributeSchema.get("mutability"); if (mutability != null && mutability.toString().equalsIgnoreCase("readOnly")) { // readOnly String message = String.format(MessageConstants.ERROR_READONLY_ATTRIBUTE, attributeName); setError(HttpServletResponse.SC_BAD_REQUEST, null, message); return result; } // ?? // () } else { // ???? String message = String.format(MessageConstants.ERROR_UNKNOWN_ATTRIBUTE, attributeName); setError(HttpServletResponse.SC_BAD_REQUEST, null, message); return result; } } } else { // setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST); return result; } // ? // () LinkedHashMap<String, Object> newUserInfo = new LinkedHashMap<String, Object>(); // id? UUID uuid = UUID.randomUUID(); newUserInfo.put("id", uuid.toString()); Iterator<String> attributeIt = requestObject.keySet().iterator(); while (attributeIt.hasNext()) { // ??? String attributeName = attributeIt.next(); // ? Object attributeValue = requestObject.get(attributeName); newUserInfo.put(attributeName, attributeValue); } // meta? LinkedHashMap<String, Object> metaValues = new LinkedHashMap<String, Object>(); // meta.resourceType metaValues.put("resourceType", "User"); // meta.created SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"); xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC")); metaValues.put("created", xsdDateTime.format(new Date())); // meta.location String location = request.getScheme() + "://" + request.getServerName(); int serverPort = request.getServerPort(); if (serverPort != 80 && serverPort != 443) { location += ":" + Integer.toString(serverPort); } location += request.getContextPath(); location += "/scim/Users/" + uuid.toString(); metaValues.put("location", location); newUserInfo.put("meta", metaValues); // (??) @SuppressWarnings("unchecked") ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context .getAttribute("Users"); if (users == null) { users = new ArrayList<LinkedHashMap<String, Object>>(); } users.add(newUserInfo); context.setAttribute("Users", users); // ?? result = new LinkedHashMap<String, Object>(); attributeIt = newUserInfo.keySet().iterator(); while (attributeIt.hasNext()) { // ??? String attributeName = attributeIt.next(); // ? LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName, true); Object returned = attributeSchema.get("returned"); if (returned != null && returned.toString().equalsIgnoreCase("never")) { continue; } // ? Object attributeValue = newUserInfo.get(attributeName); result.put(attributeName, attributeValue); } return result; }
From source file:com.trsst.ui.AppServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // FLAG: limit access only to local clients if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed."); return;/*w w w.j av a 2 s.c om*/ } // in case of any posted files InputStream inStream = null; // determine if supported command: pull, push, post String path = request.getPathInfo(); System.err.println(new Date().toString() + " " + path); if (path != null) { // FLAG: limit only to pull and post if (path.startsWith("/pull/") || path.startsWith("/post")) { // FLAG: we're sending the user's keystore // password over the wire (over SSL) List<String> args = new LinkedList<String>(); if (path.startsWith("/pull/")) { path = path.substring("/pull/".length()); response.setContentType("application/atom+xml; type=feed; charset=utf-8"); // System.out.println("doPull: " + // request.getParameterMap()); args.add("pull"); if (request.getParameterMap().size() > 0) { boolean first = true; for (Object name : request.getParameterMap().keySet()) { // FLAG: don't allow "home" (server-abuse) // FLAG: don't allow "attach" (file-system access) if ("decrypt".equals(name) || "pass".equals(name)) { for (String value : request.getParameterValues(name.toString())) { args.add("--" + name.toString()); args.add(value); } } else { for (String value : request.getParameterValues(name.toString())) { if (first) { path = path + '?'; first = false; } else { path = path + '&'; } path = path + name + '=' + value; } } } } args.add(path); } else if (path.startsWith("/post")) { // System.out.println("doPost: " + // request.getParameterMap()); args.add("post"); try { // h/t http://stackoverflow.com/questions/2422468 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // process regular form field String name = item.getFieldName(); String value = item.getString("UTF-8").trim(); // System.out.println("AppServlet: " + name // + " : " + value); if (value.length() > 0) { // FLAG: don't allow "home" (server-abuse) // FLAG: don't allow "attach" (file-system // access) if ("id".equals(name)) { if (value.startsWith("urn:feed:")) { value = value.substring("urn:feed:".length()); } args.add(value); } else if (!"home".equals(name) && !"attach".equals(name)) { args.add("--" + name); args.add(value); } } else { log.debug("Empty form value for name: " + name); } } else if (item.getSize() > 0) { // process form file field (input type="file"). // String filename = FilenameUtils.getName(item // .getName()); if (item.getSize() > 1024 * 1024 * 10) { throw new FileUploadException("Current maximum upload size is 10MB"); } String name = item.getFieldName(); if ("icon".equals(name) || "logo".equals(name)) { args.add("--" + name); args.add("-"); } inStream = item.getInputStream(); // NOTE: only handles one file! } else { log.debug("Ignored form field: " + item.getFieldName()); } } } catch (FileUploadException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not parse multipart request: " + e); return; } } // send post data if any to command input stream if (inStream != null) { args.add("--attach"); } //System.out.println(args); // make sure we don't create another local server args.add("--host"); args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/feed"); PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8"); int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream); if (result != 0) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error code: " + result); } else { outStream.flush(); } return; } // otherwise: determine if static resource request if (path.startsWith("/")) { path = path.substring(1); } byte[] result = resources.get(path); String mimetype = null; if (result == null) { // if ("".equals(path) || path.endsWith(".html")) { // treat all html requests with index doc result = resources.get("index.html"); mimetype = "text/html"; // } } if (result != null) { if (mimetype == null) { if (path.endsWith(".html")) { mimetype = "text/html"; } else if (path.endsWith(".css")) { mimetype = "text/css"; } else if (path.endsWith(".js")) { mimetype = "application/javascript"; } else if (path.endsWith(".png")) { mimetype = "image/png"; } else if (path.endsWith(".jpg")) { mimetype = "image/jpeg"; } else if (path.endsWith(".jpeg")) { mimetype = "image/jpeg"; } else if (path.endsWith(".gif")) { mimetype = "image/gif"; } else { mimetype = new Tika().detect(result); } } if (request.getHeader("If-None-Match:") != null) { // client should always use cached version log.info("sending 304"); response.setStatus(304); // Not Modified return; } // otherwise allow ETag/If-None-Match response.setHeader("ETag", Long.toHexString(path.hashCode())); if (mimetype != null) { response.setContentType(mimetype); } response.setContentLength(result.length); response.getOutputStream().write(result); return; } } // // otherwise: 404 Not Found // response.sendError(HttpServletResponse.SC_NOT_FOUND); }
From source file:com.viewer.controller.ViewerController.java
@RequestMapping(value = "/ViewDocument", method = RequestMethod.POST, headers = { "Content-type=application/json" }) @ResponseBody/*from w w w. j av a 2s . co m*/ public ViewDocumentResponse viewDoc(@RequestBody ViewDocumentParameters params, HttpServletRequest request) throws Exception { // To Set License License lic = new License(); lic.setLicense(_licensePath); params.setUseHtmlBasedEngine(true); if (params.getUseHtmlBasedEngine()) { DocumentInfoContainer docInfo = _htmlHandler.getDocumentInfo(new DocumentInfoOptions(params.getPath())); int maxWidth = 0; int maxHeight = 0; for (PageData pageData : docInfo.getPages()) { if (pageData.getHeight() > maxHeight) { maxHeight = pageData.getHeight(); maxWidth = pageData.getWidth(); } } FileData fileData = new FileData(); fileData.setDateCreated(new Date()); fileData.setDateModified(docInfo.getLastModificationDate()); fileData.setPageCount(docInfo.getPages().size()); fileData.setPages(docInfo.getPages()); fileData.setMaxWidth(maxWidth); fileData.setMaxHeight(maxHeight); ViewDocumentResponse result = new ViewDocumentResponse(); 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()); try { result.setDocumentDescription( (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false)); } catch (ParseException x) { throw new ServletException(x); } result.setDocumentDescription( (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false)); 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); } } return result; } else { DocumentInfoContainer docInfo = _imageHandler .getDocumentInfo(new DocumentInfoOptions(params.getPath())); int maxWidth = 0; int maxHeight = 0; for (PageData pageData : docInfo.getPages()) { if (pageData.getHeight() > maxHeight) { maxHeight = pageData.getHeight(); maxWidth = pageData.getWidth(); } } FileData fileData = new FileData(); fileData.setDateCreated(new Date()); fileData.setDateModified(docInfo.getLastModificationDate()); fileData.setPageCount(docInfo.getPages().size()); fileData.setPages(docInfo.getPages()); fileData.setMaxWidth(maxWidth); fileData.setMaxHeight(maxHeight); ViewDocumentResponse result = new ViewDocumentResponse(); result.setPageCss(new String[0]); result.setLic(true); result.setPdfDownloadUrl(GetPdfDownloadUrl(params)); result.setPdfPrintUrl(GetPdfPrintUrl(params)); params.setUseHtmlBasedEngine(true); 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.setDocumentDescription( (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false)); 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); return result; } }