How to commit programmatically via a managed bean? - oracle-adf

I have a managed bean that changes an attribute value and calls a popup.
I need also to commit the changes made (without having to click a commit button), I tried some code but it does nothing.
Help me, please.
DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding operationBinding = bindings.getOperationBinding("Commit");
operationBinding.execute();

You can use the following functions to commit the change made to an Iterator programmatically (In an action listener for example) :
public static ViewObjectImpl getViewObjectFromIterator(String nomIterator) {
ViewObjectImpl returnVO = null;
DCBindingContainer dcb = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
if (dcb != null) {
DCIteratorBinding iter = dcb.findIteratorBinding(nomIterator);
if (iter != null) {
returnVO = (ViewObjectImpl)iter.getViewObject();
}
}
return returnVO;
}
private void commit(String IteratorName) {
ViewObject vo = this.getViewObjectFromIterator(IteratorName);
try {
vo.getApplicationModule().getTransaction().validate();
vo.getApplicationModule().getTransaction().commit();
} catch (ValidationException e) {
String validationErrorMessage = e.getDetailMessage();
//Occur when some committed data is rejected due to validation error.
//log it : log(Level.WARNING, " " + validationErrorMessage);
}
catch (Exception e) {
//Log it and warn something unexpected occured
}
}
//In your action listener simply call the commit function as follow
//You can Find YOUR_ITERATOR_NAME the your PageDef Binding file in the Executables Column
commit("YOUR_ITERATOR_NAME");
See more : https://gist.github.com/CedricL46/04570c1f078583321ad680ee8ba28f72

Related

MSAL4j - How to handle MsalThrottlingException?

I use MSAL4j and there is an exception type named MsalThrottlingException. How can I handle it when I catch it? I need an example implementation.
try{
Future<IAuthenticationResult> future =
confidentialClientApplication.acquireToken(authorizationCodeParameters);
IAuthenticationResult authenticationResult = future.get(1, TimeUnit.MINUTES);
}
catch(ExecutionException e){
if(e.getCause() instanceof MsalThrottlingException){
//how to handle it
}
}
https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-error-handling-java
There was a document about it also(you can see the screen shot in above link), but it doesn't give a example handling implementation. Could you give an example?
This worked for me:
private static String PREFIX_RETRY_STR = "com.microsoft.aad.msal4j.MsalThrottlingException: Request was throttled according to instructions from STS. Retry in ";
private static String SUFFIX_RETRY_STR = " ms.";
(...)
if (e.getCause() instanceof MsalThrottlingException) {
int waitTime = Integer.parseInt(e.getMessage().replace(PREFIX_RETRY_STR, "").replace(SUFFIX_RETRY_STR, ""));
try {
TimeUnit.MILLISECONDS.sleep(waitTime);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
result = pca.acquireToken(parameters).join();
} else
throw e;

Verification in Selenium webdriver

I am new to the automation world, I am trying to verfy an item in the list to see if it has been deleted or not.. I have used the following syntax but it says company found, which is not suppose to be the answer.. Please help
internal void verifycompany()
{
Thread.Sleep(1000);
int b = 1;
bool CompanyName = Driver.driver.FindElement(By.XPath(".//*[#id='companies']/tr[" + b + "]/td[1]")).Displayed;
if (CompanyName == false)
{
Console.WriteLine("company not found, test succesful");
Base.test.Log(LogStatus.Info, "company not found, test succesful");
}
else
{
b++;
Base.test.Log(LogStatus.Info, "Company found, test unscuccesful");
}
}
Unfortunately, isDisplayed does not return false if it is not displayed, it throws an exception stating that it couldn't be found (geez thanks).
What I did is create a reusable method where I can pass in an element and it'll throw it through a try catch and return true if found, or false if the exception is thrown.
Something like the below - I use java but it should help you figure out a way around your problem:
public boolean isDisplayed(WebElement webElement) {
try {
return element.isDisplayed();
} catch (NoSuchElementException e) {
return false;
}
}
If you don't want to create a reusable method, just throw your find element line into a try catch.
boolean CompanyName;
try {
CompanyName = findElementAndIsDisplayedCode;
} catch (NoSuchElementException e) {
CompanyName = false;
}

Winforms recursive file scan blocks UI

I have a program that searches the given directory and adds all the files to a list view. My problem is that the ui thread gets stuck while the search is busy. I have tried using tasks but can’t get it to work in async. The list view must be updated after each file has been found.
I have done a lot of reading about the TPL and how to use it but can’t get it to work in this case. I got it to work where the processing of data is in one method that create a task to process it. Can any one tel me what is wrong in the code below and how to fix it?
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
WalkDirectory(new DirectoryInfo(drive));
});
}
public void testTaskUpdateLabel(string labelTeks)
{
Task taskUpdateLabel = new Task(() =>
{
label4.Text = labelTeks;
});
taskUpdateLabel.Start(uiScheduler);
}
public void testTaskUpdateLabel(string labelTeks)
{
Task taskUpdateLabel = new Task(() =>
{
label4.Text = labelTeks;
});
taskUpdateLabel.Start(uiScheduler);
}
public bool WalkDirectory(DirectoryInfo directory)
{
if (directory == null)
{
throw new ArgumentNullException("directory");
}
return this.WalkDirectories(directory);
}
private bool WalkDirectories(DirectoryInfo directory)
{
bool continueScan = true;
continueScan = WalkFilesInDirectory(directory);
if (continueScan)
{
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
try
{
if ((subDirectory.Attributes & FileAttributes.ReparsePoint) != 0)
{
continue;
}
if (!(continueScan = WalkDirectory(subDirectory)))
{
break;
}
}
catch (UnauthorizedAccessException)
{
continue;
}
}
}
if (continueScan)
{
testTaskUpdateLabel(directory.FullName);
}
return continueScan;
}
private bool WalkFilesInDirectory(DirectoryInfo directory)
{
bool continueScan = true;
// Break up the search pattern in separate patterns
string[] searchPatterns = _searchPattern.Split(';');
// Try to find files for each search pattern
foreach (string searchPattern in searchPatterns)
{
if (!continueScan)
{
break;
}
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles(searchPattern))
{
try
{
testTaskUpdate(file.FullName);
}
catch (UnauthorizedAccessException)
{
continue;
}
}
}
return continueScan;
}
If you use a BackgroundWorker class, the UI will work and progress can be updated in the ProgressChanged event handler.
MSDN Reference
Can any one tel me what is wrong in the code below and how to fix it?
The problem is here
public void testTaskUpdateLabel(string labelTeks)
{
Task taskUpdateLabel = new Task(() =>
{
label4.Text = labelTeks;
});
taskUpdateLabel.Start(uiScheduler);
}
You should not use TPL to update the UI. TPL tasks are for doing non UI work and UI should only be updated on the UI thread. You already moved the work on a thread pool thread (via Task.Run), so the only problem you need to solve is how to update the UI from inside the worker. There are many ways to do that - using Control.Invoke/BeginInvoke, SynchronizationContext etc, but the preferred approach for TPL is to pass and use IProgress<T> interface. Don't be fooled by the name - the interface is an abstraction of a callback with some data. There is a standard BCL provided implementation - Progress<T> class with the following behavior, according to the documentation
Any handler provided to the constructor or event handlers registered with the ProgressChanged event are invoked through a SynchronizationContext instance captured when the instance is constructed.
i.e. perfectly fits in UI update scenarios.
With all that being said, here is how you can apply that to your code. We'll use IProgress<string> and will call Report method and pass the full name for each file/directory we find - a direct replacement of your testTaskUpdateLabel calls.
private void button1_Click(object sender, EventArgs e)
{
var progress = new Progress<string>(text => label4.Text = text);
Task.Run(() =>
{
WalkDirectory(new DirectoryInfo(drive), progress);
});
}
public bool WalkDirectory(DirectoryInfo directory, IProgress<string> progress)
{
if (directory == null) throw new ArgumentNullException("directory");
if (progress == null) throw new ArgumentNullException("progress");
return WalkDirectories(directory, progress);
}
bool WalkDirectories(DirectoryInfo directory, IProgress<string> progress)
{
// ...
if (!(continueScan = WalkDirectories(subDirectory, progress)))
// ...
if (continueScan)
progress.Report(directory.FullName);
// ...
}
bool WalkFilesInDirectory(DirectoryInfo directory, IProgress<string> progress)
{
// ...
try
{
progress.Report(file.FullName);
}
// ...
}
I got it to work by making the walkDirectory, walkDirectories and WalkFiles methods async. Thus using the await keyword before I call the testUpdate and testUpdateLabel methods. This way the listview is updated with the search results while the search is running without blocking the UI thread. I.E. the user can cancel the search when the file he was searching for has been found.

How to handle error using TemData[ ] in asp.net mvc?

I want to handle following errors using TempData:
1) My custom Error defined by me if certain condition is not fulfilled.
2) To display the exact SQL-server error.
Note: I am Using Redirect after the code.
May be you need like this: In the controller
public ActionResult SaveProduct(Product model)
{
var ErrorString = null;
// your custom validations for example,
if(model.Name == null) ErrorString = "Name is empty";
try
{
// your db save operations
}
catch (Exception exception)
{
ErrorString = exception.Message;
}
if(ErrorString != null) TempData["Error"] = ErrorString;
return Redirect("YourAction");
}
And in View:
#{
var error = (string)TempData["Error"];
}
#if (!string.IsNullOrEmpty(error))
{
<p>#Html.Raw(error)</p>
}

CXF WS, Interceptor: stop processing, respond with fault

I'm scratching my head over this:
Using an Interceptor to check a few SOAP headers, how can I abort the interceptor chain but still respond with an error to the user?
Throwing a Fault works regarding the output, but the request is still being processed and I'd rather not have all services check for some flag in the message context.
Aborting with "message.getInterceptorChain().abort();" really aborts all processing, but then there's also nothing returned to the client.
What's the right way to go?
public class HeadersInterceptor extends AbstractSoapInterceptor {
public HeadersInterceptor() {
super(Phase.PRE_LOGICAL);
}
#Override
public void handleMessage(SoapMessage message) throws Fault {
Exchange exchange = message.getExchange();
BindingOperationInfo bop = exchange.getBindingOperationInfo();
Method action = ((MethodDispatcher) exchange.get(Service.class)
.get(MethodDispatcher.class.getName())).getMethod(bop);
if (action.isAnnotationPresent(NeedsHeaders.class)
&& !headersPresent(message)) {
Fault fault = new Fault(new Exception("No headers Exception"));
fault.setFaultCode(new QName("Client"));
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element detail = doc.createElementNS(Soap12.SOAP_NAMESPACE, "mynamespace");
detail.setTextContent("Missing some headers...blah");
fault.setDetail(detail);
} catch (ParserConfigurationException e) {
}
// bad: message.getInterceptorChain().abort();
throw fault;
}
}
}
Following the suggestion by Donal Fellows I'm adding an answer to my question.
CXF heavily relies on Spring's AOP which can cause problems of all sorts, at least here it did. I'm providing the complete code for you. Using open source projects I think it's just fair to provide my own few lines of code for anyone who might decide not to use WS-Security (I'm expecting my services to run on SSL only). I wrote most of it by browsing the CXF sources.
Please, comment if you think there's a better approach.
/**
* Checks the requested action for AuthenticationRequired annotation and tries
* to login using SOAP headers username/password.
*
* #author Alexander Hofbauer
*/
public class AuthInterceptor extends AbstractSoapInterceptor {
public static final String KEY_USER = "UserAuth";
#Resource
UserService userService;
public AuthInterceptor() {
// process after unmarshalling, so that method and header info are there
super(Phase.PRE_LOGICAL);
}
#Override
public void handleMessage(SoapMessage message) throws Fault {
Logger.getLogger(AuthInterceptor.class).trace("Intercepting service call");
Exchange exchange = message.getExchange();
BindingOperationInfo bop = exchange.getBindingOperationInfo();
Method action = ((MethodDispatcher) exchange.get(Service.class)
.get(MethodDispatcher.class.getName())).getMethod(bop);
if (action.isAnnotationPresent(AuthenticationRequired.class)
&& !authenticate(message)) {
Fault fault = new Fault(new Exception("Authentication failed"));
fault.setFaultCode(new QName("Client"));
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element detail = doc.createElementNS(Soap12.SOAP_NAMESPACE, "test");
detail.setTextContent("Failed to authenticate.\n" +
"Please make sure to send correct SOAP headers username and password");
fault.setDetail(detail);
} catch (ParserConfigurationException e) {
}
throw fault;
}
}
private boolean authenticate(SoapMessage msg) {
Element usernameNode = null;
Element passwordNode = null;
for (Header header : msg.getHeaders()) {
if (header.getName().getLocalPart().equals("username")) {
usernameNode = (Element) header.getObject();
} else if (header.getName().getLocalPart().equals("password")) {
passwordNode = (Element) header.getObject();
}
}
if (usernameNode == null || passwordNode == null) {
return false;
}
String username = usernameNode.getChildNodes().item(0).getNodeValue();
String password = passwordNode.getChildNodes().item(0).getNodeValue();
User user = null;
try {
user = userService.loginUser(username, password);
} catch (BusinessException e) {
return false;
}
if (user == null) {
return false;
}
msg.put(KEY_USER, user);
return true;
}
}
As mentioned above, here's the ExceptionHandler/-Logger. At first I wasn't able to use it in combination with JAX-RS (also via CXF, JAX-WS works fine now). I don't need JAX-RS anyway, so that problem is gone now.
#Aspect
public class ExceptionHandler {
#Resource
private Map<String, Boolean> registeredExceptions;
/**
* Everything in my project.
*/
#Pointcut("within(org.myproject..*)")
void inScope() {
}
/**
* Every single method.
*/
#Pointcut("execution(* *(..))")
void anyOperation() {
}
/**
* Log every Throwable.
*
* #param t
*/
#AfterThrowing(pointcut = "inScope() && anyOperation()", throwing = "t")
public void afterThrowing(Throwable t) {
StackTraceElement[] trace = t.getStackTrace();
Logger logger = Logger.getLogger(ExceptionHandler.class);
String info;
if (trace.length > 0) {
info = trace[0].getClassName() + ":" + trace[0].getLineNumber()
+ " threw " + t.getClass().getName();
} else {
info = "Caught throwable with empty stack trace";
}
logger.warn(info + "\n" + t.getMessage());
logger.debug("Stacktrace", t);
}
/**
* Handles all exceptions according to config file.
* Unknown exceptions are always thrown, registered exceptions only if they
* are set to true in config file.
*
* #param pjp
* #throws Throwable
*/
#Around("inScope() && anyOperation()")
public Object handleThrowing(ProceedingJoinPoint pjp) throws Throwable {
try {
Object ret = pjp.proceed();
return ret;
} catch (Throwable t) {
// We don't care about unchecked Exceptions
if (!(t instanceof Exception)) {
return null;
}
Boolean throwIt = registeredExceptions.get(t.getClass().getName());
if (throwIt == null || throwIt) {
throw t;
}
}
return null;
}
}
Short answer, the right way to abort in a client-side interceptor before the sending the request is to create the Fault with a wrapped exception :
throw new Fault(
new ClientException( // or any non-Fault exception, else blocks in
// abstractClient.checkClientException() (waits for missing response code)
"Error before sending the request"), Fault.FAULT_CODE_CLIENT);
Thanks to post contributors for helping figuring it out.
CXF allows you to specify that your interceptor goes before or after certain interceptors. If your interceptor is processing on the inbound side (which based on your description is the case) there is an interceptor called CheckFaultInterceptor. You can configure your interceptor to go before it:
public HeadersInterceptor(){
super(Phase.PRE_LOGICAL);
getBefore().add(CheckFaultInterceptor.class.getName());
}
The check fault interceptor in theory checks if a fault has occurred. If one has, it aborts the interceptor chain and invokes the fault handler chain.
I have not yet been able to test this (it is fully based on the available documentation I've come across trying to solve a related problem)

Resources