Multiple exception catch block java 8 eclipse - eclipse

I'm getting an unhandled message exception for IOException. As you can see in the pasted code I've handled the IOException. The JDK for both eclipse & the project is Java 8 update 121 so I know catching multiple exceptions is supported. What am I doing wrong?
try (InputStream inputStream = BatchMessageProperties.class.getClassLoader().
getResourceAsStream(propertiesFileName)) {
load(inputStream);
//need to make sure all properties are present & not null.
validate(this);
} catch (IOException | InvalidBatchMessagePropertiesFileException ex) {
logger.error(ex.getLocalizedMessage());
ex.printStackTrace();
throw ex;
}

You do rethrow ex inside your catch block, which may be an IOException, right?

Related

NullPointerException with lambda expression - working with loops

I have 2 pieces of codes, one written with the java old style and the other is written with lambda expression,
The first:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
for(Object o:enumConstants) {
try {
constantsMap.put(o.toString(),o.getClass().getDeclaredField("lookupValue").getInt(o));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Is working fine and filling the map correctly
The other:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(Collectors.toMap
(e -> e.toString(), e -> {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
return null;
}
}
)));
Is giving null pointer exception, though by debugging the line e.getClass().getDeclaredField("lookupValue").getInt(e) I see it gets filled by value
My questions are:
1-what is wrong with this code?
2- how can I debug effectively inside stream methods in eclipse, is there a way to see elements getting populated inside the map one by one as in normal loop ? I could see the first element by putting a breakpoint but then the exceptions is fired immediately
3- is there a cleaner way to handle the exception inside the lambda expression, I tried wrapping the whole code with try/catch but compiler is still complaining that the exception is not handled.
Answer to any question is appreciated :)
EDIT:
Q1 answered by Holger in comments
IDE added
As stated in comment posted by Holger in comment, you can see that there is known bug in Java 8, with unresolved status, because of which you cannot put null values using Collectors.toMap, see issue here: https://bugs.openjdk.java.net/browse/JDK-8148463
Intellij IDEA has a great support for debugging Java 8 streams. Check this article: https://www.baeldung.com/intellij-debugging-java-streams
No, there currrently isn't, or I don't know about it. My suggestion for improving your code is to extract a method where you can handle your exception:
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(
Collectors.toMap(e -> e.toString(),
this::getInteger
)));
}
private Integer getInteger(Object e) {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
return null;
}
}

drools-7.23.0.Final KieContainerImpl KieBaseException

In running my application, I receive an error: Cannot find a default KieBaseException! called from KieContainerImpl.
I cannot find KieContainerImpl in the source code for drools-7.23.0.Final.
I have searched the source code org.kie.api.KieBase and drools.compiler.builder.imp, but unable to find KieContainerImpl
try
{
kContainer = ks.newKieContainer();
System.out.println("\ninitialized KieContainer:\t" + kContainer);
// Verify that kContainer was properly loaded
Results results = kContainer.verify();
...
/*
* A KieBase represents a compiled version of a set of assets.
*/
kBase = kContainer.getKieBase();
System.out.println("\ninitialized kBase:\n" + kBase);
}
catch (NoClassDefFoundError e)
{
e.printStackTrace();
}
catch (Exception ex)
{
System.out.println("Exception!");
ex.printStackTrace();
}
I expected the verify function to work. Here is the result:
initialized KieContainer: org.drools.compiler.kie.builder.impl.KieContainerImpl#767e20cf
Exception!
java.lang.RuntimeException: Cannot find a default KieBaseException at org.drools.compiler.kie.builder.impl.KieContainerImpl.getKieBase(KieContainerImpl.java:553)
at chemistryAdvisor.ChemistryAdvisor.initializeRuleEngine(ChemistryAdvisor.java:477)
at chemistryAdvisor.ChemistryAdvisor.main(ChemistryAdvisor.java:227)
java.lang.RuntimeException: Cannot find a default KieSession
at org.drools.compiler.kie.builder.impl.KieContainerImpl.findKieSessionModel(KieContainerImpl.java:684)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:677)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:660)
at chemistryAdvisor.ChemistryAdvisor.initializeRuleEngine(ChemistryAdvisor.java:496)
at chemistryAdvisor.ChemistryAdvisor.main(ChemistryAdvisor.java:227)
Welcome to ChemistryAdvisor!
When invoking kContainer.getKieBase(); without specifying any parameter, Drools expects to find a KieBase marked as default in your kmodule.xml.
Take a look at my answer in this other question.
Hope it helps,

ClassNotFoundException jdbc driver postgresql [duplicate]

This question already has an answer here:
ClassNotFoundException with PostgreSQL and JDBC
(1 answer)
Closed 5 years ago.
so I am writing a programm that accesses a database but whenever i can the method Class.forName("org.postgresql.Driver); the ClassNotFoundException is thrown.
I have looked at every solution to this problem I could find, but nothing worked.
I hope you can help me with this.
Code:
public static void editDatabase(String[] values){
Connection connect = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("org.postgresql.Driver");
connect = DriverManager.getConnection(values[0],values[1],values[2]);
statement = connect.createStatement();
result = statement.executeQuery("select * from Kunde");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This problem means that your project does not load 'org.postgresql.Driver' at init.
If you are using IntelliJ, you must add org.postgresql.Driver using 'Project Structure', it's located at your top right window.
If you're not using IDE, I do recommend you to use one.
You could also use Maven and add 'org.postgresql.Driver' as a requirement for your project.
Bye.

Getting error on deploying the process definition in activiti-rest using java code

Hi all i am trying to deploy process definiton in activiti-rest by using java rest.But getting error as 'Exception in thread "main" Bad Request (400)'.I have tried a lots in google but not found any solution for that.Please help me where is the actual fault in my code.Find below my java code and errors.
My Errors
Starting the internal HTTP client
Exception in thread "main" Bad Request (400) - The request could not be understood by the server due to malformed syntax
at org.restlet.resource.ClientResource.doError(ClientResource.java:590)
at org.restlet.resource.ClientResource.handleInbound(ClientResource.java:1153)
at org.restlet.resource.ClientResource.handle(ClientResource.java:1048)
at org.restlet.resource.ClientResource.handle(ClientResource.java:1023)
at org.restlet.resource.ClientResource.post(ClientResource.java:1485)
at org.restlet.resource.ClientResource.post(ClientResource.java:1424)
at com.bizruntime.activiti.rest.Activiti_Rest_BuyEconomyOrBusinsessClassTIcket.TicketClass.createdeployment(TicketClass.java:40)
at com.bizruntime.activiti.rest.Activiti_Rest_BuyEconomyOrBusinsessClassTIcket.Ticke_Test.main(Ticke_Test.java:13)
My Java Code
/**
*Client Resource
*/
private static ClientResource getClientResource(String uri){
ClientResource resource=new ClientResource("http://localhost:8431/activiti-rest/service");
resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,kermit,kermit);
return resource;
}
/**
* Creating Deployment
*/
public static JSONObject createdeployment(){
String uri=REST_URI+"/repository/deployments";
log.debug("uri(Create Deploymnet):: "+uri);
JSONObject my_data=new JSONObject();
try {
my_data.put("name","BuyTicket.bpmn20.xml");
Representation response=getClientResource(uri).post(my_data);
JSONObject object=new JSONObject(response.getText());
if(object!=null){
log.info("Deployed Successfully.....");
return object;
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
cfr. http://activiti.org/userguide/index.html#_create_a_new_deployment: the body should not be a json multipart/form-data file that is a bpmn20.xml file (or a .zip in case of multiple files)

Redirect from CustomProductDisplayCmd to 404 page if unavailable product

My custom implementation of a ProductDisplayCmd looks like this...
public void performExecute( ) throws ECException {
super.performExecute();
(my code here)
Now, if a product is unavailable, the super throws an ECApplicationException with this message:
com.ibm.commerce.exception.ECApplicationException: The catalog entry
number "253739" and part number "9788703055992" is not valid for the
current contract.
With a SEO enabled URL, I get redirected to our custom 404 page ("Gee sorry, that product is no longer available. Try one of our fantastic alternatives...")
http://bktestapp01.tm.dom/shop/sbk/bent-isager-nielsen-efterforskerne
With the old-style URL, i instead get an error page due to an untrapped exception.
http://bktestapp01.tm.dom/webapp/wcs/stores/servlet/ProductDisplay?langId=100&storeId=10651&catalogId=10013&club=SBK&productId=253739
Since I can catch the exception, I suppose I have the option of manually redirecting to the 404 page, but is that the way to go? In particular: The exception type does not seem to tell me exactly what is wrong, so I might accidentally make a 404 out of another kind of error.
Here's what I ended up with: Catch the exception from super, then decide if the reason it was thrown is that the product is unavailable. If so, then redirect to the 404 page, else re-throw exception.
Implementation:
public void performExecute( ) throws ECException {
try {
super.performExecute();
} catch (final ECApplicationException e) {
// Let's see if the problem is something that should really be causing a redirect
makeProductHelperAndRedirectTo404IfProductNotAvailable(e);
// If we get here, noting else was thrown
log.error("The reason super.performExecute threw an ECException is unknown and so we can't recover. Re-throwing it.");
throw e;
}
...and in the makeProductblablabla method:
private ProductDataHelper makeProductHelperAndRedirectTo404IfProductNotAvailable(final ECException cause) throws ECSystemException,
ECApplicationException {
final ProductDataHelper productHelper;
try {
log.trace("Trying to determine if the reason super.performExecute threw an ECException is that the product is unavailable in the store. The execption is attached to this logline.", cause);
productHelper = makeProductHelper(getProductId());
if (productHelper != null) {
if (!productHelper.isActiveInClub()) {
log.trace("Decided that the reason super.performExecute threw an ECException is that the product is unavailable in the store. The execption is attached to this logline. NB! That exception is DISCARDED", cause);
final String pn = productHelper.getISBN();
final ECApplicationException systemException = new ECApplicationException(ECMessage._ERR_PROD_NOT_EXISTING, this.getClass().getName(), "productIsPublished", new Object[]{ pn });
systemException.setErrorTaskName("ProductDisplayErrorView");
throw systemException;
}
}
return productHelper;
} catch (RemoteException e) {
log.error("I was trying to determine if the reason super.performExecute threw an ECException is that the product is unavailable in the store. The original ECException is attached to this logline. NB! That exception is DISCARDED", cause);
throw new ECSystemException(ECMessage._ERR_GENERIC, super.getClass().getName(), "performExecute",ECMessageHelper.generateMsgParms(e.getMessage()), e);
} catch (NamingException e) {
log.error("I was trying to determine if the reason super.performExecute threw an ECException is that the product is unavailable in the store. The original ECException is attached to this logline. NB! That exception is DISCARDED", cause);
throw new ECSystemException(ECMessage._ERR_GENERIC, super.getClass().getName(), "performExecute",ECMessageHelper.generateMsgParms(e.getMessage()), e);
} catch (FinderException e) {
log.error("I was trying to determine if the reason super.performExecute threw an ECException is that the product is unavailable in the store. The original ECException is attached to this logline. NB! That exception is DISCARDED", cause);
throw new ECSystemException(ECMessage._ERR_GENERIC, super.getClass().getName(), "performExecute",ECMessageHelper.generateMsgParms(e.getMessage()), e);
} catch (CreateException e) {
log.error("I was trying to determine if the reason super.performExecute threw an ECException is that the product is unavailable in the store. The original ECException is attached to this logline. NB! That exception is DISCARDED", cause);
throw new ECSystemException(ECMessage._ERR_GENERIC, super.getClass().getName(), "performExecute",ECMessageHelper.generateMsgParms(e.getMessage()), e);
}
}