List of usage examples for javax.servlet ServletContext getAttribute
public Object getAttribute(String name);
null
if there is no attribute by that name. From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.SalesReturnAgentAction.java
/** * This method is used to accept valid packs and books * /*from w w w . jav a2 s .c om*/ * @return String * @throws Exception */ public String saveSalesReturnData() throws Exception { logger.info("enter in to save book and pack function#############################"); ServletContext sc = ServletActionContext.getServletContext(); HttpSession session = getRequest().getSession(); SalesReturnAgentHelper helper = new SalesReturnAgentHelper(); int receipt_id = 0; game_Name = (String) session.getAttribute("GAME_NAME"); organization_Name = (String) session.getAttribute("ORG_NAME"); orgId = ((Integer) session.getAttribute("ORG_CODE")).intValue(); logger.info("game_Name " + game_Name); logger.info("organization_Name " + organization_Name); //int org_id = helper.getOrganizationIdFromDataBase(organization_Name); int game_id = helper.getGameIdFromDataBase(game_Name.split("-")[1]); String newBookStatus = "INACTIVE"; logger.info("Game Id is :" + game_id); logger.info("org Id is :" + orgId); List<PackBean> packList = (List<PackBean>) session.getAttribute("VERIFIED_PACK_LIST"); List<BookBean> bookList = (List<BookBean>) session.getAttribute("VERIFIED_BOOK_LIST"); logger.info("packList " + packList); logger.info("bookList " + bookList); setSavedPackBeanList(helper.selectValidPacks(packList)); setSavedBookBeanList(helper.selectValidBooks(bookList)); session.setAttribute("VALID_PACK_LIST", getSavedPackBeanList()); session.setAttribute("VALID_BOOK_LIST", getSavedBookBeanList()); logger.info("getSavedPackBeanList() " + getSavedPackBeanList()); logger.info("getSavedBookBeanList() " + getSavedBookBeanList()); String rootPath = (String) session.getAttribute("ROOT_PATH"); UserInfoBean userInfoBean = (UserInfoBean) session.getAttribute("USER_INFO"); String loggedInUserOrgName = userInfoBean.getOrgName(); if ("BO-AGENT".equals(sc.getAttribute("BOOK_ACTIVATION_AT"))) { newBookStatus = "ACTIVE"; } receipt_id = helper.doTransaction(game_id, orgId, getSavedPackBeanList(), getSavedBookBeanList(), session, rootPath, newBookStatus); boolean isSet = helper.showCreditNote(receipt_id); session.setAttribute("showCreditNote", isSet); logger.info("book and pack save function is complete"); return SUCCESS; }
From source file:org.apache.click.util.ClickUtils.java
/** * Return the application configuration service instance from the given * servlet context./*from w w w .j a v a 2s .c om*/ * * @param servletContext the servlet context to get the config service instance * @return the application config service instance */ public static ConfigService getConfigService(ServletContext servletContext) { ConfigService configService = (ConfigService) servletContext.getAttribute(ConfigService.CONTEXT_NAME); if (configService != null) { return configService; } else { String msg = "could not find ConfigService in the SerlvetContext under the" + " name '" + ConfigService.CONTEXT_NAME + "'.\nThis can occur" + " if ClickUtils.getConfigService() is called before" + " ClickServlet is initialized by the servlet container.\n" + "To fix ensure that ClickServlet is loaded at startup by" + " editing your web.xml and setting the load-on-startup to 0:\n\n" + " <servlet>\n" + " <servlet-name>ClickServlet</servlet-name>\n" + " <servlet-class>org.apache.click.ClickServlet</servlet-class>\n" + " <load-on-startup>0</load-on-startup>\n" + " </servlet>\n"; throw new RuntimeException(msg); } }
From source file:org.apache.tapestry.request.RequestContext.java
/** * Writes the state of the context to the writer, typically for inclusion * in a HTML page returned to the user. This is useful * when debugging. The Inspector uses this as well. * **//*from w w w. j a v a2 s. c o m*/ public void write(IMarkupWriter writer) { // Create a box around all of this stuff ... writer.begin("table"); writer.attribute("class", "request-context-border"); writer.begin("tr"); writer.begin("td"); // Get the session, if it exists, and display it. HttpSession session = getSession(); if (session != null) { object(writer, "Session"); writer.begin("table"); writer.attribute("class", "request-context-object"); section(writer, "Properties"); header(writer, "Name", "Value"); pair(writer, "id", session.getId()); datePair(writer, "creationTime", session.getCreationTime()); datePair(writer, "lastAccessedTime", session.getLastAccessedTime()); pair(writer, "maxInactiveInterval", session.getMaxInactiveInterval()); pair(writer, "new", session.isNew()); List names = getSorted(session.getAttributeNames()); int count = names.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Attributes"); header(writer, "Name", "Value"); } String name = (String) names.get(i); pair(writer, name, session.getAttribute(name)); } writer.end(); // Session } object(writer, "Request"); writer.begin("table"); writer.attribute("class", "request-context-object"); // Parameters ... List parameters = getSorted(_request.getParameterNames()); int count = parameters.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Parameters"); header(writer, "Name", "Value(s)"); } String name = (String) parameters.get(i); String[] values = _request.getParameterValues(name); writer.begin("tr"); writer.attribute("class", getRowClass()); writer.begin("th"); writer.print(name); writer.end(); writer.begin("td"); if (values.length > 1) writer.begin("ul"); for (int j = 0; j < values.length; j++) { if (values.length > 1) writer.beginEmpty("li"); writer.print(values[j]); } writer.end("tr"); } section(writer, "Properties"); header(writer, "Name", "Value"); pair(writer, "authType", _request.getAuthType()); pair(writer, "characterEncoding", _request.getCharacterEncoding()); pair(writer, "contentLength", _request.getContentLength()); pair(writer, "contentType", _request.getContentType()); pair(writer, "method", _request.getMethod()); pair(writer, "pathInfo", _request.getPathInfo()); pair(writer, "pathTranslated", _request.getPathTranslated()); pair(writer, "protocol", _request.getProtocol()); pair(writer, "queryString", _request.getQueryString()); pair(writer, "remoteAddr", _request.getRemoteAddr()); pair(writer, "remoteHost", _request.getRemoteHost()); pair(writer, "remoteUser", _request.getRemoteUser()); pair(writer, "requestedSessionId", _request.getRequestedSessionId()); pair(writer, "requestedSessionIdFromCookie", _request.isRequestedSessionIdFromCookie()); pair(writer, "requestedSessionIdFromURL", _request.isRequestedSessionIdFromURL()); pair(writer, "requestedSessionIdValid", _request.isRequestedSessionIdValid()); pair(writer, "requestURI", _request.getRequestURI()); pair(writer, "scheme", _request.getScheme()); pair(writer, "serverName", _request.getServerName()); pair(writer, "serverPort", _request.getServerPort()); pair(writer, "contextPath", _request.getContextPath()); pair(writer, "servletPath", _request.getServletPath()); // Now deal with any headers List headers = getSorted(_request.getHeaderNames()); count = headers.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Headers"); header(writer, "Name", "Value"); } String name = (String) headers.get(i); String value = _request.getHeader(name); pair(writer, name, value); } // Attributes List attributes = getSorted(_request.getAttributeNames()); count = attributes.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Attributes"); header(writer, "Name", "Value"); } String name = (String) attributes.get(i); pair(writer, name, _request.getAttribute(name)); } // Cookies ... Cookie[] cookies = _request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (i == 0) { section(writer, "Cookies"); header(writer, "Name", "Value"); } Cookie cookie = cookies[i]; pair(writer, cookie.getName(), cookie.getValue()); } // Cookies loop } writer.end(); // Request object(writer, "Servlet"); writer.begin("table"); writer.attribute("class", "request-context-object"); section(writer, "Properties"); header(writer, "Name", "Value"); pair(writer, "servlet", _servlet); pair(writer, "name", _servlet.getServletName()); pair(writer, "servletInfo", _servlet.getServletInfo()); ServletConfig config = _servlet.getServletConfig(); List names = getSorted(config.getInitParameterNames()); count = names.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Init Parameters"); header(writer, "Name", "Value"); } String name = (String) names.get(i); ; pair(writer, name, config.getInitParameter(name)); } writer.end(); // Servlet ServletContext context = config.getServletContext(); object(writer, "Servlet Context"); writer.begin("table"); writer.attribute("class", "request-context-object"); section(writer, "Properties"); header(writer, "Name", "Value"); pair(writer, "majorVersion", context.getMajorVersion()); pair(writer, "minorVersion", context.getMinorVersion()); pair(writer, "serverInfo", context.getServerInfo()); names = getSorted(context.getInitParameterNames()); count = names.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Initial Parameters"); header(writer, "Name", "Value"); } String name = (String) names.get(i); pair(writer, name, context.getInitParameter(name)); } names = getSorted(context.getAttributeNames()); count = names.size(); for (int i = 0; i < count; i++) { if (i == 0) { section(writer, "Attributes"); header(writer, "Name", "Value"); } String name = (String) names.get(i); pair(writer, name, context.getAttribute(name)); } writer.end(); // Servlet Context writeSystemProperties(writer); writer.end("table"); // The enclosing border }
From source file:com.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java
@Override public void contextInitialized(ServletContextEvent evt) { super.contextInitialized(evt); ServletContext ctx = evt.getServletContext(); // First - Load Custom Error List try {//from ww w . j a v a 2s. com Class.forName("com.osbitools.ws.shared.prj.CustErrorList"); } catch (ClassNotFoundException e) { // Ignore Error } // Initialize Entity Utils IEntityUtils eut = getEntityUtils(); ctx.setAttribute("entity_utils", eut); // Initiate LangSetFileUtils ctx.setAttribute("ll_set_utils", new LangSetUtils()); // Check if git repository exists and create one // Using ds subdirectory as git root repository File drepo = new File( getConfigDir(ctx) + File.separator + eut.getPrjRootDirName() + File.separator + ".git"); Git git; try { if (!drepo.exists()) { if (!drepo.mkdirs()) throw new RuntimeErrorException( new Error("Unable create directory '" + drepo.getAbsolutePath() + "'")); try { git = createGitRepo(drepo); } catch (Exception e) { throw new RuntimeErrorException(new Error( "Unable create new repo on path: " + drepo.getAbsolutePath() + ". " + e.getMessage())); } getLogger(ctx).info("Created new git repository '" + drepo.getAbsolutePath() + "'"); } else if (!drepo.isDirectory()) { throw new RuntimeErrorException( new Error(drepo.getAbsolutePath() + " is regular file and not a directory")); } else { git = Git.open(drepo); getLogger(ctx).debug("Open existing repository " + drepo.getAbsolutePath()); } } catch (IOException e) { // Something unexpected and needs to be analyzed e.printStackTrace(); throw new RuntimeErrorException(new Error(e)); } // Save git handler ctx.setAttribute("git", git); // Check if remote destination set/changed StoredConfig config = git.getRepository().getConfig(); String rname = (String) ctx.getAttribute(PrjMgrConstants.PREMOTE_GIT_NAME); String rurl = (String) ctx.getAttribute("git_remote_url"); if (!Utils.isEmpty(rname) && !Utils.isEmpty(rurl)) { String url = config.getString("remote", rname, "url"); if (!rurl.equals(url)) { config.setString("remote", rname, "url", rurl); try { config.save(); } catch (IOException e) { getLogger(ctx).error("Error saving git remote url. " + e.getMessage()); } } } // Temp directory for files upload String tname = System.getProperty("java.io.tmpdir"); getLogger(ctx).info("Using temporarily directory '" + tname + "' for file uploads"); File tdir = new File(tname); if (!tdir.exists()) throw new RuntimeErrorException( new Error("Temporarily directory for file upload '" + tname + "' is not found")); if (!tdir.isDirectory()) throw new RuntimeErrorException( new Error("Temporarily directory for file upload '" + tname + "' is not a directory")); DiskFileItemFactory dfi = new DiskFileItemFactory(); dfi.setSizeThreshold( ((Integer) ctx.getAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)) * 1024 * 1024); dfi.setRepository(tdir); evt.getServletContext().setAttribute("dfi", dfi); // Save entity utils in context evt.getServletContext().setAttribute("entity_utils", getEntityUtils()); }
From source file:com.rapid.core.Application.java
public static Application load(ServletContext servletContext, File file, boolean initialise) throws JAXBException, JSONException, InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException, IOException, ParserConfigurationException, SAXException, TransformerFactoryConfigurationError, TransformerException, RapidLoadingException, XPathExpressionException { // get the logger Logger logger = (Logger) servletContext.getAttribute("logger"); // trace log that we're about to load a page logger.trace("Loading application from " + file); // open the xml file into a document Document appDocument = XML.openDocument(file); // specify the version as -1 int xmlVersion = -1; // look for a version node Node xmlVersionNode = XML.getChildElement(appDocument.getFirstChild(), "XMLVersion"); // if we got one update the version if (xmlVersionNode != null) xmlVersion = Integer.parseInt(xmlVersionNode.getTextContent()); // if the version of this xml isn't the same as this class we have some work to do! if (xmlVersion != XML_VERSION) { // get the page name String name = XML.getChildElementValue(appDocument.getFirstChild(), "name"); // log the difference logger.debug("Application " + name + " with xml version " + xmlVersion + ", current xml version is " + XML_VERSION);/*from w w w . j a va 2s.c om*/ // // Here we would have code to update from known versions of the file to the current version // // check whether there was a version node in the file to start with if (xmlVersionNode == null) { // create the version node xmlVersionNode = appDocument.createElement("XMLVersion"); // add it to the root of the document appDocument.getFirstChild().appendChild(xmlVersionNode); } // set the xml to the latest version xmlVersionNode.setTextContent(Integer.toString(XML_VERSION)); // save it XML.saveDocument(appDocument, file); logger.debug("Updated " + name + " application xml version to " + XML_VERSION); } // get the unmarshaller Unmarshaller unmarshaller = RapidHttpServlet.getUnmarshaller(); try { // unmarshall the application Application application = (Application) unmarshaller.unmarshal(file); // if we don't want pages loaded or resource generation skip this if (initialise) { // load the pages (actually clears down the pages collection and reloads the headers) application.getPages().loadpages(servletContext); // initialise the application and create the resources application.initialise(servletContext, true); } // log that the application was loaded logger.info("Loaded application " + application.getName() + "/" + application.getVersion() + (initialise ? "" : " (no initialisation)")); return application; } catch (JAXBException ex) { throw new RapidLoadingException("Error loading application file at " + file, ex); } }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private Object instantiateBean(String name, Map<String, String> expressions) throws Exception { Object bean = null;/*ww w.j a v a2 s . c o m*/ ServletContext context = WebContext.getApplication(); HttpSession session = WebContext.getSession(); HttpServletRequest request = WebContext.getRequest(); if (request.getAttribute(name) != null) { bean = request.getAttribute(name); executeInjection(bean); return bean; } synchronized (session) { if (session.getAttribute(name) != null) { bean = session.getAttribute(name); executeInjection(bean); return bean; } } if (context.getAttribute(name) != null) { bean = context.getAttribute(name); executeInjection(bean); return bean; } if (webBeans.containsKey(name)) { Class<?> clazz = webBeans.get(name); bean = clazz.newInstance(); WebBean webBean = clazz.getAnnotation(WebBean.class); if (webBean.scope().equals(ScopeType.REQUEST)) { request.setAttribute(name, bean); } else if (webBean.scope().equals(ScopeType.SESSION)) { synchronized (session) { session.setAttribute(name, bean); } } else if (webBean.scope().equals(ScopeType.APPLICATION)) { context.setAttribute(name, bean); } else { return null; } executeInjection(bean); executePreSet(name, bean, expressions); executePostConstruct(bean); } return bean; }
From source file:jp.or.openid.eiwg.scim.operation.Operation.java
/** * /* ww w. ja v a2 s . com*/ * * @param context * @param request * @param attributes * @param requestJson */ public LinkedHashMap<String, Object> updateUserInfo(ServletContext context, HttpServletRequest request, String targetId, 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; } } } // id? LinkedHashMap<String, Object> targetInfo = null; @SuppressWarnings("unchecked") ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context .getAttribute("Users"); Iterator<LinkedHashMap<String, Object>> usersIt = null; if (users != null && !users.isEmpty()) { usersIt = users.iterator(); while (usersIt.hasNext()) { LinkedHashMap<String, Object> userInfo = usersIt.next(); Object id = SCIMUtil.getAttribute(userInfo, "id"); if (id != null && id instanceof String) { if (targetId.equals(id.toString())) { targetInfo = userInfo; break; } } } } if (targetInfo == null) { setError(HttpServletResponse.SC_NOT_FOUND, null, MessageConstants.ERROR_NOT_FOUND); 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, false); 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 { if (!attributeName.equalsIgnoreCase("schemas") && !attributeName.equalsIgnoreCase("id") && !attributeName.equalsIgnoreCase("meta")) { // ???? 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> updateUserInfo = new LinkedHashMap<String, Object>(); // updateUserInfo.put("id", targetId); Iterator<String> attributeIt = requestObject.keySet().iterator(); while (attributeIt.hasNext()) { // ??? String attributeName = attributeIt.next(); // ? Object attributeValue = requestObject.get(attributeName); updateUserInfo.put(attributeName, attributeValue); } // meta Object metaObject = targetInfo.get("meta"); @SuppressWarnings("unchecked") LinkedHashMap<String, Object> metaValues = (LinkedHashMap<String, Object>) metaObject; // meta.lastModified SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"); xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC")); metaValues.put("lastModified", xsdDateTime.format(new Date())); updateUserInfo.put("meta", metaValues); // (??) usersIt.remove(); users.add(updateUserInfo); context.setAttribute("Users", users); // ?? result = new LinkedHashMap<String, Object>(); attributeIt = updateUserInfo.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 = updateUserInfo.get(attributeName); result.put(attributeName, attributeValue); } return result; }
From source file:edu.cornell.mannlib.vitro.webapp.search.solr.SolrSetup.java
@Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); StartupStatus ss = StartupStatus.getBean(context); /* setup the http connection with the solr server */ String solrServerUrlString = ConfigurationProperties.getBean(sce).getProperty("vitro.local.solr.url"); if (solrServerUrlString == null) { ss.fatal(this, "Could not find vitro.local.solr.url in deploy.properties. " + "Vitro application needs a URL of a solr server that it can use to index its data. " + "It should be something like http://localhost:${port}" + context.getContextPath() + "solr"); return;/*from w ww. j ava 2s.c om*/ } URL solrServerUrl = null; try { solrServerUrl = new URL(solrServerUrlString); } catch (MalformedURLException e) { ss.fatal(this, "Can't connect with the solr server. " + "The value for vitro.local.solr.url in deploy.properties is not a valid URL: " + solrServerUrlString); return; } try { CommonsHttpSolrServer server; boolean useMultiPartPost = true; //It would be nice to use the default binary handler but there seem to be library problems server = new CommonsHttpSolrServer(solrServerUrl, null, new XMLResponseParser(), useMultiPartPost); server.setSoTimeout(10000); // socket read timeout server.setConnectionTimeout(10000); server.setDefaultMaxConnectionsPerHost(100); server.setMaxTotalConnections(100); server.setMaxRetries(1); context.setAttribute(SOLR_SERVER, server); /* set up the individual to solr doc translation */ OntModel jenaOntModel = ModelContext.getJenaOntModel(context); Model displayModel = ModelContext.getDisplayModel(context); /* try to get context attribute DocumentModifiers * and use that as the start of the list of DocumentModifier * objects. This allows other ContextListeners to add to * the basic set of DocumentModifiers. */ @SuppressWarnings("unchecked") List<DocumentModifier> modifiers = (List<DocumentModifier>) context.getAttribute("DocumentModifiers"); if (modifiers == null) modifiers = new ArrayList<DocumentModifier>(); modifiers.add(new NameFields(RDFServiceUtils.getRDFServiceFactory(context))); modifiers.add(new NameBoost(1.2f)); modifiers.add(new ThumbnailImageURL(jenaOntModel)); /* try to get context attribute SearchIndexExcludes * and use that as the start of the list of exclude * objects. This allows other ContextListeners to add to * the basic set of SearchIndexExcludes . */ @SuppressWarnings("unchecked") List<SearchIndexExcluder> excludes = (List<SearchIndexExcluder>) context .getAttribute("SearchIndexExcludes"); if (excludes == null) excludes = new ArrayList<SearchIndexExcluder>(); excludes.add(new ExcludeBasedOnNamespace(INDIVIDUAL_NS_EXCLUDES)); excludes.add(new ExcludeBasedOnTypeNamespace(TYPE_NS_EXCLUDES)); excludes.add(new ExcludeBasedOnType(OWL_TYPES_EXCLUDES)); excludes.add(new ExcludeNonFlagVitro()); excludes.add(new SyncingExcludeBasedOnType(displayModel)); IndividualToSolrDocument indToSolrDoc = new IndividualToSolrDocument(excludes, modifiers); /* setup solr indexer */ SolrIndexer solrIndexer = new SolrIndexer(server, indToSolrDoc); // This is where the builder gets the list of places to try to // get objects to index. It is filtered so that non-public text // does not get into the search index. WebappDaoFactory wadf = (WebappDaoFactory) context.getAttribute("webappDaoFactory"); VitroFilters vf = VitroFilterUtils.getPublicFilter(context); wadf = new WebappDaoFactoryFiltering(wadf, vf); // make objects that will find additional URIs for context nodes etc List<StatementToURIsToUpdate> uriFinders = makeURIFinders(jenaOntModel, wadf.getIndividualDao()); // Make the IndexBuilder IndexBuilder builder = new IndexBuilder(solrIndexer, wadf, uriFinders); // Save it to the servlet context so we can access it later in the webapp. context.setAttribute(IndexBuilder.class.getName(), builder); // set up listeners so search index builder is notified of changes to model ServletContext ctx = sce.getServletContext(); SearchReindexingListener srl = new SearchReindexingListener(builder); ModelContext.registerListenerForChanges(ctx, srl); ss.info(this, "Setup of Solr index completed."); } catch (Throwable e) { ss.fatal(this, "could not setup local solr server", e); } }
From source file:jp.or.openid.eiwg.scim.operation.Operation.java
/** * // w ww .j a v a 2s . c om * * @param context * @param request * @param targetId * @param attributes * @param filter * @param sortBy * @param sortOrder * @param startIndex * @param count */ public ArrayList<LinkedHashMap<String, Object>> searchUserInfo(ServletContext context, HttpServletRequest request, String targetId, String attributes, String filter, String sortBy, String sortOrder, String startIndex, String count) { ArrayList<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; } } } // ???????? // (sortBy)? // (sortOrder)? // ?(startIndex)? // 1??(count)? // // () // result = new ArrayList<LinkedHashMap<String, Object>>(); // ? @SuppressWarnings("unchecked") ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context .getAttribute("Users"); if (users != null && !users.isEmpty()) { Iterator<LinkedHashMap<String, Object>> usersIt = users.iterator(); while (usersIt.hasNext()) { boolean isMatched = false; LinkedHashMap<String, Object> userInfo = usersIt.next(); // id??????? if (targetId != null && !targetId.isEmpty()) { Object id = SCIMUtil.getAttribute(userInfo, "id"); if (id != null && id instanceof String) { // id???? if (targetId.equals(id.toString())) { if (filter != null && !filter.isEmpty()) { // ???? boolean matched = false; try { matched = SCIMUtil.checkUserSimpleFilter(context, userInfo, filter); } catch (SCIMUtilException e) { result = null; setError(e.getCode(), e.getType(), e.getMessage()); break; } if (matched) { isMatched = true; } } else { isMatched = true; } } } } else { if (filter != null && !filter.isEmpty()) { // ???? boolean matched = false; try { matched = SCIMUtil.checkUserSimpleFilter(context, userInfo, filter); } catch (SCIMUtilException e) { result = null; setError(e.getCode(), e.getType(), e.getMessage()); break; } if (matched) { isMatched = true; } } else { isMatched = true; } } if (isMatched) { // ?? LinkedHashMap<String, Object> resultInfo = new LinkedHashMap<String, Object>(); Iterator<String> attributeIt = userInfo.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 = userInfo.get(attributeName); resultInfo.put(attributeName, attributeValue); } result.add(resultInfo); } } } return result; }