How to obtain page's organization in liferay portlet correctly?
I tried:
Company. Is not an organization, but a portal instance.
Group. Is group of current user, not of current page.
UPDATE
I am in the portlet class' doView method. I know how to pass anything I can obtain here upwards to JSP to be accessible via EL/JSTL.
UPDATE 2
group.getOrganizationId() always returns zero.
UPDATE 3
This code I use to prepare variables
private void storeVariables(RenderRequest renderRequest) {
PortletPreferences prefs = renderRequest.getPreferences();
String image_id = (String) prefs.getValue("image_id", "communicator");
ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
Company company = themeDisplay.getCompany();
Group group = themeDisplay.getScopeGroup();
log.info("group = {}", group);
long organizationId = group.getOrganizationId();
log.info("organizationId = {}", organizationId);
PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
String contextPath = renderRequest.getContextPath();
if( !contextPath.endsWith("/") ) {
contextPath = contextPath + "/";
}
renderRequest.setAttribute("images", images);
renderRequest.setAttribute("image", images.get(image_id));
renderRequest.setAttribute("image_id", image_id);
renderRequest.setAttribute("themeDisplay", themeDisplay);
renderRequest.setAttribute("portletDisplay", portletDisplay);
renderRequest.setAttribute("contextPath", contextPath);
}
UPDATE 3
The following code in JSP returns empty string
<!-- scopeGroupId = <c:out value="${scopeGroupId}"/> -->
A group is a container of content and pages, and it's the internal entity for sites, layout scopes, staging and so on.
In Liferay 6.1, a site (which was called community in previous versions) can be associated to an organization. It depends on where you are (in a JSP, in the portlet class, etc.), but, if you have the entity representing the current Group, you can write something like this:
Organization organization = null;
if (group.isOrganization()) {
organization = OrganizationLocalServiceUtil.getOrganization(group.getOrganizationId());
}
Hope it helps. Ask if you need help in order to retrieve the Group object...
Related
I would like to create a Liferay hook that creates public pages on server start.
I already have the hook bound to server start. But I have some problems with creating the page. Maybe I am wrong about user, group, community, etc. (remember that this hook doesn't have access to themeDisplay).
Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID));
long companyId = company.getCompanyId();
User defaultUser = UserLocalServiceUtil.getDefaultUser(companyId);
long userId = defaultUser.getUserId();
long groupId = GroupLocalServiceUtil.getCompanyGroup(PortalUtil.getDefaultCompanyId()).getGroupId();
boolean privateLayout = false;
long parentLayoutId = LayoutConstants.DEFAULT_PARENT_LAYOUT_ID;
String name = page.getName();
String title = null;
String description = null;
String type = LayoutConstants.TYPE_PORTLET;
boolean hidden = false;
String friendlyUrl = "/test";
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
LayoutLocalServiceUtil.addLayout(userId, groupId, privateLayout, parentLayoutId, name, title, description, type, hidden, friendlyUrl, serviceContext);
LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();
layoutTypePortlet.setLayoutTemplateId(userId, page.getLayoutId());
LayoutLocalServiceUtil.updateLayout(layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), layout.getTypeSettings());
The page is never listed...
You might want to check the leftovers of that old sevencogs hook demo code - James Falkner has blogged about it and resurrected some of the code. It might not be for the current version, but if there are any API changes, they're minor.
Pay special attention to the "Adding a Layout (Page) to a Site" paragraph in that article and compare it with your code.
Also note that "on server start" means that you'll have to pay attention to not create the same page twice. It'd happen on every single server start - or actually on every deployment of the hook that you write.
I would like to use p:rating component, to vote and save the value into the database (if it is already voted to be able to extract the value from the db later). In the Entity i have also comments fields and i would like if comments are already written to add only the vote so i sometimes i make merge instead of persist (if there is nothing for this request written in the DB).
I have the following code in my .xhtml page:
<h:form
rendered="#{not empty userRequestBean.request.hiredAgency.city}">
<p:rating value="#{userRequestBean.rating}" stars="10"
onRate="#{userRequestBean.rateAgency()}">
</p:rating>
</h:form>
In my bean I have:
#ManagedBean(name = "userRequestBean")
#SessionScoped
public class UserRequestBean implements Serializable {
private Integer rating; // Plus get and set methods
private TComment agencyComment = new TComment();
public void rateAgency() {
if (rating == null) return;
EntityManager em = HibernateUtil.getEntityManager();
if (!em.getTransaction().isActive())
em.getTransaction().begin();
Query queryAgencyComment = em.createQuery("select comment "
+ "from TRequest req join req.requestComments comment "
+ "where req.id = :requestId ");
Long requestId = (Long) request.getId();
queryAgencyComment.setParameter("requestId", requestId);
agencyComment = (TComment) queryAgencyComment.getSingleResult();
if (agencyComment.equals(null)) {
agencyComment = new TComment();
agencyComment.settRequest(request);
agencyComment.setCommentDate(new Date());
agencyComment.setAssessment(rating);
em.persist(agencyComment);
em.getTransaction().commit();
} else {
agencyComment.setAssessment(5);
em.merge(agencyComment);
em.getTransaction().commit();
}
}
But onRate, the method rateAgency is not executed. It is executed only once when the page is rendered. How can i implement this working?
The attribute onRate defines a JavaScript (client side) action, whilst you are trying to run a server method.
You need an ajax action instead:
<p:rating value="#{userRequestBean.rating}" stars="10" >
<p:ajax event="rate" listener="#{userRequestBean.rateAgency()}" />
</p:rating>
Useful links:
PrimeFaces showcase
A good JSF Tutorial (like Oracle's Java EE 7 Tutorial)
I use javax.naming.directory.DirContext to create a LDAP request for Active Directory. This request returns groups of which the user with given name is member of.
hSearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setCountLimit(1);
searchCtls.setReturningAttributes(new String[]{"memberOf"});
String searchFilter = MessageFormat.format("(sAMAccountName={0})", new Object[]{userName});
NamingEnumeration answer = null;
try {
String hostDC = host.replaceAll("\\.", ",dc=");
adSearchRequestCr = adSearchRequestCr.replace("DL3", getDomainName(host, 3));
adSearchRequestCr = adSearchRequestCr.replace("DL2", getDomainName(host, 2));
adSearchRequestCr = adSearchRequestCr.replace("DL1", getDomainName(host, 1));
answer = context.search(adSearchRequestCr, searchFilter, searchCtls);
}
This works fine but now I need to change this request. Changed request should return not just group in which the user is, but also parent groups of that group and so on (tree of groups). I read about LDAP_MATCHING_RULE_IN_CHAIN, but I still didn`t manage to use it.
Please help with using LDAP_MATCHING_RULE_IN_CHAIN or smth similar to get new aim of the request.
Finally I created recursive by myself without using LDAP_MATCHING_RULE_IN_CHAIN. Firstly I get groups of which the user is member of. I retrieve this groups with attribute "memberOf" - this attribute contains parent groups. And then I make same operation for parent groups until my search is finished. This works fast.
I have a scenario in which users who are created in the liferay will be assigned tools(in the form of iframe). The number of iframes will differ for each user, and when the user logs in, that many number of iframes should come up automatically in his public page.
How can I achieve this ? Is there a way I can save this in preferences of public pages(which will be unique for each user) ? Or should I be using the DB to achieve the same?
Thank you
Adding of iframes to liferay can be done dynamically from code, and this is achieved by following code:
long companyId = themeDisplay.getCompanyId();
long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
Layout layout = LayoutLocalServiceUtil.getLayout(themeDisplay.getPlid());
LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();
String iframePortletId = layoutTypePortlet.addPortletId(themeDisplay.getUserId(),PortletKeys.IFRAME,"column-2",-1);
PortletPreferences prefs = PortletPreferencesLocalServiceUtil.getPreferences(companyId,ownerId,ownerType,layout.getPlid(),iframePortletId);
prefs.setValue("src", "http://www.google.com");
com.liferay.portal.model.PortletPreferences objPortletPref=PortletPreferencesLocalServiceUtil.updatePreferences(ownerId, ownerType, layout.getPlid(), iframePortletId, prefs);
LayoutLocalServiceUtil.updateLayout(layout.getGroupId(),layout.isPrivateLayout(),layout.getLayoutId(),layout.getTypeSettings());
This will add an iframe dynamically.
Thank you.
I’m building a J2EE web application which uses Oracle SSO with an OID back-end as the means for authenticating users.
If a user wants to use the application, first he must provide a valid login/password at SSO's login page.
When the user is done using the application, he may click on the logout button; behind the scenes, the action associated with this button invalidates the user’s session and clears up the cookies using the following Java code:
private void clearCookies(HttpServletResponse res, HttpServletRequest req) {
res.setContentType("text/html");
for (Cookie cookie : req.getCookies()) {
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setDomain(req.getHeader("host"));
res.addCookie(cookie);
}
}
Also, I have an onclick JavaScript event associated with the logout button, which is supposed to delete the SSO cookies by calling the delOblixCookie() function (as found in some Oracle forum):
function delCookie(name, path, domain) {
var today = new Date();
// minus 2 days
var deleteDate = new Date(today.getTime() - 48 * 60 * 60 * 1000);
var cookie = name + "="
+ ((path == null) ? "" : "; path=" + path)
+ ((domain == null) ? "" : "; domain=" + domain)
+ "; expires=" + deleteDate;
document.cookie = cookie;
}
function delOblixCookie() {
// set focus to ok button
var isNetscape = (document.layers);
if (isNetscape == false || navigator.appVersion.charAt(0) >= 5) {
for (var i=0; i<document.links.length; i++) {
if (document.links.href == "javascript:top.close()") {
document.links.focus();
break;
}
}
}
delCookie('ObTEMC', '/');
delCookie('ObSSOCookie', '/');
// in case cookieDomain is configured delete same cookie to all subdomains
var subdomain;
var domain = new String(document.domain);
var index = domain.indexOf(".");
while (index > 0) {
subdomain = domain.substring(index, domain.length);
if (subdomain.indexOf(".", 1) > 0) {
delCookie('ObTEMC', '/', subdomain);
delCookie('ObSSOCookie', '/', subdomain);
}
domain = subdomain;
index = domain.indexOf(".", 1);
}
}
However, my users are not getting logged out from SSO after they hit the logout button: although a new session is created if they try to access the index page, the SSO login page is not presented to them and they can go straight to the main page without having to authenticate. Only if they manually delete the cookies from the browser, the login page shows up again - not what I need: the users must provide their login/password every time they log out from the application, so I believe there must be something wrong in the code that deletes the cookies.
I’d greatly appreciate any help with this problem, thanks in advance.
Oracle have two web SSO products - Oracle Access Manager and Oracle Single Sign On. The Javascript code you have posted is for Access Manager, so it won't help you. Besides, you shouldn't need to do anything in Javascript to log the user out.
Have a look at the logout section of the OSSO docs. It recommends using the following code:
// Clear application session, if any
String l_return_url := return url to your application
response.setHeader( "Osso-Return-Url", l_return_url);
response.sendError( 470, "Oracle SSO" );
You need a page, with a name of logout, that includes those JavaScript functions.
That's what the documentation says:
The WebGate logs a user out when it receives a URL containing
"logout." (including the "."), with the exceptions of logout.gif and
logout.jpg, for example, logout.html or logout.pl. When the WebGate
receives a URL with this string, the value of the ObSSOCookie is set
to "logout.
Cookies don't "delete" untill the browser is closed.