code
stringlengths
73
34.1k
label
stringclasses
1 value
public List<LocaleBean> getLocales(Locale currentLocale) { List<LocaleBean> locales = new ArrayList<>(); // get the array of locales available from the portal List<Locale> portalLocales = localeManagerFactory.getPortalLocales(); for (Locale locale : portalLocales) { if (currentLocale != null) { // if a current locale is available, display language names // using the current locale locales.add(new LocaleBean(locale, currentLocale)); } else { locales.add(new LocaleBean(locale)); } } return locales; }
java
public Locale getCurrentUserLocale(PortletRequest request) { final HttpServletRequest originalPortalRequest = this.portalRequestUtils.getPortletHttpRequest(request); IUserInstance ui = userInstanceManager.getUserInstance(originalPortalRequest); IUserPreferencesManager upm = ui.getPreferencesManager(); final IUserProfile userProfile = upm.getUserProfile(); LocaleManager localeManager = userProfile.getLocaleManager(); // first check the session locales List<Locale> sessionLocales = localeManager.getSessionLocales(); if (sessionLocales != null && sessionLocales.size() > 0) { return sessionLocales.get(0); } // if no session locales were found, check the user locales List<Locale> userLocales = localeManager.getUserLocales(); if (userLocales != null && userLocales.size() > 0) { return userLocales.get(0); } // if no selected locale was found either in the session or user layout, // just return null return null; }
java
public void updateUserLocale(HttpServletRequest request, String localeString) { IUserInstance ui = userInstanceManager.getUserInstance(request); IUserPreferencesManager upm = ui.getPreferencesManager(); final IUserProfile userProfile = upm.getUserProfile(); LocaleManager localeManager = userProfile.getLocaleManager(); if (localeString != null) { // build a new List<Locale> from the specified locale Locale userLocale = localeManagerFactory.parseLocale(localeString); List<Locale> locales = Collections.singletonList(userLocale); // set this locale in the session localeManager.setSessionLocales(locales); // if the current user is logged in, also update the persisted // user locale final IPerson person = ui.getPerson(); if (!person.isGuest()) { try { localeManager.setUserLocales(Collections.singletonList(userLocale)); localeStore.updateUserLocales(person, new Locale[] {userLocale}); // remove person layout framgent from session since it contains some of the data // in previous // translation and won't be cleared until next logout-login (applies when using // RDBMDistributedLayoutStore as user layout store). person.setAttribute(Constants.PLF, null); upm.getUserLayoutManager().loadUserLayout(true); } catch (Exception e) { throw new PortalException(e); } } } }
java
public TenantOperationResponse importWithResources( final ITenant tenant, final Set<Resource> resources) { /* * First load dom4j Documents and sort the entity files into the proper order */ final Map<PortalDataKey, Set<BucketTuple>> importQueue; try { importQueue = prepareImportQueue(tenant, resources); } catch (Exception e) { final TenantOperationResponse error = new TenantOperationResponse(this, TenantOperationResponse.Result.ABORT); error.addMessage( createLocalizedMessage( FAILED_TO_LOAD_TENANT_TEMPLATE, new String[] {tenant.getName()})); return error; } log.trace( "Ready to import data entity templates for new tenant '{}'; importQueue={}", tenant.getName(), importQueue); // We're going to report on every item imported; TODO it would be better // if we could display human-friendly entity type name + sysid (fname, etc.) final StringBuilder importReport = new StringBuilder(); /* * Now import the identified entities each bucket in turn */ try { importQueue(tenant, importQueue, importReport); } catch (Exception e) { final TenantOperationResponse error = new TenantOperationResponse(this, TenantOperationResponse.Result.ABORT); error.addMessage(finalizeImportReport(importReport)); error.addMessage( createLocalizedMessage( FAILED_TO_IMPORT_TENANT_TEMPLATE_DATA, new String[] {tenant.getName()})); return error; } TenantOperationResponse rslt = new TenantOperationResponse(this, TenantOperationResponse.Result.SUCCESS); rslt.addMessage(finalizeImportReport(importReport)); rslt.addMessage( createLocalizedMessage(TENANT_ENTITIES_IMPORTED, new String[] {tenant.getName()})); return rslt; }
java
private Map<PortalDataKey, Set<BucketTuple>> prepareImportQueue( final ITenant tenant, final Set<Resource> templates) throws Exception { final Map<PortalDataKey, Set<BucketTuple>> rslt = new HashMap<>(); Resource rsc = null; try { for (Resource r : templates) { rsc = r; if (log.isDebugEnabled()) { log.debug( "Loading template resource file for tenant " + "'" + tenant.getFname() + "': " + rsc.getFilename()); } final Document doc = reader.read(rsc.getInputStream()); PortalDataKey atLeastOneMatchingDataKey = null; for (PortalDataKey pdk : dataKeyImportOrder) { boolean matches = evaluatePortalDataKeyMatch(doc, pdk); if (matches) { // Found the right bucket... log.debug("Found PortalDataKey '{}' for data document {}", pdk, r.getURI()); atLeastOneMatchingDataKey = pdk; Set<BucketTuple> bucket = rslt.get(atLeastOneMatchingDataKey); if (bucket == null) { // First of these we've seen; create the bucket; bucket = new HashSet<>(); rslt.put(atLeastOneMatchingDataKey, bucket); } BucketTuple tuple = new BucketTuple(rsc, doc); bucket.add(tuple); /* * At this point, we would normally add a break; * statement, but group_membership.xml files need to * match more than one PortalDataKey. */ } } if (atLeastOneMatchingDataKey == null) { // We can't proceed throw new RuntimeException( "No PortalDataKey found for QName: " + doc.getRootElement().getQName()); } } } catch (Exception e) { log.error( "Failed to process the specified template: {}", (rsc != null ? rsc.getFilename() : "null"), e); throw e; } return rslt; }
java
private void importQueue( final ITenant tenant, final Map<PortalDataKey, Set<BucketTuple>> queue, final StringBuilder importReport) throws Exception { final StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setRootObject(new RootObjectImpl(tenant)); IDataTemplatingStrategy templating = new SpELDataTemplatingStrategy(portalSpELService, ctx); Document doc = null; try { for (PortalDataKey pdk : dataKeyImportOrder) { Set<BucketTuple> bucket = queue.get(pdk); if (bucket != null) { log.debug( "Importing the specified PortalDataKey tenant '{}': {}", tenant.getName(), pdk.getName()); for (BucketTuple tuple : bucket) { doc = tuple.getDocument(); Source data = templating.processTemplates( doc, tuple.getResource().getURL().toString()); dataHandlerService.importData(data, pdk); importReport.append(createImportReportLineItem(pdk, tuple)); } } } } catch (Exception e) { log.error( "Failed to process the specified template document:\n{}", (doc != null ? doc.asXML() : "null"), e); throw e; } }
java
public void updateCurrentUsername(String newUsername) { final String originalThreadName = originalThreadNameLocal.get(); if (originalThreadName != null && newUsername != null) { final Thread currentThread = Thread.currentThread(); final String threadName = getThreadName(originalThreadName, newUsername); currentThread.setName(threadName); } }
java
public Set<Entity> search(String entityType, String searchTerm) { if (StringUtils.isBlank(entityType) && StringUtils.isBlank(searchTerm)) { return null; } Set<Entity> results = new HashSet<Entity>(); EntityEnum entityEnum = EntityEnum.getEntityEnum(entityType); EntityIdentifier[] identifiers; Class<?> identifierType; // if the entity type is a group, use the group service's findGroup method // to locate it if (entityEnum.isGroup()) { identifiers = GroupService.searchForGroups( searchTerm, GroupService.SearchMethod.CONTAINS_CI, entityEnum.getClazz()); identifierType = IEntityGroup.class; } // otherwise use the getGroupMember method else { identifiers = GroupService.searchForEntities( searchTerm, GroupService.SearchMethod.CONTAINS_CI, entityEnum.getClazz()); identifierType = entityEnum.getClazz(); } for (EntityIdentifier entityIdentifier : identifiers) { if (entityIdentifier.getType().equals(identifierType)) { IGroupMember groupMember = GroupService.getGroupMember(entityIdentifier); Entity entity = getEntity(groupMember); results.add(entity); } } return results; }
java
private IAuthorizationPrincipal getAuthorizationPrincipal(Authentication authentication) { final Object authPrincipal = authentication.getPrincipal(); logger.trace("getAuthorizationPrincipal -- authPrincipal=[{}]", authPrincipal); String username; if (authPrincipal instanceof UserDetails) { // User is authenticated UserDetails userDetails = (UserDetails) authPrincipal; logger.trace( "getAuthorizationPrincipal -- AUTHENTICATED, userDetails=[{}]", userDetails); username = userDetails.getUsername(); } else { // Which guest user are we? final HttpServletRequest req = portalRequestUtils.getCurrentPortalRequest(); final IPerson person = personManager.getPerson(req); logger.trace("getAuthorizationPrincipal -- UNAUTHENTICATED, person=[{}]", person); username = person.getUserName(); } return authorizationServiceFacade.newPrincipal(username, IPerson.class); }
java
public final void setDuration(int duration) { if (isComplete()) { this.getLogger() .warn( "{} is already closed, the new duration of {} will be ignored on: {}", this.getClass().getSimpleName(), duration, this); return; } this.duration = duration; }
java
protected IEntityGroup createUportalGroupFromGrouperGroup(WsGroup wsGroup) { IEntityGroup iEntityGroup = new EntityGroupImpl(wsGroup.getName(), IPerson.class); // need to set the group name and description to the actual // display name and description iEntityGroup.setName(wsGroup.getDisplayName()); iEntityGroup.setDescription(wsGroup.getDescription()); return iEntityGroup; }
java
protected WsGroup findGroupFromKey(String key) { WsGroup wsGroup = null; if (key != null) { GcFindGroups gcFindGroups = new GcFindGroups(); gcFindGroups.addGroupName(key); WsFindGroupsResults results = gcFindGroups.execute(); // if no results were returned, return null if (results != null && results.getGroupResults() != null && results.getGroupResults().length > 0) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "found group from key " + key + ": " + results.getGroupResults()[0]); } wsGroup = results.getGroupResults()[0]; } } return wsGroup; }
java
protected static String getStemPrefix() { String uportalStem = GrouperClientUtils.propertiesValue(STEM_PREFIX, false); // make sure it ends in colon if (!StringUtils.isBlank(uportalStem)) { if (uportalStem.endsWith(":")) { uportalStem = uportalStem.substring(0, uportalStem.length() - 1); } } return uportalStem; }
java
@Override public void perform() throws PortalException { // push the change into the PLF if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX)) { // we are dealing with an incorporated node ParameterEditManager.removeParmEditDirective(nodeId, name, person); } else { // node owned by user so add parameter child directly Document plf = RDBMDistributedLayoutStore.getPLF(person); Element plfNode = plf.getElementById(nodeId); removeParameterChild(plfNode, name); } // push the change into the ILF removeParameterChild(ilfNode, name); }
java
public static PortletCategoryBean create( String id, String name, String description, Set<PortletCategoryBean> subcategories, Set<PortletDefinitionBean> portlets) { return new PortletCategoryBean(id, name, description, subcategories, portlets); }
java
@PreAuthorize( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))") @RequestMapping(value = "/permissions/owners.json", method = RequestMethod.GET) public ModelAndView getOwners() { // get a list of all currently defined permission owners List<IPermissionOwner> owners = permissionOwnerDao.getAllPermissionOwners(); ModelAndView mv = new ModelAndView(); mv.addObject("owners", owners); mv.setViewName("json"); return mv; }
java
@PreAuthorize( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))") @RequestMapping(value = "/permissions/owners/{owner}.json", method = RequestMethod.GET) public ModelAndView getOwners( @PathVariable("owner") String ownerParam, HttpServletResponse response) { IPermissionOwner owner; if (StringUtils.isNumeric(ownerParam)) { long id = Long.valueOf(ownerParam); owner = permissionOwnerDao.getPermissionOwner(id); } else { owner = permissionOwnerDao.getPermissionOwner(ownerParam); } // if the IPermissionOwner was found, add it to the JSON model if (owner != null) { ModelAndView mv = new ModelAndView(); mv.addObject("owner", owner); mv.setViewName("json"); return mv; } // otherwise return a 404 not found error code else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } }
java
@PreAuthorize( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))") @RequestMapping(value = "/permissions/activities.json", method = RequestMethod.GET) public ModelAndView getActivities(@RequestParam(value = "q", required = false) String query) { if (StringUtils.isNotBlank(query)) { query = query.toLowerCase(); } List<IPermissionActivity> activities = new ArrayList<>(); Collection<IPermissionOwner> owners = permissionOwnerDao.getAllPermissionOwners(); for (IPermissionOwner owner : owners) { for (IPermissionActivity activity : owner.getActivities()) { if (StringUtils.isBlank(query) || activity.getName().toLowerCase().contains(query)) { activities.add(activity); } } } Collections.sort(activities); ModelAndView mv = new ModelAndView(); mv.addObject("activities", activities); mv.setViewName("json"); return mv; }
java
@PreAuthorize( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))") @RequestMapping(value = "/permissions/{activity}/targets.json", method = RequestMethod.GET) public ModelAndView getTargets( @PathVariable("activity") Long activityId, @RequestParam("q") String query) { IPermissionActivity activity = permissionOwnerDao.getPermissionActivity(activityId); Collection<IPermissionTarget> targets = Collections.emptyList(); if (activity != null) { IPermissionTargetProvider provider = targetProviderRegistry.getTargetProvider(activity.getTargetProviderKey()); SortedSet<IPermissionTarget> matchingTargets = new TreeSet<>(); // add matching results for this identifier provider to the set targets = provider.searchTargets(query); for (IPermissionTarget target : targets) { if ((StringUtils.isNotBlank(target.getName()) && target.getName().toLowerCase().contains(query)) || target.getKey().toLowerCase().contains(query)) { matchingTargets.addAll(targets); } } } ModelAndView mv = new ModelAndView(); mv.addObject("targets", targets); mv.setViewName("json"); return mv; }
java
@PreAuthorize( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))") @RequestMapping("/v5-5/permissions/assignments/users/{username}") public ModelAndView getAssignmentsForUser( @PathVariable("username") String username, @RequestParam(value = "includeInherited", required = false, defaultValue = "false") boolean includeInherited) { final JsonEntityBean entity = groupListHelper.getEntity(EntityEnum.PERSON.toString(), username, false); final List<JsonPermission> permissions = getPermissionsForEntity(entity, includeInherited); final ModelAndView mv = new ModelAndView(); mv.addObject("assignments", permissions); mv.setViewName("json"); return mv; }
java
private void setReportFormTabs(final TabRenderReportForm report) { if (!report.getTabs().isEmpty()) { // Tabs are already set, do nothing return; } final Set<AggregatedTabMapping> tabs = this.getTabs(); if (!tabs.isEmpty()) { report.getTabs().add(tabs.iterator().next().getId()); } }
java
@javax.annotation.Resource(name = "dataFileIncludes") public void setDataFileIncludes(Set<String> dataFileIncludes) { this.dataFileIncludes = dataFileIncludes; }
java
private void importDataArchive( final Resource resource, final ArchiveInputStream resourceStream, BatchImportOptions options) { final File tempDir = Files.createTempDir(); try { ArchiveEntry archiveEntry; while ((archiveEntry = resourceStream.getNextEntry()) != null) { final File entryFile = new File(tempDir, archiveEntry.getName()); if (!archiveEntry.isDirectory()) { entryFile.getParentFile().mkdirs(); IOUtils.copy( new CloseShieldInputStream(resourceStream), new FileOutputStream(entryFile)); } } importDataDirectory(tempDir, null, options); } catch (IOException e) { throw new RuntimeException( "Failed to extract data from '" + resource + "' to '" + tempDir + "' for batch import.", e); } finally { FileUtils.deleteQuietly(tempDir); } }
java
private List<FutureHolder<?>> waitForFutures( final Queue<? extends FutureHolder<?>> futures, final PrintWriter reportWriter, final File reportDirectory, final boolean wait) throws InterruptedException { final List<FutureHolder<?>> failedFutures = new LinkedList<>(); for (Iterator<? extends FutureHolder<?>> futuresItr = futures.iterator(); futuresItr.hasNext(); ) { final FutureHolder<?> futureHolder = futuresItr.next(); // If waiting, or if not waiting but the future is already done do the get final Future<?> future = futureHolder.getFuture(); if (wait || (!wait && future.isDone())) { futuresItr.remove(); try { // Don't bother doing a get() on canceled futures if (!future.isCancelled()) { if (this.maxWait > 0) { future.get(this.maxWait, this.maxWaitTimeUnit); } else { future.get(); } reportWriter.printf( REPORT_FORMAT, "SUCCESS", futureHolder.getDescription(), futureHolder.getExecutionTimeMillis()); } } catch (CancellationException e) { // Ignore cancellation exceptions } catch (ExecutionException e) { logger.error("Failed: " + futureHolder); futureHolder.setError(e); failedFutures.add(futureHolder); reportWriter.printf( REPORT_FORMAT, "FAIL", futureHolder.getDescription(), futureHolder.getExecutionTimeMillis()); try { final String dataReportName = SafeFilenameUtils.makeSafeFilename( futureHolder.getDataType() + "_" + futureHolder.getDataName() + ".txt"); final File dataReportFile = new File(reportDirectory, dataReportName); final PrintWriter dataReportWriter = new PrintWriter(new BufferedWriter(new FileWriter(dataReportFile))); try { dataReportWriter.println( "FAIL: " + futureHolder.getDataType() + " - " + futureHolder.getDataName()); dataReportWriter.println( "--------------------------------------------------------------------------------"); e.getCause().printStackTrace(dataReportWriter); } finally { IOUtils.closeQuietly(dataReportWriter); } } catch (Exception re) { logger.warn( "Failed to write error report for failed " + futureHolder + ", logging root failure here", e.getCause()); } } catch (TimeoutException e) { logger.warn("Failed: " + futureHolder); futureHolder.setError(e); failedFutures.add(futureHolder); future.cancel(true); reportWriter.printf( REPORT_FORMAT, "TIMEOUT", futureHolder.getDescription(), futureHolder.getExecutionTimeMillis()); } } } return failedFutures; }
java
@Override public String setParameterValue(String parameterName, String parameterValue) { // don't try to store a null value if (parameterValue == null) return null; return (String) parameters.put(parameterName, parameterValue); }
java
static void applyAndUpdateParmEditSet(Document plf, Document ilf, IntegrationResult result) { Element pSet = null; try { pSet = getParmEditSet(plf, null, false); } catch (Exception e) { LOG.error("Exception occurred while getting user's DLM " + "paramter-edit-set.", e); } if (pSet == null) return; NodeList edits = pSet.getChildNodes(); for (int i = edits.getLength() - 1; i >= 0; i--) { if (applyEdit((Element) edits.item(i), ilf) == false) { pSet.removeChild(edits.item(i)); result.setChangedPLF(true); } else { result.setChangedILF(true); } } if (pSet.getChildNodes().getLength() == 0) { plf.getDocumentElement().removeChild(pSet); result.setChangedPLF(true); } }
java
private static boolean applyEdit(Element edit, Document ilf) { String nodeID = edit.getAttribute(Constants.ATT_TARGET); Element channel = ilf.getElementById(nodeID); if (channel == null) return false; // now get the name of the parameter to be edited and find that element String parmName = edit.getAttribute(Constants.ATT_NAME); String parmValue = edit.getAttribute(Constants.ATT_USER_VALUE); NodeList ilfParms = channel.getChildNodes(); Element targetParm = null; for (int i = 0; i < ilfParms.getLength(); i++) { Element ilfParm = (Element) ilfParms.item(i); if (ilfParm.getAttribute(Constants.ATT_NAME).equals(parmName)) { targetParm = ilfParm; break; } } if (targetParm == null) // parameter not found so we are free to set { Element parameter = ilf.createElement("parameter"); parameter.setAttribute("name", parmName); parameter.setAttribute("value", parmValue); parameter.setAttribute("override", "yes"); channel.appendChild(parameter); return true; } /* TODO Add support for fragments to set dlm:editAllowed attribute for * channel parameters. (2005.11.04 mboyd) * * In the commented code below, the check for editAllowed will never be * seen on a parameter element in the * current database schema approach used by DLM. This is because * parameters are second class citizens of the layout structure. They * are not found in the up_layout_struct table but only in the * up_layout_param table. DLM functionality like dlm:editAllowed, * dlm:moveAllowed, dlm:deleteAllowed, and dlm:addChildAllowed were * implemented without schema changes by adding these as parameters to * structural elements and upon loading any parameter that begins with * 'dlm:' is placed as an attribute on the containing structural * element. So any channel parameter entry with dlm:editAllowed has that * value placed as an attribute on the containing channel not on the * parameter that was meant to have it. * * The only solution would be to add special dlm:parm children below * channels that would get the editAllowed value and then when creating * the DOM don't create those as child elements but use them to set the * attribute on the corresponding parameter by having the name of the * dlm:parm element be the name of the parameter to which it is to be * related. * * The result of this lack of functionality is that fragments can't * mark any channel parameters as dlm:editAllowed='false' thereby * further restricting which channel parameters can be edited beyond * what the channel definition specifies during publishing. */ // Attr editAllowed = targetParm.getAttributeNode( Constants.ATT_EDIT_ALLOWED ); // if ( editAllowed != null && editAllowed.getNodeValue().equals("false")) // return false; // target parm found. See if channel definition will still allow changes. Attr override = targetParm.getAttributeNode(Constants.ATT_OVERRIDE); if (override != null && !override.getNodeValue().equals(Constants.CAN_OVERRIDE)) return false; // now see if the change is still needed if (targetParm.getAttribute(Constants.ATT_VALUE).equals(parmValue)) return false; // user's edit same as fragment or chan def targetParm.setAttribute("value", parmValue); return true; }
java
private static Element getParmEditSet(Document plf, IPerson person, boolean create) throws PortalException { Node root = plf.getDocumentElement(); Node child = root.getFirstChild(); while (child != null) { if (child.getNodeName().equals(Constants.ELM_PARM_SET)) return (Element) child; child = child.getNextSibling(); } if (create == false) return null; String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person.getID(), e); } Element parmSet = plf.createElement(Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_ID, ID); parmSet.setIdAttribute(Constants.ATT_ID, true); root.appendChild(parmSet); return parmSet; }
java
public static synchronized void addParmEditDirective( String targetId, String name, String value, IPerson person) throws PortalException { Document plf = (Document) person.getAttribute(Constants.PLF); Element parmSet = getParmEditSet(plf, person, true); NodeList edits = parmSet.getChildNodes(); Element existingEdit = null; for (int i = 0; i < edits.getLength(); i++) { Element edit = (Element) edits.item(i); if (edit.getAttribute(Constants.ATT_TARGET).equals(targetId) && edit.getAttribute(Constants.ATT_NAME).equals(name)) { existingEdit = edit; break; } } if (existingEdit == null) // existing one not found, create a new one { addParmEditDirective(targetId, name, value, person, plf, parmSet); return; } existingEdit.setAttribute(Constants.ATT_USER_VALUE, value); }
java
private static void addParmEditDirective( String targetID, String name, String value, IPerson person, Document plf, Element parmSet) throws PortalException { String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit node " + "Id for userId=" + person.getID(), e); } Element parm = plf.createElement(Constants.ELM_PARM_EDIT); parm.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_EDIT); parm.setAttribute(Constants.ATT_ID, ID); parm.setIdAttribute(Constants.ATT_ID, true); parm.setAttributeNS(Constants.NS_URI, Constants.ATT_TARGET, targetID); parm.setAttribute(Constants.ATT_NAME, name); parm.setAttribute(Constants.ATT_USER_VALUE, value); parmSet.appendChild(parm); }
java
public static void removeParmEditDirective(String targetId, String name, IPerson person) throws PortalException { Document plf = (Document) person.getAttribute(Constants.PLF); Element parmSet = getParmEditSet(plf, person, false); if (parmSet == null) return; // no set so no edit to remove NodeList edits = parmSet.getChildNodes(); for (int i = 0; i < edits.getLength(); i++) { Element edit = (Element) edits.item(i); if (edit.getAttribute(Constants.ATT_TARGET).equals(targetId) && edit.getAttribute(Constants.ATT_NAME).equals(name)) { parmSet.removeChild(edit); break; } } if (parmSet.getChildNodes().getLength() == 0) // no more edits, remove { Node parent = parmSet.getParentNode(); parent.removeChild(parmSet); } }
java
public static final <T> T dropTableIfExists( JdbcOperations jdbcOperations, final String table, final Function<JdbcOperations, T> preDropCallback) { LOGGER.info("Dropping table: " + table); final boolean tableExists = doesTableExist(jdbcOperations, table); if (tableExists) { final T ret = preDropCallback.apply(jdbcOperations); jdbcOperations.execute("DROP TABLE " + table); return ret; } return null; }
java
public static boolean doesTableExist(JdbcOperations jdbcOperations, final String table) { final boolean tableExists = jdbcOperations.execute( new ConnectionCallback<Boolean>() { @Override public Boolean doInConnection(Connection con) throws SQLException, DataAccessException { final DatabaseMetaData metaData = con.getMetaData(); final ResultSet tables = metaData.getTables( null, null, null, new String[] {"TABLE"}); while (tables.next()) { final String dbTableName = tables.getString("TABLE_NAME"); if (table.equalsIgnoreCase(dbTableName)) { return true; } } return false; } }); return tableExists; }
java
@Override public int getPortalUID(IPerson person, boolean createPortalData) throws AuthorizationException { int uid; String username = (String) person.getAttribute(IPerson.USERNAME); // only synchronize a non-guest request. if (PersonFactory.getGuestUsernames().contains(username)) { uid = __getPortalUID(person, createPortalData); } else { synchronized (getLock(person)) { uid = __getPortalUID(person, createPortalData); } } return uid; }
java
private PortalUser getPortalUser(final String userName) { return jdbcOperations.execute( (ConnectionCallback<PortalUser>) con -> { PortalUser portalUser = null; PreparedStatement pstmt = null; try { String query = "SELECT USER_ID FROM UP_USER WHERE USER_NAME=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, userName); ResultSet rs = null; try { if (log.isDebugEnabled()) log.debug( "RDBMUserIdentityStore::getPortalUID(userName=" + userName + "): " + query); rs = pstmt.executeQuery(); if (rs.next()) { portalUser = new PortalUser(); portalUser.setUserId(rs.getInt("USER_ID")); portalUser.setUserName(userName); } } finally { try { if (rs != null) { rs.close(); } } catch (Exception e) { } } } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } return portalUser; }); }
java
@RequestMapping(params = "action=export") public ModelAndView getExportView(PortletRequest request) { Map<String, Object> model = new HashMap<String, Object>(); // add a list of all permitted export types final Iterable<IPortalDataType> exportPortalDataTypes = this.portalDataHandlerService.getExportPortalDataTypes(); final List<IPortalDataType> types = getAllowedTypes(request, IPermission.EXPORT_ACTIVITY, exportPortalDataTypes); model.put("supportedTypes", types); return new ModelAndView("/jsp/ImportExportPortlet/export", model); }
java
@RequestMapping(params = "action=delete") public ModelAndView getDeleteView(PortletRequest request) { Map<String, Object> model = new HashMap<String, Object>(); // add a list of all permitted deletion types final Iterable<IPortalDataType> deletePortalDataTypes = this.portalDataHandlerService.getDeletePortalDataTypes(); final List<IPortalDataType> types = getAllowedTypes(request, IPermission.DELETE_ACTIVITY, deletePortalDataTypes); model.put("supportedTypes", types); return new ModelAndView("/jsp/ImportExportPortlet/delete", model); }
java
public void validateEditDetails(GroupForm group, MessageContext context) { // ensure the group name is set if (StringUtils.isBlank(group.getName())) { context.addMessage( new MessageBuilder().error().source("name").code("please.enter.name").build()); } }
java
public String getTypeAndIdHash() { assert (entityType != null); assert (id != null); String idStr = id.replaceAll("\\W", "__"); return entityType.toString().toLowerCase() + "_" + idStr; }
java
private void filterAnalyticsGroups( IGroupMember groupMember, JsonNode config, Map<String, Boolean> isMemberCache) { if (config == null) { return; } final JsonNode dimensionGroups = config.get("dimensionGroups"); if (dimensionGroups == null) { return; } for (final Iterator<JsonNode> groupItr = dimensionGroups.elements(); groupItr.hasNext(); ) { final JsonNode group = groupItr.next(); final JsonNode valueNode = group.get("value"); if (valueNode == null) { continue; } final String groupName = valueNode.asText(); Boolean isMember = isMemberCache.get(groupName); if (isMember == null) { isMember = isMember(groupMember, groupName); isMemberCache.put(groupName, isMember); } if (!isMember) { groupItr.remove(); } } }
java
private boolean isMember(IGroupMember groupMember, String groupName) { try { IEntityGroup group = GroupService.findGroup(groupName); if (group != null) { return groupMember.isDeepMemberOf(group); } final EntityIdentifier[] results = GroupService.searchForGroups( groupName, GroupService.SearchMethod.DISCRETE, IPerson.class); if (results == null || results.length == 0) { this.logger.warn( "No portal group found for '{}' no users will be placed in that group for analytics", groupName); return false; } if (results.length > 1) { this.logger.warn( "{} groups were found for groupName '{}'. The first result will be used.", results.length, groupName); } group = (IEntityGroup) GroupService.getGroupMember(results[0]); return groupMember.isDeepMemberOf(group); } catch (Exception e) { this.logger.warn( "Failed to determine if {} is a member of {}, returning false", groupMember, groupName, e); return false; } }
java
@PostConstruct public void warnOnApathyKeyInMappings() { if (null != profileKeyForNoSelection && immutableMappings.containsKey(profileKeyForNoSelection)) { logger.warn( "Configured to treat profile key {} as apathy, " + "yet also configured to map that key to profile fname {}. Apathy wins. " + "This is likely just fine, but it might be a misconfiguration.", profileKeyForNoSelection, immutableMappings.get(profileKeyForNoSelection)); } }
java
protected void chunkString( final List<CharacterEvent> characterEvents, final CharSequence buffer, int patternIndex) { // Iterate over the chunking patterns for (; patternIndex < this.chunkingPatterns.length; patternIndex++) { final Pattern pattern = this.chunkingPatterns[patternIndex]; final Matcher matcher = pattern.matcher(buffer); if (matcher.find()) { final CharacterEventSource eventSource = this.chunkingPatternEventSources.get(pattern); int prevMatchEnd = 0; do { // Add all of the text up to the match as a new chunk, use subSequence to avoid // extra string alloc this.chunkString( characterEvents, buffer.subSequence(prevMatchEnd, matcher.start()), patternIndex + 1); // Get the generated CharacterEvents for the match final MatchResult matchResult = matcher.toMatchResult(); eventSource.generateCharacterEvents(this.request, matchResult, characterEvents); prevMatchEnd = matcher.end(); } while (matcher.find()); // Add any remaining text from the original CharacterDataEvent if (prevMatchEnd < buffer.length()) { this.chunkString( characterEvents, buffer.subSequence(prevMatchEnd, buffer.length()), patternIndex + 1); } return; } } // Buffer didn't match anything, just append the string data // de-duplication of the event string data final String eventString = buffer.toString(); characterEvents.add(CharacterDataEventImpl.create(eventString)); }
java
@Override public IPerson getPerson(HttpServletRequest request) throws PortalSecurityException { /* * This method overrides the implementation of getPerson() in BasePersonManager, but we only * want the RemoteUser behavior here if we're using RemoteUser AuthN. */ if (!remoteUserSecurityContextFactory.isEnabled()) { return super.getPerson(request); } // Return the person object if it exists in the user's session final HttpSession session = request.getSession(false); IPerson person = null; if (session != null) { person = (IPerson) session.getAttribute(PERSON_SESSION_KEY); if (person != null) { return person; } } try { // Create a new instance of a person person = createPersonForRequest(request); // If the user has authenticated with the server which has implemented web // authentication, // the REMOTE_USER environment variable will be set. String remoteUser = request.getRemoteUser(); // We don't want to ignore the security contexts which are already configured in // security.properties, so we // retrieve the existing security contexts. If one of the existing security contexts is // a RemoteUserSecurityContext, // we set the REMOTE_USER field of the existing RemoteUserSecurityContext context. // // If a RemoteUserSecurityContext does not already exist, we create one and populate the // REMOTE_USER field. ISecurityContext context; Enumeration subContexts = null; boolean remoteUserSecurityContextExists = false; // Retrieve existing security contexts. context = person.getSecurityContext(); if (context != null) subContexts = context.getSubContexts(); if (subContexts != null) { while (subContexts.hasMoreElements()) { ISecurityContext ctx = (ISecurityContext) subContexts.nextElement(); // Check to see if a RemoteUserSecurityContext already exists, and set the // REMOTE_USER if (ctx instanceof RemoteUserSecurityContext) { RemoteUserSecurityContext remoteuserctx = (RemoteUserSecurityContext) ctx; remoteuserctx.setRemoteUser(remoteUser); remoteUserSecurityContextExists = true; } } } // If a RemoteUserSecurityContext doesn't already exist, create one. // This preserves the default behavior of this class. if (!remoteUserSecurityContextExists) { RemoteUserSecurityContext remoteuserctx = new RemoteUserSecurityContext(remoteUser); person.setSecurityContext(remoteuserctx); } } catch (Exception e) { // Log the exception logger.error("Exception creating person for request: {}", request, e); } if (session != null) { // Add this person object to the user's session session.setAttribute(PERSON_SESSION_KEY, person); } // Return the new person object return (person); }
java
public static String makeSafeFilename(String filename) { // Replace invalid characters for (final Map.Entry<Pattern, String> pair : REPLACEMENT_PAIRS.entrySet()) { final Pattern pattern = pair.getKey(); final Matcher matcher = pattern.matcher(filename); filename = matcher.replaceAll(pair.getValue()); } // Make sure the name doesn't violate a Windows reserved word... for (Pattern pattern : WINDOWS_INVALID_PATTERNS) { if (pattern.matcher(filename).matches()) { filename = "uP-" + filename; break; } } return filename; }
java
@SuppressWarnings("unchecked") protected <D extends CachedPortletResultHolder<T>, T extends Serializable> CacheState<D, T> getPortletCacheState( HttpServletRequest request, IPortletWindow portletWindow, PublicPortletCacheKey publicCacheKey, Ehcache publicOutputCache, Ehcache privateOutputCache) { final CacheState<D, T> cacheState = new CacheState<D, T>(); cacheState.setPublicPortletCacheKey(publicCacheKey); final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId(); // Check for publicly cached data D cachedPortletData = (D) this.getCachedPortletData(publicCacheKey, publicOutputCache, portletWindow); if (cachedPortletData != null) { cacheState.setCachedPortletData(cachedPortletData); return cacheState; } // Generate private cache key final HttpSession session = request.getSession(); final String sessionId = session.getId(); final IPortletEntityId entityId = portletWindow.getPortletEntityId(); final PrivatePortletCacheKey privateCacheKey = new PrivatePortletCacheKey(sessionId, portletWindowId, entityId, publicCacheKey); cacheState.setPrivatePortletCacheKey(privateCacheKey); // Check for privately cached data cachedPortletData = (D) this.getCachedPortletData(privateCacheKey, privateOutputCache, portletWindow); if (cachedPortletData != null) { cacheState.setCachedPortletData(cachedPortletData); return cacheState; } return cacheState; }
java
@PreAuthorize( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))") @RequestMapping(value = "/permissions/principals.json", method = RequestMethod.GET) public ModelAndView getPrincipals( @RequestParam(value = "q") String query, HttpServletRequest request, HttpServletResponse response) throws Exception { /* * Add groups and people matching the search query to the JSON model */ ModelAndView mv = new ModelAndView(); List<JsonEntityBean> groups = new ArrayList<JsonEntityBean>(); groups.addAll(listHelper.search(EntityEnum.GROUP.toString(), query)); Collections.sort(groups); mv.addObject("groups", groups); List<JsonEntityBean> people = new ArrayList<JsonEntityBean>(); people.addAll(listHelper.search(EntityEnum.PERSON.toString(), query)); Collections.sort(people); mv.addObject("people", people); mv.setViewName("json"); return mv; }
java
static Element appendChild(Element plfChild, Element parent, boolean copyChildren) { Document document = parent.getOwnerDocument(); Element copy = (Element) document.importNode(plfChild, false); parent.appendChild(copy); // set the identifier for the doc if warrented String id = copy.getAttribute(Constants.ATT_ID); if (id != null && !id.equals("")) copy.setIdAttribute(Constants.ATT_ID, true); if (copyChildren) { NodeList children = plfChild.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { if (children.item(i) instanceof Element) appendChild((Element) children.item(i), copy, true); } } return copy; }
java
private boolean isLocked(Class entityType, String entityKey) throws LockingException { return isLocked(entityType, entityKey, null); }
java
@Override public void renew(IEntityLock lock, int duration) throws LockingException { if (isValid(lock)) { Date newExpiration = getNewExpiration(duration); getLockStore().update(lock, newExpiration); ((EntityLockImpl) lock).setExpirationTime(newExpiration); } else { throw new LockingException("Could not renew " + lock + " : lock is invalid."); } }
java
public PortletDefinitionForm createPortletDefinitionForm(IPerson person, String portletId) { IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(portletId); // create the new form final PortletDefinitionForm form; if (def != null) { // if this is a pre-existing portlet, set the category and permissions form = new PortletDefinitionForm(def); form.setId(def.getPortletDefinitionId().getStringId()); // create a JsonEntityBean for each current category and add it // to our form bean's category list Set<PortletCategory> categories = portletCategoryRegistry.getParentCategories(def); for (PortletCategory cat : categories) { form.addCategory(new JsonEntityBean(cat)); } addPrincipalPermissionsToForm(def, form); } else { form = createNewPortletDefinitionForm(); } /* TODO: Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */ // User must have SOME FORM of lifecycle permission over AT LEAST ONE // category in which this portlet resides; lifecycle permissions are // hierarchical, so we'll test with the weakest. if (!hasLifecyclePermission(person, PortletLifecycleState.CREATED, form.getCategories())) { logger.warn( "User '" + person.getUserName() + "' attempted to edit the following portlet without MANAGE permission: " + def); throw new SecurityException("Not Authorized"); } return form; }
java
public void removePortletRegistration(IPerson person, PortletDefinitionForm form) { /* TODO: Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */ // Arguably a check here is redundant since -- in the current // portlet-manager webflow -- you can't get to this point in the // conversation with out first obtaining a PortletDefinitionForm; but // it makes sense to check permissions here as well since the route(s) // to reach this method could evolve in the future. // Let's enforce the policy that you may only delete a portlet thet's // currently in a lifecycle state you have permission to MANAGE. // (They're hierarchical.) if (!hasLifecyclePermission(person, form.getLifecycleState(), form.getCategories())) { logger.warn( "User '" + person.getUserName() + "' attempted to remove portlet '" + form.getFname() + "' without the proper MANAGE permission"); throw new SecurityException("Not Authorized"); } IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(form.getId()); /* * It's very important to remove portlets via the portletPublishingService * because that API cleans up details like category memberships and permissions. */ portletPublishingService.removePortletDefinition(def, person); }
java
public boolean shouldDisplayLayoutLink( IPerson person, PortletDefinitionForm form, String portletId) { if (!form.isNew()) { return false; } // only include the "do layout" link for published portlets. if (form.getLifecycleState() != PortletLifecycleState.PUBLISHED) { return false; } // check that the user can edit at least 1 fragment. Map<String, String> layouts = fragmentAdminHelper.getAuthorizedDlmFragments(person.getUserName()); if (layouts == null || layouts.isEmpty()) { return false; } // check that the user has subscribe priv. IAuthorizationPrincipal authPrincipal = authorizationService.newPrincipal( person.getUserName(), EntityEnum.PERSON.getClazz()); return authPrincipal.canSubscribe(portletId); }
java
public String getFragmentAdminURL(HttpServletRequest request) { IPortalUrlBuilder builder = urlProvider.getPortalUrlBuilderByPortletFName( request, PORTLET_FNAME_FRAGMENT_ADMIN_PORTLET, UrlType.RENDER); IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPortletUrlBuilder(); portletUrlBuilder.setPortletMode(PortletMode.VIEW); portletUrlBuilder.setWindowState(WindowState.MAXIMIZED); return builder.getUrlString(); }
java
public Set<String> getArbitraryPortletPreferenceNames(PortletDefinitionForm form) { // set default values for all portlet parameters PortletPublishingDefinition cpd = this.portletPublishingDefinitionDao.getChannelPublishingDefinition( form.getTypeId()); Set<String> currentPrefs = new HashSet<>(); currentPrefs.addAll(form.getPortletPreferences().keySet()); for (Step step : cpd.getSteps()) { if (step.getPreferences() != null) { for (Preference pref : step.getPreferences()) { currentPrefs.remove(pref.getName()); } } } return currentPrefs; }
java
public List<PortletApplicationDefinition> getPortletApplications() { final PortletRegistryService portletRegistryService = portalDriverContainerServices.getPortletRegistryService(); final List<PortletApplicationDefinition> contexts = new ArrayList<>(); for (final Iterator<String> iter = portletRegistryService.getRegisteredPortletApplicationNames(); iter.hasNext(); ) { final String applicationName = iter.next(); final PortletApplicationDefinition applicationDefninition; try { applicationDefninition = portletRegistryService.getPortletApplication(applicationName); } catch (PortletContainerException e) { throw new RuntimeException( "Failed to load PortletApplicationDefinition for '" + applicationName + "'"); } final List<? extends PortletDefinition> portlets = applicationDefninition.getPortlets(); portlets.sort( new ComparableExtractingComparator<PortletDefinition, String>( String.CASE_INSENSITIVE_ORDER) { @Override protected String getComparable(PortletDefinition o) { final List<? extends DisplayName> displayNames = o.getDisplayNames(); if (displayNames != null && displayNames.size() > 0) { return displayNames.get(0).getDisplayName(); } return o.getPortletName(); } }); contexts.add(applicationDefninition); } contexts.sort( new ComparableExtractingComparator<PortletApplicationDefinition, String>( String.CASE_INSENSITIVE_ORDER) { @Override protected String getComparable(PortletApplicationDefinition o) { final String portletContextName = o.getName(); if (portletContextName != null) { return portletContextName; } final String applicationName = o.getContextPath(); if ("/".equals(applicationName)) { return "ROOT"; } if (applicationName.startsWith("/")) { return applicationName.substring(1); } return applicationName; } }); return contexts; }
java
private void copyAssertionAttributesToUserAttributes(Assertion assertion) { if (!copyAssertionAttributesToUserAttributes) { return; } // skip this if there are no attributes or if the attribute set is empty. if (assertion.getPrincipal().getAttributes() == null || assertion.getPrincipal().getAttributes().isEmpty()) { return; } Map<String, List<Object>> attributes = new HashMap<>(); // loop over the set of person attributes from CAS... for (Map.Entry<String, Object> attrEntry : assertion.getPrincipal().getAttributes().entrySet()) { log.debug( "Adding attribute '{}' from Assertion with value '{}'; runtime type of value is {}", attrEntry.getKey(), attrEntry.getValue(), attrEntry.getValue().getClass().getName()); // Check for credential if (decryptCredentialToPassword && key != null && cipher != null && attrEntry.getKey().equals(CREDENTIAL_KEY)) { try { final String encPwd = (String) (attrEntry.getValue() instanceof List ? ((List) attrEntry.getValue()).get(0) : attrEntry.getValue()); byte[] cred64 = DatatypeConverter.parseBase64Binary(encPwd); cipher.init(Cipher.DECRYPT_MODE, key); final byte[] cipherData = cipher.doFinal(cred64); final Object pwd = new String(cipherData, UTF_8); attributes.put(PASSWORD_KEY, Collections.singletonList(pwd)); } catch (Exception e) { log.warn("Cannot decipher credential", e); } } // convert each attribute to a list, if necessary... List<Object> valueList; if (attrEntry.getValue() instanceof List) { valueList = (List<Object>) attrEntry.getValue(); } else { valueList = Collections.singletonList(attrEntry.getValue()); } // add the attribute... attributes.put(attrEntry.getKey(), valueList); } // get the attribute descriptor from Spring... IAdditionalDescriptors additionalDescriptors = (IAdditionalDescriptors) applicationContext.getBean(SESSION_ADDITIONAL_DESCRIPTORS_BEAN); // add the new properties... additionalDescriptors.addAttributes(attributes); }
java
@Override public IBasicEntity get(Class<? extends IBasicEntity> type, String key) throws CachingException { return EntityCachingServiceLocator.getEntityCachingService().get(type, key); }
java
public IBasicEntity get(EntityIdentifier entityID) throws CachingException { return EntityCachingServiceLocator.getEntityCachingService() .get(entityID.getType(), entityID.getKey()); }
java
@Override public void remove(Class<? extends IBasicEntity> type, String key) throws CachingException { EntityCachingServiceLocator.getEntityCachingService().remove(type, key); }
java
@RequestMapping("VIEW") public String renderError(RenderRequest request, RenderResponse response, ModelMap model) throws Exception { HttpServletRequest httpRequest = this.portalRequestUtils.getPortletHttpRequest(request); IPortletWindowId currentFailedPortletWindowId = (IPortletWindowId) request.getAttribute(REQUEST_ATTRIBUTE__CURRENT_FAILED_PORTLET_WINDOW_ID); model.addAttribute("portletWindowId", currentFailedPortletWindowId); Exception cause = (Exception) request.getAttribute(REQUEST_ATTRIBUTE__CURRENT_EXCEPTION_CAUSE); model.addAttribute("exception", cause); final String rootCauseMessage = ExceptionUtils.getRootCauseMessage(cause); model.addAttribute("rootCauseMessage", rootCauseMessage); // Maintenance Mode? if (cause != null && cause instanceof MaintenanceModeException) { return "/jsp/PortletError/maintenance"; } IUserInstance userInstance = this.userInstanceManager.getUserInstance(httpRequest); if (hasAdminPrivileges(userInstance)) { IPortletWindow window = this.portletWindowRegistry.getPortletWindow( httpRequest, currentFailedPortletWindowId); window.setRenderParameters(new ParameterMap()); IPortalUrlBuilder adminRetryUrl = this.portalUrlProvider.getPortalUrlBuilderByPortletWindow( httpRequest, currentFailedPortletWindowId, UrlType.RENDER); model.addAttribute("adminRetryUrl", adminRetryUrl.getUrlString()); final IPortletWindow portletWindow = portletWindowRegistry.getPortletWindow( httpRequest, currentFailedPortletWindowId); final IPortletEntity parentPortletEntity = portletWindow.getPortletEntity(); final IPortletDefinition parentPortletDefinition = parentPortletEntity.getPortletDefinition(); model.addAttribute("channelDefinition", parentPortletDefinition); StringWriter stackTraceWriter = new StringWriter(); cause.printStackTrace(new PrintWriter(stackTraceWriter)); model.addAttribute("stackTrace", stackTraceWriter.toString()); return "/jsp/PortletError/detailed"; } // no admin privileges, return generic view return "/jsp/PortletError/generic"; }
java
private String getAttributeValue(Attributes attrs, int attribute) throws NamingException { NamingEnumeration values = null; String aValue = ""; if (!isAttribute(attribute)) return aValue; Attribute attrib = attrs.get(attributes[attribute]); if (attrib != null) { for (values = attrib.getAll(); values.hasMoreElements(); ) { aValue = (String) values.nextElement(); break; // take only the first attribute value } } return aValue; }
java
@Override public UserProfile addUserProfile(final IPerson person, final IUserProfile profile) { final int userId = person.getID(); final int layoutId = getLayoutId(person, profile); // generate an id for this profile return jdbcOperations.execute( (ConnectionCallback<UserProfile>) con -> { String sQuery; PreparedStatement pstmt = con.prepareStatement( "INSERT INTO UP_USER_PROFILE " + "(USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, STRUCTURE_SS_ID, THEME_SS_ID," + "DESCRIPTION, LAYOUT_ID) VALUES (?,?,?,?,?,?,?,?)"); int profileId = getNextKey(); pstmt.setInt(1, userId); pstmt.setInt(2, profileId); pstmt.setString(3, profile.getProfileFname()); pstmt.setString(4, profile.getProfileName()); pstmt.setInt(5, profile.getStructureStylesheetId()); pstmt.setInt(6, profile.getThemeStylesheetId()); pstmt.setString(7, profile.getProfileDescription()); pstmt.setInt(8, layoutId); sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, STRUCTURE_SS_ID, THEME_SS_ID, DESCRIPTION, LAYOUT_ID) VALUES (" + userId + ",'" + profileId + ",'" + profile.getProfileFname() + "','" + profile.getProfileName() + "'," + profile.getStructureStylesheetId() + "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "', " + profile.getLayoutId() + ")"; logger.debug("addUserProfile(): {}", sQuery); try { pstmt.executeUpdate(); UserProfile newProfile = new UserProfile(); newProfile.setProfileId(profileId); newProfile.setLayoutId(layoutId); newProfile.setLocaleManager(profile.getLocaleManager()); newProfile.setProfileDescription(profile.getProfileDescription()); newProfile.setProfileFname(profile.getProfileFname()); newProfile.setProfileName(profile.getProfileName()); newProfile.setStructureStylesheetId( profile.getStructureStylesheetId()); newProfile.setSystemProfile(false); newProfile.setThemeStylesheetId(profile.getThemeStylesheetId()); return newProfile; } finally { pstmt.close(); } }); }
java
private void createLayout(HashMap layoutStructure, Document doc, Element root, int structId) { while (structId != 0) { LayoutStructure ls = (LayoutStructure) layoutStructure.get(structId); // replaced with call to method in containing class to allow overriding // by subclasses of RDBMUserLayoutStore. // Element structure = ls.getStructureDocument(doc); Element structure = getStructure(doc, ls); root.appendChild(structure); String id = structure.getAttribute("ID"); if (id != null && !id.equals("")) { structure.setIdAttribute("ID", true); } createLayout(layoutStructure, doc, structure, ls.getChildId()); structId = ls.getNextId(); } }
java
protected String getNextStructId(final IPerson person, final String prefix) { final int userId = person.getID(); return nextStructTransactionOperations.execute( status -> jdbcOperations.execute( new ConnectionCallback<String>() { @Override public String doInConnection(Connection con) throws SQLException, DataAccessException { try (Statement stmt = con.createStatement()) { String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId; logger.debug("getNextStructId(): {}", sQuery); int currentStructId; try (ResultSet rs = stmt.executeQuery(sQuery)) { if (rs.next()) { currentStructId = rs.getInt(1); } else { throw new SQLException( "no rows returned for query [" + sQuery + "]"); } } int nextStructId = currentStructId + 1; String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID=" + currentStructId; logger.debug("getNextStructId(): {}", sUpdate); stmt.executeUpdate(sUpdate); return prefix + nextStructId; } } })); }
java
private int getLayoutID(final int userId, final int profileId) { return jdbcOperations.execute( (ConnectionCallback<Integer>) con -> { String query = "SELECT LAYOUT_ID " + "FROM UP_USER_PROFILE " + "WHERE USER_ID=? AND PROFILE_ID=?"; int layoutId = 0; PreparedStatement pstmt = con.prepareStatement(query); logger.debug( "getLayoutID(userId={}, profileId={} ): {}", userId, profileId, query); pstmt.setInt(1, userId); pstmt.setInt(2, profileId); try { ResultSet rs = pstmt.executeQuery(); if (rs.next()) { layoutId = rs.getInt(1); if (rs.wasNull()) { layoutId = 0; } } } finally { pstmt.close(); } return layoutId; }); }
java
public static String getResourceAsURLString(Class<?> requestingClass, String resource) throws ResourceMissingException { return getResourceAsURL(requestingClass, resource).toString(); }
java
public static InputStream getResourceAsStream(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException { return getResourceAsURL(requestingClass, resource).openStream(); }
java
public static InputSource getResourceAsSAXInputSource(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException { URL url = getResourceAsURL(requestingClass, resource); InputSource source = new InputSource(url.openStream()); source.setPublicId(url.toExternalForm()); return source; }
java
public static Document getResourceAsDocument( Class<?> requestingClass, String resource, boolean validate) throws ResourceMissingException, IOException, ParserConfigurationException, SAXException { Document document = null; InputStream inputStream = null; try { DocumentBuilderFactory factoryToUse = null; if (validate) { factoryToUse = ResourceLoader.validatingDocumentBuilderFactory; } else { factoryToUse = ResourceLoader.nonValidatingDocumentBuilderFactory; } inputStream = getResourceAsStream(requestingClass, resource); DocumentBuilder db = factoryToUse.newDocumentBuilder(); db.setEntityResolver(new DTDResolver()); db.setErrorHandler( new SAXErrorHandler("ResourceLoader.getResourceAsDocument(" + resource + ")")); document = db.parse(inputStream); } finally { if (inputStream != null) inputStream.close(); } return document; }
java
public static Document getResourceAsDocument(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException, ParserConfigurationException, SAXException { // Default is non-validating... return getResourceAsDocument(requestingClass, resource, false); }
java
public static Properties getResourceAsProperties(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException { InputStream inputStream = null; Properties props = null; try { inputStream = getResourceAsStream(requestingClass, resource); props = new Properties(); props.load(inputStream); } finally { if (inputStream != null) inputStream.close(); } return props; }
java
public static String getResourceAsString(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException { String line = null; BufferedReader in = null; StringBuffer sbText = null; try { in = new BufferedReader( new InputStreamReader( getResourceAsStream(requestingClass, resource), UTF_8)); sbText = new StringBuffer(1024); while ((line = in.readLine()) != null) sbText.append(line).append("\n"); } finally { if (in != null) in.close(); } return sbText.toString(); }
java
public void setContextParameters( Map<String, String> principals, Map<String, String> credentials, String ctxName, ISecurityContext securityContext) { if (log.isDebugEnabled()) { final StringBuilder msg = new StringBuilder(); msg.append("Preparing to authenticate; setting parameters for context name '") .append(ctxName) .append("', context class '") .append(securityContext.getClass().getName()) .append("'"); // Display principalTokens... msg.append("\n\t Available Principal Tokens"); for (final Object o : principals.entrySet()) { final Map.Entry<?, ?> y = (Map.Entry<?, ?>) o; msg.append("\n\t\t").append(y.getKey()).append("=").append(y.getValue()); } // Keep credentialTokens secret, but indicate whether they were provided... msg.append("\n\t Available Credential Tokens"); for (final Object o : credentials.entrySet()) { final Map.Entry<?, ?> y = (Map.Entry<?, ?>) o; final String val = (String) y.getValue(); String valWasSpecified = null; if (val != null) { valWasSpecified = val.trim().length() == 0 ? "empty" : "provided"; } msg.append("\n\t\t").append(y.getKey()).append(" was ").append(valWasSpecified); } log.debug(msg.toString()); } String username = principals.get(ctxName); String credential = credentials.get(ctxName); // If username or credential are null, this indicates that the token was not // set in security.properties. We will then use the value for root. username = username != null ? username : (String) principals.get(BASE_CONTEXT_NAME); credential = credential != null ? credential : (String) credentials.get(BASE_CONTEXT_NAME); if (log.isDebugEnabled()) { log.debug("Authentication::setContextParameters() username: " + username); } // Retrieve and populate an instance of the principal object final IPrincipal principalInstance = securityContext.getPrincipalInstance(); if (username != null && !username.equals("")) { principalInstance.setUID(username); } // Retrieve and populate an instance of the credentials object final IOpaqueCredentials credentialsInstance = securityContext.getOpaqueCredentialsInstance(); if (credentialsInstance != null) { credentialsInstance.setCredentials(credential); } }
java
protected void publishRenderEvent( IPortletWindow portletWindow, HttpServletRequest httpServletRequest, RenderPart renderPart, long executionTime, boolean cached) { final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId(); // Determine if the portlet was targeted final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(httpServletRequest); final boolean targeted = portletWindowId.equals(portalRequestInfo.getTargetedPortletWindowId()); renderPart.publishRenderExecutionEvent( this.portalEventFactory, this, httpServletRequest, portletWindowId, executionTime, targeted, cached); }
java
protected void publishResourceEvent( IPortletWindow portletWindow, HttpServletRequest httpServletRequest, long executionTime, boolean usedBrowserCache, boolean usedPortalCache) { final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId(); this.portalEventFactory.publishPortletResourceExecutionEvent( httpServletRequest, this, portletWindowId, executionTime, usedBrowserCache, usedPortalCache); }
java
protected void enforceConfigPermission( final HttpServletRequest httpServletRequest, final IPortletWindow portletWindow) { Validate.notNull( httpServletRequest, "Servlet request must not be null to determine remote user."); Validate.notNull(portletWindow, "Portlet window must not be null to determine its mode."); final PortletMode portletMode = portletWindow.getPortletMode(); if (portletMode != null) { if (IPortletRenderer.CONFIG.equals(portletMode)) { final IPerson person = this.personManager.getPerson(httpServletRequest); final EntityIdentifier ei = person.getEntityIdentifier(); final AuthorizationServiceFacade authorizationServiceFacade = AuthorizationServiceFacade.instance(); final IAuthorizationPrincipal ap = authorizationServiceFacade.newPrincipal(ei.getKey(), ei.getType()); final IPortletEntity portletEntity = portletWindow.getPortletEntity(); final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); if (!ap.canConfigure(portletDefinition.getPortletDefinitionId().getStringId())) { logger.error( "User {} attempted to use portlet {} in {} but lacks permission to use that mode. " + "THIS MAY BE AN ATTEMPT TO EXPLOIT A HISTORICAL SECURITY FLAW. " + "You should probably figure out who this user is and why they are trying to access " + "unauthorized portlet modes.", person.getUserName(), portletDefinition.getFName(), portletMode); throw new AuthorizationException( person.getUserName() + " does not have permission to render '" + portletDefinition.getFName() + "' in " + portletMode + " PortletMode."); } } } }
java
@Override public Object[] getAttributeValues(String key) { if (userAttributes == null) { return null; } final List<Object> values = userAttributes.get(key); if (values != null) { return values.toArray(); } return null; }
java
@Override public void setAttribute(String key, Object value) { if (value == null) { setAttribute(key, null); } else { setAttribute(key, Collections.singletonList(value)); } }
java
@Override public boolean isGuest() { String userName = (String) getAttribute(IPerson.USERNAME); boolean isGuestUsername = PersonFactory.getGuestUsernames().contains(userName); boolean isAuthenticated = m_securityContext != null && m_securityContext.isAuthenticated(); return isGuestUsername && !isAuthenticated; }
java
public IEntityStore newInstance() throws GroupsException { try { return new RDBMEntityStore(); } catch (Exception ex) { log.error("ReferenceEntityStoreFactory.newInstance(): " + ex); throw new GroupsException(ex); } }
java
protected Deque<XMLEvent> getAdditionalEvents(XMLEvent event) { final XMLEvent additionalEvent = this.getAdditionalEvent(event); if (additionalEvent == null) { return null; } final Deque<XMLEvent> additionalEvents = new LinkedList<XMLEvent>(); additionalEvents.push(additionalEvent); return additionalEvents; }
java
protected String getStyleSheetName(final HttpServletRequest request, PreferencesScope scope) { final String stylesheetNameFromRequest; if (scope.equals(PreferencesScope.STRUCTURE)) { stylesheetNameFromRequest = (String) request.getAttribute(STYLESHEET_STRUCTURE_OVERRIDE_REQUEST_ATTRIBUTE); } else { stylesheetNameFromRequest = (String) request.getAttribute(STYLESHEET_THEME_OVERRIDE_REQUEST_ATTRIBUTE_NAME); } return stylesheetNameFromRequest; }
java
@RequestMapping public void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirect = this.selectRedirectionUrl(request); final HttpSession session = request.getSession(false); if (session != null) { // Record that an authenticated user is requesting to log out try { final IPerson person = personManager.getPerson(request); if (person != null && person.getSecurityContext().isAuthenticated()) { this.portalEventFactory.publishLogoutEvent(request, this, person); } } catch (final Exception e) { logger.error( "Exception recording logout " + "associated with request " + request, e); } final String originalUid = this.identitySwapperManager.getOriginalUsername(session); // Logging out from a swapped user, just redirect to the Login servlet if (originalUid != null) { redirect = request.getContextPath() + "/Login"; } else { // Clear out the existing session for the user try { session.invalidate(); } catch (final IllegalStateException ise) { // IllegalStateException indicates session was already invalidated. // This is fine. LogoutController is looking to guarantee the logged out // session is invalid; // it need not insist that it be the one to perform the invalidating. if (logger.isTraceEnabled()) { logger.trace( "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session.", ise); } } } } if (logger.isTraceEnabled()) { logger.trace( "Redirecting to " + redirect + " to send the user back to the guest page."); } final String encodedRedirectURL = response.encodeRedirectURL(redirect); response.sendRedirect(encodedRedirectURL); }
java
protected static void loadProps() { PropertiesManager.props = new Properties(); try { String pfile = System.getProperty(PORTAL_PROPERTIES_FILE_SYSTEM_VARIABLE); if (pfile == null) { pfile = PORTAL_PROPERTIES_FILE_NAME; } PropertiesManager.props.load(PropertiesManager.class.getResourceAsStream(pfile)); } catch (Throwable t) { log.error("Unable to read portal.properties file.", t); } }
java
public static String getProperty(String name) throws MissingPropertyException { if (log.isTraceEnabled()) { log.trace("entering getProperty(" + name + ")"); } if (PropertiesManager.props == null) loadProps(); String val = getPropertyUntrimmed(name); val = val.trim(); if (log.isTraceEnabled()) { log.trace("returning from getProperty(" + name + ") with return value [" + val + "]"); } return val; }
java
public static String getPropertyUntrimmed(String name) throws MissingPropertyException { if (PropertiesManager.props == null) loadProps(); if (props == null) { boolean alreadyReported = registerMissingProperty(name); throw new MissingPropertyException(name, alreadyReported); } String val = props.getProperty(name); if (val == null) { boolean alreadyReported = registerMissingProperty(name); throw new MissingPropertyException(name, alreadyReported); } return val; }
java
private static boolean registerMissingProperty(String name) { final boolean previouslyReported = !PropertiesManager.missingProperties.add(name); if (!previouslyReported && log.isInfoEnabled()) { log.info("Property [" + name + "] was requested but not found."); } return previouslyReported; }
java
public static String getProperty(String name, String defaultValue) { if (PropertiesManager.props == null) loadProps(); String returnValue = defaultValue; try { returnValue = getProperty(name); } catch (MissingPropertyException mpe) { // Do nothing, since we have already recorded and logged the missing property. } return returnValue; }
java
public static boolean getPropertyAsBoolean(final String name, final boolean defaultValue) { if (PropertiesManager.props == null) loadProps(); boolean returnValue = defaultValue; try { returnValue = getPropertyAsBoolean(name); } catch (MissingPropertyException mpe) { // do nothing, since we already logged the missing property } return returnValue; }
java
public static byte getPropertyAsByte(final String name, final byte defaultValue) { if (PropertiesManager.props == null) loadProps(); byte returnValue = defaultValue; try { returnValue = getPropertyAsByte(name); } catch (Throwable t) { log.error( "Could not retrieve or parse as byte property [" + name + "], defaulting to [" + defaultValue + "]", t); } return returnValue; }
java
public static Version parseVersion(String versionString) { final Matcher versionMatcher = VERSION_PATTERN.matcher(versionString); if (!versionMatcher.matches()) { return null; } final int major = Integer.parseInt(versionMatcher.group(1)); final int minor = Integer.parseInt(versionMatcher.group(2)); final int patch = Integer.parseInt(versionMatcher.group(3)); final String local = versionMatcher.group(4); if (local != null) { return new SimpleVersion(major, minor, patch, Integer.valueOf(local)); } return new SimpleVersion(major, minor, patch); }
java
public static Version.Field getMostSpecificMatchingField(Version v1, Version v2) { if (v1.getMajor() != v2.getMajor()) { return null; } if (v1.getMinor() != v2.getMinor()) { return Version.Field.MAJOR; } if (v1.getPatch() != v2.getPatch()) { return Version.Field.MINOR; } final Integer l1 = v1.getLocal(); final Integer l2 = v2.getLocal(); if (l1 != l2 && (l1 == null || l2 == null || !l1.equals(l2))) { return Version.Field.PATCH; } return Version.Field.LOCAL; }
java
public UrlStringBuilder setParameter(String name, String... values) { this.setParameter(name, values != null ? Arrays.asList(values) : null); return this; }
java
public UrlStringBuilder addParameter(String name, String... values) { this.addParameter(name, values != null ? Arrays.asList(values) : null); return this; }
java
public UrlStringBuilder setParameters(String namespace, Map<String, List<String>> parameters) { for (final String name : parameters.keySet()) { Validate.notNull(name, "parameter map cannot contain any null keys"); } this.parameters.clear(); this.addParameters(namespace, parameters); return this; }
java
public UrlStringBuilder setPath(String... elements) { Validate.noNullElements(elements, "elements cannot be null"); this.path.clear(); this.addPath(elements); return this; }
java
public UrlStringBuilder addPath(String element) { Validate.notNull(element, "element cannot be null"); this.path.add(element); return this; }
java
public UrlStringBuilder addPath(String... elements) { Validate.noNullElements(elements, "elements cannot be null"); for (final String element : elements) { this.path.add(element); } return this; }
java
@SuppressWarnings("unchecked") protected Map<String, IPortletPreference> getSessionPreferences( IPortletEntityId portletEntityId, HttpServletRequest httpServletRequest) { final HttpSession session = httpServletRequest.getSession(); final Map<IPortletEntityId, Map<String, IPortletPreference>> portletPreferences; // Sync on the session to ensure the Map isn't in the process of being created synchronized (session) { portletPreferences = (Map<IPortletEntityId, Map<String, IPortletPreference>>) session.getAttribute(PORTLET_PREFERENCES_MAP_ATTRIBUTE); } if (portletPreferences == null) { return null; } return portletPreferences.get(portletEntityId); }
java