I've written this code, but when run, it shows the error
sql command not properly ended
How can I fix it?
DatabasetableUI
public class DatabasetableUI extends UI {
#Override
protected void init(VaadinRequest request) {
DatabaseTableScreen screen = new DatabaseTableScreen();
try {
JDBCConnectionPool connectionPool = new SimpleJDBCConnectionPool( "oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:#usadc-sdbxt21:1521:GFRWMUAT","user", "password");
screen.populate("case_upload_history", connectionPool);
} catch (SQLException e) {
//System.out.println("Application");;
throw new RuntimeException( e.getMessage());
} enter code here
setContent( screen);
}
}
DatabaseTableScreen
public class DatabaseTableScreen extends VerticalLayout {private SQLContainer container;
private Table table;
public DatabaseTableScreen() {
setMargin( true);
table = new Table();
table.setPageLength( 10);
table.setEditable( true);
table.setSizeFull();
enter code here
//table.addGeneratedColumn("",new RemoveItemColumnGenerator());
addComponent(table);
}
public void populate( String tableName, JDBCConnectionPool connectionPool) {
QueryDelegate query = new TableQuery( tableName, connectionPool);
try {
container=new SQLContainer(query);
table.setContainerDataSource( container);
} catch (SQLException e) {
throw new RuntimeException( e);
}
}
}
Use the third argument to the TableQueryconstructor, like this:
QueryDelegate query = new TableQuery( tableName, connectionPool, new OracleGenerator());
Related
I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.
public class LoginWindow {
public void CreateLoginWindow () {
/** Set Style to Main Frame **/
JFrame main_window = new JFrame();
main_window.setUndecorated(true);
main_window.setLocationRelativeTo(null);
main_window.setLayout(new BorderLayout());
main_window.setLayout(new FlowLayout());
main_window.setVisible(false);
main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
main_window.setSize(1920,1080);
main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/** Some Codes **/
JButton login_button = new JButton("Click to Exit");
login_button.setBounds(920,480,120,45);
/** Login Button Action **/
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
main_window.dispose();
}
});
main_window.add(login_button);
main_window.setVisible(true);
}
}
It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.
And this is my ValidateLogin Class :
public class ValidateLogin {
public Boolean ValidateLoginAction (String username, String password){
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
if ( right_password.equals(password) ){
return true;
} else {
return false;
}
}
}
And this is my ConnectToDB Class :
public class ConnectToDB {
/** Connect to Database **/
private Connection connect() {
String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return connection;
}
/** Get Password of an Username **/
public String GetPassOfAnUsername(String username){
String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";
try (Connection connection = this.connect();
PreparedStatement statement= connection.prepareStatement(password);
ResultSet results = statement.executeQuery()) {
return results.getString("Password");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
}
And this is my MainWindow Class :
public class MainWindow {
public static void main(String[] args) {
LoginWindow loginWindow = new LoginWindow();
loginWindow.CreateLoginWindow();
}
}
I have tried and I am able to close the window and jvm exits also. I provide below the button action code snippet.
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
}
catch(Exception ex) {
//handle exception
}
finally {
main_window.dispose();
}
}
});
Have the username_field and password_field variables been instantiated somewhere? Perhaps the line where you are accessing the getText() method is throwing a NullPointerException when the actionPerformed method is being called and so the program never reaches the main_window.dispose() line.
Try checking if both of those variables are null when the actionPerformed method is being executed before you try to access the getText() method from them.
On a further note, check if the connection the database is being established successfully.
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
The second line might also throw a NullPointerException in case validate_login is null because your code will return null from your ConnectToDB() constructor in case the connection fails.
I am using ORMLite framework on an android project and I am stuck while using OpenHelperManager.getHelper() on multiple repo classes.
Here is a brief of my code structure :-
DatabaseHelper class which is responsible for creating database and tables
public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
public static String DATABASE_NAME = "muffet.db";
public static int DATABASE_VERSION = 5;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
}
#Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
// Creating tables
try {
TableUtils.createTable(connectionSource, Category.class);
TableUtils.createTable(connectionSource, Transaction.class);
TableUtils.createTable(connectionSource, Budget.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Category.class, true);
TableUtils.dropTable(connectionSource, Transaction.class, true);
TableUtils.dropTable(connectionSource, Budget.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
TransactionRepo which is responsible for accessing database.
public class TransactionRepo extends DatabaseHelper {
// private Dao<Transaction, Integer> transactionDao = null;
private RuntimeExceptionDao<Transaction, Integer> transactionRuntimeDao = null;
public TransactionRepo(Context context) {
super(context);
}
public RuntimeExceptionDao<Transaction, Integer> getTransactionRuntimeDao(){
if(transactionRuntimeDao == null){
transactionRuntimeDao = getRuntimeExceptionDao(Transaction.class);
}
return transactionRuntimeDao;
}
/**
* Save Transaction to database
*/
public void save(Transaction transaction){
try {
transactionRuntimeDao = getTransactionRuntimeDao();
transactionRuntimeDao.createOrUpdate(transaction);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Get all list of data
*/
public List<Transaction> getAll(){
try{
transactionRuntimeDao = getTransactionRuntimeDao();
return transactionRuntimeDao.queryForAll();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
TransactionServiceImpl which is a service class for getting data from the TransactionRepo
public class TransactionServiceImpl implements TransactionService {
TransactionRepo transactionRepo;
#Override
public void save(Transaction transaction, Activity activity) {
transactionRepo = OpenHelperManager.getHelper(activity, TransactionRepo.class);
transactionRepo.save(transaction);
OpenHelperManager.releaseHelper();
}
#Override
public List<Transaction> getAll(Activity activity) {
transactionRepo = OpenHelperManager.getHelper(activity, TransactionRepo.class);
List<Transaction> transactionList = transactionRepo.getAll();
OpenHelperManager.releaseHelper();
return transactionList;
}
}
It works fine when I run it. But when I try to access some another repository class which extends DatabaseHelper , and use the OpenHelperManager.getHelper() like for example :-
CategoryRepo categoryRepo = OpenHelperManager.getHelper(activity, CategoryRepo.class);
I get error as java.lang.IllegalStateException: Helper class was class com.muffet.persistence.repository.TransactionRepo but is trying to be reset to class com.muffet.persistence.repository.CategoryRepo
This clearly means that the OpenHelperManager has saved instance of TransactionRepo and when I try to get and set it as CategoryRepo it is unable to cast or something like that.
How can I solve this issue?
Thank you
public static synchronized void releaseHelper() {
instanceCount--;
logger.trace("releasing helper {}, instance count = {}", helper, instanceCount);
if (instanceCount <= 0) {
if (helper != null) {
logger.trace("zero instances, closing helper {}", helper);
helper.close();
helper = null;
wasClosed = true;
}
if (instanceCount < 0) {
logger.error("too many calls to release helper, instance count = {}", instanceCount);
}
}
}
The releasetHelper method did not reset helperClass static menber:
private static Class<? extends OrmLiteSqliteOpenHelper> helperClass = null;
So when you want to getHelper of another class, as below said:
private static void innerSetHelperClass(Class<? extends OrmLiteSqliteOpenHelper> openHelperClass) {
// make sure if that there are not 2 helper classes in an application
if (openHelperClass == null) {
throw new IllegalStateException("Helper class was trying to be reset to null");
} else if (helperClass == null) {
helperClass = openHelperClass;
} else if (helperClass != openHelperClass) {
throw new IllegalStateException("Helper class was " + helperClass + " but is trying to be reset to "
+ openHelperClass);
}
}
Thus even your previous helperclass('helperClass') is parent of your later helperclass('openHelperClass'), but still, not equal. That's the reason for exception you seen.
My suggestion is to call
OpenHelperManager.setOpenHelperClass(CategoryRepo.class);
before
CategoryRepo categoryRepo = OpenHelperManager.getHelper(activity, CategoryRepo.class);
I'm newly with Guice.
I want to use Guice for initializing object without writing new directly.
Here is my main():
public class VelocityParserTest {
public static void main(String[] args) throws IOException {
try {
PoenaRequestService poenaService = new PoenaRequestService();
System.out.println(poenaService.sendRequest("kbkCode"));
} catch (PoenaServiceException e) {
e.printStackTrace();
}
}
}
PoenaRequestService:
public class PoenaRequestService {
private static final String TEMPLATE_PATH = "resources/xml_messages/bp12/message01.xml";
public static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PoenaRequestService.class);
#Inject
#Named("poena_service")
private HttpService poenaService;
public String sendRequest(/*TaxPayer taxPayer,*/ String kbk) throws PoenaServiceException {
LOG.info(String.format("Generating poena message request for string: %s", kbk));
Map<String, String> replaceValues = new HashMap<>();
replaceValues.put("guid", "guid");
replaceValues.put("iinbin", "iinbin");
replaceValues.put("rnn", "rnn");
replaceValues.put("taxOrgCode", "taxOrgCode");
replaceValues.put("kbk", "kbk");
replaceValues.put("dateMessage", "dateMessage");
replaceValues.put("applyDate", "applyDate");
ServiceResponseMessage result;
try {
String template = IOUtils.readFileIntoString(TEMPLATE_PATH);
Document rq = XmlUtil.parseDocument(StringUtils.replaceValues(template, replaceValues));
result = poenaService.execute(HttpMethod.POST, null, rq);
} catch (IOException e) {
throw new PoenaServiceException("Unable to read template file: " + TEMPLATE_PATH, e);
} catch (SAXException e) {
throw new PoenaServiceException("Unable to parse result document, please check template file: " + TEMPLATE_PATH, e);
} catch (HttpServiceException e) {
throw new PoenaServiceException(e);
}
if (result.isSuccess()) {
return (String) result.getResult();
}
throw new PoenaServiceException("HTTP service error code '" + result.getStatusCode() + "', message: " + result.getStatusMessage());
}
}
When I tried to debug this I see next picture:
As e result I got NullPointerException.
I couldn't figure out this behavior. Why does this exactly happen?
Any suggestions?
It's not working because you're not actually using Guice. You need to create an injector and bind your dependencies to something. Something akin to this:
public class VelocityParserTest {
public static void main(String[] args) throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() {
#Override
protected void configure() {
bind(PoenaRequestService.class).asEagerSingleton();
bind(HttpService.class)
.annotatedWith(Names.named("poena_service"))
.toInstance(...);
}
});
try {
PoenaRequestService poenaService = injector.getInstance(PoenaRequestService.class);
System.out.println(poenaService.sendRequest("kbkCode"));
} catch (PoenaServiceException e) {
e.printStackTrace();
}
}
}
I have a REST service accepting POST requests. Is there any way I can trigger a method inside my running swing GUI from that service? I want to make it possible to refresh the GUI table of posted data after every POST request is made. Is there any event handling mechanism for doing this?
REST service code:
#POST
#Consumes({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
#Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
public Response createServiceRegistration(
#PathParam("serviceProviderId") final String serviceProviderId ,
final ServiceRegistration aServiceRegistration
) throws IOException, ServletException
{
try
{
ServiceRegistration newServiceRegistration = OrchestratorAdaptorManager.createServiceRegistration(httpServletRequest, aServiceRegistration, serviceProviderId);
httpServletResponse.setHeader("ETag", OrchestratorAdaptorManager.getETagFromServiceRegistration(newServiceRegistration));
/////////////////////////////////////////////////////
// Accessing and writing registration data to database
//
try
{
System.out.println("establishing database connection");
Registration registration = new Registration();
registration.createConnection();
registration.insertRegistration(aServiceRegistration.getService().toString(), aServiceRegistration.getTitle(), aServiceRegistration.getLabel());
registration.shutdown();
}
catch(Exception exc)
{
exc.printStackTrace();
throw new RuntimeException("Error inserting ServiceRegistration to the database", exc);
}
//
// Disconnected from the base
///////////////////////////////////////////////////
return Response.created(newServiceRegistration.getAbout()).entity(aServiceRegistration).build();
}
catch (Exception e)
{
e.printStackTrace();
throw new WebApplicationException(e);
}
//Trigger changes in GUI here :/
}
Class which I used to update the table every 10 seconds:
class CheckServices extends TimerTask
{
DefaultTableModel model;
protected CheckServices(DefaultTableModel model)
{
this.model = model;
}
#Override
public void run()
{
Registration reg = new Registration();
try
{
reg.createConnection();
ServiceRegistration[] sr = reg.selectRegistrations();
reg.shutdown();
System.out.println("Adding Registration Resources");
int rows = model.getRowCount();
for(int i = 0; i < rows; i++)
{
model.removeRow(0);
}
for(ServiceRegistration srItem : sr)
{
System.out.println("--> " + srItem.getTitle());
Object[] row = { false , srItem.getService().toString(), srItem.getTitle(), srItem.getLabel()};
model.addRow(row);
}
}
catch (URISyntaxException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have a main frame that has a list and "add" button. When I click on the 'add' button, one frame will be shown that I can enter name, family and id.
And by clicking on the "addAPerson", the name will be stored in the SQL. But when I close the frame, the new person will not be added to my list which is in my main frame but if I close the main frame and run it again, the new person will be added to the list.
How can I update the JList without running the main frame?
My main frame (a part of that):
public class ListFrame extends javax.swing.JFrame {
private InformationClass client;
private DefaultListModel model = new DefaultListModel();
/** Creates new form ListFrame. */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
fillTable();
}
public void fillTable() {
try {
List<InformationClass> list = null;
list = Manager.getClientListFromMySQL();
if (list == null) {
JOptionPane.showMessageDialog(
this,
"You should add a person to your list",
"Information",
JOptionPane.OK_OPTION);
return;
}
else {
for (int i = 0; i < list.size(); i++) {
InformationClass list1 = list.get(i);
model.add(i, list1.getId());
}
jList1.setModel(model);
}
}
catch (SQLException ex) {
Logger.getLogger(
ListFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My frame which will be shown when you click on the add button (a part of that):
public class Add extends javax.swing.JFrame {
private InformationClass client;
public Add(InformationClass client) {
initComponents();
this.client = client;
}
private void addAPersonActionPerformed(java.awt.event.ActionEvent evt) {
submit();
clear();
}
private void submit() {
String s1 = nameF.getText();
String s2 = familyF.getText();
String s3 = iDf.getText();
if (s1.equals("") || s2.equals("") || s3.equals("")) {
JOptionPane.showMessageDialog(
this,
"fill the empty name/family/id text fields",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else {
try {
boolean b = Manager.isAddPerson(s1, s2, s3);
if (b == false) {
Manager.addPerson(s1, s2, s3);
JOptionPane.showMessageDialog(
this,
"The person has been added successfully",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(
this,
"These datas has been added before!!",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
My Manager class (a part of that):
public static void addPerson(String name, String family, String yahooId) {
PreparedStatement pstmt;
String query;
try {
query = ("INSERT INTO newpersontable(name,family,yahooId) VALUES(?,?,?)");
pstmt = (PreparedStatement) conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, family);
pstmt.setString(3, yahooId);
pstmt.executeUpdate();
}
catch (SQLException e) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, e);
}
}
An implementation of the Observer pattern will do the trick.
Your InformationClass calls the Manager to add a person, if it is not already known. But you want that new person appear in the ListFrame. With the Observer pattern, the ListFrame will observe the Manager if it has some added, changed or deleted records. If it is the case, the ListFrame can update itself with the actual values, that it just requests again from the Manager.
We need one additional interface, a Listener and some methods on the Manager, that's all.
Here's a basic implementation:
public interface PersonsModelChangeListener {
public void modelHasChanged();
}
In Manager, add the following fields and methods:
List<PersonsModelChangeListener> listeners = new ArrayList<PersonsModelChangeListener>();
public void addListener(PersonsModelChangeListener listener) {
listeners.add(listener);
}
private void fireModelChangeEvent() {
for (PersonsModelChangeListener listener:listeners) {
listener.modelHasChanged();
}
}
Add the following line to the add method of Manager:
public void add(String s1, String s2, String s3) {
// existing code
fireModelChanged();
}
Next step: make ListFrame implement the PersonsModelChangeListener interface and implement the modelHasChanged method so that ListFrame can 'get' the actual values whenever the Managers data set has changed.
Edit
public class Manager {
// existing code
private static List<PersonsModelChangeListener> listeners = new ArrayList<PersonsModelChangeListener>();
public static void addListener(PersonsModelChangeListener listener) {
listeners.add(listener);
}
private static void fireModelChangeEvent() {
for (PersonsModelChangeListener listener:listeners) {
listener.modelHasChanged();
}
}
public static void addPerson(String name, String family, String yahooId) {
PreparedStatement pstmt;
String query;
try {
query = ("INSERT INTO newpersontable(name,family,yahooId) VALUES(?,?,?)");
pstmt = (PreparedStatement) conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, family);
pstmt.setString(3, yahooId);
pstmt.executeUpdate();
fireModelChangedEvent();
} catch (SQLException e) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, e);
}
}
public class ListFrame extends javax.swing.JFrame implements PersonsModelChangeListener {
// your fields
/** Creates new form ListFrame */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
fillTable();
Manager.addListener(this);
}
#Override
public void modelHasChanged() {
// this method will be called when you add something with the
// Manager.
// Add your code here to get the actual data from the Manager
// and update this component
}
}
Hope it helps :)
In the submit method save the created person and create a field for it which you can 'get' from the actionPerformed method for the 'add' button in the ListFrame class. Then just add it to the list model.
you just call the update method at the end of your coding.the update method should display the table.So when you add some thing to the list it will get updated in the database. so at the end of your coding it will call the update method which will display the updated table.Hopu u got my point