setRedirect(true) in wicket 6.x or 7.x - wicket

I have code something like this, So how can I write in wicket 6.x or 7.x
1.
catch (Exception e) {
log.error("**** Exception ***********");
setRedirect(true);
log.errorException(e);
showErrorMsg(getLocalizer().getString("request.process.page.error", this));
}
2.
if (admin != null && admin.getId().equalsIgnoreCase(aId) == false) {
log.error("UserId do not match");
setRedirect(true);
showErrorMsg(getLocalizer().getString("internal.user.gccverf.auth.failed", this));
}
I have method like this
private void showErrorMsg(String errorMsg) {
setResponsePage(new ErrorPage(this.getPage(), getLocalizer().getString("label.applicaiton.error.page", this), errorMsg));
}

Just remove setRedirect(true);.
Another way is to replace it with: setResponsePage(getPage().getPageClass(), getPage().getPageParameters()). This will tell Wicket to create a new instance of the current page's class and render it. In this case it is important that showErrorMsg() uses Session#error() otherwise the error won't be available for the next page.

Related

Vert.x: How to wait for a future to complete

Is there a way to wait for a future to complete without blocking the event loop?
An example of a use case with querying Mongo:
Future<Result> dbFut = Future.future();
mongo.findOne("myusers", myQuery, new JsonObject(), res -> {
if(res.succeeded()) {
...
dbFut.complete(res.result());
}
else {
...
dbFut.fail(res.cause());
}
}
});
// Here I need the result of the DB query
if(dbFut.succeeded()) {
doSomethingWith(dbFut.result());
}
else {
error();
}
I know the doSomethingWith(dbFut.result()); can be moved to the handler, yet if it's long, the code will get unreadable (Callback hell ?) It that the right solution ? Is that the omny solution without additional libraries ?
I'm aware that rxJava simplifies the code, but as I don't know it, learning Vert.x and rxJava is just too much.
I also wanted to give a try to vertx-sync. I put the dependency in the pom.xml; everything got downloaded fine but when I started my app, I got the following error
maurice#mickey> java \
-javaagent:~/.m2/repository/co/paralleluniverse/quasar-core/0.7.5/quasar-core-0.7.5-jdk8.jar \
-jar target/app-dev-0.1-fat.jar \
-conf conf/config.json
Error opening zip file or JAR manifest missing : ~/.m2/repository/co/paralleluniverse/quasar-core/0.7.5/quasar-core-0.7.5-jdk8.jar
Error occurred during initialization of VM
agent library failed to init: instrument
I know what the error means in general, but I don't know in that context... I tried to google for it but didn't find any clear explanation about which manifest to put where. And as previously, unless mandatory, I prefer to learn one thing at a time.
So, back to the question : is there a way with "basic" Vert.x to wait for a future without perturbation on the event loop ?
You can set a handler for the future to be executed upon completion or failure:
Future<Result> dbFut = Future.future();
mongo.findOne("myusers", myQuery, new JsonObject(), res -> {
if(res.succeeded()) {
...
dbFut.complete(res.result());
}
else {
...
dbFut.fail(res.cause());
}
}
});
dbFut.setHandler(asyncResult -> {
if(asyncResult.succeeded()) {
// your logic here
}
});
This is a pure Vert.x way that doesn't block the event loop
I agree that you should not block in the Vertx processing pipeline, but I make one exception to that rule: Start-up. By design, I want to block while my HTTP server is initialising.
This code might help you:
/**
* #return null when waiting on {#code Future<Void>}
*/
#Nullable
public static <T>
T awaitComplete(Future<T> f)
throws Throwable
{
final Object lock = new Object();
final AtomicReference<AsyncResult<T>> resultRef = new AtomicReference<>(null);
synchronized (lock)
{
// We *must* be locked before registering a callback.
// If result is ready, the callback is called immediately!
f.onComplete(
(AsyncResult<T> result) ->
{
resultRef.set(result);
synchronized (lock) {
lock.notify();
}
});
do {
// Nested sync on lock is fine. If we get a spurious wake-up before resultRef is set, we need to
// reacquire the lock, then wait again.
// Ref: https://stackoverflow.com/a/249907/257299
synchronized (lock)
{
// #Blocking
lock.wait();
}
}
while (null == resultRef.get());
}
final AsyncResult<T> result = resultRef.get();
#Nullable
final Throwable t = result.cause();
if (null != t) {
throw t;
}
#Nullable
final T x = result.result();
return x;
}

Eclipse plugin - getting the IStackframe object from a selection in DebugView

So, this is the problem I am stuck at for a few weeks.
I am developing an Eclipse plugin which fills in a View with custom values depending on a particular StackFrame selection in the Debug View.
In particular, I want to listen to the stackframe selected and would like to get the underlying IStackFrame object.
However, I have tried more than a dozen things and all of them have failed. So I tried adding DebugContextListener to get the DebugContextEvent and finally the selection. However, the main issue is that ISelection doesn't return the underlying IStackFrame object. It instead returns an object of type AbstractDMVMNode.DMVMContext. I tried getting an adapter but that didn't work out too. I posted this question sometime back also:
Eclipse Plugin Dev- Extracting IStackFrame object from selection in Debug View
Since then, I have tried out many different approaches. I tried adding IDebugEventSetListener (but this failed as it cannot identify stack frame selection in the debug view).
I tried adding an object contribution action but this too was pointless as it ultimately returned me an ISelection which is useless as it only returns me an object of class AbstractDMVMNode.DMVMContext and not IStackframe.
Moreover, I checked out the implementation of the VariablesView source code itself in the org.eclipse.debug.ui plugin. It looks like a few versions back (VariablesView source code in version 3.2), the underlying logic was to use the ISelection and get the IStackFrame. All the other resources on the internet also advocate the same. However, now, this scheme no longer works as ISelection doesn't return you an IStackFrame. Also, the source code for the latest eclipse Debug plugin (which doesn't use this scheme) was not very intuitive for me.
Can anyone tell how I should proceed ? Is hacking the latest Eclipse source code for VariablesView my only option ? This doesn't look like a good design practice and I believe there should be a much more elegant way of doing this.
PS: I have tried all the techniques and all of them return an ISelection. So, if your approach too return the same thing, then it is most likely incorrect.
Edit (Code snippet for trying to adapt the ISelection):
// Following is the listener implemnetation
IDebugContextListener flistener = new IDebugContextListener() {
#Override
public void debugContextChanged(DebugContextEvent event) {
if ((event.getFlags() & DebugContextEvent.ACTIVATED) > 0) {
contextActivated(event.getContext());
}
};
};
// Few things I tried in the contextActivated Method
//Attempt 1 (Getting the Adapter):
private void contextActivated(ISelection context) {
if (context instanceof StructuredSelection) {
Object data = ((StructuredSelection) context).getFirstElement();
if( data instanceof IAdaptable){
System.out.println("check1");
IStackFrame model = (IStackFrame)((IAdaptable)data).getAdapter(IStackFrame.class);
if(model != null){
System.out.println("success" + model.getName());
}
}
}
}
// Attemp2 (Directly getting it from ISelection):
private void contextActivated(ISelection context) {
if (context instanceof StructuredSelection) {
System.out.println("a");
Object data = ((StructuredSelection) context).getFirstElement();
if (data instanceof IStackFrame) {
System.out.println("yes");
} else {
System.out.println("no" + data.getClass().getName());
}
}
// This always execute the else and it prints: org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode.DMVMContext
}
// Attemp3 (Trying to obtain it from the viewer (similiar to object action binding in some ways):
private void contextActivated(ISelection context) {
VariablesView variablesView = (VariablesView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(IDebugUIConstants.ID_VARIABLE_VIEW);
if (variablesView != null) {
Object input = ((TreeViewer) variablesView.getViewer()).getInput();
if(input != null) System.out.println(input.getClass().getName());
if (input instanceof IStackFrame) {
System.out.println("success");
} else if (input instanceof IThread) {
System.out.println("success");
try {
IStackFrame[] stackFrames = ((IThread) input).getStackFrames();
for (IStackFrame iStackFrame : stackFrames) {
printVariables(iStackFrame);
}
} catch (DebugException e) {
e.printStackTrace();
}
}
}
}
While I am building this view to work with both JDT & CDT, I am testing it out on the C project. So, this might be the reason why I always get the returned object type as AbstractDMVMNode.DMVMContext. Should my implementation be different to handle both these cases ? I believe I should be building a generic view. Also, if AbstractDMVMNode.DMVMContext is CDT specific, I should I go about implementing it for the CDT case?

EF: EnsureLoadedForContext method

I am reading EF's source code and found this method below. According to the method name, it make sure that the dbcontext is loaded. When I test this with EF Codefirst sample, this method is added the current assembly (my sample console) to "_knownAssemblies"..
I don't see any code of loading the assembly. And I don't see any code that checks whether the assembly is loaded or not.
Is that the naming issue or Did I miss out something? Thanks in advance.
public virtual void EnsureLoadedForContext(Type contextType)
{
DebugCheck.NotNull(contextType);
Debug.Assert(typeof(DbContext).IsAssignableFrom(contextType));
var contextAssembly = contextType.Assembly;
if (contextType == typeof(DbContext)
|| _knownAssemblies.ContainsKey(contextAssembly))
{
return;
}
if (_configurationOverrides.IsValueCreated)
{
lock (_lock)
{
if (_configurationOverrides.Value.Count != 0)
{
return;
}
}
}
if (!ConfigurationSet)
{
var foundConfigurationType =
_loader.TryLoadFromConfig(AppConfig.DefaultInstance) ??
_finder.TryFindConfigurationType(contextType);
if (foundConfigurationType != null)
{
SetConfigurationType(foundConfigurationType);
}
}
else if (!contextAssembly.IsDynamic // Don't throw for proxy contexts created in dynamic assemblies
&& !_loader.AppConfigContainsDbConfigurationType(AppConfig.DefaultInstance))
{
var foundType = _finder.TryFindConfigurationType(contextType);
if (foundType != null)
{
if (_configuration.Value.Owner.GetType() == typeof(DbConfiguration))
{
throw new InvalidOperationException(Strings.ConfigurationNotDiscovered(foundType.Name));
}
if (foundType != _configuration.Value.Owner.GetType())
{
throw new InvalidOperationException(
Strings.SetConfigurationNotDiscovered(_configuration.Value.Owner.GetType().Name, contextType.Name));
}
}
}
_knownAssemblies.TryAdd(contextAssembly, null);
}
The method EnsureLoadedForContext does not load the context but loads a configuration for the context type passed to the method. When you look at the name of the method with the type name on which the method is created (DbConfigurationManager.EnsureLoadedForContext) it is much more clear that the method is related to loading a configuration rather than loading a context. Finally you can look at a comment to one of the bugs which reads:
EnsureLoadedForContext is called from various places as soon as a context type is known to ensure that the correct DbConfiguration is found.

Eclipse RCP p2 update not working

I have a personal Eclipse RCP product (com.example.product) based on one personal feature (com.example.feature) which is composed of one personal plugin (com.example.plugin) and a bunch of others from Eclipse Helios (3.6). I want the app to check for updates and update itself if necessary from a p2 site. I want it to be headless, ie the user does not interact in the update process, but may see progress in a dialog.
I based my implementation for the updates on the RCP Mail application. I changed the P2Util.checkForUpdates method a bit to include some logging so I can see what, if anything, is going wrong there:
static IStatus checkForUpdates(IProvisioningAgent agent,
IProgressMonitor monitor) throws OperationCanceledException,
InvocationTargetException {
ProvisioningSession session = new ProvisioningSession(agent);
UpdateOperation operation = new UpdateOperation(session);
SubMonitor sub = SubMonitor.convert(monitor,
"Checking for application updates...", 200);
IStatus status = operation.resolveModal(sub.newChild(100));
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
return status;
}
if (status.getSeverity() == IStatus.CANCEL)
throw new OperationCanceledException();
if (status.getSeverity() != IStatus.ERROR) {
try {
logger.info( "Status is " + status );
Update[] updates = operation.getPossibleUpdates();
for( Update u : updates){
logger.info( "Update is " + u );
}
ProvisioningJob job = operation.getProvisioningJob(null);
if( job == null ){
logger.error( "Provisioning Job is null" );
}
status = job.runModal(sub.newChild(100));
if (status.getSeverity() == IStatus.CANCEL) {
throw new OperationCanceledException();
}
} catch ( Exception e ){
logger.error( "Exception while trying to get updates", e);
}
}
return status;
}
I have a p2.inf file in my feature at the same level as my example.product file. It contains:
org.eclipse.equinox.p2.touchpoint.eclipse.addRepository":
instructions.configure=\
org.eclipse.equinox.p2.touchpoint.eclipse.addRepository(type:0,location:file${#58}/C${#58}/workspace/updatesite/);\
org.eclipse.equinox.p2.touchpoint.eclipse.addRepository(type:1,location:file${#58}/C${#58}/workspace/updatesite/);
I build the product with plugin, feature and product IDs set to 1.0.0.
I can export and run my product from eclipse using the product export wizard. I tick generate metadata repository when I do this.
I create my update site using the Create an Update Site Project option in the Feature Manfiest Editor. I add my `com.example.feature' and build it. Just to see if it works I try browsing it via eclipse IDE Install New Software option and I can see the feature there.
I build the update site with all 3 IDs changed to 1.0.1. When I start the app it says there are no updates to install, there are no errors in the logs.
I don't know why it doesn't update from the update site, but things that have crossed my mind are:
1) I may need more info in the p2.inf file, but I'm not sure what, maybe something like namespace, name and range, but I can't find a good practical example.
2) In the checkForUpdates method I may need to do something with profiles to change what installable units are being updated. Again, I only found comments hinting at this and not any example code that shows how.
Any hints or ideas are much appreciated here, this is eating a lot of time.
Look at this code. Rebuild your product with a new product version and try to setup a http server. It didnt work with file repo for me. Just publishing the feature will not work.
final IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
sub = SubMonitor.convert(monitor, Messages.getString("UpdateManager.searchforupdates"), 200); //$NON-NLS-1$
final Update update = getUpdate(profile, provisioningContext, engine, context);
status = operation.resolveModal(sub.newChild(100));
LogHelper.log(status);
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
status = null;
return;
}
if (status.getSeverity() == IStatus.CANCEL)
throw new OperationCanceledException();
if (status.getSeverity() != IStatus.ERROR) {
log(IStatus.INFO, "Checking for available update matches", null); //$NON-NLS-1$
Update[] selected = new Update[1];
operation.setSelectedUpdates(new Update[0]);
for (Update available : operation.getPossibleUpdates()) {
if (available.equals(update)) {
log(IStatus.INFO, "Update matches available: " + update, null); //$NON-NLS-1$
selected[0] = available;
operation.setSelectedUpdates(selected);
}
}
if (selected[0] == null) {
status = null;
monitor.setCanceled(true);
log(IStatus.WARNING, "No Update matches selected", null); //$NON-NLS-1$
return;
}
ProvisioningJob job = operation.getProvisioningJob(monitor);
if (job != null) {
status = job.runModal(sub.newChild(100));
if (status.getSeverity() != IStatus.ERROR) {
prefStore.setValue(JUSTUPDATED, true);
Display.getDefault().syncExec(new Runnable() {
public void run() {
PlatformUI.getWorkbench().restart();
}
});
} else {
LogHelper.log(status);
}
} else {
log(IStatus.INFO, "getJob returned null", null); //$NON-NLS-1$
status = null;
}
if (status != null && status.getSeverity() == IStatus.CANCEL)
throw new OperationCanceledException();
}
}
};
Display.getDefault().asyncExec(new Runnable() {
public void run() {
try {
new ProgressMonitorDialog(null).run(true, true, runnable);
} catch (InvocationTargetException x) {
log(IStatus.ERROR, "Runnable failure", x); //$NON-NLS-1$
} catch (InterruptedException e) {
}
}
});
#user473284's answer had some suggestions that I used but I don't know if they were definite requirements
1) using a local web server instead of trying to point to a file
2) Incrementing the product version and using the update repository generated by the export product wizard.
I never did find the implementation for the getUpdate method referenced from the code sample so I couldn't make use of the snippet.
After the above changes I was still left with the app detecting no updates on startup. Debugging showed that my repository was not showing up in the session. I had to explicitly add the update url in the code, despite having it in the p2.inf and in set in the feature manifest editor form field. Here's the code for this:
public static void addUpdateSite(IProvisioningAgent provisioningAgent)
throws InvocationTargetException {
// Load repository manager
IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) provisioningAgent
.getService(IMetadataRepositoryManager.SERVICE_NAME);
if (metadataManager == null) {
logger.error( "Metadata manager was null");
Throwable throwable = new
Throwable("Could not load Metadata Repository Manager");
throwable.fillInStackTrace();
throw new InvocationTargetException(throwable);
}
// Load artifact manager
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) provisioningAgent
.getService(IArtifactRepositoryManager.SERVICE_NAME);
if (artifactManager == null) {
logger.error( "Artifact manager was null");
Throwable throwable = new Throwable(
"Could not load Artifact Repository Manager");
throwable.fillInStackTrace();
throw new InvocationTargetException(throwable);
}
// Load repo
try {
URI repoLocation = new URI("http://localhost/respository");
logger.info( "Adding repository " + repoLocation );
metadataManager.loadRepository(repoLocation, null);
artifactManager.loadRepository(repoLocation, null);
} catch (ProvisionException pe) {
logger.error( "Caught provisioning exception " + pe.getMessage(), pe);
throw new InvocationTargetException(pe);
} catch (URISyntaxException e) {
logger.error( "Caught URI syntax exception " + e.getMessage(), e);
throw new InvocationTargetException(e);
}
}
I now call this first thing in the checkForUpdates method from the original question. After this change my app at least now sees the update and attempts to install it. I'm still having problem but that deserves a separate question of its own which I've created at https://stackoverflow.com/questions/3944953/error-during-p2-eclipse-rcp-app-headless-update
Web server is not mandatory, you can get updates with file location.
It is mandatory to change product version too.
You can't update those features with Update Site Project build which are exported with product, however you can do that with some hacking in exported product.
If you add some other features with (Install New Softwares) option then you can update these features with Update Site Project build.
Hopefully this will be helpful. If you need more clarification you can ask.

How to display a generic error page in Asp.Net MVC 2

I have the following in my base controller:
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
Exception exception = filterContext.Exception;
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, exception).GetHttpCode() != 500)
{
return;
}
// TODO: What is the namespace for ExceptionType?
//if (!ExceptionType.IsInstanceOfType(exception))
//{
// return;
//}
// Send Email
MailException(exception);
// TODO: What does this line do?
base.OnException(filterContext);
filterContext.Result = new ViewResult
{
ViewName = "Error"
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
}
In my Shared folder, I have an Error.aspx View.
Web.config
<customErrors mode="On" />
I am still seeing the yellow screen when an exception occurs. What am I doing incorrectly?
I would imagine that invoking base.OnException handler is what is causing your problem. Without actually looking at the code, I would imagine that it is what is responsible for handling the error and generating a response with the exception and stack trace. Remove that line from your code -- it's not needed as since you're replacing the ViewResult anyway.
I would recommend that you use ELMAH and implement a HandleError attribute that works with it: see this question. ELMAH is very flexible and configuration driven, rather than code driven.
Server.ClearError()
What happens if you call that?