Java 8, Optional. throwing Exceptions, and Re-throwing exceptions, preventing null - exception

I have confusing (lack of comprehension) trying to translate some part of my code to Optional on Java 8.
First example mock Code
private void privateMethodOne(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<CustomResponseDto> responseEntity;
try {
responseEntity = callWebClientRequestOne();
} catch (Exception e) {
RuntimeException ex = new CustomClientException(customRequesDto, e.getMessage());
log.error(ex.getMessage());
throw ex;
}
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
}
In the First example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
How to do the same in a Single line?
Second example mock Code
private void privateMethodTwo(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<byte[]> responseEntity = null;
try {
responseEntity = callWebClientRequestTwo();
} catch (Exception e) {
mapExceptions.put(customRequesDto, e.getMessage());
}
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
// continue the executions
}
Second example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
How to perform the same in a Single line?

Related

actframework can't save in database using $.merge

i'am trying to read data from a form and save it to database.first i read entity from database and use $.merge(formdata).filter("-id").to(entity) .I print the value and it's changed successful.But when i call dao.save it do nothing;
the action code below
#PutAction("{id}")
public void update(#DbBind("id") #NotNull Category cate,Category category, ActionContext context) {
notFoundIfNull(cate);
try {
$.merge(category).filter("-id").to(cate);
System.out.print("name is " + cate.getName());
// cate.setName("test"); // success
this.dao.save(cate);
// redirect("/admin/categories");
} catch (io.ebean.DataIntegrityException e) {
context.flash().error(e.getMessage());
render("edit", category);
}
}
dao.save successful when i call cate.setName("test");
Can someone help me solve this problem?
I solved this problem by myself using the following code
public void mergeTo(Base target){
if(!this.getClass().isAssignableFrom(target.getClass())){
return;
}
Method[] methods = this.getClass().getMethods();
for(Method fromMethod: methods){
if(fromMethod.getDeclaringClass().equals(this.getClass())
&& fromMethod.getName().startsWith("get")){
String fromName = fromMethod.getName();
String toName = fromName.replace("get", "set");
try {
Method toMetod = target.getClass().getMethod(toName, fromMethod.getReturnType());
Object value = fromMethod.invoke(this, (Object[])null);
if(value != null){
toMetod.invoke(target, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

JavaFX table row color, too many database connections

I want to to print my row red when book is out of stock but i am getting error like that every time i try new idea to manage that:
"com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Data source rejected establishment of connection, message from
server: "Too many connections"
Even if i try to close all connections in same loop...
So here we go:
private boolean checkIfOutOfStock(BookDetail book) throws SQLException{
String query = "select * from tbl_loan where book_id = " + book.getId() + " ";
dc = new DbConnection();
conn = dc.connect();
PreparedStatement checkPst = conn.prepareStatement(query);
ResultSet checkRs = checkPst.executeQuery(query);
if(checkRs.next()){
checkRs.close();
checkPst.close();
return true;
} else
{
checkRs.close();
checkPst.close();
return false;
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
dc = new DbConnection();
conn = dc.connect();
selectionModel = editTabPane.getSelectionModel();
editTableBooks.setRowFactory(tv -> new TableRow<BookDetail>() {
#Override
public void updateItem(BookDetail item, boolean empty) {
super.updateItem(item, empty) ;
if (item == null) {
setStyle("");
} else
try {
if (checkIfOutOfStock(item)) {
setStyle("-fx-background-color: tomato;");
} else {
setStyle("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
It works fine until i slide up and down table few times... its like everytime i slide table im opening new connection. Any idea how to solve it?
Hey do you mean something like that?
editTableBooks.setRowFactory(tv -> new TableRow<BookDetail>() {
#Override
public void updateItem(BookDetail item, boolean empty) {
super.updateItem(item, empty) ;
Platform.runLater(new Runnable() {
#Override
public void run() {
if (item == null) {
setStyle("");
} else
try {
if (checkIfOutOfStock(item)) {
setStyle("-fx-background-color: tomato;");
} else {
setStyle("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
It doesn't change anything or i just didn't get it :P

How can I call another method after all `FutureTask` have finished their computations?

I have the following method that creates and deploys applications in different PaaS:
private void deployModulesInPaaS() {
ExecutorService executor = Executors.newFixedThreadPool(listModules
.size());
ModuleParsed mod;
for (Iterator<ModuleParsed> iterator = listModules.iterator(); iterator
.hasNext();) {
mod = (ModuleParsed) iterator.next();
try {
switch (mod.getId_paas()) {
case 1:
GAEDeployer gaeDeployer = new GAEDeployer(mod.getId_paas(),
mod.getId_component(), "//whatever/path");
FutureTask<URI> gaeFuture = new FutureTask<URI>(gaeDeployer);
executor.execute(gaeFuture);
mod.setDeployedURI(gaeFuture.get());
break;
case 2:
AzureDeployer azureDeployer = new AzureDeployer(
"subscription", "path_certificate", "password",
"storageAccountName", "storageAccountKey");
FutureTask<URI> azureFuture = new FutureTask<URI>(
azureDeployer);
executor.execute(azureFuture);
mod.setDeployedURI(azureFuture.get());
break;
default:
System.out.println("The PaaS identifier of module "
+ mod.getId_component() + " is unknown.");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
How can I call another method once all FutureTask have finished their computations?
I have read about Command pattern and about Listener but I'm not sure if these would be the right ones nor how to implement them in this case.
You really need ListenableFuture, please search the keyword "fan-in" on this page.
Another way with CountDownLatch and overriding FutureTask.done(),not recommended:
private void deployModulesInPaaS() {
CountDownLatch countDownLatch = new CountDownLatch(listModules.size());
ExecutorService executor = Executors.newFixedThreadPool(listModules
.size());
ModuleParsed mod;
for (Iterator<ModuleParsed> iterator = listModules.iterator(); iterator
.hasNext();) {
mod = (ModuleParsed) iterator.next();
try {
switch (mod.getId_paas()) {
case 1:
GAEDeployer gaeDeployer = new GAEDeployer(mod.getId_paas(),
mod.getId_component(), "//whatever/path");
FutureTask<URI> gaeFuture = new FutureTask<URI>(gaeDeployer) {
#Override
protected void done() {
super.done();
countDownLatch.countDown();
}
};
executor.execute(gaeFuture);
mod.setDeployedURI(gaeFuture.get());
break;
case 2:
AzureDeployer azureDeployer = new AzureDeployer(
"subscription", "path_certificate", "password",
"storageAccountName", "storageAccountKey");
FutureTask<URI> azureFuture = new FutureTask<URI>(
azureDeployer) {
#Override
protected void done() {
super.done();
countDownLatch.countDown();
}
};
executor.execute(azureFuture);
mod.setDeployedURI(azureFuture.get());
break;
default:
System.out.println("The PaaS identifier of module "
+ mod.getId_component() + " is unknown.");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
countDownLatch.await();
// do finally
}

Glassfish "Connection closed" error with a connection pool, JDBC, and SQL Server 2008

When I try to do more than one transaction in a JSF page, I get the following error:
A potential connection leak detected for connection pool MSSQL. The stack trace of the thread is provided below :
com.sun.enterprise.resource.pool.ConnectionPool.setResourceStateToBusy(ConnectionPool.java:324)
com.sun.enterprise.resource.pool.ConnectionPool.getResourceFromPool(ConnectionPool.java:758)
com.sun.enterprise.resource.pool.ConnectionPool.getUnenlistedResource(ConnectionPool.java:632)
com.sun.enterprise.resource.pool.AssocWithThreadResourcePool.getUnenlistedResource(AssocWithThreadResourcePool.java:196)
com.sun.enterprise.resource.pool.ConnectionPool.internalGetResource(ConnectionPool.java:526)
com.sun.enterprise.resource.pool.ConnectionPool.getResource(ConnectionPool.java:381)
com.sun.enterprise.resource.pool.PoolManagerImpl.getResourceFromPool(PoolManagerImpl.java:245)
com.sun.enterprise.resource.pool.PoolManagerImpl.getResource(PoolManagerImpl.java:170)
com.sun.enterprise.connectors.ConnectionManagerImpl.getResource(ConnectionManagerImpl.java:338)
com.sun.enterprise.connectors.ConnectionManagerImpl.internalGetConnection(ConnectionManagerImpl.java:301)
com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:190)
com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:165)
com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:160)
com.sun.gjc.spi.base.DataSource.getConnection(DataSource.java:113)
cl.codesin.colegios.util.persistencia.DAOManejador.abrir(DAOManejador.java:126)
Please notice the last line I pasted:
cl.codesin.colegios.util.persistencia.DAOManejador.abrir(DAOManejador.java:126)
abrir does the following:
public void abrir() throws SQLException {
try
{
if(this.con==null || this.con.isClosed())
this.con = fuenteDatos.getConnection();
}
catch(SQLException e)
{
throw e;
}
}
It works in a singleton DAO manager this way: the DAO manager has one instance of each DAO and manages a single connection that every DAO shares. When a DAO is requested, it does the following:
public DAORegion getDAOregion() throws SQLException {
try
{
if(con == null) //con is the connection the DAO manager uses
{
this.abrir();
}
}
catch(SQLException e)
{
throw e;
}
if(this.DAOregion==null)
{
this.DAOregion = new DAORegion(this.con);
}
return DAOregion;
}
When closing a connection, the manager just calls to con.close() without anything else.
By the way, I have no persistence.xml since I'm working with JDBC.
What am I doing wrong? Thank you beforehand.
EDIT: By desactivating the leak detection from the Glassfish server I could avoid the exception, however I'm still getting a "Connection closed" error. Worst is, now I don't know exactly where the error is being thrown.
EDIT 2: I changed my DAO manager again. Here's the implementation.
public class DAOManejador {
public static DAOManejador getInstancia() {
return DAOManejadorSingleton.INSTANCIA;
}
//This is just a sample, every getDAOXXX works the same.
public DAOUsuario getDAOusuario() throws SQLException {
try
{
if(con == null)
{
this.abrir();
}
}
catch(SQLException e)
{
throw e;
}
if(this.DAOusuario==null)
{
this.DAOusuario = new DAOUsuario(this.con, this.stmt, this.res);
}
return DAOusuario;
}
public void abrir() throws SQLException {
try
{
if(this.con==null || this.con.isClosed())
this.con = fuenteDatos.getConnection();
}
catch(SQLException e)
{
throw e;
}
}
public void iniciaTransaccion() throws SQLException {
try
{
con.setAutoCommit(false);
}
catch(SQLException e)
{
throw e;
}
}
public void cierraTransaccion() throws SQLException {
try
{
con.setAutoCommit(true);
}
catch(SQLException e)
{
throw e;
}
}
public void comprometer() throws SQLException {
try
{
con.commit();
}
catch(SQLException e)
{
throw e;
}
}
public void deshacer() throws SQLException {
try
{
con.rollback();
}
catch(SQLException e)
{
throw e;
}
}
public void cerrar() throws SQLException {
try
{
if(this.stmt!=null && !this.stmt.isClosed())
stmt.close();
if(this.res!=null && !this.res.isClosed())
this.res.close();
if(this.con!=null && !this.con.isClosed())
con.close();
}
catch(SQLException e)
{
throw e;
}
}
public void comprometerYTerminarTransaccion() throws SQLException {
try
{
this.comprometer();
this.cierraTransaccion();
}
catch(SQLException e)
{
throw e;
}
}
public void comprometerYCerrarConexion() throws SQLException {
try
{
this.comprometer();
this.cierraTransaccion();
this.cerrar();
}
catch(SQLException e)
{
throw e;
}
}
//Protegidos
#Override
protected void finalize() throws SQLException, Throwable
{
try
{
this.cerrar();
}
finally
{
super.finalize();
}
}
//Private
private DataSource fuenteDatos;
private Connection con = null;
private PreparedStatement stmt = null;
private ResultSet res = null;
private DAOUsuario DAOusuario = null;
private DAORegion DAOregion = null;
private DAOProvincia DAOprovincia = null;
private DAOComuna DAOcomuna = null;
private DAOColegio DAOcolegio = null;
private DAOManejador() throws Exception {
try
{
InitialContext ctx = new InitialContext();
this.fuenteDatos = (DataSource)ctx.lookup("jndi/MSSQL");
}
catch(Exception e){ throw e; }
}
private static class DAOManejadorSingleton {
public static final DAOManejador INSTANCIA;
static
{
DAOManejador dm;
try
{
dm = new DAOManejador();
}
catch(Exception e)
{ dm=null; }
INSTANCIA = dm;
}
}
}
What I did now is to provide a single access point for every DAO. When a DAO wants to use a statement or a resource, they'll all use the same one. When they need to open again one, the system does the following:
public abstract class DAOGenerico<T> {
//Protected
protected final String nombreTabla;
protected Connection con;
protected PreparedStatement stmt;
protected ResultSet res;
protected DAOGenerico(Connection con, PreparedStatement stmt, ResultSet res, String nombreTabla) {
this.nombreTabla = nombreTabla;
this.con = con;
this.stmt = stmt;
this.res = res;
}
//Prepares a query
protected final void prepararConsulta(String query) throws SQLException
{
try
{
if(this.stmt!=null && !this.stmt.isClosed())
this.stmt.close();
this.stmt = this.con.prepareStatement(query);
}
catch(SQLException e){ throw e; }
}
//Gets a ResultSet
protected final void obtenerResultados() throws SQLException {
try
{
if(this.res!=null && !this.res.isClosed())
this.res.close();
this.res = this.stmt.executeQuery();
}
catch(SQLException e){ throw e; }
}
}
And it still doesn't work.
I tried not doing anything when closing the connection. I commented the code in the cerrar method, and for some reason, it works! Even when it's a bad practice! Is it okay to keep it like that, or should I find a way to close a connection?
Disregard this, I found what's wrong. I hope someone can make good use of this in the future.
The problem
if(this.con==null || this.con.isClosed())
this.con = fuenteDatos.getConnection();
Each time I try to open a connection, I get a completely brand new connection. What's the problem with this?
public DAOUsuario getDAOusuario() throws SQLException {
try
{
if(con == null)
{
this.abrir();
}
}
catch(SQLException e)
{
throw e;
}
if(this.DAOusuario==null)
{
this.DAOusuario = new DAOUsuario(this.con, this.stmt, this.res);
}
return DAOusuario;
}
Only when I create a new instance of the DAO I assign it a new connection. What will happen in the following case then?
DAOManejador daoManager = DAOManejador.getInstancia(); //Get an instance of the DAO manager
daoManager.abrir(); //Open the connection
DAOUsuario daoUser = daoManager.getDAOusuario(); //Get a DAOUsuario, a type of DAO. It'll have the same connection as the DAOManager, and it'll be stored in the instance of the DAO manager
... //Do database stuff
daoManager.cerrar(); //Close the connection
daoManager.abrir(); //Open the connection again. Note that this will be a new instance of the conection rather than the old one
If, from here, you try to do database stuff, you'll get a Connection closed error since daoUser will still hold the old connection.
What I did
I modified the DAO manager class. It no longer has a getDAOXXX() per DAO, but rather the following:
public DAOGenerico getDAO(Tabla t) throws SQLException {
try
{
if(con == null || this.con.isClosed())
{
this.abrir();
}
}
catch(SQLException e)
{
throw e;
}
switch(t)
{
case REGION:
return new DAORegion(this.con, this.stmt, this.res);
case PROVINCIA:
return new DAOProvincia(this.con, this.stmt, this.res);
case COMUNA:
return new DAOComuna(this.con, this.stmt, this.res);
case USUARIO:
return new DAOUsuario(this.con, this.stmt, this.res);
case COLEGIO:
return new DAOColegio(this.con, this.stmt, this.res);
default:
throw new SQLException("Se intentó vincular a una tabla que no existe.");
}
}
Each time the user requests a DAO, it'll ask the manager to return the correct type of DAO. But instead of storing each instance, the manager will create new instances depending on the current connection (con is the connection, stmt is a PreparedStatement and res is a ResultSet - they will be used so they can be closed when the manager closes the connection so nothing leaks). Tabla is an enum holding the current table names in the database so it can return the correct DAO. This worked with no problems whatsoever. The rest of the class is the same, so if you want to use it, just replace the DAOUsuario method with the one above and it should work fine.

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help