This codes can't check NoResultException - java

This is the Code I was made. It shouldn't get and enter to NoResultException, but it doesn't as expected. There is an unused data. I try to print out, here is the output : "[ ]"
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = tableDataRangka.getSelectedRow();
String idRangka = tableDataRangka.getValueAt(row, 0).toString();
System.out.println( relasiRumahkayuRangkaDAO.getRelasiByIdRangka(idRangka).toString() );
} catch (NoResultException nre) {
// Doing something..
} catch (Exception ex) {
Logger.getLogger(MasterDataProjectUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code of method "getRelasiByIdRangka" :
public List<RelasiRumahKayuRangka> getRelasiByIdRangka(String idRangka) throws Exception{
initEntityManager();
List<RelasiRumahKayuRangka> rrDrs = new ArrayList<>();
Query q = em.createNamedQuery("RelasiRumahKayuRangka.findByIdRangka");
q.setParameter("idRangka", idRangka);
rrDrs.addAll(q.getResultList());
closeEntityManager();
return rrDrs;
}
And this one is the JPA query, findByIdRangka :
#NamedQuery(name = "RelasiRumahKayuRangka.findByIdRangka", query = "SELECT r FROM RelasiRumahKayuRangka r WHERE r.relasiRumahKayuRangkaPK.idRangka = :idRangka"),
Do you guys know the solution, so the code can be catched by NoResultException ?

In your code. if the result set is empty then list will also be empty.
Make use of that situation and throw a desired exception.
In your getRelasiByIdRangka(String idRangka) add following changes.
public List<RelasiRumahKayuRangka>
getRelasiByIdRangka( String idRangka ) throws Exception {
initEntityManager();
// rest of the code here
// ...
// check if some results are found or not
if( rrDrs.isEmpty() ) { // or ( rrDrs.size() == 0 )
throw new NoResultException( "No results found" );
} // if empty
// this should be a filled in list
return rrDrs;
} // end of method

Related

Get ID of the room from Json

I need to get the ID of room by its name from JSONObject.
I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json
So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").
Any ideas how to do that?
So far I have something like this:
private static String GetIdRoom(String room) {
String id = "";
JSONObject myResponse = SendHTTP("/groups", "GET", "");
try {
// some code to get ID of room
} catch (Exception ex) {
System.out.println("error - " + ex);
}
return null ;
}
Iterator<?> ids = myResponse.keys();
while( ids.hasNext() ) {
id = (String) ids.next();
if(myResponse.getJSONObject(id).getString("name").equals(room)){
return id;
}
}

How verify if a member is admin?

I'm working on a bot for supergroups.
How I can verify if member is admin?
my lib:org.telegram 4.2 https://core.telegram.org/bots/api
I tried with ChatMember, GetChatAdministrators and SendMessage methods but I have no idea how insert parameters because they don't ask them but they have only .get option (null respose). Only GetChatAdministrators permit a .set method for ChatID but it give error
GetChatAdministrators getadmin = new GetChatAdministrators().setChatId(ChatIDSupergroup);
ArrayList<ChatMember> s = null;
try {
s = getadmin.deserializeResponse(null); //Unable to deserialize response
} catch (TelegramApiRequestException e) {
e.printStackTrace();
}
ChatMember member = new ChatMember(); //There are only get options
String status=member.getStatus(); //null
I had a same problem but I couldn't find an answer from anywhere. Then I tried myself and finally today I found the following solution:
public List<ChatMember> getChatAdministrators(Long chatId){
List<ChatMember> chatAdministrators = Collections.emptyList();
try {
chatAdministrators = execute(new GetChatAdministrators(String.valueOf(chatId)));
} catch (TelegramApiException e) {
e.printStackTrace();
}
return chatAdministrators;
}
This method returns list of administrators of telegram groups, supergroups or channels.
function adminCheck( id, chat_id ) {
var bAdminCheck = false;
var name = "";
var aChatMember = getChatAdministrators( chat_id );
var contents = JSON.parse( aChatMember );
var i = 0;
while( !bAdminCheck && ( i < contents.result.length ) ) {
if( id == contents.result[i].user.id ) {
bAdminCheck = true;
}
i++;
}
return {
AdminCheck: bAdminCheck,
};
}
Available methods
source:
https://core.telegram.org/bots/api#available-methods
getChatAdministrators
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

DAO and Synchronization between threads

I'm developing a Javafx application, that synchronizes some data from two different databases.
In the call method I get all the data and store it in an ArrayList. Then I loop through the ArrayList and I try to get that same data from the second database.
If it exists I compare it for differences and if there are differences I update it. Otherwise, if it dosen't exist, I insert it via a DAO object method.
The problem is that sometimes the second database takes some time to provide the response so the process continues its execution and the new data will be compared with old data.
My question is, how can I stop the process until the data has all been fetched and then proceed to the synchronization logic?
#Override
protected Map call() throws Exception {
Map<String, Integer> m = new HashMap();
updateTitle( "getting the data ..." );
int i, updated = 0, inserted = 0;
// creating first database instance
DAOFactory db1Dao = DAOFactory.getInstance( "db1" );
//creating the first database dataObject instance
Db1EmployerDAO empDb1Dao = db1Dao.getDAODb1Employer();
// creating second database instance
DAOFactory db2Dao = DAOFactory.getInstance( "db2" );
//creating the second database dataObject instance
Db2EmployeurDAO empDb2Dao = db2Dao.getDAODb2Employer();
Employer emp;
// getting all the object
List< Employer > LEmpDb1 = empDb1Dao.getAll();
updateTitle( "Data proccessing ..." );
//for each data in the list
for( i = 1; i <= LEmpDb1.size(); i++ ){
if( isCancelled() )
break;
updateMessage( "Processing employer : "+ LEmpDb1.get( i-1 ).getNemploy() +" "+ LEmpDb1.get( i-1 ).getRaison() );
//trying to get the object from the second database which the
//process sometimes pass befor the result is getting which is my problem
emp = empDb2Dao.getEmployerByNo( LEmpDb1.get( i-1 ).getNemploy() );
if( emp != null){
if( !LEmpDb1.get( i-1 ).equals( emp ) )
if( empDb2Dao.update( LEmpDb1.get( i-1 ) ) ){
updated++;
LOG.log( "MAJ employeur : "+ LEmpDb1.get( i ).getNemploy()+" => "+LEmpDb1.get( i ).getDifferences( emp ) );
}
} else {
if( empDb2Dao.insert( LEmpDb1.get( i-1 ) ) )
inserted++;
}
updateProgress( i, LEmpDb1.size() );
}
m.put( "upd", updated );
m.put( "ins", inserted );
m.put( "all", LEmpDb1.size() );
return m;
}
The getEmployerByNo method
public synchronized Employer getEmployerByNo( String no_emp ) throws DAOException {
Employeur emp = null;
Connection con = null;
PreparedStatement stm = null;
ResultSet res = null;
try{
con = dao.getConnection();
stm = preparedRequestInitialisation( con, GET_BY_NO_SQL, no_emp );
res = stm.executeQuery();
if( res.next() ){
//map is a function that map the database resultset data with the object properties
emp = map( res );
LOG.info( "getting the employer : "+ no_emp );
}
} catch( SQLException e ){
throw new DAOException( e.getLocalizedMessage() );
} finally{
silentClose( res, stm, con );
}
return emp;
}
Look into using an ExecutorService and Future.get() as needed to wait for completion. See the documentation here and here. Here is a more-or-less complete example:
public class Application implements Runnable {
private final ExecutorService pool = Executors.newCachedThreadPool();
public void run() {
Dao firstDao = new DaoImpl();
Dao secondDao = new AnotherDaoImpl();
FetchAllTask fetchAll = new FetchAllTask(firstDao);
Future<?> fetchAllFuture = pool.submit(fetchAll);
try {
fetchAllFuture.get();
} catch (Exception e) {
// TODO handle
System.out.println("An exception occurred!");
e.printStackTrace();
}
ConcurrentSkipListSet<AnObject> items = fetchAll.getItems();
Iterator<AnObject> it = items.iterator();
while (it.hasNext()) {
// insert your cancellation logic here
// ...
AnObject daoObj = it.next();
FetchOneTask fetchOne = new FetchOneTask(secondDao, daoObj.getId());
Future<?> fetchOneFuture = pool.submit(fetchOne);
try {
fetchOneFuture.get();
AnObject anotherDaoObj = fetchOne.getAnObject();
if (anotherDaoObj == null) {
// the object retrievied by the first dao (first datasource)
// is not in the second; it needs to be inserted into the second
System.out.println(String.format("Inserting %s", daoObj));
secondDao.insert(daoObj);
} else {
System.out.println(String.format("Updating %s to %s", anotherDaoObj, daoObj));
secondDao.update(daoObj);
}
} catch (Exception e) {
System.out.println("An exception occurred!");
e.printStackTrace();
}
}
Set<AnObject> itemsInSecondDb = secondDao.fetchAll();
for (AnObject o : itemsInSecondDb) {
System.out.println(o);
}
pool.shutdown();
}
// ... invoke the app thread from somewhere else
}

SQLiteException: near "null": syntax error (code 1): , while compiling: create table

Please help me, i get this errors when i run my app use Idea
here is screen of error
http://prntscr.com/en3lcu
here is part of code where create table
private String getTableDDL(final Class<? extends GlassContract.Table> table) {
return getTableDDL(table, GlassContract.getTableName(table));
}
private String getTableDDL(final Class<? extends GlassContract.Table> table, String tableName) {
final StringBuilder sql = new StringBuilder(128);
sql.append("create table ").append(tableName).append(" (");
for (final Field field : table.getFields()) {
if (field.getName().startsWith("_") || field.isAnnotationPresent(Deprecated.class))
continue;
try {
sql.append(field.get(null));
} catch (Exception ignore) {
}
try {
final Field type = table.getDeclaredField("_SQL_" + field.getName() + "_TYPE");
sql.append(' ').append(type.get(null));
} catch (Exception ignore) {
sql.append(" TEXT");
}
sql.append(',');
}
try {
final Field type = table.getDeclaredField("_PK_COMPOSITE");
sql.append("PRIMARY KEY(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
try {
final Field type = table.getDeclaredField("_UNIQUE_COMPOSITE");
sql.append("UNIQUE(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
sql.setLength(sql.length() - 1); // chop off last comma
sql.append(')');
Log.v(TAG, "DDL for " + table.getSimpleName() + ": " + sql);
return sql.toString();
}
I please help me, because I break my head))
Are you really trying to create text fields in your table that are named null?
Even if this works (and I am not sure it does), you are duplicating this and creating two identically named fields called null
The first field in that CREATE TABLE statement doesn't have a proper name (it is "null"). That's why it blows up.
There's more fields with illegal names as well.

junit testing - assertEquals for exception

How can I use assertEquals to see if the exception message is correct?
The test passes but I don't know if it hits the correct error or not.
The test I am running.
#Test
public void testTC3()
{
try {
assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
}
catch (Exception e) {
}
}
The method being tested.
public static int shippingCost(char packageType, int weight) throws Exception
{
String e1 = "Legal Values: Package Type must be P or R";
String e2 = "Legal Values: Weight < 0";
int cost = 0;
if((packageType != 'P')&&(packageType != 'R'))
{
throw new Exception(e1);
}
if(weight < 0)
{
throw new Exception(e2);
}
if(packageType == 'P')
{
cost += 10;
}
if(weight <= 25)
{
cost += 10;
}
else
{
cost += 25;
}
return cost;
}
}
Thanks for the help.
try {
assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
Assert.fail( "Should have thrown an exception" );
}
catch (Exception e) {
String expectedMessage = "this is the message I expect to get";
Assert.assertEquals( "Exception message must be correct", expectedMessage, e.getMessage() );
}
The assertEquals in your example would be comparing the return value of the method call to the expected value, which isn't what you want, and of course there isn't going to be a return value if the expected exception occurs. Move the assertEquals to the catch block:
#Test
public void testTC3()
{
try {
Shipping.shippingCost('P', -5);
fail(); // if we got here, no exception was thrown, which is bad
}
catch (Exception e) {
final String expected = "Legal Values: Package Type must be P or R";
assertEquals( expected, e.getMessage());
}
}
Works perfectly for me.
try{
assertEquals("text", driver.findElement(By.cssSelector("html element")).getText());
}catch(ComparisonFailure e){
System.err.println("assertequals fail");
}
if assertEquals fails ComparisonFailure will handle it
Java 8 solution
Here is a utility function that I wrote:
public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )
{
try
{
runnable.run();
}
catch( Throwable throwable )
{
if( throwable instanceof AssertionError && throwable.getCause() != null )
throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
#SuppressWarnings( "unchecked" )
T result = (T)throwable;
return result;
}
assert false; //expected exception was not thrown.
return null; //to keep the compiler happy.
}
(taken from my blog)
Use it as follows:
#Test
public void testThrows()
{
RuntimeException e = expectException( RuntimeException.class, () ->
{
throw new RuntimeException( "fail!" );
} );
assert e.getMessage().equals( "fail!" );
}
Also, if you would like to read some reasons why you should not want to assertTrue that the message of your exception is equal to a particular value, see this: https://softwareengineering.stackexchange.com/a/278958/41811
This is nice library that allows asserting exceptions in a clean way.
Example:
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
when(myList).get(1);
// then: we expect an IndexOutOfBoundsException
then(caughtException())
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessage("Index: 1, Size: 0")
.hasNoCause();

Categories

Resources