I've got a custom exception called "LoginException". It might be thrown from any class. So I want to make an advice to do something(for example, print "Ooops") after throwing. So I decided to use AOP. Something like this:
#Aspect
public class LogoutAdvice {
#AfterThrowing(throwing = "e")
public void myAfterThrowing(JoinPoint joinPoint, LoginException e) {
System.out.println("IDS HABBENING");
}
}
Code:
#Transactional
public DynamicTable getTable(int status_id, HttpServletRequest request)
throws HibernateException, LoginException, SQLException {
try {
ResultSet rs = requestDAO.getRequestResultSet(
cookieDAO.get(SESS_ATTR, request), status_id);
DynamicTable dt = new DynamicTable();
String[] columnArray;
LinkedList<String[]> dataList = new LinkedList<String[]>();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
columnArray = new String[columnCount - META_COLUMNS_COUNT];
for (int i = 0; i < columnArray.length; i++) {
columnArray[i] = rsmd.getColumnName(META_COLUMNS_COUNT + i + 1);
}
dt.setTitleArray(columnArray);
while (rs.next()) {
String[] dataArray = new String[columnArray.length];
for (int i = 0; i < columnArray.length; i++) {
dataArray[i] = ParamUtil.toString(rs
.getObject(META_COLUMNS_COUNT + i + 1));
}
dataList.add(dataArray);
}
dt.setDataList(dataList);
return dt;
} catch (SQLException e) {
String message = e.getMessage();
String[] errorsArray = AuthErrorsConst.ERROR;
for (int i = 0; i < errorsArray.length; i++) {
if (message.contains(errorsArray[i])) {
throw new LoginException(); // LOOK AT THIS
}
}
throw e;
}
}
How can I do that?
Be sure the exception is being thrown
catch (SQLException e) {
String message = e.getMessage();
String[] errorsArray = AuthErrorsConst.ERROR;
for (int i = 0; i < errorsArray.length; i++) {
if (message.contains(errorsArray[i])) {
System.out.println("throwing LoginException")// NEW
throw new LoginException(); // LOOK AT THIS
}
}
throw e;
}
About
#Aspect
public class LogoutAdvice {
#AfterThrowing(throwing = "e")
public void myAfterThrowing(JoinPoint joinPoint, LoginException e) {
System.out.println("IDS HABBENING");
}
}
Be sure Spring has enable to work with #Aspect and furthermore it be able to scan your LogoutAdvice aspect, normally I declare them how
#Aspect
#Component// to be scanned by Spring
public class LogoutAdvice {
Change your #AfterThrowing to
#AfterThrowing(pointcut = "execution(* *.*(..))",throwing = "e")
Use a point cut in your #AfterThrowing annotation
Therefore your annotation will need to look something like below
#AfterThrowing(pointcut = "execution(public * *(..))",throwing = "e")
Please refer to below link for elaborate explanation:
http://www.compiletimeerror.com/2013/05/spring-aop-after-throwing-advice.html#.VCAnsvmSw2c
1) Check you LoginException class as it should be a proper exception class.
2) throw the exception object "e" in catch block
3)
#Aspect
#Component
public class LogoutAdvice {
#AfterThrowing(pointcut = "execution (* * com..*(..)", throwing = "e")
public void myAfterThrowing(JoinPoint joinPoint, LoginException e) {
System.out.println("IDS HABBENING");
}
}
4) in spring configuration file
<aop:aspectj-autoproxy/>
thats enough.
Related
I have the following class imp with inner class ScoringSummaryImplementation, when I tested the mean() method alone it works correctly, but when I test it as I show in the main method the answer goes incorrectly, I need to know the reason:
public class imp implements Normalizer {
public static List<BigDecimal> dataToBeNormalized = new ArrayList<>();
#Override
public ScoringSummary zscore(Path csvPath, Path destPath, String colToStandardize) {
ScoringSummary scoringObejct = new ScoringSummaryImplementation();
if (!Files.exists(csvPath)) {
throw new IllegalArgumentException("source file not found");
}
try {
readDataToBeNormalized(csvPath, destPath, colToStandardize);
} catch (IOException ex) {
Logger.getLogger(imp.class.getName()).log(Level.SEVERE, null, ex);
} catch (CsvValidationException ex) {
Logger.getLogger(imp.class.getName()).log(Level.SEVERE, null, ex);
}
//Z-score
for (int i = 0; i < dataToBeNormalized.size(); i++) {
BigDecimal sub = (dataToBeNormalized.get(i).subtract(scoringObejct.mean()));
try {
BigDecimal divide = sub.divide(scoringObejct.standardDeviation(), 2, RoundingMode.HALF_EVEN);
dataToBeNormalized.set(i, divide);
} catch (ArithmeticException e) {
}
}
return scoringObejct;
}
private void readDataToBeNormalized(Path csvPath, Path destPath, String colToStandardize) throws FileNotFoundException, IOException, CsvValidationException {
int indexOfTheCol = -1;
CSVReader reader = new CSVReader(new FileReader(csvPath.toString()));
String[] header = reader.readNext();
for (int i = 0; i < header.length; i++) {
if (header[i].equalsIgnoreCase(colToStandardize)) {
indexOfTheCol = i;
}
}
if (indexOfTheCol == -1) {
throw new IllegalArgumentException("column " + colToStandardize + " not found");
}
String[] values;
while ((values = reader.readNext()) != null) {
dataToBeNormalized.add(new BigDecimal(values[indexOfTheCol]));
}
}
//Inner class to implement ScoringSummary
public static class ScoringSummaryImplementation implements ScoringSummary {
#Override
public BigDecimal mean() {
BigDecimal sum = new BigDecimal("0");
BigDecimal sizeOfTheList = new BigDecimal(dataToBeNormalized.size());
for (int i = 0; i < dataToBeNormalized.size(); i++) {
sum = sum.add(dataToBeNormalized.get(i));
}
sum.divide(sizeOfTheList, 2, RoundingMode.HALF_EVEN);
return sum.divide(sizeOfTheList, 2, RoundingMode.HALF_EVEN);
}
}
}
// test in the main:
public class Test {
public static void main(String [] args){
Path p = Paths.get("C:\\Users\\DELL\\Documents\\GitHub\\J2EE\\demo\\src\\main\\java\\com\\mycompany\\demo\\d.csv");
Path p2 = Paths.get("C:\\Users\\DELL\\Documents\\GitHub\\J2EE\\demo\\src\\main\\java\\com\\mycompany\\demo\\des.csv");
Normalizer n1 = new imp ();
ScoringSummary n2 = n1.zscore(p, p2, "age");
BigDecimal mean = n2.mean();
System.out.println(mean);
}
}
Here is output:
0.82
Here is age column:
|age |
|5434|
|42423|
|54534|
|3333|
I'm using spring 5 and mockito, but in a test process i have a problem where my bean is done null and i get a NullPointerException, how can i fix it?
infact, my SpringContext.getBean returns null but it work correctly when the application is in runtime mode.
java.lang.NullPointerException
at com.novinkish.batch.ParallerMakerTest.testSendData(ParallerMakerTest.java:53)
.
.
Caused by: java.lang.NullPointerException
at com.novinkish.batch.util.SpringContext.getBean(SpringContext.java:14)
my test class is like this:
#RunWith(MockitoJUnitRunner.class)
public class ParallerMakerTest {
#Mock
private CommonRestCallerImpl restCallerImpl;
#Test
public void testSendData(){
PersonDTO personDTO_1 = new PersonDTO("1111111111", "name_1", "L_name_1", "2000/05/09", (short) 0);
PersonDTO personDTO_2 = new PersonDTO(4646L, "1111111111", "name_1", "L_name_1", "2000/05/09", (short) 1);
List<PersonDTO> resultDtoList = new ArrayList<PersonDTO>();
try {
when(restCallerImpl.callService(ServiceNameJNDI.SAVE_PERSON, personDTO_1, PersonDTO.class)).thenReturn(personDTO_2);
} catch (Exception e) {
e.printStackTrace();
}
ForkJoinPool pool = new ForkJoinPool();
PersonSessionParallerMaker maker = new PersonSessionParallerMaker(restCallerImpl, Arrays.asList(personDTO_1));
pool.execute(maker);
try {
pool.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
resultDtoList = (List<PersonDTO>) pool.invoke(maker);
Assert.assertNotNull(resultDtoList);
Assert.assertEquals(1, ((PersonDTO)resultDtoList.get(0)).getStatus().intValue());
}
and my class is:
public class PersonSessionParallerMaker extends RecursiveTask {
private CommonRestCaller restCaller;
private List<PersonDTO> initList = new ArrayList<PersonDTO>();
private List<PersonDTO> resultList = new ArrayList<PersonDTO>();
private PersonDTO target;
public PersonSessionParallerMaker(CommonRestCaller restCaller, List<PersonDTO> initList) {
this.initList = initList;
this.restCaller = restCaller;
}
public PersonSessionParallerMaker(PersonDTO target) {
this.target = target;
}
#Override
protected Object compute() {
/*MASTER Thread*/
if (target == null) {
for (PersonDTO personDTO : initList) {
/*CREATE FORK (SUB THREAD)*/
PersonSessionParallerMaker parallerMaker = new PersonSessionParallerMaker(personDTO);
invokeAll(parallerMaker);
resultList.add((PersonDTO) parallerMaker.join());
}
return resultList;
} else if (target.getStatus() == 0) {
callService();
return target;
} else
return null;
}
public void callService() {
System.out.println("1.restCaller = " + restCaller);
/*For Unit Test*/
if (restCaller == null) {
System.out.println("2.restCaller = " + restCaller);
restCaller = (CommonRestCaller) SpringContext.getBean(CommonRestCallerImpl.class);
System.out.println("3.restCaller = " + restCaller);
}
try {
System.out.println("target.toString() = " + target.toString());
target = (PersonDTO) restCaller.callService(ServiceNameJNDI.SAVE_PERSON, target, PersonDTO.class);
} catch (Exception e) {
e.printStackTrace();
target.setStatus((short) 2);
}
}
}
You are mixing up unit testing and integration testing here.
What you have written, is a unit test. Unit tests run - per definiton - isolated from the whole application, therefore you have no access to the application context. The purpose of a unit test is to test one specific class.
If you want to test the behaviour of your whole application, you have to write an integration test.
See https://www.baeldung.com/spring-boot-testing#integration-testing-with-springboottest for further reading.
My DAO Class:
#SuppressWarnings("unchecked")
public int getRowCount(Map<String, Object> searchParam) throws DAOReadException {
List<Client> clientRow = null;
try {
Criteria criteria = Criteria.forClass(Client.class);
//set criteria search
for (String key : searchParam.keySet()) {
/*if(key.equals("ClientPK.clientId1")){
criteria.add(Restrictions.like("ClientPK.clientId", searchParam.get(key)));
}*/
if(key.equals("clientPK.clientId")){
criteria.add(Restrictions.eq(key, Integer.parseInt(searchParam.get(key).toString())));
}
if(key.equals("clientName")){
criteria.add(Restrictions.like(key, searchParam.get(key)));
}
if(key.equals("status")){
criteria.add(Restrictions.eq(key, Short.parseShort(searchParam.get(key).toString())));
}
//Bug# 12544 start
if(key.equals("orgId"))
{
criteria.add(Restrictions.eq("ClientPK.orgId", searchParam.get(key)));
}
//Bug# 12544 End
}
criteria.addOrder(Order.desc("createdDate"));
clientRow = (List<Client>) findByCriteria(criteria);
}
catch (Exception e) {
throw new DAOReadException(e);
}
int rowCount = 0;
if (clientRow != null) {
rowCount = clientRow.size();
}
return rowCount;
}
}
error is :
java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: ClientPK of: com.vin.eretail.model.client.Client [select this from com.vin.eretail.model.client.Client as this where this.ClientPK.orgId=? order by this.createdDate desc]
seems to change like below:
//Bug# 12544 start
if(key.equals("orgId"))
{
criteria.add(Restrictions.eq("clientPK.orgId", searchParam.get(key)));
}
//Bug# 12544 End
still need to see your Client class
Is there away to customize Error Handling in ADF Faces without ADF BC?
This is my approach.
Class MyErrorHandler extends DCErrorHandlerImpl
public class MyErrorHandler extends DCErrorHandlerImpl {
private static final ADFLogger logger = ADFLogger.createADFLogger(MyErrorHandler.class);
private static ResourceBundle rb =
ResourceBundle.getBundle("error.handling.messages.ErrorMessages_de_DE");
public MyErrorHandler() {
super(true);
}
public MyErrorHandler(boolean setToThrow) {
super(setToThrow);
}
public void reportException(DCBindingContainer bc, java.lang.Exception ex) {
disableAppendCodes(ex);
logger.info("entering reportException() method");
BindingContext ctx = bc.getBindingContext();
if (ex instanceof NullPointerException) {
logger.severe(ex);
JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
super.reportException(bc, e);
} else if (ex instanceof RowValException) {
Object[] exceptions = ((RowValException) ex).getDetails();
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] instanceof RowValException) {
this.reportException(bc, (Exception) exceptions[i]);
} else if (exceptions[i] instanceof AttrValException) {
super.reportException(bc, (Exception) exceptions[i]);
}
}
} else {
this.reportException(bc, ex);
}
} else if (ex instanceof TxnValException) {
Object[] exceptions = ((TxnValException) ex).getDetails();
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] instanceof RowValException) {
this.reportException(bc, (Exception) exceptions[i]);
} else {
super.reportException(bc, (Exception) exceptions[i]);
}
}
} else {
super.reportException(bc, ex);
}
}
else if (ex instanceof oracle.jbo.DMLException) {
JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
super.reportException(bc, e);
} else if (ex instanceof javax.xml.ws.WebServiceException) {
JboException e = new JboException(rb.getString("WEB_SERVICE_EXCEPTION"));
super.reportException(bc, e);
}
else if (ex instanceof JboException) {
super.reportException(bc, ex);
}
}
public static FacesMessage getMessageFromBundle(String key, FacesMessage.Severity severity) {
ResourceBundle bundle =
ResourceBundle.getBundle("sahaj.apps.vleadministration.view.resources.VLEAdministrationUIBundle");
String summary = JSFUtils.getStringSafely(bundle, key, null);
String detail = JSFUtils.getStringSafely(bundle, key + "_detail", summary);
FacesMessage message = new FacesMessage(summary, detail);
message.setSeverity(severity);
return message;
}
private void disableAppendCodes(Exception ex) {
if (ex instanceof JboException) {
JboException jboEx = (JboException) ex;
jboEx.setAppendCodes(false);
Object[] detailExceptions = jboEx.getDetails();
if ((detailExceptions != null) && (detailExceptions.length > 0)) {
for (int z = 0, numEx = detailExceptions.length; z < numEx; z++) {
System.err.println("Detailed Exception : "+ detailExceptions[z].toString());
disableAppendCodes((Exception) detailExceptions[z]);
}
}
}
}
#Override
protected boolean skipException(Exception ex) {
if (ex instanceof JboException) {
return false;
} else if (ex instanceof SQLIntegrityConstraintViolationException) {
return true;
}
return super.skipException(ex);
}
private String handleApplicationError(String errorMessageRaw) {
String errorMessageCode = getErrorCode(errorMessageRaw);
// application error code
String errorMessage = null;
for (String key : errorPrefixes) {
if (errorMessageCode.startsWith(key)) {
try {
errorMessage = rb.getString(errorMessageCode);
} catch (MissingResourceException mre) {
// application error code not found in the bundle,
// use original message
return errorMessageRaw;
}
break;
}
}
// return the formated application error message
return errorMessage;
}
private String getErrorCode(String errorMessageRaw) {
// check for null/empty error message
if (errorMessageRaw == null || errorMessageRaw.isEmpty()) {
return errorMessageRaw;
}
int start = 0;
String currentErrorCodePrefix = null;
int count = 0;
// check for error message
for (String errorCode : errorPrefixes) {
count += 1;
start = errorMessageRaw.indexOf(errorCode);
if (start >= 0) {
currentErrorCodePrefix = errorCode;
start += currentErrorCodePrefix.length();
break;
}
if (count == errorPrefixes.size())
return errorMessageRaw;
}
int endIndex = start + 5;
// get the CURRENT error code
return currentErrorCodePrefix + errorMessageRaw.substring(start, endIndex);
}
#Override
public String getDisplayMessage(BindingContext bindingContext, Exception exception) {
String data=super.getDisplayMessage(bindingContext, exception);
System.err.println("Exception DATA : "+ data);
String msg= handleApplicationError(data);
System.err.println("Exception MSG : "+ msg);
return msg;
}
#Override
public DCErrorMessage getDetailedDisplayMessage(BindingContext bindingContext, RegionBinding regionBinding,
Exception exception) {
return super.getDetailedDisplayMessage(bindingContext, regionBinding, exception);
}
private static Set<String> errorPrefixes = new HashSet<String>();
static {
errorPrefixes.add("JBO-");
errorPrefixes.add("ORA-");
errorPrefixes.add("DCA-");
}
}
In my DataBinding.cpx
<Application xmlns="http://xmlns.oracle.com/adfm/application" version="12.1.2.66.68" id="DataBindings"
SeparateXMLFiles="false" Package="de.nkk.oasis.ui.web" ClientType="Generic"
ErrorHandlerClass="MyErrorHandler">
After that i generate Data Controller from Myclass.
//MyClass
/**
* method throwing a Nullpointer exception
*/
public void throwNPE() {
Object o = null;
String s = o.toString();
//bang occurs in the line above, no need for any more code
//...
}
/**
* Method that throws a single JboException
*/
public void throwJboException(){
throw new JboException("This is a JboException thrown in ADF BC");
}
and bind the two methods to JSF
<af:button actionListener="#{bindings.throwNPE.execute}" text="throwNPE"
disabled="#{!bindings.throwNPE.enabled}" id="b2"/>
<af:button actionListener="#{bindings.throwJboException.execute}" text="throwJboException"
disabled="#{!bindings.throwJboException.enabled}" id="b3"/>
NOW COMES MY PROBLEM:
Whenever i click one the Button i get
DCA-29000 unexcepted Exception
Try remove
disabled="#{!bindings.throwNPE.enabled}"
and
disabled="#{!bindings.throwJboException.enabled}"
Please review the following piece of code:
try {
db.beginTransaction();
db.execSQL(DBConstants.PRAG_FOR_KEYS_ON);
db.execSQL(DBConstants._BLDG_CREATE);
db.execSQL(DBConstants._BLDG_INDEX);
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT+x);
}
db.execSQL(DBConstants.PRAG_FOR_KEYS_OFF);
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
}finally{
db.endTransaction();
}
Each of the insert constants (representing a row of new data) are numbered thus:
public static final String _BLDG_INSERT0 = "<SQL insert statement>"
...all the way up to 28 ("_BLDG_INSERT28").
Is there ANY way i can execute these SQL statements in a for loop? If i can, how do i concactenate the number on to the name of the constant AND have it recognized by the java interpreter in the correct way?
Thanks!
It's not clear from the question whether you are able to change the constants. If you can, it would be better if you could put the statements in an array.
String[] _BLDG_INSERT = {"<SQL insert statement>", // 0
"<SQL insert statement>", // 1
...
"<SQL insert statement>" // 28
};
And then you can just access them like this.
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT[x]);
}
Or better still:
for(String s : DBConstants._BLDG_INSERT) {
db.execSQL(s);
}
public ArrayList<String> getAllRecord()
{
ArrayList<String> total = new ArrayList<String>();
Cursor cursor1 = null;
try
{
cursor1 = getDBobject().rawQuery(
"select * from "
+ Your table name + ";", null);
if (cursor1.moveToFirst())
{
do
{
String cid = cursor1.getString(1);
total.add(cid);
}
while (cursor1.moveToNext());
}
}
catch (Exception e)
{
System.out.println("" + TAG + " :" + e);
}
finally
{
if (cursor1 != null && !cursor1.isClosed())
{
cursor1.close();
}
}
return total;
}
This will return you all the datas according to your insertion order
Try something like this:
public class testeReflection {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException{
MyClass myClass = new MyClass();
Class aClass = MyClass.class;
for(int i = 0; i < 5; i++){
try {
Field field = aClass.getField("VAR" + i);
String s = (String)field.get(myClass);
System.out.println("myClass[" + i + "] = " + s);
} catch (NoSuchFieldException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static class MyClass{
public static final String VAR0 = "VARIAVEL 01";
public static final String VAR1 = "VARIAVEL 02";
public static final String VAR2 = "VARIAVEL 03";
public static final String VAR3 = "VARIAVEL 04";
public static final String VAR4 = "VARIAVEL 05";
}
}