List of usage examples for javax.servlet ServletContext setAttribute
public void setAttribute(String name, Object object);
From source file:jp.or.openid.eiwg.scim.operation.Operation.java
/** * ?/* w ww .j a v 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:jp.or.openid.eiwg.scim.operation.Operation.java
/** * //from w w w . ja va2s. 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:org.tobarsegais.webapp.ServletContextListenerImpl.java
public void contextInitialized(ServletContextEvent sce) { ServletContext application = sce.getServletContext(); Map<String, String> bundles = new HashMap<String, String>(); Map<String, Toc> contents = new LinkedHashMap<String, Toc>(); List<IndexEntry> keywords = new ArrayList<IndexEntry>(); Directory index = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer); IndexWriter indexWriter;/* w ww. j a v a2 s. c o m*/ try { indexWriter = new IndexWriter(index, indexWriterConfig); } catch (IOException e) { application.log("Cannot create search index. Search will be unavailable.", e); indexWriter = null; } for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) { if (path.endsWith(".jar")) { String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar")); application.log("Parsing " + path); URLConnection connection = null; try { URL url = new URL("jar:" + application.getResource(path) + "!/"); connection = url.openConnection(); if (!(connection instanceof JarURLConnection)) { application.log(path + " is not a jar file, ignoring"); continue; } JarURLConnection jarConnection = (JarURLConnection) connection; JarFile jarFile = jarConnection.getJarFile(); Manifest manifest = jarFile.getManifest(); if (manifest != null) { String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName"); if (symbolicName != null) { int i = symbolicName.indexOf(';'); if (i != -1) { symbolicName = symbolicName.substring(0, i); } bundles.put(symbolicName, key); key = symbolicName; } } JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml"); if (pluginEntry == null) { application.log(path + " does not contain a plugin.xml file, ignoring"); continue; } Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry)); Extension tocExtension = plugin.getExtension("org.eclipse.help.toc"); if (tocExtension == null || tocExtension.getFile("toc") == null) { application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring"); continue; } JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc")); if (tocEntry == null) { application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc") + ", ignoring"); continue; } Toc toc; try { toc = Toc.read(jarFile.getInputStream(tocEntry)); } catch (IllegalStateException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); continue; } contents.put(key, toc); Extension indexExtension = plugin.getExtension("org.eclipse.help.index"); if (indexExtension != null && indexExtension.getFile("index") != null) { JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index")); if (indexEntry != null) { try { keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren()); } catch (IllegalStateException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } } else { application.log( path + " is missing the referenced index: " + indexExtension.getFile("index")); } } application.log(path + " successfully parsed and added as " + key); if (indexWriter != null) { application.log("Indexing content of " + path); Set<String> files = new HashSet<String>(); Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>(); stack.push(Collections.singleton(toc).iterator()); while (!stack.empty()) { Iterator<? extends TocEntry> cur = stack.pop(); if (cur.hasNext()) { TocEntry entry = cur.next(); stack.push(cur); if (!entry.getChildren().isEmpty()) { stack.push(entry.getChildren().iterator()); } String file = entry.getHref(); if (file == null) { continue; } int hashIndex = file.indexOf('#'); if (hashIndex != -1) { file = file.substring(0, hashIndex); } if (files.contains(file)) { // already indexed // todo work out whether to just pull the section continue; } Document document = new Document(); document.add(new Field("title", entry.getLabel(), Field.Store.YES, Field.Index.ANALYZED)); document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES, Field.Index.NO)); JarEntry docEntry = jarFile.getJarEntry(file); if (docEntry == null) { // ignore missing file continue; } InputStream inputStream = null; try { inputStream = jarFile.getInputStream(docEntry); org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream)); document.add(new Field("contents", docDoc.body().text(), Field.Store.NO, Field.Index.ANALYZED)); indexWriter.addDocument(document); } finally { IOUtils.closeQuietly(inputStream); } } } } } catch (XMLStreamException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } catch (MalformedURLException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } catch (IOException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } finally { if (connection instanceof HttpURLConnection) { // should never be the case, but we should try to be sure ((HttpURLConnection) connection).disconnect(); } } } } if (indexWriter != null) { try { indexWriter.close(); } catch (IOException e) { application.log("Cannot create search index. Search will be unavailable.", e); } application.setAttribute("index", index); } application.setAttribute("toc", Collections.unmodifiableMap(contents)); application.setAttribute("keywords", new Index(keywords)); application.setAttribute("bundles", Collections.unmodifiableMap(bundles)); application.setAttribute("analyzer", analyzer); application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer)); }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadApplications(ServletContext servletContext) throws JAXBException, JSONException, InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException, IOException, ParserConfigurationException, SAXException, TransformerFactoryConfigurationError, TransformerException, RapidLoadingException, XPathExpressionException { // get any existing applications Applications applications = (Applications) servletContext.getAttribute("applications"); // check we got some if (applications != null) { // loop the application ids for (String appId : applications.getIds()) { // loop the versions for (String version : applications.getVersions(appId).keySet()) { // get the version Application application = applications.get(appId, version); // close it application.close(servletContext); }//from w w w . j a va2 s . c om } } // make a new set of applications applications = new Applications(); File applicationFolderRoot = new File(servletContext.getRealPath("/WEB-INF/applications/")); for (File applicationFolder : applicationFolderRoot.listFiles()) { if (applicationFolder.isDirectory()) { // get the list of files in this folder - should be all version folders File[] applicationFolders = applicationFolder.listFiles(); // assume we didn't need to version boolean versionCreated = false; // if we got some if (applicationFolders != null) { try { // look for an application file in the root of the application folder File applicationFile = new File(applicationFolder.getAbsoluteFile() + "/application.xml"); // set a version for this app (just in case it doesn't have one) String version = "1"; // if it exists here, it's in the wrong (non-versioned) place! if (applicationFile.exists()) { // create a file for the new version folder File versionFolder = new File(applicationFolder + "/" + version); // keep appending the version if the folder already exists while (versionFolder.exists()) { // append .1 to the version 1, 1.1, 1.1.1, etc version += ".1"; versionFolder = new File(applicationFolder + "/" + version); } // make the dir versionFolder.mkdir(); _logger.info(versionFolder + " created"); // copy in all files and pages folder for (File file : applicationFolders) { // copy all files and the pages folder if (!file.isDirectory() || (file.isDirectory() && "pages".equals(file.getName()))) { // make a desintation file File destFile = new File(versionFolder + "/" + file.getName()); // this is not a version folder itself, copy it to the new version folder Files.copyFolder(file, destFile); // delete the file or folder Files.deleteRecurring(file); // log _logger.info(file + " moved to " + destFile); } } // record that we created a version versionCreated = true; } // application.xml non-versioned check try { // get the version folders File[] versionFolders = applicationFolder.listFiles(); // get a marshaller Marshaller marshaller = RapidHttpServlet.getMarshaller(); // loop them for (File versionFolder : versionFolders) { // check is folder if (versionFolder.isDirectory()) { // look for an application file in the version folder applicationFile = new File(versionFolder + "/application.xml"); // if it exists if (applicationFile.exists()) { // placeholder for the application we're going to version up or just load Application application = null; // if we had to create a version for it if (versionCreated) { // load without resources application = Application.load(servletContext, applicationFile, false); // set the new version application.setVersion(version); // re-initialise it without resources (for the security adapter) application.initialise(servletContext, false); // marshal the updated application object to it's file FileOutputStream fos = new FileOutputStream(applicationFile); marshaller.marshal(application, fos); fos.close(); // get a dir for the pages File pageDir = new File(versionFolder + "/pages"); // check it exists if (pageDir.exists()) { // loop the pages files for (File pageFile : pageDir.listFiles()) { // read the contents of the file String pageContent = Strings.getString(pageFile); // replace all old file references pageContent = pageContent .replace("/" + application.getId() + "/", "/" + application.getId() + "/" + application.getVersion() + "/") .replace("~?a=" + application.getId() + "&", "~?a=" + application.getId() + "&" + application.getVersion() + "&"); // create a file writer FileWriter fs = new FileWriter(pageFile); // save the changes fs.write(pageContent); // close the writer fs.close(); _logger.info(pageFile + " updated with new references"); } } // make a dir for it's web resources File webDir = new File(application.getWebFolder(servletContext)); webDir.mkdir(); _logger.info(webDir + " created"); // loop all the files in the parent for (File file : webDir.getParentFile().listFiles()) { // check not dir if (!file.isDirectory()) { // create a destination file for the new location File destFile = new File(webDir + "/" + file.getName()); // copy it to the new destination Files.copyFile(file, destFile); // delete the file or folder file.delete(); _logger.info(file + " moved to " + destFile); } } } // (re)load the application application = Application.load(servletContext, applicationFile); // put it in our collection applications.put(application); } } // folder check } // version folder loop } catch (Exception ex) { // log the exception _logger.error(ex); } // version load catch } catch (Exception ex) { // log it _logger.error("Error creating version folder for app " + applicationFolder, ex); } // version folder creation catch } // application folders check } // application folder check } // application folder loop // store them in the context servletContext.setAttribute("applications", applications); _logger.info(applications.size() + " applications loaded"); return applications.size(); }