List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost
public String getRemoteHost();
From source file:org.nema.medical.mint.server.controller.JobsController.java
@RequestMapping(method = RequestMethod.POST, value = "/jobs/updatestudy") public void updateStudy(HttpServletRequest req, HttpServletResponse res) throws IOException { String jobID = UUID.randomUUID().toString(); File jobFolder = new File(jobTemp, jobID); jobFolder.mkdirs();/* w w w.ja v a2s . c o m*/ // the list of files uploaded List<File> files = new ArrayList<File>(); // the set of form parameters Map<String, String> params = new HashMap<String, String>(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "expected multipart form data"); return; } try { handleUpload(req, jobFolder, files, params); } catch (FileUploadException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to parse multipart form data"); return; } if (files.size() < 1) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "at least one file (containing metadata) is required."); return; } if (!params.containsKey(HttpMessagePart.STUDY_UUID.toString())) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter " + HttpMessagePart.STUDY_UUID); return; } final String studyUUID = params.get(HttpMessagePart.STUDY_UUID.toString()); final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, studyUUID, res, studyDAO); if (studyStatus != Utils.StudyStatus.OK) { return; } if (!params.containsKey(HttpMessagePart.OLD_VERSION.toString())) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter " + HttpMessagePart.OLD_VERSION); return; } final String oldVersionString = params.get(HttpMessagePart.OLD_VERSION.toString()); final int oldVersion = StringUtils.isBlank(oldVersionString) ? -1 : Integer.parseInt(oldVersionString); JobInfo jobInfo = new JobInfo(); jobInfo.setId(jobID); jobInfo.setStudyID(studyUUID); jobInfo.setStatus(JobStatus.IN_PROGRESS); jobInfo.setStatusDescription("0% complete"); String jobURI = req.getContextPath() + "/jobs/status/" + jobInfo.getId(); jobInfoDAO.saveOrUpdateJobInfo(jobInfo); File studyFolder = new File(studiesRoot, studyUUID); final StudyUpdateProcessor processor = new StudyUpdateProcessor(jobFolder, studyFolder, availableTypes, oldVersion, req.getRemoteUser(), req.getRemoteHost(), jobInfoDAO, studyDAO, updateDAO); executor.execute(processor); // process immediately in the background res.setStatus(HttpServletResponse.SC_SEE_OTHER); res.setHeader("Location", jobURI); }
From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java
private Boolean isAccessAuthorized(StudyFile file, HttpServletRequest req, VDCUser user, VDC vdc, UserGroup ipUserGroup) {//from w ww .j a v a2 s . co m Boolean authorized = false; // first check is to see if this request is from localhost. // localhost is authorized to get anything it wants, // no questions asked. String localHostByName = "localhost"; String localHostNumeric = "127.0.0.1"; if (!isLockssCrawlRequest(req)) { // This is a non-LOCKSS download request. if (localHostByName.equals(req.getRemoteHost()) || localHostNumeric.equals(req.getRemoteHost())) { return true; } // then check to see if this request is from our dedicated // DSB host. DSB host is authorized to get any file without // restrictions. // (Chances are this is no longer required -- L.A. -- ?) String dsbHost = System.getProperty("vdc.dsb.host"); if (dsbHost == null) { // vdc.dsb.host isn't set; // fall back to the old-style option: dsbHost = System.getProperty("vdc.dsb.url"); } boolean isDSBrequest = false; if (dsbHost != null) { if (dsbHost.equals(req.getRemoteHost())) { return true; } else { try { String dsbHostIPAddress = InetAddress.getByName(dsbHost).getHostAddress(); if (dsbHostIPAddress.equals(req.getRemoteHost())) { return true; } } catch (UnknownHostException ex) { // no need to do anything; // this probably means the "vdc.dsb.host" setting is // misconfigured. in any event, safe to assume this is NOT // a DSB call } } } // Now, let's check if the file is authorized for this specific user: if (!file.isFileRestrictedForUser(user, ipUserGroup)) { return true; } } else { // this is a LOCKSS crawler: if (isAuthorizedLockssCrawler(file, req)) { return true; } } // We've exhausted the possibilities: return false; }
From source file:thinwire.render.web.WebServlet.java
private Set<String> getStartArguments(HttpServletRequest request) { Set<String> args = new TreeSet<String>(); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String[]> e : ((Map<String, String[]>) request.getParameterMap()).entrySet()) { String key = e.getKey();// ww w. j a va 2s . c om String[] values = e.getValue(); if (values.length > 1) { for (int i = 0; i < values.length; i++) { sb.append(key).append(i).append('=').append(values[i]); } } else { sb.append(key).append('=').append(values[0]); } args.add(sb.toString()); sb.setLength(0); } String extraArguments = getInitParameter(InitParam.EXTRA_ARGUMENTS.mixedCaseName()); if (extraArguments == null) extraArguments = ""; extraArguments = "," + extraArguments + ","; if (extraArguments.indexOf(",contextParam,") >= 0) { ServletContext sc = getServletContext(); for (Enumeration<String> ipn = sc.getInitParameterNames(); ipn.hasMoreElements();) { String name = ipn.nextElement(); sb.append("CONTEXT_PARAM_").append(name).append('=').append(sc.getInitParameter(name)); args.add(sb.toString()); sb.setLength(0); } } if (extraArguments.indexOf(",initParam,") >= 0) { InitParam[] initParams = InitParam.values(); ipn_loop: for (Enumeration<String> ipn = getInitParameterNames(); ipn.hasMoreElements();) { String name = ipn.nextElement(); for (InitParam ip : initParams) { if (ip.mixedCaseName().equals(name)) continue ipn_loop; } sb.append("INIT_PARAM_").append(name).append('=').append(getInitParameter(name)); args.add(sb.toString()); sb.setLength(0); } } if (extraArguments.indexOf(",header,") >= 0) { for (Enumeration<String> hn = request.getHeaderNames(); hn.hasMoreElements();) { String name = hn.nextElement(); sb.append("HEADER_").append(name.toUpperCase()).append('=').append(request.getHeader(name)); args.add(sb.toString()); sb.setLength(0); } } if (extraArguments.indexOf(",clientInfo,") >= 0) { sb.append("CLIENT_INFO_USER").append('=').append(request.getRemoteUser()); args.add(sb.toString()); sb.setLength(0); sb.append("CLIENT_INFO_HOST").append('=').append(request.getRemoteHost()); args.add(sb.toString()); sb.setLength(0); sb.append("CLIENT_INFO_ADDRESS").append('=').append(request.getRemoteAddr()); args.add(sb.toString()); sb.setLength(0); } return args; }
From source file:io.datenwelt.cargo.rest.Request.java
public Request(HttpServletRequest servletRequest, List<ContentType> supportedContentTypes, List<ContentEncoding> supportedContentEncodings) throws APIException { this.servletRequest = servletRequest; this.supportedContentTypes = supportedContentTypes; this.supportedContentEncodings = supportedContentEncodings; this.method = servletRequest.getMethod(); this.path = Segment.normalize(servletRequest.getPathInfo()); StringBuffer url = servletRequest.getRequestURL(); String query = servletRequest.getQueryString(); if (query != null && !query.isEmpty()) { url.append("?").append(query); }/* w w w . j a va2 s. c om*/ // Parse request URI and construct the base URI. try { requestURI = new URI(url.toString()); String basePath = (servletRequest.getContextPath() == null ? "" : servletRequest.getContextPath()) + (servletRequest.getServletPath() == null ? "" : servletRequest.getServletPath()); baseURI = URI.create(new StringBuffer().append(requestURI.getScheme()).append("://") .append(requestURI.getRawAuthority()).append("/").append(basePath).toString()); path = Segment.normalize(requestURI.getPath()); if (path.startsWith(basePath)) { path = path.substring(basePath.length()); } } catch (URISyntaxException ex) { throw new APIException(new InternalServerError(), "Unable to parse request URI from string '" + requestURI + "'. Using defaut value for base URI. Error: " + ex.getMessage(), ex); } // Parse query string. String queryString = servletRequest.getQueryString(); this.queries.addAll(Query.parseQueryString(queryString)); // Parse header values Enumeration headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement().toString(); Enumeration values = servletRequest.getHeaders(name); while (values.hasMoreElements()) { Header header = headers.get(name); if (header == null) { header = new Header(name); headers.put(header.getName(), header); } String value = values.nextElement().toString(); header.add(Header.decode(name, value)); } } // Collect infos about the remote end. remoteAddress = servletRequest.getRemoteAddr(); remoteHost = servletRequest.getRemoteHost(); remotePort = servletRequest.getRemotePort(); }
From source file:co.agileventure.jwtauth.web.controller.UserProcessorImpl.java
public ResponseEntity processUser(final HttpServletRequest request, final User.Provider provider, final String id, final String displayName, final String email, final String picture, final String name, final String givenName, final String familyName) throws JOSEException, ParseException { User user = null;//from www .j a v a 2 s . c o m switch (provider) { case FACEBOOK: user = userService.findByFacebook(id); break; case GOOGLE: user = userService.findByGoogle(id); break; default: return new ResponseEntity<String>("Unknown OAUTH2.0 Provider", HttpStatus.NOT_FOUND); } //If not found by provider try to find it by email if (user == null && StringUtils.isNotEmpty(email)) { user = userService.findByEmail(email); } // Step 3a. If user is already signed in then link accounts. User userToSave; final String authHeader = request.getHeader(AuthUtils.AUTH_HEADER_KEY); if (StringUtils.isNotBlank(authHeader)) { if (user == null) { return new ResponseEntity<String>(String.format(CONFLICT_MSG, provider.capitalize()), HttpStatus.CONFLICT); } final String subject = AuthUtils.getSubject(authHeader); final User foundUser = userService.findOne(subject); if (foundUser == null) { return new ResponseEntity<String>(NOT_FOUND_MSG, HttpStatus.NOT_FOUND); } userToSave = foundUser; boolean updated = setUserProvider(provider, userToSave, id); if (userToSave.getDisplayName() == null) { userToSave.setDisplayName(displayName); updated = true; } if (userToSave.getPicture() == null) { userToSave.setPicture(picture); updated = true; } if (updated) { userToSave = userService.save(userToSave); } } else { // Step 3b. Create a new user account or return an existing one. if (user != null) { userToSave = user; if (setUserProvider(provider, userToSave, id)) { if (userToSave.getPicture() == null) { userToSave.setPicture(picture); } userToSave = userService.save(userToSave); } } else { userToSave = new User(); userToSave.setId(UUID.randomUUID().toString()); userToSave.setDisplayName(displayName); userToSave.setEmail(email); userToSave.setName(name); userToSave.setGivenName(givenName); userToSave.setPicture(picture); userToSave.setFamilyName(familyName); setUserProvider(provider, userToSave, id); userToSave = userService.save(userToSave); } } Token token = AuthUtils.createToken(request.getRemoteHost(), userToSave.getId()); return new ResponseEntity<Token>(token, HttpStatus.OK); }
From source file:edu.umich.its.lti.google.GoogleLtiServlet.java
/** * Getting the instructors email address( that is needed during for manipulating permission calls) stored in the Setting service(SS) from the Session instead of SS * as call to SS intermittently not fetching correct value. * @param request//from www. ja v a 2 s . c o m * @param response * @param tcSessionData * @return * @throws ServletException * @throws IOException */ private FolderPermissionsHandler getHandler(HttpServletRequest request, HttpServletResponse response, TcSessionData tcSessionData) throws ServletException, IOException { M_log.debug("In the Folder Permission handler call for request: " + request.getParameter(PARAMETER_ACTION)); FolderPermissionsHandler result = null; String siteId = tcSessionData.getContextId(); String fileId = request.getParameter(PARAM_FILE_ID); TcSiteToGoogleLink link = null; String instructorEmailAddress = ""; String value = getSettingsValueFromSession(request); if (value != null) { link = TcSiteToGoogleStorage.parseLink(value); instructorEmailAddress = link.getUserEmailAddress(); } else { link = GoogleCache.getInstance().getLinkForSite(siteId); if (link == null) { StringBuilder sb = new StringBuilder(); sb.append("Error: cannot modify permissions to folder #"); sb.append(fileId); sb.append(" - did not find link with course #"); sb.append(tcSessionData.getContextId()); M_log.warn(sb.toString()); return null; } instructorEmailAddress = link.getUserEmailAddress(); GoogleCache.getInstance().clearLinkForSite(siteId); } GoogleCredential googleCredential = null; if (instructorEmailAddress.equalsIgnoreCase(tcSessionData.getUserEmailAddress())) { // Logged in user is instructor: use their access token googleCredential = getGoogleCredential(request); } else { // This is unlikely to happen for whole roster, but will be // useful for code modifying a single student's/ or other instructor //permissions in roster googleCredential = GoogleSecurity.authorize(getGoogleServiceAccount(request.getRemoteHost()), instructorEmailAddress); } Drive drive = GoogleSecurity.getGoogleDrive(googleCredential); result = new FolderPermissionsHandler(link, drive, fileId); return result; }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.TrackbackServlet.java
/** * Service incoming POST requests.//from ww w . ja v a2 s .c o m * * Here we handle incoming trackback posts. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String error = null; PrintWriter pw = response.getWriter(); Weblog weblog = null; WeblogEntry entry = null; RollerMessages messages = new RollerMessages(); WeblogTrackbackRequest trackbackRequest = null; if (!WebloggerRuntimeConfig.getBooleanProperty("users.trackbacks.enabled")) { // TODO: i18n error = "Trackbacks are disabled for this site"; } else { try { trackbackRequest = new WeblogTrackbackRequest(request); if ((trackbackRequest.getTitle() == null) || "".equals(trackbackRequest.getTitle())) { trackbackRequest.setTitle(trackbackRequest.getUrl()); } if (trackbackRequest.getExcerpt() == null) { trackbackRequest.setExcerpt(""); } else if (trackbackRequest.getExcerpt().length() >= 255) { trackbackRequest.setExcerpt(trackbackRequest.getExcerpt().substring(0, 252) + "..."); } // lookup weblog specified by comment request weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(trackbackRequest.getWeblogHandle()); if (weblog == null) { throw new WebloggerException("unable to lookup weblog: " + trackbackRequest.getWeblogHandle()); } // lookup entry specified by comment request WeblogEntryManager weblogMgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); entry = weblogMgr.getWeblogEntryByAnchor(weblog, trackbackRequest.getWeblogAnchor()); if (entry == null) { throw new WebloggerException("unable to lookup entry: " + trackbackRequest.getWeblogAnchor()); } } catch (Exception e) { // some kind of error parsing the request or looking up weblog logger.debug("error creating trackback request", e); error = e.getMessage(); } } if (error != null) { pw.println(this.getErrorResponse(error)); return; } try { // check if trackbacks are allowed for this entry // this checks site-wide settings, weblog settings, and entry settings if (entry != null && entry.getCommentsStillAllowed() && entry.isPublished()) { // Track trackbacks as comments WeblogEntryComment comment = new WeblogEntryComment(); comment.setContent("[Trackback] " + trackbackRequest.getExcerpt()); comment.setName(trackbackRequest.getBlogName()); comment.setUrl(trackbackRequest.getUrl()); comment.setWeblogEntry(entry); comment.setRemoteHost(request.getRemoteHost()); comment.setNotify(Boolean.FALSE); comment.setPostTime(new Timestamp(new Date().getTime())); // run new trackback through validators int validationScore = commentValidationManager.validateComment(comment, messages); logger.debug("Comment Validation score: " + validationScore); if (validationScore == 100 && weblog.getCommentModerationRequired()) { // Valid comments go into moderation if required comment.setStatus(WeblogEntryComment.PENDING); } else if (validationScore == 100) { // else they're approved comment.setStatus(WeblogEntryComment.APPROVED); } else { // Invalid comments are marked as spam comment.setStatus(WeblogEntryComment.SPAM); } // save, commit, send response if (!WeblogEntryComment.SPAM.equals(comment.getStatus()) || !WebloggerRuntimeConfig.getBooleanProperty("trackbacks.ignoreSpam.enabled")) { WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); mgr.saveComment(comment); WebloggerFactory.getWeblogger().flush(); // only invalidate the cache if comment isn't moderated if (!weblog.getCommentModerationRequired()) { // Clear all caches associated with comment CacheManager.invalidate(comment); } // Send email notifications MailUtil.sendEmailNotification(comment, messages, I18nMessages.getMessages(trackbackRequest.getLocaleInstance()), validationScore == 100); if (WeblogEntryComment.PENDING.equals(comment.getStatus())) { pw.println(this.getSuccessResponse("Trackback submitted to moderator")); } else { pw.println(this.getSuccessResponse("Trackback accepted")); } } } else if (entry != null) { // TODO: i18n error = "Comments and Trackbacks are disabled for the entry you specified."; } else { // TODO: i18n error = "Entry not specified."; } } catch (Exception e) { error = e.getMessage(); if (error == null) { error = e.getClass().getName(); } } if (error != null) { pw.println(this.getErrorResponse(error)); } }
From source file:com.sg.rest.filters.LoggerFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString()); throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST); }//w w w . ja v a2s .c om HttpServletRequest httpRequest = (HttpServletRequest) request; StringBuilder sb = new StringBuilder(); //General header sb.append(System.lineSeparator()); sb.append(INCOMING_REQUEST); //Request url sb.append(System.lineSeparator()); sb.append(REQUEST_URL); sb.append(httpRequest.getRequestURL()); //Method sb.append(System.lineSeparator()); sb.append(METHOD); sb.append(httpRequest.getMethod()); //Parameters if (httpRequest.getParameterNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(PARAMETERS); Enumeration enParams = httpRequest.getParameterNames(); while (enParams.hasMoreElements()) { sb.append(System.lineSeparator()); String paramName = (String) enParams.nextElement(); sb.append(paramName); sb.append(" : "); sb.append(httpRequest.getParameter(paramName)); } } //Attributes if (httpRequest.getAttributeNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(ATTRIBUTES); Enumeration enAttribs = httpRequest.getAttributeNames(); while (enAttribs.hasMoreElements()) { sb.append(System.lineSeparator()); String attribName = (String) enAttribs.nextElement(); sb.append(attribName); sb.append(" : "); sb.append(httpRequest.getAttribute(attribName)); } } //Headers if (httpRequest.getHeaderNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(HEADERS); Enumeration enHeaders = httpRequest.getHeaderNames(); while (enHeaders.hasMoreElements()) { sb.append(System.lineSeparator()); String headerName = (String) enHeaders.nextElement(); sb.append(headerName); sb.append(" : "); sb.append(httpRequest.getHeader(headerName)); } } //AuthType if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) { sb.append(System.lineSeparator()); sb.append(AUTH_TYPE); sb.append(httpRequest.getAuthType()); } //Cookies if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) { sb.append(System.lineSeparator()); sb.append(COOKIES); for (Cookie cookie : httpRequest.getCookies()) { sb.append(System.lineSeparator()); sb.append(cookie.getName()); sb.append(" : "); sb.append(cookie.getValue()); } } //RemoteAddr if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_ADDR); sb.append(httpRequest.getRemoteAddr()); } //RemoteHost if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_HOST); sb.append(httpRequest.getRemoteHost()); } //User principal if (httpRequest.getUserPrincipal() != null) { if (httpRequest.getUserPrincipal().getName() != null && !httpRequest.getUserPrincipal().getName().isEmpty()) { sb.append(System.lineSeparator()); sb.append(PRINCIPAL); sb.append(httpRequest.getUserPrincipal().getName()); } } //Body ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest( (HttpServletRequest) request); String body = IOUtils.toString(wrappedRequest.getReader()); if (body != null && !body.isEmpty()) { sb.append(System.lineSeparator()); sb.append(BODY); sb.append(System.lineSeparator()); sb.append(body); } wrappedRequest.resetInputStream(); LOGGER.info(sb.toString()); chain.doFilter(wrappedRequest, response); }
From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java
/** * Set all the values from a request on this request object and set this request * as the one which the values were copied from * @param req any request/*from www . j a v a 2s. c o m*/ */ public void setRequestValues(HttpServletRequest req) { if (req == null) { throw new IllegalArgumentException("request cannot be null"); } // get the collections of values out Enumeration<String> attribNames = req.getAttributeNames(); while (attribNames.hasMoreElements()) { String name = (String) attribNames.nextElement(); Object obj = req.getAttribute(name); if (obj != null) { attributes.put(name, obj); } } Cookie[] ck = req.getCookies(); if (ck != null) { for (int i = 0; i < ck.length; i++) { cookies.add(ck[i]); } } Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> henum = req.getHeaders(name); Vector<String> v = new Vector<String>(1); while (henum.hasMoreElements()) { String h = henum.nextElement(); v.add(h); } } for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) { parameters.put(entry.getKey(), entry.getValue()); } // get the basic values out this.locale = req.getLocale(); this.method = req.getMethod(); this.contentType = req.getContentType(); this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding(); this.contentLength = req.getContentLength(); this.contextPath = req.getContextPath(); this.pathInfo = req.getPathInfo(); this.queryString = req.getQueryString(); this.requestURI = req.getRequestURI(); this.servletPath = req.getServletPath(); this.scheme = req.getScheme(); this.protocol = req.getProtocol(); this.serverName = req.getServerName(); this.serverPort = req.getServerPort(); this.remoteAddr = req.getRemoteAddr(); this.remoteHost = req.getRemoteHost(); this.realDispatcher = true; }
From source file:org.kchine.r.server.http.frontend.CommandServlet.java
protected void doAny(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = null;/*from www. j a va 2s . c o m*/ Object result = null; try { final String command = request.getParameter("method"); do { if (command.equals("ping")) { result = "pong"; break; } else if (command.equals("logon")) { session = request.getSession(false); if (session != null) { result = session.getId(); break; } String login = (String) PoolUtils.hexToObject(request.getParameter("login")); String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd")); boolean namedAccessMode = login.contains("@@"); String sname = null; if (namedAccessMode) { sname = login.substring(login.indexOf("@@") + "@@".length()); login = login.substring(0, login.indexOf("@@")); } System.out.println("login :" + login); System.out.println("pwd :" + pwd); if (_rkit == null && (!login.equals(System.getProperty("login")) || !pwd.equals(System.getProperty("pwd")))) { result = new BadLoginPasswordException(); break; } HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils .hexToObject(request.getParameter("options")); if (options == null) options = new HashMap<String, Object>(); System.out.println("options:" + options); RPFSessionInfo.get().put("LOGIN", login); RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr()); RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost()); boolean nopool = !options.keySet().contains("nopool") || ((String) options.get("nopool")).equals("") || !((String) options.get("nopool")).equalsIgnoreCase("false"); boolean save = options.keySet().contains("save") && ((String) options.get("save")).equalsIgnoreCase("true"); boolean selfish = options.keySet().contains("selfish") && ((String) options.get("selfish")).equalsIgnoreCase("true"); String privateName = (String) options.get("privatename"); int memoryMin = DEFAULT_MEMORY_MIN; int memoryMax = DEFAULT_MEMORY_MAX; try { if (options.get("memorymin") != null) memoryMin = Integer.decode((String) options.get("memorymin")); if (options.get("memorymax") != null) memoryMax = Integer.decode((String) options.get("memorymax")); } catch (Exception e) { e.printStackTrace(); } boolean privateEngineMode = false; RServices r = null; URL[] codeUrls = null; if (_rkit == null) { if (namedAccessMode) { try { if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { if (PoolUtils.isStubCandidate(sname)) { r = (RServices) PoolUtils.hexToStub(sname, PoolUtils.class.getClassLoader()); } else { r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy( System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname); } } else { if (PoolUtils.isStubCandidate(sname)) { r = (RServices) PoolUtils.hexToStub(sname, PoolUtils.class.getClassLoader()); } else { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname); } } } catch (Exception e) { e.printStackTrace(); } } else { if (nopool) { /* ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System .getProperty("private.servant.node.name"); Registry registry = spFactory.getServantProvider().getRegistry(); NodeManager nm = null; try { nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName); } catch (NotBoundException nbe) { nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name")); } catch (Exception e) { result = new NoNodeManagerFound(); break; } r = (RServices) nm.createPrivateServant(nodeName); */ if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy( System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "db", new Class<?>[] { DBLayerInterface.class }); if (privateName != null && !privateName.equals("")) { try { r = (RServices) dbLayer.lookup(privateName); } catch (Exception e) { //e.printStackTrace(); } } if (r == null) { final String uid = (privateName != null && !privateName.equals("")) ? privateName : UUID.randomUUID().toString(); final String[] jobIdHolder = new String[1]; new Thread(new Runnable() { public void run() { try { String command = "java -Dlog.file=" + System.getProperty("submit.ssh.biocep.home") + "/log/%{uid}.log" + " -Drmi.port.start=" + System.getProperty("submit.ssh.rmi.port.start") + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host=" + System.getProperty("submit.ssh.host") + " -Dwait=true" + " -jar " + System.getProperty("submit.ssh.biocep.home") + "/biocep-core.jar"; jobIdHolder[0] = SSHUtils.execSshBatch(command, uid, System.getProperty("submit.ssh.prefix"), System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home")); System.out.println("jobId:" + jobIdHolder[0]); } catch (Exception e) { e.printStackTrace(); } } }).start(); long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout")); long tStart = System.currentTimeMillis(); while ((System.currentTimeMillis() - tStart) < TIMEOUT) { try { r = (RServices) dbLayer.lookup(uid); } catch (Exception e) { } if (r != null) break; try { Thread.sleep(10); } catch (Exception e) { } } if (r != null) { try { r.setJobId(jobIdHolder[0]); } catch (Exception e) { r = null; } } } } else { System.out.println("LocalHttpServer.getLocalHttpServerPort():" + LocalHttpServer.getLocalHttpServerPort()); System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():" + LocalHttpServer.getLocalHttpServerPort()); if (privateName != null && !privateName.equals("")) { try { r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName); } catch (Exception e) { //e.printStackTrace(); } } if (r == null) { codeUrls = (URL[]) options.get("urls"); System.out.println("CODE URL->" + Arrays.toString(codeUrls)); //String r = ServerManager.createR(System.getProperty("r.binary"), false, false, PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(), ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(), LocalRmiRegistry.getLocalRmiRegistryPort()), memoryMin, memoryMax, privateName, false, codeUrls, null, (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1"); } privateEngineMode = true; } } else { if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy .getDynamicProxy(System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "servant.provider", new Class<?>[] { ServantProvider.class }); boolean wait = options.keySet().contains("wait") && ((String) options.get("wait")).equalsIgnoreCase("true"); String poolname = ((String) options.get("poolname")); if (wait) { r = (RServices) (poolname == null || poolname.trim().equals("") ? servantProvider.borrowServantProxy() : servantProvider.borrowServantProxy(poolname)); } else { r = (RServices) (poolname == null || poolname.trim().equals("") ? servantProvider.borrowServantProxyNoWait() : servantProvider.borrowServantProxyNoWait(poolname)); } System.out.println("---> borrowed : " + r); } else { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } boolean wait = options.keySet().contains("wait") && ((String) options.get("wait")).equalsIgnoreCase("true"); String poolname = ((String) options.get("poolname")); if (wait) { r = (RServices) (poolname == null || poolname.trim().equals("") ? spFactory.getServantProvider().borrowServantProxy() : spFactory.getServantProvider().borrowServantProxy(poolname)); } else { r = (RServices) (poolname == null || poolname.trim().equals("") ? spFactory.getServantProvider().borrowServantProxyNoWait() : spFactory.getServantProvider() .borrowServantProxyNoWait(poolname)); } } } } } else { r = _rkit.getR(); } if (r == null) { result = new NoServantAvailableException(); break; } session = request.getSession(true); Integer sessionTimeOut = null; try { if (options.get("sessiontimeout") != null) sessionTimeOut = Integer.decode((String) options.get("sessiontimeout")); } catch (Exception e) { e.printStackTrace(); } if (sessionTimeOut != null) { session.setMaxInactiveInterval(sessionTimeOut); } session.setAttribute("TYPE", "RS"); session.setAttribute("R", r); session.setAttribute("NOPOOL", nopool); session.setAttribute("SAVE", save); session.setAttribute("LOGIN", login); session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode); session.setAttribute("PROCESS_ID", r.getProcessId()); session.setAttribute("JOB_ID", r.getJobId()); session.setAttribute("SELFISH", selfish); session.setAttribute("IS_RELAY", _rkit != null); if (privateName != null) session.setAttribute("PRIVATE_NAME", privateName); if (codeUrls != null && codeUrls.length > 0) { session.setAttribute("CODEURLS", codeUrls); } session.setAttribute("THREADS", new ThreadsHolder()); ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP")) .put(session.getId(), session); saveSessionAttributes(session); Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext() .getAttribute("R_SESSIONS")).get(r); if (sessionVector == null) { sessionVector = new Vector<HttpSession>(); ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS")) .put(r, sessionVector); } sessionVector.add(session); if (_rkit == null && save) { UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r); } System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners()); if (selfish || !r.hasRCollaborationListeners()) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); GDDevice[] devices = r.listDevices(); for (int i = 0; i < devices.length; ++i) { String deviceName = devices[i].getId(); System.out.println("??? ---- deviceName=" + deviceName); session.setAttribute(deviceName, devices[i]); } } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } if (privateEngineMode) { if (options.get("newdevice") != null) { GDDevice deviceProxy = null; GDDevice[] dlist = r.listDevices(); if (dlist == null || dlist.length == 0) { deviceProxy = r.newDevice(480, 480); } else { deviceProxy = dlist[0]; } String deviceName = deviceProxy.getId(); session.setAttribute(deviceName, deviceProxy); session.setAttribute("maindevice", deviceProxy); saveSessionAttributes(session); } if (options.get("newgenericcallbackdevice") != null) { GenericCallbackDevice genericCallBackDevice = null; GenericCallbackDevice[] clist = r.listGenericCallbackDevices(); if (clist == null || clist.length == 0) { genericCallBackDevice = r.newGenericCallbackDevice(); } else { genericCallBackDevice = clist[0]; } String genericCallBackDeviceName = genericCallBackDevice.getId(); session.setAttribute(genericCallBackDeviceName, genericCallBackDevice); session.setAttribute("maingenericcallbackdevice", genericCallBackDevice); saveSessionAttributes(session); } } result = session.getId(); break; } else if (command.equals("logondb")) { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } String login = (String) PoolUtils.hexToObject(request.getParameter("login")); String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd")); HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils .hexToObject(request.getParameter("options")); if (options == null) options = new HashMap<String, Object>(); System.out.println("options:" + options); session = request.getSession(true); Integer sessionTimeOut = null; try { if (options.get("sessiontimeout") != null) sessionTimeOut = Integer.decode((String) options.get("sessiontimeout")); } catch (Exception e) { e.printStackTrace(); } if (sessionTimeOut != null) { session.setMaxInactiveInterval(sessionTimeOut); } session.setAttribute("TYPE", "DBS"); session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry()); session.setAttribute("SUPERVISOR", new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry())); session.setAttribute("THREADS", new ThreadsHolder()); ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP")) .put(session.getId(), session); saveSessionAttributes(session); result = session.getId(); break; } session = request.getSession(false); if (session == null) { result = new NotLoggedInException(); break; } if (command.equals("logoff")) { if (session.getAttribute("TYPE").equals("RS")) { if (_rkit != null) { /* Enumeration<String> attributeNames = session.getAttributeNames(); while (attributeNames.hasMoreElements()) { String aname = attributeNames.nextElement(); if (session.getAttribute(aname) instanceof GDDevice) { try { _rkit.getRLock().lock(); ((GDDevice) session.getAttribute(aname)).dispose(); } catch (Exception e) { e.printStackTrace(); } finally { _rkit.getRLock().unlock(); } } } */ } } try { session.invalidate(); } catch (Exception ex) { ex.printStackTrace(); } result = null; break; } final boolean[] stop = { false }; final HttpSession currentSession = session; if (command.equals("invoke")) { String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname")); final Object servant = session.getAttribute(servantName); if (servant == null) { throw new Exception("Bad Servant Name :" + servantName); } String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname")); ClassLoader urlClassLoader = this.getClass().getClassLoader(); if (session.getAttribute("CODEURLS") != null) { urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"), this.getClass().getClassLoader()); } Class<?>[] methodSignature = (Class[]) PoolUtils .hexToObject(request.getParameter("methodsignature")); final Method m = servant.getClass().getMethod(methodName, methodSignature); if (m == null) { throw new Exception("Bad Method Name :" + methodName); } final Object[] methodParams = (Object[]) PoolUtils .hexToObject(request.getParameter("methodparameters"), urlClassLoader); final Object[] resultHolder = new Object[1]; Runnable rmiRunnable = new Runnable() { public void run() { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); resultHolder[0] = m.invoke(servant, methodParams); if (resultHolder[0] == null) resultHolder[0] = RMICALL_DONE; } catch (InvocationTargetException ite) { if (ite.getCause() instanceof ConnectException) { currentSession.invalidate(); resultHolder[0] = new NotLoggedInException(); } else { resultHolder[0] = ite.getCause(); } } catch (Exception e) { final boolean wasInterrupted = Thread.interrupted(); if (wasInterrupted) { resultHolder[0] = new RmiCallInterrupted(); } else { resultHolder[0] = e; } } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } }; Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable); ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread); rmiThread.start(); long t1 = System.currentTimeMillis(); while (resultHolder[0] == null) { if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) { rmiThread.interrupt(); resultHolder[0] = new RmiCallTimeout(); break; } try { Thread.sleep(10); } catch (Exception e) { } } try { ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread); } catch (IllegalStateException e) { } if (resultHolder[0] instanceof Throwable) { throw (Throwable) resultHolder[0]; } if (resultHolder[0] == RMICALL_DONE) { result = null; } else { result = resultHolder[0]; } break; } if (command.equals("interrupt")) { final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")) .getThreads().clone(); for (int i = 0; i < tvec.size(); ++i) { try { tvec.elementAt(i).interrupt(); } catch (Exception e) { e.printStackTrace(); } } stop[0] = true; ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads()) .removeAllElements(); result = null; break; } else if (command.equals("saveimage")) { UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"), (RServices) session.getAttribute("R")); result = null; break; } else if (command.equals("loadimage")) { UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), (RServices) session.getAttribute("R")); result = null; break; } else if (command.equals("newdevice")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); boolean broadcasted = new Boolean(request.getParameter("broadcasted")); GDDevice deviceProxy = null; if (broadcasted) { deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice( Integer.decode(request.getParameter("width")), Integer.decode(request.getParameter("height"))); } else { deviceProxy = ((RServices) session.getAttribute("R")).newDevice( Integer.decode(request.getParameter("width")), Integer.decode(request.getParameter("height"))); } String deviceName = deviceProxy.getId(); System.out.println("deviceName=" + deviceName); session.setAttribute(deviceName, deviceProxy); saveSessionAttributes(session); result = deviceName; break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("listdevices")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); result = new Vector<String>(); for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) { String attributeName = e.nextElement(); if (attributeName.startsWith("device_")) { ((Vector<String>) result).add(attributeName); } } break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("newgenericcallbackdevice")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R")) .newGenericCallbackDevice(); String genericCallBackDeviceName = genericCallBackDevice.getId(); session.setAttribute(genericCallBackDeviceName, genericCallBackDevice); saveSessionAttributes(session); result = genericCallBackDeviceName; break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("newspreadsheetmodeldevice")) { String spreadsheetModelDeviceId = request.getParameter("id"); SpreadsheetModelRemote model = null; if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) { model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote( Integer.decode(request.getParameter("rowcount")), Integer.decode(request.getParameter("colcount"))); } else { model = ((RServices) session.getAttribute("R")) .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId); } SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice(); String spreadsheetDeviceId = spreadsheetDevice.getId(); session.setAttribute(spreadsheetDeviceId, spreadsheetDevice); saveSessionAttributes(session); result = spreadsheetDeviceId; break; } else if (command.equals("list")) { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } result = spFactory.getServantProvider().getRegistry().list(); break; } } while (true); } catch (TunnelingException te) { result = te; te.printStackTrace(); } catch (Throwable e) { result = new TunnelingException("Server Side", e); e.printStackTrace(); } response.setContentType("application/x-java-serialized-object"); new ObjectOutputStream(response.getOutputStream()).writeObject(result); response.flushBuffer(); }