how prevent duplicate code in wicket - wicket

Sorry my english is bad
I have two class profile and EditProfile
in both class i have
protected void addContent(PageParameters pageParameters) {
final String email = pageParameters.get(ListUser.USER_EMAIL).toString();
final User loggedUser = getLoggedUser();
if (email == null) {
redirectToInterceptPage(new ErrorPage404(null));
return;
}
User userByEmail = userService.findByEmail(email);
if (userByEmail == null) {
redirectToInterceptPage(new ForbiddenPage403(null));
return;
}
final UserDetachableModel user = new UserDetachableModel(userByEmail);
// If the user is not active, there is no need to edit your profile.
if (!user.getObject().isActive()) {
redirectToInterceptPage(new ErrorPage404(null));
return;
}
// Only admins can see the profile of other users.
if (!loggedUser.getUserRole().equals(UserRole.ADMIN) && !loggedUser.getEmail().equalsIgnoreCase(email)) {
redirectToInterceptPage(new ForbiddenPage403(null));
return;
}
......PROCESS TO SEE PROFILE OR EDIT PROFILE........
}
I use a CustomMountedPage that i use to hide the serial number of wicket.
Example http://HOST/Page/subPage?ID&PARAMS to see http://HOST/Page/subPage?PARAMS and access to another profile
How prevent duplicate code!!

You can use Panels. They have their own markup file like a normal page but you can use them in any other Wicket-Page as a component.
Have a look at this page to see how to use panels correctly.

Related

How to Keep Tabs on a Particular Tab?

In my firefox sdk addon, I want to use a custom webpage from my data directory as my settings/about page.
But I am having trouble keeping tabs on the tab!
So I have a button that calls the OptionsPanel() function to open my webpage in a new tab. Now, I want to make it so if the user forgets that tab is open and pushes the button again, that it activates the already-open settings tab. That means I need to know that the tab is open and I need to be able to switch to it if it is OR open it if it is not already open.
Here is what I've come up with so far, but it doesn't work; it just always opens a new tab. I don't even know if I'm barking up the right tree.
const tabs = require("sdk/tabs");
var optionsTab;
function OptionsPanel(){
var opsTab = GetTabByID(optionsTab.id);
if(opsTab == null){
tabs.open( data.url("OptionsPanel.html") );
optionsTab.id = tabs.tab.id; <======errors out as undefined
}else{
opsTab.activate();
}
}
//return a handle to the tab that matches specified tab id
function GetTabByID(whatid){
for(let thistab of tabs){
if(thistab.id = whatid){
return thistab;
}
}
return null;
}
So, here are my goals:
Open my page in a new tab if it isn't already open.
If the tab is already open, then switch to that tab.
If the page is open when the browser loads, then be ready to switch to that tab if the user pushes the options button.
Why would you think tabs module has a tab property?
Normally you would use the activeTab property instead. However it does not get updated immediately after tabs.open is called. One has to use tabs[tabs.length - 1] instead.
const tabs = require("sdk/tabs");
var optionsTabId;
function OptionsPanel(){
var opsTab = GetTabByID(optionsTabId);
if (opsTab == null) {
tabs.open( data.url("OptionsPanel.html") );
optionsTabId = tabs[tabs.length - 1].id;
} else {
opsTab.activate();
}
}
Additionally, you made a mistake in GetTabByID.
//return a handle to the tab that matches specified tab id
function GetTabByID(whatid){
for(let thistab of tabs){
if(thistab.id == whatid){ // use == to compare
return thistab;
}
}
return null;
}
Keep in mind this assumes that it is not possible to navigate away from your options tab. I would check optsTab.url just in case.
Alternatively you could make use of the tab event interface
const tabs = require("sdk/tabs");
const OPTIONS_URL = data.url("OptionsPanel.html");
var optionsTab = null;
function OptionsPanel(){
if (optionsTab == null) {
tabs.open(OPTIONS_URL);
tabs.once('ready', function(tab) {
optionsTab = tab;
optionsTab.on('ready', function readyListener(tab) {
if (tab.url !== OPTIONS_URL) {
optionsTab.off('ready', readyListener);
optionsTab = null;
}
})
optionsTab.once('close', function(tab) {
optionsTab = null;
})
});
} else {
optionsTab.activate();
}
}

Where to call an Action when user removes an uploaded image in GWTUpload?

I am using GWTUpload , the library is in here https://code.google.com/p/gwtupload/
The Example code at client side found on that website has this structure:
// Attach an image to the pictures viewer
private OnLoadPreloadedImageHandler showImage = new OnLoadPreloadedImageHandler() {
public void onLoad(PreloadedImage image) {
//showImageFlowPanel code solution 1
image.setWidth("75px");
showImageFlowPanel.add(image);
}
};
private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
public void onFinish(IUploader uploader) {
if (uploader.getStatus() == Status.SUCCESS) {
new PreloadedImage(uploader.fileUrl(), showImage);
UploadedInfo info = uploader.getServerInfo();
String headShotImageUrl="http://"+Window.Location.getHost()+"/" +"images/uploaded/"+info.message;
//headShotImage code solution 2
if(!"".equals(headShotImageUrl) && UriUtils.isSafeUri(headShotImageUrl)){
headShotImage.setUrl(UriUtils.fromString(headShotImageUrl));
}
}
}
};
The example uses showImageFlowPanel (solution 1) to store the image but I want to store the image inside headShotImage which take the url after user uploaded image successfully, see the headShotImage (solution 2) code above.
Ok, the headShotImage code work fine but I dont know how to remove it when users remove the image. If I use showImageFlowPanel as in the solution 1 then the program remove the image automatically for me and I do not need to do anything.
So my question is "Where to call an Action when user removes an uploaded image in GWTUpload?"
You have to use setOnCancelUploaderHandler. Take a look to this code took from the demo.
// When the user clicks a cancel button we get an event
uploader.addOnCancelUploadHandler (
new IUploader.OnCancelUploaderHandler() {
public void onCancel(IUploader uploader) {
for (String iname : uploader.getServerMessage().getUploadedFieldNames()) {
// loadedImages is an temporary table where we are adding all uploaded files
// indexed by field name
Widget w = loadedImages.get(iname);
if (w != null) {
w.removeFromParent();
loadedImages.remove(uploader.getInputName());
}
}
}
});

CQ-Dialog page properties can not be stored from site admin but works from sidekick

The purpose of the following function is to allow the user to save the edited page properties in the CQ-Dialog even though if they invalid by clicking on the button save anyway:
PageProperties.showMsg = function(dialog, config, errorMessage) {
CQ.Ext.MessageBox.buttonText.ok = "save anyway";
CQ.Ext.Msg.show({
title : "Completeness check failed",
msg : errorMessage,
buttons: CQ.Ext.Msg.OKCANCEL,
fn : function(buttons) {
if(buttons == "ok") {
dialog.form.items.each(function(field) {
// clear fields with emptyText so emptyText is not submitted
if (field.emptyText && field.el && field.el.dom && field.el.dom.value == field.emptyText) {
field.setRawValue("");
}
});
var action = new CQ.form.SlingSubmitAction(dialog.form, config);
dialog.form.isValid = function() {
return true;
};
dialog.form.doAction(action);
dialog[dialog.closeAction]();
CQ.Util.reload();
}
}
});
};
This functions works fine from the sidekick. When I click on save anyway all current values of the page properites are stored regardless if they are valid or not. This does not work from the site admin. when I call the page properties of the same page from the site admin and try to save the page properties with invalid values by clicking on save anyway, this does not works (old values are stored and nothing changes).
I hope somebody can help. thank you
I found the solution. the problem was the function CQ.Util.reload(). It prevent storing the values

Preloader in Wicket Application

In a wicket application on search event it takes few secons and sometimes minutes to show the result as its a long data . I want to show a preloader while the data is fetched from the database to let the user know something is going on when they click search . I am very new to wicket application , dont understands the things very deeply but I find AjaxLazyPreloader but as I said I want to show the preloader when the search method is called ...I am sharing the SearchSubmit method ...
private void processSearchSubmit(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.add(tableHolder);
ajaxRequestTarget.add(productTableHolder);
if (zipcode == null) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showWarningToast','Please enter a zipcode')");
} else if (!ZipCodeValidator.isValid(zipcode)) {
useZones = true;
currentZone = zipcode;
ajaxRequestTarget.add(tableHolder);
if (searchProduct != null) {
ajaxRequestTarget.add(productTableHolder);
if (lstProduct.getList().size() == 0) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showErrorToast','Sorry! This product is not avialable .')");
}
}
} else if (lstMerchants.getList().size() == 0) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showWarningToast','Sorry! There are currently no services')");
}
if (ZipCodeValidator.isValid(zipcode)) {
ajaxRequestTarget.add(tableHolder);
if (searchProduct != null && !searchProduct.equals("")) {
ajaxRequestTarget.add(productTableHolder);
if (lstProduct.getList().size() == 0) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showErrorToast','Sorry! This product is not avialable in this zip code or zone.')");
}
}
}
}
I want when this method is called till the times it fetch the result data , it should show a preloader or spinner . Can anybody suggest how to do that .??
If you need to call long execution method by clicking button check this answer.
You can also use AjaxLazyLoadPanel, check this demo (it's Java part and html part)
Either use an AjaxLazyLoadPanel or an IndicatingAjaxLink/-Button. Both will work fine in either normal or Ajax calls.
To use an AjaxLazyLoadPanel: create a subclass of AjaxLazyLoadPanel which loads the panel you want to display and add it to the AjaxRequest.
IndicatingAjaxLinks just display a spinner while the request is being processed and can be used straightforward in your current application. Use this instead of the button/link you use for formsubmits now.

ASP.NET Connection Reset on Upload

I'm running into a problem with my app (ASP.NET MVC 2) where I can't upload files (images in my case). I've changed the web.config to accept up to 20MB, and I'm trying to upload a file that's only 3MB.
The app itself has two ways to upload. The initial upload which starts a Gallery and then an additional upload to append to a Gallery.
The initial works like a charm, but the appending one fails with no explanation. Even if I re-upload the initial image as an append it still fails.
I'm a little stuck on this so I would appreciate any help you guys can offer.
Thanks in advance!
EDIT
If I "hack" the form with Firebug and direct it to the initial upload Url it works, but when it's directing to the Url it should be posting to it fails...
EDIT 2
Per Rob's request, here's the code handling the initial gallery and appending image:
[HttpPost, ValidateAntiForgeryToken]
public RedirectToRouteResult PutGallery( // Move to Ajax
[Bind(Prefix = "Gallery", Include = "ClubId,EventId,RHAccountId,RHCategoryId,Year")] Gallery Gallery,
HttpPostedFileBase File) {
if (ModelState.IsValid && (File.ContentLength > 0)) {
if (Gallery.RHAccountId > 0) {
Gallery.RHUser = this.fdc.RHAccounts.Single(
a =>
(a.RHAccountId == Gallery.RHAccountId)).RHUser;
} else {
if (!this.fdc.RHUsers.Any(
u =>
(u.User.Name == Gallery.Username))) {
if (!this.fdc.Users.Any(
u =>
(u.Name == Gallery.Username))) {
Gallery.RHUser = new RHUser() {
User = new User() {
Name = Gallery.Username
}
};
} else {
Gallery.RHUser = new RHUser() {
User = this.fdc.Users.Single(
u =>
(u.Name == Gallery.Username))
};
};
} else {
Gallery.RHUser = this.fdc.RHUsers.Single(
u =>
(u.User.Name == Gallery.Username));
};
};
Image Image = new Image() {
Gallery = Gallery
};
this.fdc.Galleries.InsertOnSubmit(Gallery);
this.fdc.Images.InsertOnSubmit(Image);
this.fdc.SubmitChanges();
Files.Save(Image.ImageId, File);
return RedirectToAction("Default", "Site");
} else {
return RedirectToAction("Default", "Site");
};
}
[HttpPost, ValidateAntiForgeryToken]
public RedirectToRouteResult PutImage(
[Bind(Prefix = "Image", Include = "GalleryId")] Image Image,
HttpPostedFileBase File) {
Gallery Gallery = this.fdc.Galleries.Single(
g =>
(g.GalleryId == Image.GalleryId));
if (File.ContentLength > 0) {
this.fdc.Images.InsertOnSubmit(Image);
this.fdc.SubmitChanges();
Files.Save(Image.ImageId, File);
};
return RedirectToAction("Gallery", "Site", new {
Category = Gallery.RHCategory.Category.EncodedName,
GalleryId = Gallery.GalleryId
});
}
SIDENOTE:
Could Cassini, VS 2010's built in web server, be the cause?
Ok, so I figured it out, it only took a lengthy install of IIS locally on my machine + the configuration, to have it tell me that I miss-spelled controller as controlls in the routes.
Really annoying that it took all of that to get the real error, so Cassini was partially at fault...
So, the moral of the story is, make sure you spell everything correctly.