I have a problem with syntax SQL. When i mvn jetty:run then occur following error:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "user" at
line 1, co lumn 14.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknow
n Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source
)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException
(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Un
known Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown So
urce)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown So
urce)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
reateTableNotExist(CustomContextLoaderListener.java:68)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
reateTable(CustomContextLoaderListener.java:48)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
ontextInitialized(CustomContextLoaderListener.java:36)
Here file CustomContextLoaderListene which encouter error:
package edu.java.spring.service.user.controller;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
public class CustomContextLoaderListener extends ContextLoaderListener{
#Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("hibernate shutdown database");
try {
DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/userdb;shutdown=true");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n Spring-MVC application destroyed \n");
super.contextDestroyed(event);
}
#Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("\n Spring-MVC application inited \n");
try {
createTable();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.contextInitialized(event);
}
public void createTable() throws SQLException{
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection connection = DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/subjectdb;create=true");
createTableNotExist(connection,"user", "create table user"
+ "(username varchar(1000) primary key,"
+ "password varchar(1000),birthday date,"
+ "age integer,gender varchar(100))");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createTableNotExist(Connection connection,
String tableName,String createTableSQL) throws SQLException{
DatabaseMetaData dbmd = connection.getMetaData();
ResultSet rs = dbmd.getTables(null, null,tableName.toUpperCase(), null);
if (rs.next()){
System.out.println("Table" + rs.getString("TABLE_NAME") + "already exists");
return;
}
Statement statement = connection.createStatement();
statement.execute(createTableSQL);
System.out.println("\n\n executed" + createTableSQL + "\n\n");
statement.close();
}
}
"user" it is a built-in function in derby. Enter another table name and it should start work
Related
we migrated a websphere j2ee app to spring boot. Everything looked great but now we found out that the message listeners are sometimes processing some messages twice.
It looks like to me it happens when one message is been processed and not yet commited, an other concurrent consumer can get the same message and also process it.
Looks like the message broker doesn't hold it back, doesn't reserves it for consumer 1.
import bitronix.tm.resource.jms.PoolingConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.transaction.PlatformTransactionManager;
import javax.jms.ConnectionFactory;
import javax.jms.Session;
import java.util.Properties;
#Configuration
#EnableJms
#EnableCaching(proxyTargetClass = true)
public class JmsConfig {
#Bean
ConnectionFactory jmsXAConnectionFactory() {
PoolingConnectionFactory connectionFactory = new PoolingConnectionFactory();
connectionFactory.setClassName("com.ibm.mq.jms.MQXAQueueConnectionFactory");
connectionFactory.setUniqueName("mq-xa-" + appName);
connectionFactory.setAllowLocalTransactions(true);
connectionFactory.setTestConnections(false);
connectionFactory.setUser(user);
connectionFactory.setPassword(password);
connectionFactory.setMaxIdleTime(1800);
connectionFactory.setMinPoolSize(1);
connectionFactory.setMaxPoolSize(25);
connectionFactory.setAcquisitionTimeout(60);
connectionFactory.setAutomaticEnlistingEnabled(true);
connectionFactory.setDeferConnectionRelease(true);
connectionFactory.setShareTransactionConnections(false);
Properties driverProperties = connectionFactory.getDriverProperties();
driverProperties.setProperty("queueManager", queueManager);
driverProperties.setProperty("hostName", connName);
driverProperties.setProperty("port", "1414");
driverProperties.setProperty("channel", channel);
driverProperties.setProperty("transportType", "1");
driverProperties.setProperty("messageRetention", "1");
return connectionFactory;
}
#Primary
#Bean
public BitronixTransactionManager btronixTransactionManager() throws SystemException {
TransactionManagerServices.getConfiguration().setServerId("bitronix-tm-" + appName);
TransactionManagerServices.getConfiguration().setLogPart1Filename(jtaLogDir + "/btm1.tlog");
TransactionManagerServices.getConfiguration().setLogPart2Filename(jtaLogDir + "/btm2.tlog");
TransactionManagerServices.getTransactionManager().setTransactionTimeout(180);
return TransactionManagerServices.getTransactionManager();
}
#Bean
public PlatformTransactionManager platformTransactionManager(
BitronixTransactionManager transactionManager, UserTransaction userTransaction) {
return new JtaTransactionManager(userTransaction, transactionManager);
}
#Bean("wgstatusML")
public DefaultMessageListenerContainer wagenstatusMessageListenerContainer(
ConnectionFactory jmsXAConnectionFactory,
PlatformTransactionManager jtaTransactionManager,
#Qualifier("wagenstatusBean") WagenstatusBean wagenstatusBean) {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
container.setConnectionFactory(jmsXAConnectionFactory);
container.setTransactionManager(jtaTransactionManager);
container.setDestinationName(WAGENSTATUS_QUEUE);
container.setMessageListener(wagenstatusBean);
container.setAutoStartup(false);
container.setConcurrentConsumers(2);
container.setClientId("wgstatListener");
container.setSessionTransacted(false);
container.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
return container;
}
}
#Service("wagenstatusBean")
#Scope(SCOPE_PROTOTYPE)
public class WagenstatusBean extends AbstractMDB {
#Transactional(propagation = REQUIRED)
public void onMessage(javax.jms.Message msg) {
String localMessageText = null;
try {
try {
localMessageText = ((TextMessage) msg).getText();
} catch (JMSException e) {
}
// here goes the actual call to the impl
String errmsg = null;
readableMessageID = null;
try {
verarbeiteMeldung(msg);
} catch (InvalidMessageException ime) {
errmsg = ime.getMessage();
}
if (sendMessageToErrorQueue) {
// generate business logging entry
try {
logBusinessData(localMessageText, BusinessLogger.STATUS_ERROR);
} catch (Exception e) {
LOGGER.error("", e);
}
if (localMessageText != null) {
localMessageText = this.addErrorMessageToXML(localMessageText, errmsg);
}
DispatcherServiceLocator.getDispatcherBean().sendToDestination(
QueueNames.WAGENSTATUS_ERROR_QUEUE, localMessageText);
}
} catch (ConsistencyException ex) {
// ConsistencyException used internally in the EJBEnv
// framework/template needs to be catched and translated into an EJBException
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();;
// generate business logging entry
try {
// UE03772, RfC 169: BUSINESS LOGGING POINT
logBusinessData(localMessageText, BusinessLogger.STATUS_ERROR);
} catch (Exception e) {
LOGGER.error("", e);
}
LOGGER.error("Caught a ConsistencyException in WagenStatus-onMessage", ex);
} catch (RuntimeException ex) {
// this catching is done for logging purpouse only.
LOGGER.error("Caught a RuntimeException in WagenStatus-onMessage", ex);
// generate business logging entry
try {
logBusinessData(localMessageText, BusinessLogger.STATUS_ERROR);
} catch (Exception e) {
LOGGER.error("", e);
}
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();;
}
}
How can I create a Spring Aspect (annotation driven e.g. #ExceptionTranslation) surrounding an entire method and put this method in a try...catch method?
#ExceptionTranslation
public void method() {
// do some stuff here...
}
so logically it does:
public void method() {
try {
// do some stuff here ...
} catch( Exception ex ) {
}
}
Below you can find a sample implementation of AfterThrows advice solving your problem.
CustomException.java
package com.yourpackage;
public class CustomException extends Exception {
public CustomException(final Throwable cause) {
super(cause);
}
}
ErrorBean.java
package com.yourpackage;
public class ErrorBean {
#ExceptionTranslation
public void translatedException() throws Exception {
throw new Exception("Foo");
}
public void notTranslatedException() throws Exception {
throw new Exception("Bar");
}
}
ExceptionTranslation.java
package com.yourpackage;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface ExceptionTranslation {
}
SimpleThrowsAdvice.java
package com.yourpackage;
import org.springframework.aop.Advisor;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
public class SimpleThrowsAdvice implements ThrowsAdvice {
public static void main(String[] args) throws Exception {
ErrorBean errorBean = new ErrorBean();
AnnotationMatchingPointcut pc = AnnotationMatchingPointcut.forMethodAnnotation(ExceptionTranslation.class);
SimpleThrowsAdvice advice = new SimpleThrowsAdvice();
Advisor advisor = new DefaultPointcutAdvisor(pc, advice);
ProxyFactory pf = new ProxyFactory();
pf.setTarget(errorBean);
pf.addAdvisor(advisor);
ErrorBean proxy = (ErrorBean) pf.getProxy();
try {
proxy.translatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
try {
proxy.notTranslatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
}
public void afterThrowing(Exception ex) throws Throwable {
System.out.println("***");
System.out.println("Generic Exception Capture");
System.out.println("Caught: " + ex.getClass().getName());
System.out.println("***\n");
throw new CustomException(ex);
}
}
im trying to connect my java to db2 database but im getting an error :
"Execution failed due to a distribution protocol error that will affect the successful execution of subsequent DDM commands or SQL statements.
A connection could not be established to the database because manager 0x2407 at level 0x3 is not supported."
What do you think im doing wrong? Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class conUrl {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://host:50000/test";
String user="dbuser";
String password="passwrod";
Connection connection = null;
//Statement st = null;
//Result rs = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
When I use Windows to run eclipse Android emulator to connect socket,it was successful.
However, when I use Mac os lion to run the "Same" code ,the emulator shows"unfortunately
client test was stop!!"please help me solve this.And I already add the permission to internet!
package com.example.testclientokok;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Socket socket=new Socket(InetAddress.getLocalHost(), 8888);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
server part
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
If I understand correctly, you are executing MyServer on your machine, where you also run the emulator. If the Activity running in the emulator wants to establish a connection with MyServer, then it should use the following IP address : 10.0.2.2 (and not localhost, which references the emualor loopback interface).
See http://developer.android.com/tools/devices/emulator.html#networkaddresses
THE PROBLEM
Simple sql that returns about 500 rows takes:
40 ms in Toad (this return the first 500 rows)
500-600 ms in Java with connection obtained from an instance of
oracle.jdbc.pool.OracleDataSource class.
2100-2500 ms in Java with connection obtained from the data
source configured in Weblogic on looked up via JNDI
The above timings exclude getting the connection instance.
Problem: slow performance of option 3. Why? How can it be made more reasonable?
THE SETUP
Weblogic 10.3.5
Oracle 11g RDMBS
THE TEST CODE
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.pool.OracleDataSource;
import Facility;
import BrowserSQL;
public class JDBCTest {
public static Connection conn;
public static Connection getConnection(){
String url= "localhost:1521:testdb";
String usr="test";
String pswd="test";
Connection conn = null;
try {
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:#" + url);
ods.setUser(usr);
ods.setPassword(pswd);
conn = ods.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static Connection getConnectionWeblogicJndi(){
Connection conn = null;
try {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
Context ctx = new InitialContext(ht);
DataSource ods = (DataSource)ctx.lookup("jdbc/test");
conn = ods.getConnection();
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
return conn;
}
//get the next val from given sequence.
public static void runQuery(Connection conn, String sql){
ResultSet rs=null;
Statement stmt=null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){}
}catch(SQLException ex){
ex.printStackTrace();
}
finally{
close(rs,stmt,conn);
}
}
public static void close(ResultSet rs, Statement ps, Connection conn){
if (rs!=null) {
try { rs.close(); } catch(SQLException ex) { ex.printStackTrace(); }
}
if (ps != null) {
try { ps.close(); } catch (SQLException ex) { ex.printStackTrace(); }
}
if(conn !=null){
try{ conn.close(); }catch(SQLException ex){ ex.printStackTrace(); }
}
}
public static void main(String[]arg) throws SQLException {
//Connection conn = JDBCTest.getConnectionWeblogicJndi();
Connection conn = JDBCTest.getConnection();
((OracleConnection)conn).setDefaultRowPrefetch(1000);
long a = GregorianCalendar.getInstance().getTimeInMillis();
System.out.println("Stating testGetAllFacilityByQuery..."+a);
runQuery(conn, BrowserSQL.getAllFacilities());
long b = GregorianCalendar.getInstance().getTimeInMillis();
System.out.println("End testGetAllFacilityByQuery..."+b + " -------- total time: "+(b-a)+" ms");
}
}