repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java | UserLocaleHelper.getLocales | 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 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;
} | [
"public",
"List",
"<",
"LocaleBean",
">",
"getLocales",
"(",
"Locale",
"currentLocale",
")",
"{",
"List",
"<",
"LocaleBean",
">",
"locales",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// get the array of locales available from the portal",
"List",
"<",
"Locale... | Return a list of LocaleBeans matching the currently available locales for the portal.
@param currentLocale
@return | [
"Return",
"a",
"list",
"of",
"LocaleBeans",
"matching",
"the",
"currently",
"available",
"locales",
"for",
"the",
"portal",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java#L77-L92 | train |
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java | UserLocaleHelper.getCurrentUserLocale | 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 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;
} | [
"public",
"Locale",
"getCurrentUserLocale",
"(",
"PortletRequest",
"request",
")",
"{",
"final",
"HttpServletRequest",
"originalPortalRequest",
"=",
"this",
".",
"portalRequestUtils",
".",
"getPortletHttpRequest",
"(",
"request",
")",
";",
"IUserInstance",
"ui",
"=",
... | Return the current user's locale.
@param request The current {@link PortletRequest}
@return | [
"Return",
"the",
"current",
"user",
"s",
"locale",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java#L100-L123 | train |
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java | UserLocaleHelper.updateUserLocale | 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 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);
}
}
}
} | [
"public",
"void",
"updateUserLocale",
"(",
"HttpServletRequest",
"request",
",",
"String",
"localeString",
")",
"{",
"IUserInstance",
"ui",
"=",
"userInstanceManager",
".",
"getUserInstance",
"(",
"request",
")",
";",
"IUserPreferencesManager",
"upm",
"=",
"ui",
"."... | Update the current user's locale to match the selected locale. This implementation will
update the session locale, and if the user is not a guest, will also update the locale in the
user's persisted preferences.
@param request
@param localeString | [
"Update",
"the",
"current",
"user",
"s",
"locale",
"to",
"match",
"the",
"selected",
"locale",
".",
"This",
"implementation",
"will",
"update",
"the",
"session",
"locale",
"and",
"if",
"the",
"user",
"is",
"not",
"a",
"guest",
"will",
"also",
"update",
"th... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java#L133-L168 | train |
Jasig/uPortal | uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java | TemplateDataTenantOperationsListener.importWithResources | 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 | 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;
} | [
"public",
"TenantOperationResponse",
"importWithResources",
"(",
"final",
"ITenant",
"tenant",
",",
"final",
"Set",
"<",
"Resource",
">",
"resources",
")",
"{",
"/*\n * First load dom4j Documents and sort the entity files into the proper order\n */",
"final",
"Map... | High-level implementation method that brokers the queuing, importing, and reporting that is
common to Create and Update. | [
"High",
"-",
"level",
"implementation",
"method",
"that",
"brokers",
"the",
"queuing",
"importing",
"and",
"reporting",
"that",
"is",
"common",
"to",
"Create",
"and",
"Update",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java#L319-L367 | train |
Jasig/uPortal | uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java | TemplateDataTenantOperationsListener.prepareImportQueue | 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 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;
} | [
"private",
"Map",
"<",
"PortalDataKey",
",",
"Set",
"<",
"BucketTuple",
">",
">",
"prepareImportQueue",
"(",
"final",
"ITenant",
"tenant",
",",
"final",
"Set",
"<",
"Resource",
">",
"templates",
")",
"throws",
"Exception",
"{",
"final",
"Map",
"<",
"PortalDa... | Loads dom4j Documents and sorts the entity files into the proper order for Import. | [
"Loads",
"dom4j",
"Documents",
"and",
"sorts",
"the",
"entity",
"files",
"into",
"the",
"proper",
"order",
"for",
"Import",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java#L370-L423 | train |
Jasig/uPortal | uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java | TemplateDataTenantOperationsListener.importQueue | 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 | 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;
}
} | [
"private",
"void",
"importQueue",
"(",
"final",
"ITenant",
"tenant",
",",
"final",
"Map",
"<",
"PortalDataKey",
",",
"Set",
"<",
"BucketTuple",
">",
">",
"queue",
",",
"final",
"StringBuilder",
"importReport",
")",
"throws",
"Exception",
"{",
"final",
"Standar... | Imports the specified entities in the proper order. | [
"Imports",
"the",
"specified",
"entities",
"in",
"the",
"proper",
"order",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tenants/src/main/java/org/apereo/portal/tenants/TemplateDataTenantOperationsListener.java#L426-L462 | train |
Jasig/uPortal | uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/ThreadNamingRequestFilter.java | ThreadNamingRequestFilter.updateCurrentUsername | 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 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);
}
} | [
"public",
"void",
"updateCurrentUsername",
"(",
"String",
"newUsername",
")",
"{",
"final",
"String",
"originalThreadName",
"=",
"originalThreadNameLocal",
".",
"get",
"(",
")",
";",
"if",
"(",
"originalThreadName",
"!=",
"null",
"&&",
"newUsername",
"!=",
"null",... | Update the thread name to use the specified username. Useful for authentication requests
where the username changes mid-request | [
"Update",
"the",
"thread",
"name",
"to",
"use",
"the",
"specified",
"username",
".",
"Useful",
"for",
"authentication",
"requests",
"where",
"the",
"username",
"changes",
"mid",
"-",
"request"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/ThreadNamingRequestFilter.java#L41-L48 | train |
Jasig/uPortal | uPortal-api/uPortal-api-platform-impl/src/main/java/org/apereo/portal/api/groups/EntityService.java | EntityService.search | 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 | 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;
} | [
"public",
"Set",
"<",
"Entity",
">",
"search",
"(",
"String",
"entityType",
",",
"String",
"searchTerm",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"entityType",
")",
"&&",
"StringUtils",
".",
"isBlank",
"(",
"searchTerm",
")",
")",
"{",
"r... | External search, thus case insensitive. | [
"External",
"search",
"thus",
"case",
"insensitive",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-platform-impl/src/main/java/org/apereo/portal/api/groups/EntityService.java#L52-L90 | train |
Jasig/uPortal | uPortal-spring/src/main/java/org/apereo/portal/spring/security/evaluator/PortalPermissionEvaluator.java | PortalPermissionEvaluator.getAuthorizationPrincipal | 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 | 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);
} | [
"private",
"IAuthorizationPrincipal",
"getAuthorizationPrincipal",
"(",
"Authentication",
"authentication",
")",
"{",
"final",
"Object",
"authPrincipal",
"=",
"authentication",
".",
"getPrincipal",
"(",
")",
";",
"logger",
".",
"trace",
"(",
"\"getAuthorizationPrincipal -... | Prepare a uPortal IAuthorizationPrincipal based in the Spring principal | [
"Prepare",
"a",
"uPortal",
"IAuthorizationPrincipal",
"based",
"in",
"the",
"Spring",
"principal"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-spring/src/main/java/org/apereo/portal/spring/security/evaluator/PortalPermissionEvaluator.java#L153-L174 | train |
Jasig/uPortal | uPortal-events/src/main/java/org/apereo/portal/events/aggr/BaseAggregationImpl.java | BaseAggregationImpl.setDuration | 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 | 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;
} | [
"public",
"final",
"void",
"setDuration",
"(",
"int",
"duration",
")",
"{",
"if",
"(",
"isComplete",
"(",
")",
")",
"{",
"this",
".",
"getLogger",
"(",
")",
".",
"warn",
"(",
"\"{} is already closed, the new duration of {} will be ignored on: {}\"",
",",
"this",
... | Set the duration of the interval | [
"Set",
"the",
"duration",
"of",
"the",
"interval"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/aggr/BaseAggregationImpl.java#L133-L144 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-grouper/src/main/java/org/apereo/portal/groups/grouper/GrouperEntityGroupStore.java | GrouperEntityGroupStore.createUportalGroupFromGrouperGroup | 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 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;
} | [
"protected",
"IEntityGroup",
"createUportalGroupFromGrouperGroup",
"(",
"WsGroup",
"wsGroup",
")",
"{",
"IEntityGroup",
"iEntityGroup",
"=",
"new",
"EntityGroupImpl",
"(",
"wsGroup",
".",
"getName",
"(",
")",
",",
"IPerson",
".",
"class",
")",
";",
"// need to set t... | Construct an IEntityGroup from a Grouper WsGroup.
@param wsGroup
@return the group | [
"Construct",
"an",
"IEntityGroup",
"from",
"a",
"Grouper",
"WsGroup",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-grouper/src/main/java/org/apereo/portal/groups/grouper/GrouperEntityGroupStore.java#L508-L516 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-grouper/src/main/java/org/apereo/portal/groups/grouper/GrouperEntityGroupStore.java | GrouperEntityGroupStore.findGroupFromKey | 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 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;
} | [
"protected",
"WsGroup",
"findGroupFromKey",
"(",
"String",
"key",
")",
"{",
"WsGroup",
"wsGroup",
"=",
"null",
";",
"if",
"(",
"key",
"!=",
"null",
")",
"{",
"GcFindGroups",
"gcFindGroups",
"=",
"new",
"GcFindGroups",
"(",
")",
";",
"gcFindGroups",
".",
"a... | Find the Grouper group matching the specified key.
@param key
@return the group or null | [
"Find",
"the",
"Grouper",
"group",
"matching",
"the",
"specified",
"key",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-grouper/src/main/java/org/apereo/portal/groups/grouper/GrouperEntityGroupStore.java#L524-L548 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-grouper/src/main/java/org/apereo/portal/groups/grouper/GrouperEntityGroupStore.java | GrouperEntityGroupStore.getStemPrefix | 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 | 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;
} | [
"protected",
"static",
"String",
"getStemPrefix",
"(",
")",
"{",
"String",
"uportalStem",
"=",
"GrouperClientUtils",
".",
"propertiesValue",
"(",
"STEM_PREFIX",
",",
"false",
")",
";",
"// make sure it ends in colon",
"if",
"(",
"!",
"StringUtils",
".",
"isBlank",
... | Get the prefix for the stem containing uPortal groups. If this value is non-empty, all groups
will be required to be prefixed with the specified stem name.
@return the uportal stem in the registry, without trailing colon | [
"Get",
"the",
"prefix",
"for",
"the",
"stem",
"containing",
"uPortal",
"groups",
".",
"If",
"this",
"value",
"is",
"non",
"-",
"empty",
"all",
"groups",
"will",
"be",
"required",
"to",
"be",
"prefixed",
"with",
"the",
"specified",
"stem",
"name",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-grouper/src/main/java/org/apereo/portal/groups/grouper/GrouperEntityGroupStore.java#L556-L568 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPARemoveParameter.java | LPARemoveParameter.perform | @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 | @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);
} | [
"@",
"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 ... | Remove the parameter from a channel in both the ILF and PLF using the appropriate mechanisms
for incorporated nodes versus owned nodes. | [
"Remove",
"the",
"parameter",
"from",
"a",
"channel",
"in",
"both",
"the",
"ILF",
"and",
"PLF",
"using",
"the",
"appropriate",
"mechanisms",
"for",
"incorporated",
"nodes",
"versus",
"owned",
"nodes",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPARemoveParameter.java#L40-L54 | train |
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/layout/dlm/remoting/registry/v43/PortletCategoryBean.java | PortletCategoryBean.create | 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 | public static PortletCategoryBean create(
String id,
String name,
String description,
Set<PortletCategoryBean> subcategories,
Set<PortletDefinitionBean> portlets) {
return new PortletCategoryBean(id, name, description, subcategories, portlets);
} | [
"public",
"static",
"PortletCategoryBean",
"create",
"(",
"String",
"id",
",",
"String",
"name",
",",
"String",
"description",
",",
"Set",
"<",
"PortletCategoryBean",
">",
"subcategories",
",",
"Set",
"<",
"PortletDefinitionBean",
">",
"portlets",
")",
"{",
"ret... | Creates a new bean based on the provided inputs. | [
"Creates",
"a",
"new",
"bean",
"based",
"on",
"the",
"provided",
"inputs",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/layout/dlm/remoting/registry/v43/PortletCategoryBean.java#L57-L64 | train |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java | PermissionsRESTController.getOwners | @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.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;
} | [
"@",
"PreAuthorize",
"(",
"\"hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))\"",
")",
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/permissions/owners.json\"",
",",
"method",
"=",
"Reques... | Provide a JSON view of all known permission owners registered with uPortal. | [
"Provide",
"a",
"JSON",
"view",
"of",
"all",
"known",
"permission",
"owners",
"registered",
"with",
"uPortal",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java#L96-L109 | train |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java | PermissionsRESTController.getOwners | @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/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;
}
} | [
"@",
"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",
"=",
... | Provide a detailed view of the specified IPermissionOwner. This view should contain a list of
the owner's defined activities. | [
"Provide",
"a",
"detailed",
"view",
"of",
"the",
"specified",
"IPermissionOwner",
".",
"This",
"view",
"should",
"contain",
"a",
"list",
"of",
"the",
"owner",
"s",
"defined",
"activities",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java#L115-L143 | train |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java | PermissionsRESTController.getActivities | @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/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;
} | [
"@",
"PreAuthorize",
"(",
"\"hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))\"",
")",
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/permissions/activities.json\"",
",",
"method",
"=",
"Re... | Provide a list of all registered IPermissionActivities. If an optional search string is
provided, the returned list will be restricted to activities matching the query. | [
"Provide",
"a",
"list",
"of",
"all",
"registered",
"IPermissionActivities",
".",
"If",
"an",
"optional",
"search",
"string",
"is",
"provided",
"the",
"returned",
"list",
"will",
"be",
"restricted",
"to",
"activities",
"matching",
"the",
"query",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java#L149-L176 | train |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java | PermissionsRESTController.getTargets | @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(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;
} | [
"@",
"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",
"=... | Return a list of targets defined for a particular IPermissionActivity matching the specified
search query. | [
"Return",
"a",
"list",
"of",
"targets",
"defined",
"for",
"a",
"particular",
"IPermissionActivity",
"matching",
"the",
"specified",
"search",
"query",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java#L182-L210 | train |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java | PermissionsRESTController.getAssignmentsForUser | @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 | @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;
} | [
"@",
"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",
"ModelAndV... | Provides the collection of permission assignments that apply to the specified user,
optionally including inherited assignments.
@since 5.5 | [
"Provides",
"the",
"collection",
"of",
"permission",
"assignments",
"that",
"apply",
"to",
"the",
"specified",
"user",
"optionally",
"including",
"inherited",
"assignments",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/permissions/PermissionsRESTController.java#L235-L252 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/TabRenderStatisticsController.java | TabRenderStatisticsController.setReportFormTabs | 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 | 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());
}
} | [
"private",
"void",
"setReportFormTabs",
"(",
"final",
"TabRenderReportForm",
"report",
")",
"{",
"if",
"(",
"!",
"report",
".",
"getTabs",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"// Tabs are already set, do nothing",
"return",
";",
"}",
"final",
"Set",
... | Set the tab names to have first selected by default | [
"Set",
"the",
"tab",
"names",
"to",
"have",
"first",
"selected",
"by",
"default"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/TabRenderStatisticsController.java#L99-L109 | train |
Jasig/uPortal | uPortal-io/uPortal-io-core/src/main/java/org/apereo/portal/io/xml/JaxbPortalDataHandlerService.java | JaxbPortalDataHandlerService.setDataFileIncludes | @javax.annotation.Resource(name = "dataFileIncludes")
public void setDataFileIncludes(Set<String> dataFileIncludes) {
this.dataFileIncludes = dataFileIncludes;
} | java | @javax.annotation.Resource(name = "dataFileIncludes")
public void setDataFileIncludes(Set<String> dataFileIncludes) {
this.dataFileIncludes = dataFileIncludes;
} | [
"@",
"javax",
".",
"annotation",
".",
"Resource",
"(",
"name",
"=",
"\"dataFileIncludes\"",
")",
"public",
"void",
"setDataFileIncludes",
"(",
"Set",
"<",
"String",
">",
"dataFileIncludes",
")",
"{",
"this",
".",
"dataFileIncludes",
"=",
"dataFileIncludes",
";",... | Ant path matching patterns that files must match to be included | [
"Ant",
"path",
"matching",
"patterns",
"that",
"files",
"must",
"match",
"to",
"be",
"included"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-io/uPortal-io-core/src/main/java/org/apereo/portal/io/xml/JaxbPortalDataHandlerService.java#L221-L224 | train |
Jasig/uPortal | uPortal-io/uPortal-io-core/src/main/java/org/apereo/portal/io/xml/JaxbPortalDataHandlerService.java | JaxbPortalDataHandlerService.importDataArchive | 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 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);
}
} | [
"private",
"void",
"importDataArchive",
"(",
"final",
"Resource",
"resource",
",",
"final",
"ArchiveInputStream",
"resourceStream",
",",
"BatchImportOptions",
"options",
")",
"{",
"final",
"File",
"tempDir",
"=",
"Files",
".",
"createTempDir",
"(",
")",
";",
"try"... | Extracts the archive resource and then runs the batch-import process on it. | [
"Extracts",
"the",
"archive",
"resource",
"and",
"then",
"runs",
"the",
"batch",
"-",
"import",
"process",
"on",
"it",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-io/uPortal-io-core/src/main/java/org/apereo/portal/io/xml/JaxbPortalDataHandlerService.java#L490-L520 | train |
Jasig/uPortal | uPortal-io/uPortal-io-core/src/main/java/org/apereo/portal/io/xml/JaxbPortalDataHandlerService.java | JaxbPortalDataHandlerService.waitForFutures | 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 | 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;
} | [
"private",
"List",
"<",
"FutureHolder",
"<",
"?",
">",
">",
"waitForFutures",
"(",
"final",
"Queue",
"<",
"?",
"extends",
"FutureHolder",
"<",
"?",
">",
">",
"futures",
",",
"final",
"PrintWriter",
"reportWriter",
",",
"final",
"File",
"reportDirectory",
","... | Used by batch import and export to wait for queued tasks to complete. Handles fail-fast
behavior if any of the tasks threw and exception by canceling all queued futures and logging
a summary of the failures. All completed futures are removed from the queue.
@param futures Queued futures to check for completeness
@param wait If true it will wait for all futures to complete, if false only check for
completed futures
@return a list of futures that either threw exceptions or timed out | [
"Used",
"by",
"batch",
"import",
"and",
"export",
"to",
"wait",
"for",
"queued",
"tasks",
"to",
"complete",
".",
"Handles",
"fail",
"-",
"fast",
"behavior",
"if",
"any",
"of",
"the",
"tasks",
"threw",
"and",
"exception",
"by",
"canceling",
"all",
"queued",... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-io/uPortal-io-core/src/main/java/org/apereo/portal/io/xml/JaxbPortalDataHandlerService.java#L1123-L1214 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-core/src/main/java/org/apereo/portal/layout/node/UserLayoutChannelDescription.java | UserLayoutChannelDescription.setParameterValue | @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 | @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);
} | [
"@",
"Override",
"public",
"String",
"setParameterValue",
"(",
"String",
"parameterName",
",",
"String",
"parameterValue",
")",
"{",
"// don't try to store a null value",
"if",
"(",
"parameterValue",
"==",
"null",
")",
"return",
"null",
";",
"return",
"(",
"String",... | Set a channel parameter value.
@param parameterValue a <code>String</code> value
@param parameterName a <code>String</code> value
@return a <code>String</code> value that was set. | [
"Set",
"a",
"channel",
"parameter",
"value",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-core/src/main/java/org/apereo/portal/layout/node/UserLayoutChannelDescription.java#L374-L379 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java | ParameterEditManager.applyAndUpdateParmEditSet | 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 | 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);
}
} | [
"static",
"void",
"applyAndUpdateParmEditSet",
"(",
"Document",
"plf",
",",
"Document",
"ilf",
",",
"IntegrationResult",
"result",
")",
"{",
"Element",
"pSet",
"=",
"null",
";",
"try",
"{",
"pSet",
"=",
"getParmEditSet",
"(",
"plf",
",",
"null",
",",
"false"... | Get the parm edit set if any from the plf and process each edit command removing any that
fail from the set so that the set is self cleaning.
@throws Exception | [
"Get",
"the",
"parm",
"edit",
"set",
"if",
"any",
"from",
"the",
"plf",
"and",
"process",
"each",
"edit",
"command",
"removing",
"any",
"that",
"fail",
"from",
"the",
"set",
"so",
"that",
"the",
"set",
"is",
"self",
"cleaning",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L59-L85 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java | ParameterEditManager.applyEdit | 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 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;
} | [
"private",
"static",
"boolean",
"applyEdit",
"(",
"Element",
"edit",
",",
"Document",
"ilf",
")",
"{",
"String",
"nodeID",
"=",
"edit",
".",
"getAttribute",
"(",
"Constants",
".",
"ATT_TARGET",
")",
";",
"Element",
"channel",
"=",
"ilf",
".",
"getElementById... | Attempt to apply a single channel parameter edit command and return true if it succeeds or
false otherwise. If the edit is disallowed or the target element no longer exists in the
document the edit command fails and returns false.
@throws Exception | [
"Attempt",
"to",
"apply",
"a",
"single",
"channel",
"parameter",
"edit",
"command",
"and",
"return",
"true",
"if",
"it",
"succeeds",
"or",
"false",
"otherwise",
".",
"If",
"the",
"edit",
"is",
"disallowed",
"or",
"the",
"target",
"element",
"no",
"longer",
... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L94-L168 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java | ParameterEditManager.getParmEditSet | 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 | 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;
} | [
"private",
"static",
"Element",
"getParmEditSet",
"(",
"Document",
"plf",
",",
"IPerson",
"person",
",",
"boolean",
"create",
")",
"throws",
"PortalException",
"{",
"Node",
"root",
"=",
"plf",
".",
"getDocumentElement",
"(",
")",
";",
"Node",
"child",
"=",
"... | Get the parameter edits set if any stored in the root of the document or create it if
passed-in create flag is true. | [
"Get",
"the",
"parameter",
"edits",
"set",
"if",
"any",
"stored",
"in",
"the",
"root",
"of",
"the",
"document",
"or",
"create",
"it",
"if",
"passed",
"-",
"in",
"create",
"flag",
"is",
"true",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L174-L204 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java | ParameterEditManager.addParmEditDirective | 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 | 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);
} | [
"public",
"static",
"synchronized",
"void",
"addParmEditDirective",
"(",
"String",
"targetId",
",",
"String",
"name",
",",
"String",
"value",
",",
"IPerson",
"person",
")",
"throws",
"PortalException",
"{",
"Document",
"plf",
"=",
"(",
"Document",
")",
"person",... | Create and append a parameter edit directive to parameter edits set for applying a user
specified value to a named parameter of the incorporated channel represented by the passed-in
target id. If one already exists for that node and that name then the value of the existing
edit is changed to the passed-in value. | [
"Create",
"and",
"append",
"a",
"parameter",
"edit",
"directive",
"to",
"parameter",
"edits",
"set",
"for",
"applying",
"a",
"user",
"specified",
"value",
"to",
"a",
"named",
"parameter",
"of",
"the",
"incorporated",
"channel",
"represented",
"by",
"the",
"pas... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L212-L233 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java | ParameterEditManager.addParmEditDirective | 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 | 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);
} | [
"private",
"static",
"void",
"addParmEditDirective",
"(",
"String",
"targetID",
",",
"String",
"name",
",",
"String",
"value",
",",
"IPerson",
"person",
",",
"Document",
"plf",
",",
"Element",
"parmSet",
")",
"throws",
"PortalException",
"{",
"String",
"ID",
"... | This method does the actual work of adding a newly created parameter edit and adding it to
the parameter edits set. | [
"This",
"method",
"does",
"the",
"actual",
"work",
"of",
"adding",
"a",
"newly",
"created",
"parameter",
"edit",
"and",
"adding",
"it",
"to",
"the",
"parameter",
"edits",
"set",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L239-L268 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java | ParameterEditManager.removeParmEditDirective | 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 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);
}
} | [
"public",
"static",
"void",
"removeParmEditDirective",
"(",
"String",
"targetId",
",",
"String",
"name",
",",
"IPerson",
"person",
")",
"throws",
"PortalException",
"{",
"Document",
"plf",
"=",
"(",
"Document",
")",
"person",
".",
"getAttribute",
"(",
"Constants... | Remove a parameter edit directive from the parameter edits set for applying user specified
values to a named parameter of an incorporated channel represented by the passed-in target
id. If one doesn't exists for that node and that name then this call returns without any
effects. | [
"Remove",
"a",
"parameter",
"edit",
"directive",
"from",
"the",
"parameter",
"edits",
"set",
"for",
"applying",
"user",
"specified",
"values",
"to",
"a",
"named",
"parameter",
"of",
"an",
"incorporated",
"channel",
"represented",
"by",
"the",
"passed",
"-",
"i... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L275-L297 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/JdbcUtils.java | JdbcUtils.dropTableIfExists | 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 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;
} | [
"public",
"static",
"final",
"<",
"T",
">",
"T",
"dropTableIfExists",
"(",
"JdbcOperations",
"jdbcOperations",
",",
"final",
"String",
"table",
",",
"final",
"Function",
"<",
"JdbcOperations",
",",
"T",
">",
"preDropCallback",
")",
"{",
"LOGGER",
".",
"info",
... | Check if the named table exists, if it does drop it, calling the preDropCallback first
@param jdbcOperations {@link JdbcOperations} used to check if the table exists and execute
the drop
@param table The name of the table to drop, case insensitive
@param preDropCallback The callback to execute immediately before the table is dropped
@return The result returned from the callback | [
"Check",
"if",
"the",
"named",
"table",
"exists",
"if",
"it",
"does",
"drop",
"it",
"calling",
"the",
"preDropCallback",
"first"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/JdbcUtils.java#L44-L59 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/JdbcUtils.java | JdbcUtils.doesTableExist | 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 | 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;
} | [
"public",
"static",
"boolean",
"doesTableExist",
"(",
"JdbcOperations",
"jdbcOperations",
",",
"final",
"String",
"table",
")",
"{",
"final",
"boolean",
"tableExists",
"=",
"jdbcOperations",
".",
"execute",
"(",
"new",
"ConnectionCallback",
"<",
"Boolean",
">",
"(... | Check if the specified table exists | [
"Check",
"if",
"the",
"specified",
"table",
"exists"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/JdbcUtils.java#L62-L86 | train |
Jasig/uPortal | uPortal-persondir/src/main/java/org/apereo/portal/RDBMUserIdentityStore.java | RDBMUserIdentityStore.getPortalUID | @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 | @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;
} | [
"@",
"Override",
"public",
"int",
"getPortalUID",
"(",
"IPerson",
"person",
",",
"boolean",
"createPortalData",
")",
"throws",
"AuthorizationException",
"{",
"int",
"uid",
";",
"String",
"username",
"=",
"(",
"String",
")",
"person",
".",
"getAttribute",
"(",
... | Get the portal user ID for this person object.
@param person The {@link IPerson} for whom a UID is requested
@param createPortalData indicating whether to try to create all uPortal data for this user
from template prototype
@return uPortalUID number or -1 if unable to create user.
@throws AuthorizationException if createPortalData is false and no user is found or if a sql
error is encountered | [
"Get",
"the",
"portal",
"user",
"ID",
"for",
"this",
"person",
"object",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-persondir/src/main/java/org/apereo/portal/RDBMUserIdentityStore.java#L268-L283 | train |
Jasig/uPortal | uPortal-persondir/src/main/java/org/apereo/portal/RDBMUserIdentityStore.java | RDBMUserIdentityStore.getPortalUser | 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 | 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;
});
} | [
"private",
"PortalUser",
"getPortalUser",
"(",
"final",
"String",
"userName",
")",
"{",
"return",
"jdbcOperations",
".",
"execute",
"(",
"(",
"ConnectionCallback",
"<",
"PortalUser",
">",
")",
"con",
"->",
"{",
"PortalUser",
"portalUser",
"=",
"null",
";",
"Pr... | Gets the PortalUser data store object for the specified user name.
@param userName The user's name
@return A PortalUser object or null if the user doesn't exist. | [
"Gets",
"the",
"PortalUser",
"data",
"store",
"object",
"for",
"the",
"specified",
"user",
"name",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-persondir/src/main/java/org/apereo/portal/RDBMUserIdentityStore.java#L377-L423 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/importexport/ImportExportPortletController.java | ImportExportPortletController.getExportView | @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=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);
} | [
"@",
"RequestMapping",
"(",
"params",
"=",
"\"action=export\"",
")",
"public",
"ModelAndView",
"getExportView",
"(",
"PortletRequest",
"request",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"model",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
... | Display the entity export form view.
@param request
@return | [
"Display",
"the",
"entity",
"export",
"form",
"view",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/importexport/ImportExportPortletController.java#L84-L96 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/importexport/ImportExportPortletController.java | ImportExportPortletController.getDeleteView | @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 | @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);
} | [
"@",
"RequestMapping",
"(",
"params",
"=",
"\"action=delete\"",
")",
"public",
"ModelAndView",
"getDeleteView",
"(",
"PortletRequest",
"request",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"model",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
... | Display the entity deletion form view.
@param request
@return | [
"Display",
"the",
"entity",
"deletion",
"form",
"view",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/importexport/ImportExportPortletController.java#L104-L116 | train |
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/groupadmin/GroupFormValidator.java | GroupFormValidator.validateEditDetails | 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 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());
}
} | [
"public",
"void",
"validateEditDetails",
"(",
"GroupForm",
"group",
",",
"MessageContext",
"context",
")",
"{",
"// ensure the group name is set",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"group",
".",
"getName",
"(",
")",
")",
")",
"{",
"context",
".",
... | Validate the detail editing group view
@param group
@param context | [
"Validate",
"the",
"detail",
"editing",
"group",
"view"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/groupadmin/GroupFormValidator.java#L30-L37 | train |
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/layout/dlm/remoting/JsonEntityBean.java | JsonEntityBean.getTypeAndIdHash | public String getTypeAndIdHash() {
assert (entityType != null);
assert (id != null);
String idStr = id.replaceAll("\\W", "__");
return entityType.toString().toLowerCase() + "_" + idStr;
} | java | public String getTypeAndIdHash() {
assert (entityType != null);
assert (id != null);
String idStr = id.replaceAll("\\W", "__");
return entityType.toString().toLowerCase() + "_" + idStr;
} | [
"public",
"String",
"getTypeAndIdHash",
"(",
")",
"{",
"assert",
"(",
"entityType",
"!=",
"null",
")",
";",
"assert",
"(",
"id",
"!=",
"null",
")",
";",
"String",
"idStr",
"=",
"id",
".",
"replaceAll",
"(",
"\"\\\\W\"",
",",
"\"__\"",
")",
";",
"return... | Compute a hash based on type and ID to uniquely identify this bean. This method helps avoid
the unlikely case where a group and person in the same principal list have the same ID.
<p>Periods are replaced to avoid issues in JSP EL and form names can't contain spaces. Also
SpEL parsing of form field names fails with characters such as dash or parenthesis (which
PAGS groups can have) and likely other characters so they are also replaced with underscores.
@return EntityType + "_" + ID | [
"Compute",
"a",
"hash",
"based",
"on",
"type",
"and",
"ID",
"to",
"uniquely",
"identify",
"this",
"bean",
".",
"This",
"method",
"helps",
"avoid",
"the",
"unlikely",
"case",
"where",
"a",
"group",
"and",
"person",
"in",
"the",
"same",
"principal",
"list",
... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/layout/dlm/remoting/JsonEntityBean.java#L173-L178 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/googleanalytics/GoogleAnalyticsController.java | GoogleAnalyticsController.filterAnalyticsGroups | 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 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();
}
}
} | [
"private",
"void",
"filterAnalyticsGroups",
"(",
"IGroupMember",
"groupMember",
",",
"JsonNode",
"config",
",",
"Map",
"<",
"String",
",",
"Boolean",
">",
"isMemberCache",
")",
"{",
"if",
"(",
"config",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
... | Remove groups from the AnalyticsConfig that the current user is not a member of | [
"Remove",
"groups",
"from",
"the",
"AnalyticsConfig",
"that",
"the",
"current",
"user",
"is",
"not",
"a",
"member",
"of"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/googleanalytics/GoogleAnalyticsController.java#L94-L125 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/googleanalytics/GoogleAnalyticsController.java | GoogleAnalyticsController.isMember | 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 | 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;
}
} | [
"private",
"boolean",
"isMember",
"(",
"IGroupMember",
"groupMember",
",",
"String",
"groupName",
")",
"{",
"try",
"{",
"IEntityGroup",
"group",
"=",
"GroupService",
".",
"findGroup",
"(",
"groupName",
")",
";",
"if",
"(",
"group",
"!=",
"null",
")",
"{",
... | Check if the user is a member of the specified group name
<p>Internal search, thus case sensitive. | [
"Check",
"if",
"the",
"user",
"is",
"a",
"member",
"of",
"the",
"specified",
"group",
"name"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/googleanalytics/GoogleAnalyticsController.java#L132-L166 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-core/src/main/java/org/apereo/portal/layout/profile/StickyProfileMapperImpl.java | StickyProfileMapperImpl.warnOnApathyKeyInMappings | @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 | @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));
}
} | [
"@",
"PostConstruct",
"public",
"void",
"warnOnApathyKeyInMappings",
"(",
")",
"{",
"if",
"(",
"null",
"!=",
"profileKeyForNoSelection",
"&&",
"immutableMappings",
".",
"containsKey",
"(",
"profileKeyForNoSelection",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"\"C... | Log a warning when configured such that a profile key both means apathy and means a
particular profile fname. | [
"Log",
"a",
"warning",
"when",
"configured",
"such",
"that",
"a",
"profile",
"key",
"both",
"means",
"apathy",
"and",
"means",
"a",
"particular",
"profile",
"fname",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-core/src/main/java/org/apereo/portal/layout/profile/StickyProfileMapperImpl.java#L81-L92 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/xml/stream/ChunkingEventReader.java | ChunkingEventReader.chunkString | 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 | 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));
} | [
"protected",
"void",
"chunkString",
"(",
"final",
"List",
"<",
"CharacterEvent",
">",
"characterEvents",
",",
"final",
"CharSequence",
"buffer",
",",
"int",
"patternIndex",
")",
"{",
"// Iterate over the chunking patterns",
"for",
"(",
";",
"patternIndex",
"<",
"thi... | Breaks up the String into a List of CharacterEvents based on the configured Map of Patterns
to CharacterEventSources | [
"Breaks",
"up",
"the",
"String",
"into",
"a",
"List",
"of",
"CharacterEvents",
"based",
"on",
"the",
"configured",
"Map",
"of",
"Patterns",
"to",
"CharacterEventSources"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/xml/stream/ChunkingEventReader.java#L192-L238 | train |
Jasig/uPortal | uPortal-security/uPortal-security-authn/src/main/java/org/apereo/portal/security/provider/RemoteUserPersonManager.java | RemoteUserPersonManager.getPerson | @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 | @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);
} | [
"@",
"Override",
"public",
"IPerson",
"getPerson",
"(",
"HttpServletRequest",
"request",
")",
"throws",
"PortalSecurityException",
"{",
"/*\n * This method overrides the implementation of getPerson() in BasePersonManager, but we only\n * want the RemoteUser behavior here if w... | Retrieve an IPerson object for the incoming request
@param request The current HttpServletRequest
@return IPerson object for the incoming request
@exception PortalSecurityException Description of the Exception | [
"Retrieve",
"an",
"IPerson",
"object",
"for",
"the",
"incoming",
"request"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-authn/src/main/java/org/apereo/portal/security/provider/RemoteUserPersonManager.java#L45-L121 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SafeFilenameUtils.java | SafeFilenameUtils.makeSafeFilename | 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 | 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;
} | [
"public",
"static",
"String",
"makeSafeFilename",
"(",
"String",
"filename",
")",
"{",
"// Replace invalid characters",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"Pattern",
",",
"String",
">",
"pair",
":",
"REPLACEMENT_PAIRS",
".",
"entrySet",
"(",
")",
"... | Makes 'safe' filename | [
"Makes",
"safe",
"filename"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SafeFilenameUtils.java#L48-L65 | train |
Jasig/uPortal | uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/cache/PortletCacheControlServiceImpl.java | PortletCacheControlServiceImpl.getPortletCacheState | @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 | @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;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"<",
"D",
"extends",
"CachedPortletResultHolder",
"<",
"T",
">",
",",
"T",
"extends",
"Serializable",
">",
"CacheState",
"<",
"D",
",",
"T",
">",
"getPortletCacheState",
"(",
"HttpServletRequest",
... | Get the cached portlet data looking in both the public and then private caches returning the
first found
@param request The current request
@param portletWindow The window to get data for
@param publicCacheKey The public cache key
@param publicOutputCache The public cache
@param privateOutputCache The private cache | [
"Get",
"the",
"cached",
"portlet",
"data",
"looking",
"in",
"both",
"the",
"public",
"and",
"then",
"private",
"caches",
"returning",
"the",
"first",
"found"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/cache/PortletCacheControlServiceImpl.java#L345-L384 | train |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/PrincipalsRESTController.java | PrincipalsRESTController.getPrincipals | @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 | @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;
} | [
"@",
"PreAuthorize",
"(",
"\"hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))\"",
")",
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/permissions/principals.json\"",
",",
"method",
"=",
"Re... | Return a JSON view of the uPortal principals matching the supplied query string.
@param query
@param request
@param response
@return
@throws Exception | [
"Return",
"a",
"JSON",
"view",
"of",
"the",
"uPortal",
"principals",
"matching",
"the",
"supplied",
"query",
"string",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/PrincipalsRESTController.java#L53-L79 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/PLFIntegrator.java | PLFIntegrator.appendChild | 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 | 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;
} | [
"static",
"Element",
"appendChild",
"(",
"Element",
"plfChild",
",",
"Element",
"parent",
",",
"boolean",
"copyChildren",
")",
"{",
"Document",
"document",
"=",
"parent",
".",
"getOwnerDocument",
"(",
")",
";",
"Element",
"copy",
"=",
"(",
"Element",
")",
"d... | This method copies a plf node and any of its children into the passed in compViewParent. | [
"This",
"method",
"copies",
"a",
"plf",
"node",
"and",
"any",
"of",
"its",
"children",
"into",
"the",
"passed",
"in",
"compViewParent",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/PLFIntegrator.java#L208-L225 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java | ReferenceEntityLockService.isLocked | private boolean isLocked(Class entityType, String entityKey) throws LockingException {
return isLocked(entityType, entityKey, null);
} | java | private boolean isLocked(Class entityType, String entityKey) throws LockingException {
return isLocked(entityType, entityKey, null);
} | [
"private",
"boolean",
"isLocked",
"(",
"Class",
"entityType",
",",
"String",
"entityKey",
")",
"throws",
"LockingException",
"{",
"return",
"isLocked",
"(",
"entityType",
",",
"entityKey",
",",
"null",
")",
";",
"}"
] | Answers if the entity represented by the entityType and entityKey already has a lock of some
type.
@param entityType
@param entityKey
@exception org.apereo.portal.concurrency.LockingException | [
"Answers",
"if",
"the",
"entity",
"represented",
"by",
"the",
"entityType",
"and",
"entityKey",
"already",
"has",
"a",
"lock",
"of",
"some",
"type",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java#L190-L192 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java | ReferenceEntityLockService.renew | @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 | @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.");
}
} | [
"@",
"Override",
"public",
"void",
"renew",
"(",
"IEntityLock",
"lock",
",",
"int",
"duration",
")",
"throws",
"LockingException",
"{",
"if",
"(",
"isValid",
"(",
"lock",
")",
")",
"{",
"Date",
"newExpiration",
"=",
"getNewExpiration",
"(",
"duration",
")",
... | Extends the expiration time of the lock by some service-defined increment.
@param lock IEntityLock
@exception LockingException | [
"Extends",
"the",
"expiration",
"time",
"of",
"the",
"lock",
"by",
"some",
"service",
"-",
"defined",
"increment",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/ReferenceEntityLockService.java#L370-L379 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.createPortletDefinitionForm | 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 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;
} | [
"public",
"PortletDefinitionForm",
"createPortletDefinitionForm",
"(",
"IPerson",
"person",
",",
"String",
"portletId",
")",
"{",
"IPortletDefinition",
"def",
"=",
"portletDefinitionRegistry",
".",
"getPortletDefinition",
"(",
"portletId",
")",
";",
"// create the new form"... | Construct a new PortletDefinitionForm for the given IPortletDefinition id. If a
PortletDefinition matching this ID already exists, the form will be pre-populated with the
PortletDefinition's current configuration. If the PortletDefinition does not yet exist, a new
default form will be created.
@param person user that is required to have related lifecycle permission
@param portletId identifier for the portlet definition
@return {@PortletDefinitionForm} with set values based on portlet definition or default
category and principal if no definition is found | [
"Construct",
"a",
"new",
"PortletDefinitionForm",
"for",
"the",
"given",
"IPortletDefinition",
"id",
".",
"If",
"a",
"PortletDefinition",
"matching",
"this",
"ID",
"already",
"exists",
"the",
"form",
"will",
"be",
"pre",
"-",
"populated",
"with",
"the",
"Portlet... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L179-L216 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.removePortletRegistration | 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 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);
} | [
"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 cu... | Delete the portlet with the given portlet ID.
@param person the person removing the portlet
@param form | [
"Delete",
"the",
"portlet",
"with",
"the",
"given",
"portlet",
"ID",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L518-L546 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.shouldDisplayLayoutLink | 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 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);
} | [
"public",
"boolean",
"shouldDisplayLayoutLink",
"(",
"IPerson",
"person",
",",
"PortletDefinitionForm",
"form",
",",
"String",
"portletId",
")",
"{",
"if",
"(",
"!",
"form",
".",
"isNew",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// only include the \"... | Check if the link to the Fragment admin portlet should display in the status message.
<p>Checks that the portlet is new, that the portlet has been published and that the user has
necessary permissions to go to the fragment admin page.
@param person the person publishing/editing the portlet
@param form the portlet being editted
@param portletId the id of the saved portlet
@return true If all three conditions are met | [
"Check",
"if",
"the",
"link",
"to",
"the",
"Fragment",
"admin",
"portlet",
"should",
"display",
"in",
"the",
"status",
"message",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L559-L583 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.getFragmentAdminURL | 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 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();
} | [
"public",
"String",
"getFragmentAdminURL",
"(",
"HttpServletRequest",
"request",
")",
"{",
"IPortalUrlBuilder",
"builder",
"=",
"urlProvider",
".",
"getPortalUrlBuilderByPortletFName",
"(",
"request",
",",
"PORTLET_FNAME_FRAGMENT_ADMIN_PORTLET",
",",
"UrlType",
".",
"RENDER... | Get the link to the fragment admin portlet.
@param request the current http request.
@return the portlet link | [
"Get",
"the",
"link",
"to",
"the",
"fragment",
"admin",
"portlet",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L591-L600 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.getArbitraryPortletPreferenceNames | 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 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;
} | [
"public",
"Set",
"<",
"String",
">",
"getArbitraryPortletPreferenceNames",
"(",
"PortletDefinitionForm",
"form",
")",
"{",
"// set default values for all portlet parameters",
"PortletPublishingDefinition",
"cpd",
"=",
"this",
".",
"portletPublishingDefinitionDao",
".",
"getChan... | Get a list of the key names of the currently-set arbitrary portlet preferences.
@param form
@return | [
"Get",
"a",
"list",
"of",
"the",
"key",
"names",
"of",
"the",
"currently",
"-",
"set",
"arbitrary",
"portlet",
"preferences",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L608-L623 | train |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.getPortletApplications | 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 | 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;
} | [
"public",
"List",
"<",
"PortletApplicationDefinition",
">",
"getPortletApplications",
"(",
")",
"{",
"final",
"PortletRegistryService",
"portletRegistryService",
"=",
"portalDriverContainerServices",
".",
"getPortletRegistryService",
"(",
")",
";",
"final",
"List",
"<",
"... | Retreive the list of portlet application contexts currently available in this portlet
container.
@return list of portlet context | [
"Retreive",
"the",
"list",
"of",
"portlet",
"application",
"contexts",
"currently",
"available",
"in",
"this",
"portlet",
"container",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L830-L891 | train |
Jasig/uPortal | uPortal-security/uPortal-security-authn/src/main/java/org/apereo/portal/security/provider/cas/CasAssertionSecurityContext.java | CasAssertionSecurityContext.copyAssertionAttributesToUserAttributes | 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 | 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);
} | [
"private",
"void",
"copyAssertionAttributesToUserAttributes",
"(",
"Assertion",
"assertion",
")",
"{",
"if",
"(",
"!",
"copyAssertionAttributesToUserAttributes",
")",
"{",
"return",
";",
"}",
"// skip this if there are no attributes or if the attribute set is empty.",
"if",
"("... | If enabled, convert CAS assertion person attributes into uPortal user attributes.
@param assertion the Assertion that was retrieved from the ThreadLocal. CANNOT be NULL. | [
"If",
"enabled",
"convert",
"CAS",
"assertion",
"person",
"attributes",
"into",
"uPortal",
"user",
"attributes",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-authn/src/main/java/org/apereo/portal/security/provider/cas/CasAssertionSecurityContext.java#L219-L280 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityCachingService.java | EntityCachingService.get | @Override
public IBasicEntity get(Class<? extends IBasicEntity> type, String key)
throws CachingException {
return EntityCachingServiceLocator.getEntityCachingService().get(type, key);
} | java | @Override
public IBasicEntity get(Class<? extends IBasicEntity> type, String key)
throws CachingException {
return EntityCachingServiceLocator.getEntityCachingService().get(type, key);
} | [
"@",
"Override",
"public",
"IBasicEntity",
"get",
"(",
"Class",
"<",
"?",
"extends",
"IBasicEntity",
">",
"type",
",",
"String",
"key",
")",
"throws",
"CachingException",
"{",
"return",
"EntityCachingServiceLocator",
".",
"getEntityCachingService",
"(",
")",
".",
... | Returns the cached entity identified by type and key.
@param type Class
@param key String
@return IBasicEntity entity
@exception org.apereo.portal.concurrency.CachingException | [
"Returns",
"the",
"cached",
"entity",
"identified",
"by",
"type",
"and",
"key",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityCachingService.java#L103-L107 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityCachingService.java | EntityCachingService.get | public IBasicEntity get(EntityIdentifier entityID) throws CachingException {
return EntityCachingServiceLocator.getEntityCachingService()
.get(entityID.getType(), entityID.getKey());
} | java | public IBasicEntity get(EntityIdentifier entityID) throws CachingException {
return EntityCachingServiceLocator.getEntityCachingService()
.get(entityID.getType(), entityID.getKey());
} | [
"public",
"IBasicEntity",
"get",
"(",
"EntityIdentifier",
"entityID",
")",
"throws",
"CachingException",
"{",
"return",
"EntityCachingServiceLocator",
".",
"getEntityCachingService",
"(",
")",
".",
"get",
"(",
"entityID",
".",
"getType",
"(",
")",
",",
"entityID",
... | Returns the cached entity referred to by entityID.
@param entityID entity identifier
@return IBasicEntity entity
@exception org.apereo.portal.concurrency.CachingException | [
"Returns",
"the",
"cached",
"entity",
"referred",
"to",
"by",
"entityID",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityCachingService.java#L116-L119 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityCachingService.java | EntityCachingService.remove | @Override
public void remove(Class<? extends IBasicEntity> type, String key) throws CachingException {
EntityCachingServiceLocator.getEntityCachingService().remove(type, key);
} | java | @Override
public void remove(Class<? extends IBasicEntity> type, String key) throws CachingException {
EntityCachingServiceLocator.getEntityCachingService().remove(type, key);
} | [
"@",
"Override",
"public",
"void",
"remove",
"(",
"Class",
"<",
"?",
"extends",
"IBasicEntity",
">",
"type",
",",
"String",
"key",
")",
"throws",
"CachingException",
"{",
"EntityCachingServiceLocator",
".",
"getEntityCachingService",
"(",
")",
".",
"remove",
"("... | Removes the entity identified by type and key from the cache and notifies peer caches.
@param type Class
@param key String
@exception org.apereo.portal.concurrency.CachingException | [
"Removes",
"the",
"entity",
"identified",
"by",
"type",
"and",
"key",
"from",
"the",
"cache",
"and",
"notifies",
"peer",
"caches",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityCachingService.java#L128-L131 | train |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlets/error/PortletErrorController.java | PortletErrorController.renderError | @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 | @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";
} | [
"@",
"RequestMapping",
"(",
"\"VIEW\"",
")",
"public",
"String",
"renderError",
"(",
"RenderRequest",
"request",
",",
"RenderResponse",
"response",
",",
"ModelMap",
"model",
")",
"throws",
"Exception",
"{",
"HttpServletRequest",
"httpRequest",
"=",
"this",
".",
"p... | Render the error portlet view.
@param request
@param response
@param model
@return the name of the view to display
@throws Exception | [
"Render",
"the",
"error",
"portlet",
"view",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlets/error/PortletErrorController.java#L101-L149 | train |
Jasig/uPortal | uPortal-security/uPortal-security-authn/src/main/java/org/apereo/portal/security/provider/SimpleLdapSecurityContext.java | SimpleLdapSecurityContext.getAttributeValue | 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 | 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;
} | [
"private",
"String",
"getAttributeValue",
"(",
"Attributes",
"attrs",
",",
"int",
"attribute",
")",
"throws",
"NamingException",
"{",
"NamingEnumeration",
"values",
"=",
"null",
";",
"String",
"aValue",
"=",
"\"\"",
";",
"if",
"(",
"!",
"isAttribute",
"(",
"at... | Return a single value of an attribute from possibly multiple values, grossly ignoring
anything else. If there are no values, then return an empty string.
@param attrs LDAP query results
@param attribute LDAP attribute we are interested in
@return a single value of the attribute | [
"Return",
"a",
"single",
"value",
"of",
"an",
"attribute",
"from",
"possibly",
"multiple",
"values",
"grossly",
"ignoring",
"anything",
"else",
".",
"If",
"there",
"are",
"no",
"values",
"then",
"return",
"an",
"empty",
"string",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-authn/src/main/java/org/apereo/portal/security/provider/SimpleLdapSecurityContext.java#L203-L215 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java | RDBMUserLayoutStore.addUserProfile | @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 | @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();
}
});
} | [
"@",
"Override",
"public",
"UserProfile",
"addUserProfile",
"(",
"final",
"IPerson",
"person",
",",
"final",
"IUserProfile",
"profile",
")",
"{",
"final",
"int",
"userId",
"=",
"person",
".",
"getID",
"(",
")",
";",
"final",
"int",
"layoutId",
"=",
"getLayou... | Add a user profile | [
"Add",
"a",
"user",
"profile"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java#L208-L272 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java | RDBMUserLayoutStore.createLayout | 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 | 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();
}
} | [
"private",
"void",
"createLayout",
"(",
"HashMap",
"layoutStructure",
",",
"Document",
"doc",
",",
"Element",
"root",
",",
"int",
"structId",
")",
"{",
"while",
"(",
"structId",
"!=",
"0",
")",
"{",
"LayoutStructure",
"ls",
"=",
"(",
"LayoutStructure",
")",
... | Create a layout | [
"Create",
"a",
"layout"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java#L314-L331 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java | RDBMUserLayoutStore.getNextStructId | 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 | 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;
}
}
}));
} | [
"protected",
"String",
"getNextStructId",
"(",
"final",
"IPerson",
"person",
",",
"final",
"String",
"prefix",
")",
"{",
"final",
"int",
"userId",
"=",
"person",
".",
"getID",
"(",
")",
";",
"return",
"nextStructTransactionOperations",
".",
"execute",
"(",
"st... | Return the next available structure id for a user
@return next free structure ID | [
"Return",
"the",
"next",
"available",
"structure",
"id",
"for",
"a",
"user"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java#L367-L407 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java | RDBMUserLayoutStore.getLayoutID | 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 | 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;
});
} | [
"private",
"int",
"getLayoutID",
"(",
"final",
"int",
"userId",
",",
"final",
"int",
"profileId",
")",
"{",
"return",
"jdbcOperations",
".",
"execute",
"(",
"(",
"ConnectionCallback",
"<",
"Integer",
">",
")",
"con",
"->",
"{",
"String",
"query",
"=",
"\"S... | Returns the current layout ID for the user and profile. If the profile doesn't exist or the
layout_id field is null 0 is returned.
@param userId The userId for the profile
@param profileId The profileId for the profile
@return The layout_id field or 0 if it does not exist or is null | [
"Returns",
"the",
"current",
"layout",
"ID",
"for",
"the",
"user",
"and",
"profile",
".",
"If",
"the",
"profile",
"doesn",
"t",
"exist",
"or",
"the",
"layout_id",
"field",
"is",
"null",
"0",
"is",
"returned",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java#L1491-L1525 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsURLString | public static String getResourceAsURLString(Class<?> requestingClass, String resource)
throws ResourceMissingException {
return getResourceAsURL(requestingClass, resource).toString();
} | java | public static String getResourceAsURLString(Class<?> requestingClass, String resource)
throws ResourceMissingException {
return getResourceAsURL(requestingClass, resource).toString();
} | [
"public",
"static",
"String",
"getResourceAsURLString",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
")",
"throws",
"ResourceMissingException",
"{",
"return",
"getResourceAsURL",
"(",
"requestingClass",
",",
"resource",
")",
".",
"toStr... | Returns the requested resource as a URL string.
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource to load
@return the requested resource as a URL string
@throws ResourceMissingException | [
"Returns",
"the",
"requested",
"resource",
"as",
"a",
"URL",
"string",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L180-L183 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsStream | public static InputStream getResourceAsStream(Class<?> requestingClass, String resource)
throws ResourceMissingException, IOException {
return getResourceAsURL(requestingClass, resource).openStream();
} | java | public static InputStream getResourceAsStream(Class<?> requestingClass, String resource)
throws ResourceMissingException, IOException {
return getResourceAsURL(requestingClass, resource).openStream();
} | [
"public",
"static",
"InputStream",
"getResourceAsStream",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
")",
"throws",
"ResourceMissingException",
",",
"IOException",
"{",
"return",
"getResourceAsURL",
"(",
"requestingClass",
",",
"resourc... | Returns the requested resource as a stream.
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource to load
@return the requested resource as a stream
@throws ResourceMissingException
@throws java.io.IOException | [
"Returns",
"the",
"requested",
"resource",
"as",
"a",
"stream",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L212-L215 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsSAXInputSource | 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 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;
} | [
"public",
"static",
"InputSource",
"getResourceAsSAXInputSource",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
")",
"throws",
"ResourceMissingException",
",",
"IOException",
"{",
"URL",
"url",
"=",
"getResourceAsURL",
"(",
"requestingClas... | Returns the requested resource as a SAX input source.
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource to load
@return the requested resource as a SAX input source
@throws ResourceMissingException
@throws java.io.IOException | [
"Returns",
"the",
"requested",
"resource",
"as",
"a",
"SAX",
"input",
"source",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L227-L233 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsDocument | 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, 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;
} | [
"public",
"static",
"Document",
"getResourceAsDocument",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
",",
"boolean",
"validate",
")",
"throws",
"ResourceMissingException",
",",
"IOException",
",",
"ParserConfigurationException",
",",
"SA... | Get the contents of a URL as an XML Document
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource whose contents to
load
@param validate boolean. True if the document builder factory should validate, false
otherwise.
@return the actual contents of the resource as an XML Document
@throws ResourceMissingException
@throws java.io.IOException
@throws javax.xml.parsers.ParserConfigurationException
@throws org.xml.sax.SAXException | [
"Get",
"the",
"contents",
"of",
"a",
"URL",
"as",
"an",
"XML",
"Document"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L250-L277 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsDocument | 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 Document getResourceAsDocument(Class<?> requestingClass, String resource)
throws ResourceMissingException, IOException, ParserConfigurationException,
SAXException {
// Default is non-validating...
return getResourceAsDocument(requestingClass, resource, false);
} | [
"public",
"static",
"Document",
"getResourceAsDocument",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
")",
"throws",
"ResourceMissingException",
",",
"IOException",
",",
"ParserConfigurationException",
",",
"SAXException",
"{",
"// Default ... | Get the contents of a URL as an XML Document, first trying to read the Document with
validation turned on, and falling back to reading it with validation turned off.
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource whose contents to
load
@return the actual contents of the resource as an XML Document
@throws ResourceMissingException
@throws java.io.IOException
@throws javax.xml.parsers.ParserConfigurationException
@throws org.xml.sax.SAXException | [
"Get",
"the",
"contents",
"of",
"a",
"URL",
"as",
"an",
"XML",
"Document",
"first",
"trying",
"to",
"read",
"the",
"Document",
"with",
"validation",
"turned",
"on",
"and",
"falling",
"back",
"to",
"reading",
"it",
"with",
"validation",
"turned",
"off",
"."... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L293-L299 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsProperties | 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 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;
} | [
"public",
"static",
"Properties",
"getResourceAsProperties",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
")",
"throws",
"ResourceMissingException",
",",
"IOException",
"{",
"InputStream",
"inputStream",
"=",
"null",
";",
"Properties",
... | Get the contents of a URL as a java.util.Properties object
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource whose contents to
load
@return the actual contents of the resource as a Properties object
@throws ResourceMissingException
@throws java.io.IOException | [
"Get",
"the",
"contents",
"of",
"a",
"URL",
"as",
"a",
"java",
".",
"util",
".",
"Properties",
"object"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L312-L324 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java | ResourceLoader.getResourceAsString | 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 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();
} | [
"public",
"static",
"String",
"getResourceAsString",
"(",
"Class",
"<",
"?",
">",
"requestingClass",
",",
"String",
"resource",
")",
"throws",
"ResourceMissingException",
",",
"IOException",
"{",
"String",
"line",
"=",
"null",
";",
"BufferedReader",
"in",
"=",
"... | Get the contents of a URL as a String
@param requestingClass the java.lang.Class object of the class that is attempting to load the
resource
@param resource a String describing the full or partial URL of the resource whose contents to
load
@return the actual contents of the resource as a String
@throws ResourceMissingException
@throws java.io.IOException | [
"Get",
"the",
"contents",
"of",
"a",
"URL",
"as",
"a",
"String"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L337-L353 | train |
Jasig/uPortal | uPortal-security/uPortal-security-services/src/main/java/org/apereo/portal/services/Authentication.java | Authentication.setContextParameters | 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 | 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);
}
} | [
"public",
"void",
"setContextParameters",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"principals",
",",
"Map",
"<",
"String",
",",
"String",
">",
"credentials",
",",
"String",
"ctxName",
",",
"ISecurityContext",
"securityContext",
")",
"{",
"if",
"(",
"l... | Get the principal and credential for a specific context and store them in the context.
@param principals
@param credentials
@param ctxName
@param securityContext | [
"Get",
"the",
"principal",
"and",
"credential",
"for",
"a",
"specific",
"context",
"and",
"store",
"them",
"in",
"the",
"context",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-services/src/main/java/org/apereo/portal/services/Authentication.java#L288-L341 | train |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java | PortletRendererImpl.publishRenderEvent | 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 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);
} | [
"protected",
"void",
"publishRenderEvent",
"(",
"IPortletWindow",
"portletWindow",
",",
"HttpServletRequest",
"httpServletRequest",
",",
"RenderPart",
"renderPart",
",",
"long",
"executionTime",
",",
"boolean",
"cached",
")",
"{",
"final",
"IPortletWindowId",
"portletWind... | Publish the portlet render event | [
"Publish",
"the",
"portlet",
"render",
"event"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java#L579-L602 | train |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java | PortletRendererImpl.publishResourceEvent | 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 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);
} | [
"protected",
"void",
"publishResourceEvent",
"(",
"IPortletWindow",
"portletWindow",
",",
"HttpServletRequest",
"httpServletRequest",
",",
"long",
"executionTime",
",",
"boolean",
"usedBrowserCache",
",",
"boolean",
"usedPortalCache",
")",
"{",
"final",
"IPortletWindowId",
... | Publish the portlet resource event | [
"Publish",
"the",
"portlet",
"resource",
"event"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java#L840-L856 | train |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java | PortletRendererImpl.enforceConfigPermission | 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 | 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.");
}
}
}
} | [
"protected",
"void",
"enforceConfigPermission",
"(",
"final",
"HttpServletRequest",
"httpServletRequest",
",",
"final",
"IPortletWindow",
"portletWindow",
")",
"{",
"Validate",
".",
"notNull",
"(",
"httpServletRequest",
",",
"\"Servlet request must not be null to determine remo... | Enforces config mode access control. If requesting user does not have CONFIG permission, and
the PortletWindow specifies config mode, throws AuthorizationException. Otherwise does
nothing.
@param httpServletRequest the non-null current HttpServletRequest (for determining requesting
user)
@param portletWindow a non-null portlet window that might be in config mode
@throws AuthorizationException if the user is not permitted to access config mode yet portlet
window specifies config mode
@throws java.lang.IllegalArgumentException if the request or window are null
@since 4.0.13.1, 4.0.14, 4.1. | [
"Enforces",
"config",
"mode",
"access",
"control",
".",
"If",
"requesting",
"user",
"does",
"not",
"have",
"CONFIG",
"permission",
"and",
"the",
"PortletWindow",
"specifies",
"config",
"mode",
"throws",
"AuthorizationException",
".",
"Otherwise",
"does",
"nothing",
... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletRendererImpl.java#L960-L1002 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/security/provider/PersonImpl.java | PersonImpl.getAttributeValues | @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 Object[] getAttributeValues(String key) {
if (userAttributes == null) {
return null;
}
final List<Object> values = userAttributes.get(key);
if (values != null) {
return values.toArray();
}
return null;
} | [
"@",
"Override",
"public",
"Object",
"[",
"]",
"getAttributeValues",
"(",
"String",
"key",
")",
"{",
"if",
"(",
"userAttributes",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"List",
"<",
"Object",
">",
"values",
"=",
"userAttributes",
".... | Returns multiple attributes for a key. If only one value exists, it will be returned in an
array of size one.
@param key the attribute name
@return the array of attribute values identified by the key | [
"Returns",
"multiple",
"attributes",
"for",
"a",
"key",
".",
"If",
"only",
"one",
"value",
"exists",
"it",
"will",
"be",
"returned",
"in",
"an",
"array",
"of",
"size",
"one",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/security/provider/PersonImpl.java#L80-L92 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/security/provider/PersonImpl.java | PersonImpl.setAttribute | @Override
public void setAttribute(String key, Object value) {
if (value == null) {
setAttribute(key, null);
} else {
setAttribute(key, Collections.singletonList(value));
}
} | java | @Override
public void setAttribute(String key, Object value) {
if (value == null) {
setAttribute(key, null);
} else {
setAttribute(key, Collections.singletonList(value));
}
} | [
"@",
"Override",
"public",
"void",
"setAttribute",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"setAttribute",
"(",
"key",
",",
"null",
")",
";",
"}",
"else",
"{",
"setAttribute",
"(",
"key",
",... | Sets the specified attribute to a value.
<p>Reference implementation checks for the setting of the username attribute and updates the
EntityIdentifier accordingly
@param key Attribute's name
@param value Attribute's value | [
"Sets",
"the",
"specified",
"attribute",
"to",
"a",
"value",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/security/provider/PersonImpl.java#L114-L121 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/security/provider/PersonImpl.java | PersonImpl.isGuest | @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 | @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;
} | [
"@",
"Override",
"public",
"boolean",
"isGuest",
"(",
")",
"{",
"String",
"userName",
"=",
"(",
"String",
")",
"getAttribute",
"(",
"IPerson",
".",
"USERNAME",
")",
";",
"boolean",
"isGuestUsername",
"=",
"PersonFactory",
".",
"getGuestUsernames",
"(",
")",
... | Determines whether or not this person is a "guest" user.
<p>This person is a "guest" if both of the following are true:
<ol>
<li>This person's user name is listed as a guest user account.
<li>This person does not have a live instance ISecurityContext that states he/she has been
successfully authenticated. (It can be either null or unauthenticated.)
</ol>
@return <code>true</code> If person is a guest, otherwise <code>false</code> | [
"Determines",
"whether",
"or",
"not",
"this",
"person",
"is",
"a",
"guest",
"user",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/security/provider/PersonImpl.java#L234-L240 | train |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceEntityStoreFactory.java | ReferenceEntityStoreFactory.newInstance | public IEntityStore newInstance() throws GroupsException {
try {
return new RDBMEntityStore();
} catch (Exception ex) {
log.error("ReferenceEntityStoreFactory.newInstance(): " + ex);
throw new GroupsException(ex);
}
} | java | public IEntityStore newInstance() throws GroupsException {
try {
return new RDBMEntityStore();
} catch (Exception ex) {
log.error("ReferenceEntityStoreFactory.newInstance(): " + ex);
throw new GroupsException(ex);
}
} | [
"public",
"IEntityStore",
"newInstance",
"(",
")",
"throws",
"GroupsException",
"{",
"try",
"{",
"return",
"new",
"RDBMEntityStore",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"ReferenceEntityStoreFactory.newInstan... | Return an instance of the entity store implementation.
@return IEntityStore
@exception GroupsException | [
"Return",
"an",
"instance",
"of",
"the",
"entity",
"store",
"implementation",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceEntityStoreFactory.java#L45-L52 | train |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/xml/stream/InjectingXMLEventReader.java | InjectingXMLEventReader.getAdditionalEvents | 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 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;
} | [
"protected",
"Deque",
"<",
"XMLEvent",
">",
"getAdditionalEvents",
"(",
"XMLEvent",
"event",
")",
"{",
"final",
"XMLEvent",
"additionalEvent",
"=",
"this",
".",
"getAdditionalEvent",
"(",
"event",
")",
";",
"if",
"(",
"additionalEvent",
"==",
"null",
")",
"{",... | The Deque with the additional events WILL BE MODIFIED by the calling code.
@param event The current event
@return Any additional events that should be injected before the current event. If null the
current event is returned | [
"The",
"Deque",
"with",
"the",
"additional",
"events",
"WILL",
"BE",
"MODIFIED",
"by",
"the",
"calling",
"code",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/xml/stream/InjectingXMLEventReader.java#L73-L82 | train |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/StylesheetUserPreferencesServiceImpl.java | StylesheetUserPreferencesServiceImpl.getStyleSheetName | 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 | 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;
} | [
"protected",
"String",
"getStyleSheetName",
"(",
"final",
"HttpServletRequest",
"request",
",",
"PreferencesScope",
"scope",
")",
"{",
"final",
"String",
"stylesheetNameFromRequest",
";",
"if",
"(",
"scope",
".",
"equals",
"(",
"PreferencesScope",
".",
"STRUCTURE",
... | Returns the stylesheet name if overridden in the request object.
@param request HttpRequest
@param scope Scope (Structure or Theme)
@return Stylesheet name if set as an override in the request, else null if it was not. | [
"Returns",
"the",
"stylesheet",
"name",
"if",
"overridden",
"in",
"the",
"request",
"object",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/StylesheetUserPreferencesServiceImpl.java#L1254-L1266 | train |
Jasig/uPortal | uPortal-security/uPortal-security-mvc/src/main/java/org/apereo/portal/security/mvc/LogoutController.java | LogoutController.doLogout | @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 | @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);
} | [
"@",
"RequestMapping",
"public",
"void",
"doLogout",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"String",
"redirect",
"=",
"this",
".",
"selectRedirectionUrl",
"(",
"request",
")",
";",
"final",
... | Process the incoming request and response.
@param request HttpServletRequest object
@param response HttpServletResponse object | [
"Process",
"the",
"incoming",
"request",
"and",
"response",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-mvc/src/main/java/org/apereo/portal/security/mvc/LogoutController.java#L79-L127 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.loadProps | 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 | 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);
}
} | [
"protected",
"static",
"void",
"loadProps",
"(",
")",
"{",
"PropertiesManager",
".",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"try",
"{",
"String",
"pfile",
"=",
"System",
".",
"getProperty",
"(",
"PORTAL_PROPERTIES_FILE_SYSTEM_VARIABLE",
")",
";",
"i... | Load up the portal properties. Right now the portal properties is a simple .properties file
with name value pairs. It may evolve to become an XML file later on. | [
"Load",
"up",
"the",
"portal",
"properties",
".",
"Right",
"now",
"the",
"portal",
"properties",
"is",
"a",
"simple",
".",
"properties",
"file",
"with",
"name",
"value",
"pairs",
".",
"It",
"may",
"evolve",
"to",
"become",
"an",
"XML",
"file",
"later",
"... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L83-L94 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getProperty | 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 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;
} | [
"public",
"static",
"String",
"getProperty",
"(",
"String",
"name",
")",
"throws",
"MissingPropertyException",
"{",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"trace",
"(",
"\"entering getProperty(\"",
"+",
"name",
"+",
"\")\"",
... | Returns the value of a property for a given name. Any whitespace is trimmed off the beginning
and end of the property value. Note that this method will never return null. If the requested
property cannot be found, this method throws an UndeclaredPortalException.
@param name the name of the requested property
@return value the value of the property matching the requested name
@throws MissingPropertyException - if the requested property cannot be found | [
"Returns",
"the",
"value",
"of",
"a",
"property",
"for",
"a",
"given",
"name",
".",
"Any",
"whitespace",
"is",
"trimmed",
"off",
"the",
"beginning",
"and",
"end",
"of",
"the",
"property",
"value",
".",
"Note",
"that",
"this",
"method",
"will",
"never",
"... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L105-L116 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getPropertyUntrimmed | 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 | 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;
} | [
"public",
"static",
"String",
"getPropertyUntrimmed",
"(",
"String",
"name",
")",
"throws",
"MissingPropertyException",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"if",
"(",
"props",
"==",
"null",
")",
"... | Returns the value of a property for a given name including whitespace trailing the property
value, but not including whitespace leading the property value. An UndeclaredPortalException
is thrown if the property cannot be found. This method will never return null.
@param name the name of the requested property
@return value the value of the property matching the requested name
@throws MissingPropertyException - (undeclared) if the requested property is not found | [
"Returns",
"the",
"value",
"of",
"a",
"property",
"for",
"a",
"given",
"name",
"including",
"whitespace",
"trailing",
"the",
"property",
"value",
"but",
"not",
"including",
"whitespace",
"leading",
"the",
"property",
"value",
".",
"An",
"UndeclaredPortalException"... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L127-L141 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.registerMissingProperty | 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 | 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;
} | [
"private",
"static",
"boolean",
"registerMissingProperty",
"(",
"String",
"name",
")",
"{",
"final",
"boolean",
"previouslyReported",
"=",
"!",
"PropertiesManager",
".",
"missingProperties",
".",
"add",
"(",
"name",
")",
";",
"if",
"(",
"!",
"previouslyReported",
... | Registers that a given property was sought but not found. Currently adds the property to the
set of missing properties and logs if this is the first time the property has been requested.
@param name - the name of the missing property
@return true if the property was previously registered, false otherwise | [
"Registers",
"that",
"a",
"given",
"property",
"was",
"sought",
"but",
"not",
"found",
".",
"Currently",
"adds",
"the",
"property",
"to",
"the",
"set",
"of",
"missing",
"properties",
"and",
"logs",
"if",
"this",
"is",
"the",
"first",
"time",
"the",
"proper... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L308-L315 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getProperty | 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 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;
} | [
"public",
"static",
"String",
"getProperty",
"(",
"String",
"name",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"String",
"returnValue",
"=",
"defaultValue",
";",
"try"... | Get the value of the property with the given name. If the named property is not found,
returns the supplied default value. This error handling behavior makes this method attractive
for use in static initializers.
@param name - the name of the property to be retrieved.
@param defaultValue - a fallback default value which will be returned if the property cannot
be found.
@return the value of the requested property, or the supplied default value if the named
property cannot be found.
@since 2.4 | [
"Get",
"the",
"value",
"of",
"the",
"property",
"with",
"the",
"given",
"name",
".",
"If",
"the",
"named",
"property",
"is",
"not",
"found",
"returns",
"the",
"supplied",
"default",
"value",
".",
"This",
"error",
"handling",
"behavior",
"makes",
"this",
"m... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L329-L338 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getPropertyAsBoolean | 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 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;
} | [
"public",
"static",
"boolean",
"getPropertyAsBoolean",
"(",
"final",
"String",
"name",
",",
"final",
"boolean",
"defaultValue",
")",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"boolean",
"returnValue",
"="... | Get a property as a boolean, specifying a default value. If for any reason we are unable to
lookup the desired property, this method returns the supplied default value. This error
handling behavior makes this method suitable for calling from static initializers.
@param name - the name of the property to be accessed
@param defaultValue - default value that will be returned in the event of any error
@return the looked up property value, or the defaultValue if any problem.
@since 2.4 | [
"Get",
"a",
"property",
"as",
"a",
"boolean",
"specifying",
"a",
"default",
"value",
".",
"If",
"for",
"any",
"reason",
"we",
"are",
"unable",
"to",
"lookup",
"the",
"desired",
"property",
"this",
"method",
"returns",
"the",
"supplied",
"default",
"value",
... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L350-L359 | train |
Jasig/uPortal | uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java | PropertiesManager.getPropertyAsByte | 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 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;
} | [
"public",
"static",
"byte",
"getPropertyAsByte",
"(",
"final",
"String",
"name",
",",
"final",
"byte",
"defaultValue",
")",
"{",
"if",
"(",
"PropertiesManager",
".",
"props",
"==",
"null",
")",
"loadProps",
"(",
")",
";",
"byte",
"returnValue",
"=",
"default... | Get the value of the given property as a byte, specifying a fallback default value. If for
any reason we are unable to lookup the desired property, this method returns the supplied
default value. This error handling behavior makes this method suitable for calling from
static initializers.
@param name - the name of the property to be accessed
@param defaultValue - the default value that will be returned in the event of any error
@return the looked up property value, or the defaultValue if any problem.
@since 2.4 | [
"Get",
"the",
"value",
"of",
"the",
"given",
"property",
"as",
"a",
"byte",
"specifying",
"a",
"fallback",
"default",
"value",
".",
"If",
"for",
"any",
"reason",
"we",
"are",
"unable",
"to",
"lookup",
"the",
"desired",
"property",
"this",
"method",
"return... | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L372-L387 | train |
Jasig/uPortal | uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java | VersionUtils.parseVersion | 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 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);
} | [
"public",
"static",
"Version",
"parseVersion",
"(",
"String",
"versionString",
")",
"{",
"final",
"Matcher",
"versionMatcher",
"=",
"VERSION_PATTERN",
".",
"matcher",
"(",
"versionString",
")",
";",
"if",
"(",
"!",
"versionMatcher",
".",
"matches",
"(",
")",
"... | Parse a version string into a Version object, if the string doesn't match the pattern null is
returned.
<p>The regular expression used in parsing is: ^(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:[\.-].*)?$
<p>Examples that match correctly:
<ul>
<li>4.0.5
<li>4.0.5.123123
<li>4.0.5-SNAPSHOT
<ul>
Examples do NOT match correctly:
<ul>
<li>4.0
<li>4.0.5_123123
<ul> | [
"Parse",
"a",
"version",
"string",
"into",
"a",
"Version",
"object",
"if",
"the",
"string",
"doesn",
"t",
"match",
"the",
"pattern",
"null",
"is",
"returned",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java#L46-L61 | train |
Jasig/uPortal | uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java | VersionUtils.getMostSpecificMatchingField | 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 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;
} | [
"public",
"static",
"Version",
".",
"Field",
"getMostSpecificMatchingField",
"(",
"Version",
"v1",
",",
"Version",
"v2",
")",
"{",
"if",
"(",
"v1",
".",
"getMajor",
"(",
")",
"!=",
"v2",
".",
"getMajor",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
... | Determine how much of two versions match. Returns null if the versions do not match at all.
@return null for no match or the name of the most specific field that matches. | [
"Determine",
"how",
"much",
"of",
"two",
"versions",
"match",
".",
"Returns",
"null",
"if",
"the",
"versions",
"do",
"not",
"match",
"at",
"all",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java#L68-L88 | train |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.setParameter | public UrlStringBuilder setParameter(String name, String... values) {
this.setParameter(name, values != null ? Arrays.asList(values) : null);
return this;
} | java | public UrlStringBuilder setParameter(String name, String... values) {
this.setParameter(name, values != null ? Arrays.asList(values) : null);
return this;
} | [
"public",
"UrlStringBuilder",
"setParameter",
"(",
"String",
"name",
",",
"String",
"...",
"values",
")",
"{",
"this",
".",
"setParameter",
"(",
"name",
",",
"values",
"!=",
"null",
"?",
"Arrays",
".",
"asList",
"(",
"values",
")",
":",
"null",
")",
";",... | Sets a URL parameter, replacing any existing parameter with the same name.
@param name Parameter name, can not be null
@param values Values for the parameter, null is valid
@return this | [
"Sets",
"a",
"URL",
"parameter",
"replacing",
"any",
"existing",
"parameter",
"with",
"the",
"same",
"name",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L116-L119 | train |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.addParameter | public UrlStringBuilder addParameter(String name, String... values) {
this.addParameter(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;
} | [
"public",
"UrlStringBuilder",
"addParameter",
"(",
"String",
"name",
",",
"String",
"...",
"values",
")",
"{",
"this",
".",
"addParameter",
"(",
"name",
",",
"values",
"!=",
"null",
"?",
"Arrays",
".",
"asList",
"(",
"values",
")",
":",
"null",
")",
";",... | Adds to a URL parameter, if a parameter with the same name already exists its values are
added to
@param name Parameter name, can not be null
@param values Values for the parameter, null is valid
@return this | [
"Adds",
"to",
"a",
"URL",
"parameter",
"if",
"a",
"parameter",
"with",
"the",
"same",
"name",
"already",
"exists",
"its",
"values",
"are",
"added",
"to"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L137-L140 | train |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.setParameters | 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 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;
} | [
"public",
"UrlStringBuilder",
"setParameters",
"(",
"String",
"namespace",
",",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"parameters",
")",
"{",
"for",
"(",
"final",
"String",
"name",
":",
"parameters",
".",
"keySet",
"(",
")",
")",
"{... | Removes all existing parameters and sets the contents of the specified Map as the parameters.
@param namespace String to prepend to each parameter name in the Map
@param parameters Map of parameters to set
@return this | [
"Removes",
"all",
"existing",
"parameters",
"and",
"sets",
"the",
"contents",
"of",
"the",
"specified",
"Map",
"as",
"the",
"parameters",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L174-L182 | train |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.setPath | public UrlStringBuilder setPath(String... elements) {
Validate.noNullElements(elements, "elements cannot be null");
this.path.clear();
this.addPath(elements);
return this;
} | java | public UrlStringBuilder setPath(String... elements) {
Validate.noNullElements(elements, "elements cannot be null");
this.path.clear();
this.addPath(elements);
return this;
} | [
"public",
"UrlStringBuilder",
"setPath",
"(",
"String",
"...",
"elements",
")",
"{",
"Validate",
".",
"noNullElements",
"(",
"elements",
",",
"\"elements cannot be null\"",
")",
";",
"this",
".",
"path",
".",
"clear",
"(",
")",
";",
"this",
".",
"addPath",
"... | Removes any existing path elements and sets the provided elements as the path
@param elements Path elements to set
@return this | [
"Removes",
"any",
"existing",
"path",
"elements",
"and",
"sets",
"the",
"provided",
"elements",
"as",
"the",
"path"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L243-L249 | train |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.addPath | public UrlStringBuilder addPath(String element) {
Validate.notNull(element, "element cannot be null");
this.path.add(element);
return this;
} | java | public UrlStringBuilder addPath(String element) {
Validate.notNull(element, "element cannot be null");
this.path.add(element);
return this;
} | [
"public",
"UrlStringBuilder",
"addPath",
"(",
"String",
"element",
")",
"{",
"Validate",
".",
"notNull",
"(",
"element",
",",
"\"element cannot be null\"",
")",
";",
"this",
".",
"path",
".",
"add",
"(",
"element",
")",
";",
"return",
"this",
";",
"}"
] | Adds a single element to the path.
@param element The element to add
@return this | [
"Adds",
"a",
"single",
"element",
"to",
"the",
"path",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L257-L261 | train |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.addPath | public UrlStringBuilder addPath(String... elements) {
Validate.noNullElements(elements, "elements cannot be null");
for (final String element : elements) {
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;
} | [
"public",
"UrlStringBuilder",
"addPath",
"(",
"String",
"...",
"elements",
")",
"{",
"Validate",
".",
"noNullElements",
"(",
"elements",
",",
"\"elements cannot be null\"",
")",
";",
"for",
"(",
"final",
"String",
"element",
":",
"elements",
")",
"{",
"this",
... | Adds the provided elements to the path
@param elements Path elements to add
@return this | [
"Adds",
"the",
"provided",
"elements",
"to",
"the",
"path"
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L269-L276 | train |
Jasig/uPortal | uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/services/GuestPortletEntityPreferencesImpl.java | GuestPortletEntityPreferencesImpl.getSessionPreferences | @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 | @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);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"Map",
"<",
"String",
",",
"IPortletPreference",
">",
"getSessionPreferences",
"(",
"IPortletEntityId",
"portletEntityId",
",",
"HttpServletRequest",
"httpServletRequest",
")",
"{",
"final",
"HttpSession",
... | Gets the session-stored list of IPortletPreferences for the specified request and
IPortletEntityId.
@return List of IPortletPreferences for the entity and session, may be null if no preferences
have been set. | [
"Gets",
"the",
"session",
"-",
"stored",
"list",
"of",
"IPortletPreferences",
"for",
"the",
"specified",
"request",
"and",
"IPortletEntityId",
"."
] | c1986542abb9acd214268f2df21c6305ad2f262b | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/services/GuestPortletEntityPreferencesImpl.java#L138-L157 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.