I have a simple block of code, that return false
PromoDebit promoDebit = new PromoDebit();
promoDebit.promoCode=promoCode;
promoDebit.userId=userId;
promoDebit.countUsages=countUsages;
promoDebit.endDate=endDate;
promoDebit.startDate=startDate;
promoDebit.status=1;
promoDebit.calcValue=Float.parseFloat(p.getProperty("promoPercent"));
if(promoDebit.save(flush: true)){
log.info "GOOD!"
} else {
log.info "BAD!"
}
How can I get more info about GORM.save fail? Stdrout log show nothning even if I turn on logSql in DataSource.groovy
First ,make sure that your Log4j is configured correctly.
Here http://grails.org/doc/2.3.1/guide/conf.html#logging
And ,If you wan to know more detail info on GORM.save fail like
PromoDebit promoDebit = new PromoDebit();
promoDebit.promoCode=promoCode;
promoDebit.userId=userId;
promoDebit.countUsages=countUsages;
promoDebit.endDate=endDate;
promoDebit.startDate=startDate;
promoDebit.status=1;
promoDebit.calcValue=Float.parseFloat(p.getProperty("promoPercent"));
Then ,
if (!promoDebit.save()) {
log.warn myDomainObj.errors.allErrors.join(' \n')
//each error is an instance of org.springframework.validation.FieldError
}
And , I like this one
if (!promoDebit.save()) {
promoDebit.errors.each {
println it
}
}
If you want to throw an exception for EVERY domain classes, then simply set grails.gorm.failOnError to true in grails-app/conf/Config.groovy
or Simply
promoDebit.save(failOnError:true)
Cheers!
log.warn "error occurred by saving: $promoDebit.errors"
you will see the validation failures in the log. If some SQL-constraint gets broken you will get a full-blown Exception like DataIntegrityException
Related
I am creating a custom renameParticpant to rename an Eclipse project's launch configuration files, and to change the APPNAME variable in the Makefile. The Makefile side works 100% of the time, but attempting to rename the launch configs causes the following error to occur:
<FATALERROR
FATALERROR: No input element provided
Context: <Unspecified context>
code: none
Data: null
>
This error occurs when the changes are being validated at the following line in org.eclipse.ltk.core.refactoring.PerformChangeOperation [line: 248].
fValidationStatus= fChange.isValid(new SubProgressMonitor(monitor, 1));
Below is a screenshot of the variable view. I suspect that my compositeChange is not in the correct format or is missing some information, however; the error dialogue and logs don't give any helpful information.
Debugger variable view of fChanges
The following is relevant code snippets:
// This one sparks joy (it works great, 100% success)
final HashMap<IFile, TextFileChange> textChanges = new HashMap<IFile, TextFileChange>();
// Stuff gets put inside
textChanges.put(makefile, changeAppname);
// This one does not spark joy (it runs, but results in an invalid Change)
final HashMap<IFile, RenameResourceChange> renameChanges = new HashMap<IFile, RenameResourceChange>();
// Stuff gets put inside
RenameResourceChange renameChange = new RenameResourceChange(
launch.getFile().getProjectRelativePath(), newLaunchName);
renameChanges.put(launch.getFile(), renameChange);
// This is where they get added to the hashmap.
CompositeChange result;
if (textChanges.isEmpty() && renameChanges.isEmpty()) {
result = null;
} else {
result = new CompositeChange(
String.format("Rename project references and dependencies for %1$s", proj.getName()));
for (Iterator<TextFileChange> iter = textChanges.values().iterator(); iter.hasNext();) {
result.add(iter.next());
}
for (Iterator<RenameResourceChange> iter = renameChanges.values().iterator(); iter.hasNext();) {
result.add(iter.next());
}
}
return result;
I looked into adding or generating a changeDescriptor, however that seems like the wrong approach.
In my code I used to stop the Wildfly (16.0.0.Final) programmatically like this:
[...]
Thread shutdownThread = new Thread(){
#Override
public void run() {
try {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
try {
logger.info("Stopping server...");
ObjectName objectName = new ObjectName("jboss.as:management-root=server");
mBeanServer.invoke(objectName, "shutdown", new Object[] { false, 60 }, new String[] { boolean.class.getName(), int.class.getName() });
} catch ( InstanceNotFoundException | ReflectionException | MBeanException | MalformedObjectNameException e ) {
logger.error("Failed to stop server, error msg is: " + e);
}
} catch ( Exception e ) {
logger.error(e.getMessage(), e);
}
}
};
[...]
Curiously this stopped working. I get the following error message:
WFLYJMX0012: params and description have different lengths: java.lang.IllegalArgumentException:
Any idea on that?
Thanks a lot,
Kai
In wildfly 16, they added a third parameter for graceful shutdown.
mBeanServer.invoke(objectName, "shutdown", new Object[] { false, 60, 60 }, new String[] { boolean.class.getName(), int.class.getName(), int.class.getName() });
While the third parameter is listed as optional, we had the same error until we added it.
https://wildscribe.github.io/WildFly/17.0/index.html for more information.
The error indicates that the actual arguments provided for the JMX operation does not match the signature of the operation itself.
In general, it can be motivated because you switched from a standalone to a domain configuration.
At least, you will find a similar problem if you use the CLI: in this case, you need to indicate the host name to shutdown as the first argument of the invocation, the rest of the arguments, whether restart again and the different timeouts, remains the same.
But in this concrete case, perhaps, it is not clear for me reading your question, you switched to Wildly version 16.0.0.Final from a previous one.
As you can see in the WildFly 16.0 Model Reference or if you inspect, with JConsole or some other similar tool, the mbeans exposed by the JMX tree, the shutdown operation signature is the following:
As we also mention, although the three arguments are not required, the mbean signature defines them, and all the arguments should be provided.
I am currently attempting to read/write to memory through the use of JNA for Java. For the past week I have tried a multitude of solutions, mostly from [similar projects][1] I have found online, but nothing has resolved my problem.
I know I am receiving the correct process ID of the program, then I create a Pointer using the openProcess method. Then I call getBaseAddress using the newly created Pointer. The problem I believe lies within the EnumProcessModules/Psapi method/class.
Truthfully I am slightly in over my head but this is one of the last issues I am having with this program. My overall goal is to find the base address of the program, use various offsets to access the information I am trying to modify, and then modify it appropriately. The program is 32-bit, which I have seen other people say you need to use a EnumProcessModulesEx method for? but truthfully I am unsure of how/where to implement that.
Any help would be appreciated!
You're getting an Access Denied error because Windows requires you to enable Debug privilege on your current process before accessing the memory of another process. So you will need to both run your program as Administrator, and before you call your OpenProcess code, enable debug privilege.
Here's the JNA code in my application that does this. It's a static method as I only call it once for the entire application:
/**
* Enables debug privileges for this process, required for OpenProcess() to get
* processes other than the current user
*
* #return {#code true} if debug privileges were successfully enabled.
*/
private static boolean enableDebugPrivilege() {
HANDLEByReference hToken = new HANDLEByReference();
boolean success = Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
WinNT.TOKEN_QUERY | WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
if (!success) {
LOG.error("OpenProcessToken failed. Error: {}", Native.getLastError());
return false;
}
try {
WinNT.LUID luid = new WinNT.LUID();
success = Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid);
if (!success) {
LOG.error("LookupPrivilegeValue failed. Error: {}", Native.getLastError());
return false;
}
WinNT.TOKEN_PRIVILEGES tkp = new WinNT.TOKEN_PRIVILEGES(1);
tkp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
success = Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tkp, 0, null, null);
int err = Native.getLastError();
if (!success) {
LOG.error("AdjustTokenPrivileges failed. Error: {}", err);
return false;
} else if (err == WinError.ERROR_NOT_ALL_ASSIGNED) {
LOG.debug("Debug privileges not enabled.");
return false;
}
} finally {
Kernel32.INSTANCE.CloseHandle(hToken.getValue());
}
return true;
}
I'm not sure from looking at your code whether you also have the right permissions for OpenProcess. Be sure you have the VM_READ permission. Here's what I use, your mileage may vary (I assume you'll need writing permissions as well).
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(
WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ,
false, processID);
Currently I have code that is used to change a password that is stored on an LDAP server. I am using a boolean variable to store the result if the update was successful or not, thereafter I check if the update failed via an if statement and I display an error message.
The issue I'm facing is how can I display more specific errors in the UI if the password change fails?
For example:
The existing password is invalid
The username is incorrect
The account has been locked
If someone could please advise on what could be a nice and tidy solution to my problem. Below is a snippet of the reset password method:
boolean passwordReset = this.userManagement.update(this.username, this.resetPassword, this.resetOldPassword);
if(!passwordReset){
super.addMessage(FacesMessage.SEVERITY_ERROR,super.getResource("password.error"), super.getResource("user.password.change.error"));
} else {
super.addMessage(FacesMessage.SEVERITY_INFO,super.getResource("change.password.head"), super.getResource("password.changed.success"));
}
I think you should modify the userManagement.update method to raise an exception in case of error. So depending on the error it could throw InvalidPasswordException, UsernameException, BlockedAccoutException, etc. or just throw an only exception with a custom message.
In any case, first you need to collect this information from the ldap operation.
Example code:
try {
this.userManagement.update(this.username, this.resetPassword, this.resetOldPassword);
} catch(InvalidPasswordException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource("password.error"), super.getResource("user.password.change.error"));
} catch(UsernameException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource("username.error"), super.getResource("user.name.error"));
} catch(BlockedAccoutException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource("blockaccount.error"), super.getResource(blockaccount.error"));
}
Or:
try {
this.userManagement.update(this.username, this.resetPassword, this.resetOldPassword);
} catch(UpdateUserException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource(e.getErrorCode()));
}
The problem with the first approach is that you have to create several (or a lot) of classes.
This doesn't happen with the second option, but you need a way to get the proper error message. You may add an error type/code to the exception.
Busy trying to Call RPG function from Java and got this example from JamesA. But now I am having trouble, here is my code:
AS400 system = new AS400("MachineName");
ProgramCall program = new ProgramCall(system);
try
{
// Initialise the name of the program to run.
String programName = "/QSYS.LIB/LIBNAME.LIB/FUNNAME.PGM";
// Set up the 3 parameters.
ProgramParameter[] parameterList = new ProgramParameter[2];
// First parameter is to input a name.
AS400Text OperationsItemId = new AS400Text(20);
parameterList[0] = new ProgramParameter(OperationsItemId.toBytes("TestID"));
AS400Text CaseMarkingValue = new AS400Text(20);
parameterList[1] = new ProgramParameter(CaseMarkingValue.toBytes("TestData"));
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run the program.
if (program.run() != true)
{
// Report failure.
System.out.println("Program failed!");
// Show the messages.
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
// Show each message.
System.out.println(messagelist[i]);
}
}
// Else no error, get output data.
else
{
AS400Text text = new AS400Text(50);
System.out.println(text.toObject(parameterList[1].getOutputData()));
System.out.println(text.toObject(parameterList[2].getOutputData()));
}
}
catch (Exception e)
{
//System.out.println("Program " + program.getProgram() + " issued an exception!");
e.printStackTrace();
}
// Done with the system.
system.disconnectAllServices();
The application Hangs at this lineif (program.run() != true), and I wait for about 10 minutes and then I terminate the application.
Any idea what I am doing wrong?
Edit
Here is the message on the job log:
Client request - run program QSYS/QWCRTVCA.
Client request - run program LIBNAME/FUNNAME.
File P6CASEL2 in library *LIBL not found or inline data file missing.
Error message CPF4101 appeared during OPEN.
Cannot resolve to object YOBPSSR. Type and Subtype X'0201' Authority
FUNNAME insert a row into table P6CASEPF through a view called P6CASEL2. P6CASEL2 is in a different library lets say LIBNAME2. Is there away to maybe set the JobDescription?
Are you sure FUNNAME.PGM is terminating and not hung with a MSGW? Check QSYSOPR for any messages.
Class ProgramCall:
NOTE: When the program runs within the host server job, the library list will be the initial library list specified in the job description in the user profile.
So I saw that my problem is that my library list is not setup, and for some reason, the user we are using, does not have a Job Description. So to over come this I added the following code before calling the program.run()
CommandCall command = new CommandCall(system);
command.run("ADDLIBLE LIB(LIBNAME)");
command.run("ADDLIBLE LIB(LIBNAME2)");
This simply add this LIBNAME, and LIBNAME2 to the user's library list.
Oh yes, the problem is Library list not set ... take a look at this discussion on Midrange.com, there are different work-around ...
http://archive.midrange.com/java400-l/200909/msg00032.html
...
Depe