Liferay 5.2.3 portlet configuration page issue - liferay

I wrote a portlet that has custom conf page here is configuration-action-class:
public class ConfigurationActionImpl implements ConfigurationAction {
private static Logger log = Logger.getLogger(ConfigurationActionImpl.class);
private config conf=config.getInstance();
public String render(PortletConfig config, RenderRequest renderRequest, RenderResponse renderResponse) throws Exception {
if(renderRequest.isUserInRole("administrator")){
log.info("UserRole:::admin");
return "/config.jsp";
}else if(renderRequest.isUserInRole("guest")){
log.info("UserRole:::guest");
}else if(renderRequest.isUserInRole("power-user")){
log.info("UserRole:::power-user");
return "/config.jsp";
}else if(renderRequest.isUserInRole("user")){
log.info("UserRole:::user");
}else{
log.info("UserRole:::dafug");
}
return "/config.jsp?mode=guest";
}
public void processAction(PortletConfig config, ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
conf.Names.clear();
String count = ParamUtil.getString(actionRequest, "count");
String portletResource = ParamUtil.getString(actionRequest, "portletResource");
PortletPreferences prefs = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletResource);
String[] list=count.split("/");
for(String a : list){
if( a!=null&& !a.equals("")){
String en = ParamUtil.getString(actionRequest,"En"+a);
String pa = ParamUtil.getString(actionRequest,"Pa"+a);
if(!en.equals("")&&!pa.equals("")){
conf.Names.put(pa,en);
log.info("word::"+en+"::::"+pa);
prefs.setValue("En"+a,en);
prefs.setValue("Pa"+a,pa);
}else if(a!=null&& !a.equals("")){
count=count.substring(0,count.lastIndexOf("/"+a))+count.substring(count.lastIndexOf("/"+a)+("/"+a).length());
}
}
}
prefs.setValue("count",count);
prefs.store();
}
public void serveResource(ResourceRequest request, ResourceResponse response){
log.info("HERE in conf");
}
}
This class worked fine for only one time after clicking on return to full page, the button that locate in right corner of portlets does not work and I cannot go to configuration page again!
and also the menu bar in up right corner of portal did not work after getting back from configuration page unless I delete my portlet and all of them will work fine again!

I solved this problem.
My problem is that first I should change all the to
and I change all of my JQuery code to JavaScript because some how these version of JQuery that I used generates some error with this version of Liferay (5.2.3)

Related

Install a plugin to Liferay's editor

I have a Liferay DXP installation and I would like to install a plugin to the editor. The plugin is base64image.
I was following this official guide so I created a class generally like this:
#Component(immediate = true, service = DynamicInclude.class)
public class CKEditorBase64ImageDynamicInclude implements DynamicInclude {
private BundleContext bundleContext;
#Override
public void include(HttpServletRequest request, HttpServletResponse response, String key) throws IOException {
Bundle bundle = bundleContext.getBundle();
URL entryURL = bundle.getEntry("/META-INF/resources/html/editors/ckeditor/extension/base64_images.js");
StreamUtil.transfer(entryURL.openStream(), response.getOutputStream());
}
#Override
public void register(DynamicIncludeRegistry dynamicIncludeRegistry) {
dynamicIncludeRegistry.register("com.liferay.frontend.editors.web#ckeditor#onEditorCreate");
}
#Activate
protected void activate(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
It should include the base64_images.js file where it initializes the editor. But it never works, regardless what the content of the file is. What is wrong with that?
I would like to add that the plugin files (JavaScript code) are part of my Liferay theme. I wanted base64_images.js to call its API but it also might not be the correct way how to do it.

Can't handle browser window (htmlunit)

I want to download config.bin file from site. Work with htmlunit
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setTimeout(2000);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.setConfirmHandler(new ConfirmHandler() {
public boolean handleConfirm(Page page, String message) {
System.out.println(" -----------------------");
System.out.println("handle config");
System.out.println(" -----------------------");
return true;
}
});
final HtmlPage page = webClient.getPage("http://site");
final DomElement backup = mainFrame.getElementByName("Backup");
webClient.addWebWindowListener(new WebWindowListener()
{
public void webWindowClosed(WebWindowEvent event)
{
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1");
};
public void webWindowContentChanged(WebWindowEvent
event)
{
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!2");
}
public void webWindowOpened(WebWindowEvent event)
{
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!3");
}
});
InputStream input = backup.click().getWebResponse().getContentAsStream();
Then submited ckick() I think that get stream, but got submit page. I think that I have problem with browser window and I can't handle browser window. I insert sout in handler and see when this method to called but it didn't call
the problem was in period that i install. changed setTimeout and all work.
webClient.getOptions().setTimeout(15000);

Customize CreateAccountAction in Liferay Portal

I'm trying to add "User Group" Selection field while creating a user (Self User Registration form - create_account.jsp).
Here Custom fields is not helpful because Usergroup is already exists in db. I want to insert into existing Users_UserGroups table.
I'm using below hook:
But User is not added in the group and no exception is printed.
Please suggest me for any other way to achieve this.
public class CustomCreateAccountAction extends BaseStrutsPortletAction
{
public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
throws Exception
{
System.out.println("My Custom Process Action Method is Called");
String emailid=ParamUtil.getString(actionRequest, "emailAddress");
long[] userGroupIds = null;
originalStrutsPortletAction.processAction(originalStrutsPortletAction, portletConfig, actionRequest,actionResponse);
System.out.println("This is after user is registered");
if (SessionErrors.isEmpty(actionRequest))
{
ThemeDisplay themeDisplay =(ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long newlyCreatedUserId=UserLocalServiceUtil.getUserIdByEmailAddress(themeDisplay.getCompanyId(), emailid);
long userIds[]={newlyCreatedUserId};
long dummygroupid=16206;
System.out.println("TEST UserID="+newlyCreatedUserId);
System.out.println("TEST GroupID="+dummygroupid);
//Everything went well until here.
UserServiceUtil.addUserGroupUsers(dummygroupid, userIds);
//below sysout is not printed. and no exception or user in group db created.
System.out.println("user added to group");
}
}
public String render(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, RenderRequest renderRequest, RenderResponse renderResponse) throws Exception
{
System.out.println("My Custom Render Method is Called");
return originalStrutsPortletAction.render(null, portletConfig, renderRequest, renderResponse);
}
}
for more info please have a look at this thread.
Using UserLocalServiceUtil instead of UserServiceUtil worked. Basically, the difference is that *ServiceUtil checks permissions and *LocalServiceUtil does not.
I'm not sure this is the best idea, but you can use the hook for both modify the user creación jsp and save the value via model listener on user create/modify.
Regsrds

Displaying an html page in form (error connecting to stream)

I putted an .html page in a src folder of project in order to display this page on runtime.
But I get an error on runtime that say:- Error connecting to stream.
import javax.microedition.midlet.*;
public class HtmlMidlet extends MIDlet {
public void startApp()
{
com.sun.lwuit.Display.init(this);
final com.sun.lwuit.Form form = new com.sun.lwuit.Form("");
final com.sun.lwuit.html.HTMLComponent htmlC = new com.sun.lwuit.html.HTMLComponent( );
htmlC.setRTL(true);
htmlC.setPage("jar://src/ahlam.html");
form.addComponent(htmlC);
form.setScrollable(true);
form.show( );
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
}
I think that the way that you are using to open your file is not the proper way. Is this html page in your folder? Where is your page? the root directory is /src from your project, why are you using jar:... try /ahlam.html only
Take a look on this page for more info and examples HTML Component

Debugging Package Manager Console Update-Database Seed Method

I wanted to debug the Seed() method in my Entity Framework database configuration class when I run Update-Database from the Package Manager Console but didn't know how to do it. I wanted to share the solution with others in case they have the same issue.
Here is similar question with a solution that works really well.
It does NOT require Thread.Sleep.
Just Launches the debugger using this code.
Clipped from the answer
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
The way I solved this was to open a new instance of Visual Studio and then open the same solution in this new instance of Visual Studio. I then attached the debugger in this new instance to the old instance (devenv.exe) while running the update-database command. This allowed me to debug the Seed method.
Just to make sure I didn't miss the breakpoint by not attaching in time I added a Thread.Sleep before the breakpoint.
I hope this helps someone.
If you need to get a specific variable's value, a quick hack is to throw an exception:
throw new Exception(variable);
A cleaner solution (I guess this requires EF 6) would IMHO be to call update-database from code:
var configuration = new DbMigrationsConfiguration<TContext>();
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
This allows you to debug the Seed method.
You may take this one step further and construct a unit test (or, more precisely, an integration test) that creates an empty test database, applies all EF migrations, runs the Seed method, and drops the test database again:
var configuration = new DbMigrationsConfiguration<TContext>();
Database.Delete("TestDatabaseNameOrConnectionString");
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
Database.Delete("TestDatabaseNameOrConnectionString");
But be careful not to run this against your development database!
I know this is an old question, but if all you want is messages, and you don't care to include references to WinForms in your project, I made some simple debug window where I can send Trace events.
For more serious and step-by-step debugging, I'll open another Visual Studio instance, but it's not necessary for simple stuff.
This is the whole code:
SeedApplicationContext.cs
using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Data.Persistence.Migrations.SeedDebug
{
public class SeedApplicationContext<T> : ApplicationContext
where T : DbContext
{
private class SeedTraceListener : TraceListener
{
private readonly SeedApplicationContext<T> _appContext;
public SeedTraceListener(SeedApplicationContext<T> appContext)
{
_appContext = appContext;
}
public override void Write(string message)
{
_appContext.WriteDebugText(message);
}
public override void WriteLine(string message)
{
_appContext.WriteDebugLine(message);
}
}
private Form _debugForm;
private TextBox _debugTextBox;
private TraceListener _traceListener;
private readonly Action<T> _seedAction;
private readonly T _dbcontext;
public Exception Exception { get; private set; }
public bool WaitBeforeExit { get; private set; }
public SeedApplicationContext(Action<T> seedAction, T dbcontext, bool waitBeforeExit = false)
{
_dbcontext = dbcontext;
_seedAction = seedAction;
WaitBeforeExit = waitBeforeExit;
_traceListener = new SeedTraceListener(this);
CreateDebugForm();
MainForm = _debugForm;
Trace.Listeners.Add(_traceListener);
}
private void CreateDebugForm()
{
var textbox = new TextBox {Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both, WordWrap = false};
var form = new Form {Font = new Font(#"Lucida Console", 8), Text = "Seed Trace"};
form.Controls.Add(tb);
form.Shown += OnFormShown;
_debugForm = form;
_debugTextBox = textbox;
}
private void OnFormShown(object sender, EventArgs eventArgs)
{
WriteDebugLine("Initializing seed...");
try
{
_seedAction(_dbcontext);
if(!WaitBeforeExit)
_debugForm.Close();
else
WriteDebugLine("Finished seed. Close this window to continue");
}
catch (Exception e)
{
Exception = e;
var einner = e;
while (einner != null)
{
WriteDebugLine(string.Format("[Exception {0}] {1}", einner.GetType(), einner.Message));
WriteDebugLine(einner.StackTrace);
einner = einner.InnerException;
if (einner != null)
WriteDebugLine("------- Inner Exception -------");
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _traceListener != null)
{
Trace.Listeners.Remove(_traceListener);
_traceListener.Dispose();
_traceListener = null;
}
base.Dispose(disposing);
}
private void WriteDebugText(string message)
{
_debugTextBox.Text += message;
Application.DoEvents();
}
private void WriteDebugLine(string message)
{
WriteDebugText(message + Environment.NewLine);
}
}
}
And on your standard Configuration.cs
// ...
using System.Windows.Forms;
using Data.Persistence.Migrations.SeedDebug;
// ...
namespace Data.Persistence.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
// Migrations configuration here
}
protected override void Seed(MyContext context)
{
// Create our application context which will host our debug window and message loop
var appContext = new SeedApplicationContext<MyContext>(SeedInternal, context, false);
Application.Run(appContext);
var e = appContext.Exception;
Application.Exit();
// Rethrow the exception to the package manager console
if (e != null)
throw e;
}
// Our original Seed method, now with Trace support!
private void SeedInternal(MyContext context)
{
// ...
Trace.WriteLine("I'm seeding!")
// ...
}
}
}
Uh Debugging is one thing but don't forget to call:
context.Update()
Also don't wrap in try catch without a good inner exceptions spill to the console.
https://coderwall.com/p/fbcyaw/debug-into-entity-framework-code-first
with catch (DbEntityValidationException ex)
I have 2 workarounds (without Debugger.Launch() since it doesn't work for me):
To print message in Package Manager Console use exception:
throw new Exception("Your message");
Another way is to print message in file by creating a cmd process:
// Logs to file {solution folder}\seed.log data from Seed method (for DEBUG only)
private void Log(string msg)
{
string echoCmd = $"/C echo {DateTime.Now} - {msg} >> seed.log";
System.Diagnostics.Process.Start("cmd.exe", echoCmd);
}

Resources