Logic in this method? - java

I am creating a java application to generate questions, and the method shown below is used to generate the questions. I have used a stack to order these questions by how many times they have appeared in the loop.
My problem is that it keeps producing multiple questions which are the same, which this method should prevent.
public ArrayList<String> generateQuestions(String transcript, String className, int classYear, String classGroup) {
ArrayList<String> results = new ArrayList<String>();
ArrayList<String> tags = new ArrayList<String>();
//get tags from the database
Statement stmt = null;
try {
stmt = handler.getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt != null){
try {
String result = "";
ResultSet rs = stmt.executeQuery("SELECT tags.TagName FROM class, tags, questtag, questions, questclass WHERE questtag.QuestionID = questions.QuestionID AND tags.TagID = questtag.TagID AND questions.QuestionID = questclass.QuestionID AND questclass.ClassID = class.ClassID AND class.ClassName ='"+className+"' AND class.ClassYear="+classYear+" AND class.ClassGroup ='"+classGroup+"' GROUP BY tags.TagID");
while (rs.next()) {
result = rs.getString(1);
tags.add(result);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Stack<Question> stack = new Stack<Question>();
for (String word : transcript.split("\\s+")) {
if( ! word.equalsIgnoreCase("the") || ! word.equalsIgnoreCase("I")) {
for(String tag : tags) {
if(word.equalsIgnoreCase(tag)) {
try {
stmt = handler.getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt != null){
try {
String result = "";
ResultSet rs = stmt.executeQuery("SELECT questions.Question FROM class, tags, questtag, questions, questclass WHERE questtag.QuestionID = questions.QuestionID AND tags.TagID = questtag.TagID AND questions.QuestionID = questclass.QuestionID AND questclass.ClassID = class.ClassID AND class.ClassName ='"+className+"' AND class.ClassYear="+classYear+" AND class.ClassGroup ='"+classGroup+"' AND tags.TagName = '"+tag+"'");
while (rs.next()) {
result = rs.getString(1);
Stack<Question> searchStack = new Stack<Question>();
boolean multiple = false;
if(stack.isEmpty()) { //1st question we've come to
Question question = new Question(result);
stack.push(question);
} else {
while(multiple == false && !stack.isEmpty()) {
//search through the stack
searchStack.push(stack.pop());
//if question is not already in the stack
if(((Question)searchStack.peek()).getQuestion().equalsIgnoreCase(result)) {
//then it is multiple
//add one to its noOfTimes
((Question)searchStack.peek()).addToNoOfTimes();
//order this above others with lower score
if(!stack.isEmpty()) {
if(((Question)stack.peek()).getNoOfTimes() < ((Question)searchStack.peek()).getNoOfTimes()) {
Question thisQuestion = searchStack.pop();
while(((Question)stack.peek()).getNoOfTimes() < thisQuestion.getNoOfTimes() && !stack.isEmpty()) {
searchStack.push(stack.pop());
}
stack.push(thisQuestion);
} else {
stack.push(searchStack.pop());
}
}
multiple = true;
}
}
while(!searchStack.empty())
stack.push(searchStack.pop());
if(multiple == false) {
Question question = new Question(result);
stack.push(question);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Stack<Question> reorderStack = new Stack<Question>();
while(!stack.empty()) {
reorderStack.push(stack.pop());
}
while(!reorderStack.empty()) {
Question thisQuestion = reorderStack.pop();
results.add(thisQuestion.getQuestion());
stack.push(thisQuestion);
}
}
}
}
}
}
return results;
}

Related

Data i've inserted into table does not replace old data, is there a way to replace data if it's already there?

Problem is the following: I am saving hashed password for a school project, however i am stuck on the syntax for the SQL statement to replace the data if it is already present. The table will only need to store a single username/password combination.
public class DatabaseManager {
String dbPath = "jdbc:sqlite:test.db";
public DatabaseManager () {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(dbPath);
if (conn != null) {
System.out.println("Connected to the database");
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
// Setting up database
databaseSetup(conn);
boolean tempInsertion = databaseInsert("pancake", "house", conn);
// Inserting data
if (tempInsertion) {
System.out.println("Data insertion failed");
}
// Retrieving data
List<String> retrievedData = databaseSelect(conn);
if (retrievedData == null) {
System.out.println("Data extraction failed");
}
else {
System.out.println(retrievedData.size());
}
conn.close();
}
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private boolean databaseInsert(String username, String password, Connection conn) {
String sqlInsert = "INSERT OR REPLACE INTO login(username, password) VALUES(?,?)";
PreparedStatement prepStatement;
try {
prepStatement = conn.prepareStatement(sqlInsert);
prepStatement.setString(1, encrypt(username));
prepStatement.setString(2, encrypt(password));
prepStatement.executeUpdate();
} catch (SQLException e) {
return false;
}
return true;
}
private List<String> databaseSelect(Connection conn) {
List<String> tempList = new ArrayList<String>();
String sqlSelect = "SELECT * FROM login";
Statement stmt;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlSelect);
tempList.add(rs.getString("username"));
tempList.add(rs.getString("password"));
int columnsNumber = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rs.getMetaData().getColumnName(i));
}
System.out.println("");
}
} catch (SQLException e) {
return null;
}
return tempList;
}
private void databaseSetup( Connection conn) {
String sqlExpression = "CREATE TABLE login (username varchar(255), password varchar(255))";
try {
Statement statement = conn.createStatement();
statement.execute(sqlExpression);
} catch (SQLException e) {}
}
private String encrypt(String string) {
try {
MessageDigest exampleCrypt = MessageDigest.getInstance("SHA1");
exampleCrypt.reset();
exampleCrypt.update(string.getBytes("UTF-8"));
return convertByte(exampleCrypt.digest());
}
catch(NoSuchAlgorithmException e) {
System.out.println("Error, cannot encrypt string");
e.printStackTrace();
}
catch(UnsupportedEncodingException e) {
System.out.println("Error, cannot encrypt string");
e.printStackTrace();
}
return null;
}
private static String convertByte(final byte[] hash) {
Formatter formatter1 = new Formatter();
for (byte i : hash) {
formatter1.format("%02x", i);
}
String encryptedData = formatter1.toString();
formatter1.close();
return encryptedData;
}
}
The problem as stated, is that i'd like to only store a single password/username combination at a time, as a hash. However, when this happens it duplicates the hash combination, instead of replacing it.

Using JRadioButtons with a derby database

I am trying to use the user's selection of a JRadioButton as part of a SELECT query for a derby database. For some reason, when I click the search button (called diffSearchbtn), nothing happens. What should be happening is that the SELECT query puts all the entries that match the criteria of the radio button into a JTable on a panel called dispPanel.
Here is the code for the method that assigns a string based on what button the user clicks.
private String tagValid()
{
String diff = "";
if (dEasybtn.isSelected())
{
diff = "EASY";
System.out.println("easy");
}
else if (dMedbtn.isSelected())
{
diff = "MEDIUM";
System.out.println("medium");
}
else if (dHardbtn.isSelected())
{
diff = "HARD";
System.out.println("hard");
}
else
{
diff = null;
}
return null;
}
Here is the code that is meant to display the form:
private void diffSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
if(tagValid()!=null)
{
String q = String.format("Select* from Gabby.PData where DIFFICULTY = '%d'", tagValid());
ResultSet res = Backend.query(q);
guiTable.setModel(DbUtils.resultSetToTableModel(res));
int counter = 3;
try
{
while (res.next()) {
counter++;
System.out.println("increasing counter");
}
}
catch (SQLException ex) {
Logger.getLogger(WikiPlantGUI.class.getName()).log(Level.SEVERE, null, ex);
}
if (counter == 0)
{
basePanel.removeAll();
basePanel.add(NoMatchPanel);
basePanel.repaint();
basePanel.revalidate();
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
}
}
Here is the code from the class Backend:
public static ResultSet query(String q)
{
try {
System.out.println("a query");
Statement stat = myConObj.createStatement();
ResultSet res = stat.executeQuery(q);
return res;
}
catch (SQLException e)
{
e.printStackTrace(); // tells what the error is
return null; // returns nothing
}
}
GUI screenshot
There are no error messages, and the program otherwise runs perfectly. Any idea on what's going wrong?

java, sonar, Cyclomatic Complexity

can anyone help me to reduce cylomatic complexity for below method upto 10..also considering no nesting of if else is allow as it will also cause sonar issue.
It will be great help for me
private void processIntransitFile(String fileName) {
if (StringUtils.isNotBlank(fileName))
return;
// read Intransit folder and do the processing on these files
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(intransitDir + fileName))) {
TokenRangeDTO tokenRangeDTO = new TokenRangeDTO();
int count = 0;
String header = "";
String next;
String line = bufferedReader.readLine();
LinkedHashSet<String> tokenRanges = new LinkedHashSet<>();
int trCount = 0;
boolean first = true;
boolean last = line == null;
while (!last) {
last = (next = bufferedReader.readLine()) == null;
if (!first && !last) {
tokenRanges.add(line);
}
// read first line of the file
else if (first && line.startsWith(H)) {
header = line;
first = false;
} else if (first && !line.startsWith(H)) {
tokenRangeDTO.setValidationMessage(HEADER_MISSING);
first = false;
}
// read last line of the file
else if (last && line.startsWith(T)) {
trCount = getTrailerCount(tokenRangeDTO, line, trCount);
} else if (last && !line.startsWith(T)) {
tokenRangeDTO.setValidationMessage(TRAILOR_MISSING);
}
line = next;
count++;
}
processInputFile(fileName, tokenRangeDTO, count, header, tokenRanges, trCount);
} catch (IOException e) {
LOGGER.error(IO_EXCEPTION, e);
} catch (Exception e) {
LOGGER.error("Some exception has occured", e);
} finally {
try {
FileUtils.deleteQuietly(new File(intransitDir + fileName));
} catch (Exception ex) {
LOGGER.error(STREAM_FAILURE, ex);
}
}
}
can anyone help me to reduce cylomatic complexity for below method upto 10..also considering no nesting of if else is allow as it will also cause sonar issue.
It will be great help for me
You could extract part of your code to methods and/or refactor some variables which could be used in other way. Also, when you have comments explaining your code it is a strong indicator that your logic can be improved there:
private void processIntransitFile(String fileName) {
if (StringUtils.isNotBlank(fileName)) return;
processFromIntransitDirectory(fileName);
}
private void processFromIntransitDirectory(String fileName) {
try (BufferedReader bufferedReader = new BufferedReader(getFileFromIntransitFolder(fileName))) {
TokenRangeDTO tokenRangeDTO = new TokenRangeDTO();
int count = 0;
String header = "";
String next;
String line = bufferedReader.readLine();
LinkedHashSet<String> tokenRanges = new LinkedHashSet<>();
int trCount = 0;
while (!isLastLine(line)) {
next = bufferedReader.readLine();
if (!isFirstLine(count) && !isLastLine(next)) {
tokenRanges.add(line);
}
header = readFirstLine(line, count, tokenRangeDTO);
trCount = readLastLine(line, next, trCount, tokenRangeDTO);
line = next;
count++;
}
processInputFile(fileName, tokenRangeDTO, count, header, tokenRanges, trCount);
} catch (IOException e) {
LOGGER.error(IO_EXCEPTION, e);
} catch (Exception e) {
LOGGER.error("Some exception has occured", e);
} finally {
try {
FileUtils.deleteQuietly(new File(intransitDir + fileName));
} catch (Exception ex) {
LOGGER.error(STREAM_FAILURE, ex);
}
}
}
private boolean isLastLine(String line) {
return line != null;
}
private String readFirstLine(String line, int count, TokenRangeDTO tokenRangeDTO) {
if (isFirstLine(count) && isHeader(line)) {
return line;
} else if (isFirstLine(count) && !isHeader(line)) {
tokenRangeDTO.setValidationMessage(HEADER_MISSING);
}
return StringUtils.EMPTY;
}
private int readLastLine(String line, String next, int trCount, TokenRangeDTO tokenRangeDTO){
if (isLastLine(next) && isTrailor(line)) {
return getTrailerCount(tokenRangeDTO, line, trCount);
} else if (last && !isTrailor(line)) {
tokenRangeDTO.setValidationMessage(TRAILOR_MISSING);
}
return 0;
}
private boolean isTrailor(String line) {
return line.startsWith(T);
}
private boolean isHeader(String line) {
return line.startsWith(H);
}
private boolean isFirstLine(int count) {
return count == 0;
}
private FileReader getFileFromIntransitFolder(String fileName) {
return new FileReader(intransitDir + fileName);
}
Doing this your code will be more readable, you will avoid useless variables using logic and your cyclomatic complexity will decrease.
For more tips, I recommend access refactoring.guru.

indexof string matching from data base and runtime text

I want to make website blocker in my web browser, so I made a database which contain the names of website. Now I want to check the string from database with indexOf method, but it is giving me an error while I am trying to check. Please tell me where my mistake is. Rest of the code is correct and working only database part is not working.
public void loadURL(final String url) {
try {
Connection myconnection;
myconnection = DriverManager.getConnection("jdbc:mysql://localhost/bookmarks", "roo t", "");
try {
String q = "select * from block where url=?";
PreparedStatement mysat = myconnection.prepareStatement(q);
ResultSet myresult = mysat.executeQuery();
int index1;
while (myresult.next()) {
String s2 = myresult.setString("url");
String s1 = txtURL.getText();
index1 = s1.indexOf(s2);
}
if (index1 == -1) {
JOptionPane.showMessageDialog(rootPane, "You Cannot access this website", "Error", JOptionPane.ERROR_MESSAGE);
} else {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myconnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if you use PreparedStatement you have to set a
value for each ? marker:
String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");
without you have an invalid sql syntax.

Running SQL script file through Java

In order to execute a whole SQL script file[which includes create table statements and some rules defining create table]. I found this solution in order to achieve it --->"There is great way of executing SQL scripts from Java without reading them yourself as long as you don't mind having a runtime dependency on Ant. In my opinion such a dependency is very well justified in your case. Here is sample code, where SQLExec class lives in ant.jar:
private void executeSql(String sqlFilePath) {
final class SqlExecuter extends SQLExec {
public SqlExecuter() {
Project project = new Project();
project.init();
setProject(project);
setTaskType("sql");
setTaskName("sql");
}
}
SqlExecuter executer = new SqlExecuter();
executer.setSrc(new File(sqlFilePath));
executer.setDriver(args.getDriver());
executer.setPassword(args.getPwd());
executer.setUserid(args.getUser());
executer.setUrl(args.getUrl());
executer.execute();
}
I don't know whether it will work or not!!!
Can anybody give some hints to work on the above solution? I mean how to get the code work and also let me know any other solution to execute SQL script files!!!
Thanks,
Mahesh
This is a code snippet I stole from the internet somewhere (I don't remember where) that I know works great: it wont run the way that it is below. It might give you enough clues to get yours working though, or you might find the source on Google somewhere:
private void runScriptOnce(Connection conn, Reader reader) throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}

Categories