Stores dynamically columns into SQL database - java

I am working on a basic desktop Java application. I have a "more" buttons and when I click on it a new line of JTextField and JDateChooser appears. All I want is to store these lines into database. How can I implement it?
Here is my code.
MemberDao.java
public boolean isExist(CachedRowSet crs, String colName) throws SQLException {
ResultSetMetaData meta = crs.getMetaData();
int columns = meta.getColumnCount();
for (int x = 1; x <= columns; x++) {
if (colName.equals(meta.getColumnName(x))) {
return true;
}
}
return false;
}
InsertMember.java
if(evt.getSource()==more){
try {
if(MemberDao.getInstance().isExist(crs,"mem_familyname")){
System.out.println("found");
} else {
System.out.println("not found");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
But this code gives me a NullPinterException

Related

Reduce My for loop complexity to 4 as per sonar confiuration

I integrated code to sonarqube for quality code and set method complexity is 4.
Please help me to reduce this for loop complexity to 4
for (int i = 1; i <= retryCount + count; i++) {
try {
if (cat!= null)
grps = cat.getAllGroups(category);
flag = true;
} catch (Exception e) {
if (i >= retryCount + count) {
throw new MyException(new Fault(1009,
new Object[] { e.getMessage() }));
} else {
if (e.getMessage().contains("No Records Found")) {
break;
} else {
String status = handleIOAutomationException(ctx, e);
if (status.equalsIgnoreCase("none")) {
throw new MyException(new Fault(1009,
new Object[] { e.getMessage() }));
} else if (status.equalsIgnoreCase("some")) {
}
}
}
}
if (flag) {
break;
}
}
Try to extract your logic into its own sub methods and try make these shorter. You should also try to make your identifiers more readable.
public void method() {
...
int maxLoops = retryCount + count;
for (int i = 1; i <= maxLoops; i++) {
if (tryToGetAllGroups(maxLoops, i))
break;
}
}
private boolean tryToGetAllGroups(int maxLoops, int i) throws MyException {
try {
if (cat != null)
grps = cat.getAllGroups(category);
return true;
} catch (Exception e) { // you should make Exception more specific!
if (i >= maxLoops) {
return throwFinalException(e);
} else {
if (tryToGetCat(e)) return true;
}
}
return false;
}
private boolean tryToGetCat(Exception e) throws MyException {
if (e.getMessage().contains("No Records Found")) {
return true;
} else {
String status = handleIOAutomationException(ctx, e);
if (status.equalsIgnoreCase("none")) {
throwFinalException(e);
} else if (status.equalsIgnoreCase("some")) {
// try to get cat here
}
}
return false;
}
private boolean throwFinalException(Exception e) throws MyException {
throw new MyException(new Fault(1009,
new Object[]{e.getMessage()}));
}

Simple java bot telegram: messages in loop

I'm trying to make simple telegram bot on Java.
The question is: how can I receive messages in a loop, when the user typed /start? I have already some
#Override
public void onUpdateReceived(Update update) {
Message msg = update.getMessage();
String txt = msg.getText();
if (txt.equals("/start")) {
sendMsg(msg, "Привет, меня зовут бот " + name + "!");
showHelp(msg);
run(msg, update);
} else if (txt.equals("/help")) {
showHelp(msg);
}
}
Here's showhelp:
private void showHelp(Message msg) {
try {
String inAbout = ReadFile.readFileInString(this.about);
sendMsg(msg, inAbout);
} catch (Exception ex) {
ex.printStackTrace();
}
}
sendMsg:
private void sendMsg(Message msg, String text) {
SendMessage s = new SendMessage();
s.setChatId(msg.getChatId());
s.setText(text);
try {
execute(s);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
In Run I want to read questions from data and wait for users answer, check if correct and do it in loop. In the end show how many he answered correct.
public void run(Message msg, Update update) {
try {
List<String> data = ReadFile.readFileInList(this.getData());
List<String> dataAnswers = ReadFile.readFileInList(this.answers);
this.sizeOfAnswers = data.size();
for (int i = 0; i < data.size(); i++) {
String line = data.get(i);
sendMsg(msg, line);
String inAnswer = update.getMessage().getText();
String rAns = dataAnswers.get(i);
boolean flag = checkAnswer(inAnswer, rAns);
if (flag) {
this.currentUser.incrementScore();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
String finalString = "Поздравляю, ты ответил на " + this.currentUser.getScore() + "/" + this.sizeOfAnswers
+ " вопросов!";
sendMsg(msg, finalString);
}
}
Also here is maybe some multi user problems. How should I do it? Now it's showing all questions in one second without waiting for an answer.
How it's working now

Unhandled exception type URISyntaxException when trying to make links clickable in JTable

The aim is to make the link clickable in jtable so that when user clicks on the link the desired page gets opened in the browser. One of the items fetched from database is link and my attempt is to make it active and clickable. I get the error as
Unhandled exception type URISyntaxException
For the line in my code:
final URI uri = new URI("http://www.roseindia.net");
And even if i put it in try catch block, the error doesn't seem to resolve. Rather on surrounding in a try-catch block, I get the error as
Cannot refer to a non-final variable uri inside an inner class defined in a different method
So what could be the possible solution and fix?
public class JTableButtonMouseListener extends MouseAdapter
{
private final JTable table;
public JTableButtonMouseListener(JTable table)
{
this.table = table;
}
public void mouseClicked(MouseEvent e) {
counter=0;
// System.out.println("***************************************************************");
System.out.println("counter value="+counter++);
//System.out.println("/////////////////////////////////////////////////////////////////////");
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
// System.out.println("row clicked="+row);
//System.out.println("column clicked="+column);
System.out.println("object value="+value);
System.out.println(".............................................................");
/* public void getsecname(String s)
{
String ss=s;
}*/
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
// final URI uri = null;
// URI uri;
try{
final URI uri = new URI("http://www.roseindia.net");
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
// button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
} else {
}
}
});
}
// String link_string=ob.toString();
//ob.setClickable(true);
if(value==null)
{
Object v=table.getValueAt(row, 1);
//System.out.println("--------------------------------------------");
s = v.toString();
jmenu_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jmenu_frame.setContentPane(new ListModelExample(s));
jmenu_frame.setSize(260, 200);
jmenu_frame.setVisible(true);
jmenu_frame.setLocationRelativeTo(null);
//it ends here
}
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
You can not use non-final variable inside your inner class. Discussion.
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
try {
final URI uri = new URI("http://www.roseindia.net");
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
//button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
}
}
});
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
What is telling you is that you need a try catch block to handle a URISyntaxException:
final URI;
try{
uri = new URI("http://www.roseindia.net");
} catch (URISyntaxException e) {
e.printStackTrace();
}
To solve uri cannot be resolved to a variable You could instead of using try catch, add a throws URISyntaxException to the method in which uri is declared. But I do not think that is a good practice. Maybe it works in your case.

Emma instrumenting classes incorrectly

From working with EMMA I have noticed that it fails to instrument correctly causing the class to become mangled. Below is a simple example highlighting this issue.
public void showProblem() {
try {
for (int i = 0; i > 10; i++) {
System.out.println(i);
}
} catch (final Throwable e) {
System.err.println(e);
}
}
Instrumented class
public void showProblem()
{
boolean[][] tmp3_0 = $VRc; if (tmp3_0 == null) tmp3_0; boolean[] arrayOfBoolean = $VRi()[1]; int i = 0; arrayOfBoolean[0] = true; tmpTernaryOp = tmp3_0;
try
{
do
{
Throwable e;
System.out.println(e);
e++; arrayOfBoolean[1] = true; arrayOfBoolean[2] = true; } while (e > 10); arrayOfBoolean[3] = true;
}
catch (Throwable localThrowable1)
{
System.err.println(localThrowable1); arrayOfBoolean[4] = true;
}
arrayOfBoolean[5] = true;
}
Notice that it is attempting to increment e of type Throwable and using this within the while loop.
I have found that by moving the try catch logic within the for loop it resolves this. As highlighted in the below code.
public void showProblem() {
for (int i = 0; i > 10; i++) {
try {
System.out.println(i);
} catch (final Throwable e) {
System.err.println(e);
}
}
}
Instrumented class
public void showProblem()
{
boolean[][] tmp3_0 = $VRc; if (tmp3_0 == null) tmp3_0; boolean[] arrayOfBoolean = $VRi()[1]; int i = 0;
Throwable e;
arrayOfBoolean[0] = true; tmpTernaryOp = tmp3_0;
do {
try { System.out.println(i); arrayOfBoolean[1] = true;
} catch (Throwable localThrowable1) {
System.err.println(localThrowable1); arrayOfBoolean[2] = true;
}
i++; arrayOfBoolean[3] = true; arrayOfBoolean[4] = true; } while (i > 10);
arrayOfBoolean[5] = true;
}
Has anyone else experienced these issues?
Setup
Windows 7 64
Java 1.6.0_24 64-bit
Emma v2.0, build 5312
Solution
So it turned out that the problem was to do with the debug information that eclipse was building into the classes. This was observed when using the Android generated ant scripts to execute javac and similarly caused the problem. Disabling this enabled EMMA to successfully process the class files.
I hope this information will help others.
I have tested under Windows XP with Java JRE 1.6.0_35 and EMMA 2.0.5312 without any problems. For me the decompiled code (using JAD) looks like this:
public void showProblem()
{
boolean aflag[] = ($VRc != null ? $VRc : $VRi())[2];
try
{
int i = 0;
aflag[0] = true;
do
{
aflag[2] = true;
if (i > 10)
{
System.out.println(i);
i++;
aflag[1] = true;
} else
{
break;
}
} while (true);
aflag[3] = true;
}
catch (Throwable throwable)
{
System.err.println(throwable);
aflag[4] = true;
}
aflag[5] = true;
}
P.S.: I think in your code sample you actually wanted to use i < 10 in the for loop, not i > 10, didn't you? ;-) Anyway, I used your code just as to make sure to reproduce your situation.

How to initialize JTable before fill it?

I'm writing a code for a JTable that contains search results from a DB, and I need to initialize it with no rows in each click on "doSort" button by setRowCount(0) method or by initTable() method, I've wrote the following code, but it does not work:
private void doSortActionPerformed(java.awt.event.ActionEvent evt) {
try {
ArrayList<String> all = null;
String resStr = null;
mail = new Mail();
tm.setRowCount(0);
initTable(tm);
if(incomSelect.isSelected())
try {
all = mail.select("SELECT * FROM mails WHERE type = 'incoming'");
} catch (SQLException ex) {
}
else if(outcomSelect.isSelected())
try {
all = mail.select("SELECT * FROM mails WHERE type = 'outcoming'");
} catch (SQLException ex) {
}
for(int i=0; i<all.size(); i++) {
resStr = all.get(i);
String[] resArr = resStr.split(",");
tm.insertRow(i, resArr);
}
} catch (SQLException ex) {
}
}
And initTable() code:
public void initTable(DefaultTableModel mod){
for (int i = mod.getRowCount()-1; i >= 0; i--) {
mod.removeRow(i);
}
}

Categories

Resources