tomcat ported to Google App Engine - mysql

I had the period webservice originally tomcat server.
Now I want to segment webservice transplant to GAE.
I transplant was successful.
Implementation, but this error message is displayed.
Will this cause the possibility of error?
MY CODE:
public class LOAD extends HttpServlet{
static String JBx;
static String JBy;
static String JBSx;
static String JBSy;
static String gps;
String a;
int i;
private Connection con = null; //Database objects
private Statement stat = null;
private ResultSet rs = null;
private PreparedStatement pst = null;
private String dropdbSQL = "DROP TABLE User ";
private String createdbSQL = "CREATE TABLE User (" +
" id INTEGER " +
" , name VARCHAR(20) " +
" , passwd VARCHAR(20))";
private String insertdbSQL = "insert into User(id,gps,recopy) " +
"select ifNULL(max(id),0)+1,?,? FROM User";
private String selectSQL = "select * from User ";
public static void main(String[] args)
{
}
public void SelectTable()
{
try
{
stat = con.createStatement();
rs = stat.executeQuery(selectSQL);
while(rs.next())
{
JBSx =rs.getString("gps");
JBSx="<div id=dd>"+JBSx+"</div>";
if(JBx!=null){
JBx=JBx+JBSx;
}else
{
JBx=JBSx;
}
JBSy =rs.getString("recopy");
JBSy="<div id=ff>"+JBSy+"</div>";
if(JBy!=null){
JBy=JBy+JBSy;
}
else
{
JBy=JBSy;
}
}
}
catch(SQLException e)
{
System.out.println("DropDB Exception :" + e.toString());
}
// finally
// {
// Close();
// }
}
private void Close()
{
try
{
if(rs!=null)
{
rs.close();
rs = null;
}
if(stat!=null)
{
stat.close();
stat = null;
}
if(pst!=null)
{
pst.close();
pst = null;
}
}
catch(SQLException e)
{
System.out.println("Close Exception :" + e.toString());
}
}
public LOAD()
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://hl2dm.synology.me:3306/teama",
"abc","");
}
catch(ClassNotFoundException e)
{
System.out.println("DriverClassNotFound :"+e.toString());
}
catch(SQLException x) {
System.out.println("Exception :"+x.toString());
}
}
public void doGet(HttpServletRequest rq, HttpServletResponse rp)
throws ServletException, IOException{
JBx=null;
JBy=null;
JBSx=null;
JBSy=null;
rq.setCharacterEncoding("UTF-8");
// String gps = rq.getParameter("gps");
LOAD test = new LOAD();
test.SelectTable();
HttpSession session = rq.getSession();
//session.invalidate();
// session.removeAttribute("reportx");
session.setMaxInactiveInterval(3600);
session.setAttribute("reportx",JBx);
session.setAttribute("reporty",JBy);
rp.sendRedirect(rp.encodeRedirectURL("LOADPOST"));
}
public void doPost(HttpServletRequest rq, HttpServletResponse rp)
throws ServletException, IOException{
doGet(rq, rp);
}
}
Error message:
HTTP ERROR 500
Problem accessing /LOAD. Reason:
INTERNAL_SERVER_ERROR
Caused by:
java.lang.NullPointerException
at a.b.c.LOAD.SelectTable(LOAD.java:52)
at a.b.c.LOAD.doGet(LOAD.java:149)
at a.b.c.LOAD.doPost(LOAD.java:160)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:123)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:61)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:409)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Powered by Jetty://

To answer your question, yes it will cause definite failure.
There is no MySql instance to connect to on AppEngine. You need instead to use Google Cloud SQL.
It goes something like this:
DriverManager.registerDriver(new AppEngineDriver());
con = DriverManager.getConnection("jdbc:google:rdbms://instance_name/guestbook");
See: this AppEngine guide for the complete set of steps.
Note: To use the development server with a local MySQL instance, see https://developers.google.com/appengine/docs/java/cloud-sql/developers-guide#using_the_java_development_server

Related

trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc

NetworkUtilities.java
public class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
#Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
#Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
#Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xample.newsfee: Accessing hidden method Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:46)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
2021-03-11 22:53:28.124 9391-9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity : package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159)
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build : 979eaa0, I11632bc865
Build Date : 11/18/20
OpenGL ES Shader Compiler Version: EV031.32.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067
Remote Branch : NONE
Reconstruct Branch : NOTHING
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config : S P 10.0.6 AArch64
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted.
Starting from Android 9, clear text http communication is disabled by default.
Check out the official Android documentation for this and also this question for further information.

java.sql.SQLException: Column 'mobile' not found.?

// So apparently it seems to save it but it does no show it in the table or even in the pane
package library.application.main.lmember;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import library.application.main.member.AddMemberController;
import library.application.database.Database;
public class LMemberController implements Initializable {
ObservableList<Member> list = FXCollections.observableArrayList();
#FXML
private AnchorPane anchorPane;
#FXML
private TableView<Member> tableView;
#FXML
private TableColumn<Member, String> nameCol;
#FXML
private TableColumn<Member, String> idCol;
#FXML
private TableColumn<Member, String> mobileCol;
#FXML
private TableColumn<Member, String> emailCol;
#Override
public void initialize(URL url, ResourceBundle rb) {
loadData();
initCol();
}
private void initCol(){
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
mobileCol.setCellValueFactory(new PropertyValueFactory<>("mobile"));
emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));
}
private void loadData() {
Database handel = Database.getInstance();
String qu = "SELECT * FROM MEMBER";
ResultSet rs = handel.execQuery(qu);
try {
while (rs.next()) {
String name = rs.getString("name");
String mobile = rs.getString("mobile");
String id = rs.getString("id");
String email = rs.getString("email");
list.addAll(new Member(name, id, mobile, email));
}
} catch (SQLException ex) {
Logger.getLogger(AddMemberController.class.getName()).log(Level.SEVERE, null, ex);
}
tableView.setItems(list);
}
public static class Member
{
private final SimpleStringProperty name;
private final SimpleStringProperty id;
private final SimpleStringProperty mobile;
private final SimpleStringProperty email;
public Member(String Nmame, String id, String mobil, String email)
{
this.name = new SimpleStringProperty(Nmame);
this.id = new SimpleStringProperty(id);
this.mobile = new SimpleStringProperty(mobil);
this.email = new SimpleStringProperty(email);
}
public String getName()
{
return name.get();
}
public String getId()
{
return id.get();
}
public String getMobile()
{
return mobile.get();
}
public String getEmail()
{
return email.get();
}
}
}
// And this is the error that keeps popping up Even tho i defined the mobile column it is still not working.
Table MEMBER already exists. Ready for go!
Apr 04, 2018 12:47:01 PM library.application.main.lmember.LMemberController loadData
SEVERE: null
java.sql.SQLException: Column 'mobile' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.findColumnName(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getString(Unknown Source)
at library.application.main.lmember.LMemberController.loadData(LMemberController.java:72)
at library.application.main.lmember.LMemberController.initialize(LMemberController.java:52)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at library.application.main.window.MainWindowController.loadWindow(MainWindowController.java:87)
at library.application.main.window.MainWindowController.loadMTable(MainWindowController.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)
Caused by: ERROR S0022: Column 'mobile' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 78 more
// this is my database
package library.application.database;
import javax.swing.;
import java.sql.;
public final class Database {
private static Database handel = null ;
private static final String DB_URL = "jdbc:derby:database;create=true";
private static Connection conn = null;
private static Statement stmt = null;
private Database() {
createConnection();
setupBookTable();
setupMemberTable();
}
public static Database getInstance() {
if (handel== null) {
handel = new Database();
}
return handel;
}
void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(DB_URL);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Cant load database", "Database Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
void setupBookTable() {
String TABLE_NAME = "BOOK";
try {
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null);
if (tables.next()) {
System.out.println("Table " + TABLE_NAME + " already exists. Ready for go!");
} else {
stmt.execute("CREATE TABLE " + TABLE_NAME + "("
+ " id VARCHAR (200) primary key,\n"
+ " title VARCHAR(200),\n"
+ " author VARCHAR(200),\n"
+ " publiser VARCHAR(100),\n"
+ " isAvail boolean default true"
+ " )");
}
} catch (SQLException e) {
System.err.println(e.getMessage() + " --- setupDatabase");
} finally {
}
}
void setupMemberTable() {
String TABLE_NAME = "MEMBER";
try {
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null);
if (tables.next()) {
System.out.println("Table " + TABLE_NAME + " already exists. Ready for go!");
} else {
stmt.execute("CREATE TABLE " + TABLE_NAME + "("
+ " id VARCHAR(10) primary key,\n"
+ " name VARCHAR(15),\n"
+ " mobile VARCHAR(12),\n"
+ " email VARCHAR(100)\n"
+ " )");
}
} catch (SQLException e) {
System.err.println(e.getMessage() + " --- setupDatabase");
} finally {
}
}
public ResultSet execQuery(String query) {
ResultSet result;
try {
stmt = conn.createStatement();
result = stmt.executeQuery(query);
} catch (SQLException ex) {
System.out.println("Exception at execQuery: data " + ex.getLocalizedMessage());
return null;
} finally {
}
return result;
}
public boolean execAction(String qu) {
try {
stmt = conn.createStatement();
stmt.execute(qu);
return true;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error:" + ex.getMessage(), "Error Occured", JOptionPane.ERROR_MESSAGE);
System.out.println("Exception at execQuery: data " + ex.getLocalizedMessage());
return false;
} finally {
}
}
}
Update your method where you are providing DDL statement to fix the error.
method:
void setupMemberTable() {
String TABLE_NAME = "MEMBER";
try {
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tabless = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null);
if (tabless.next()) {
System.out.println("Table " + TABLE_NAME + " already exists. Ready for go!");
} else {
stmt.execute("CREATE TABLE " + TABLE_NAME + "("
+ " id VARCHAR(10) primary key,\n"
+ " COLUMN_NAME VARCHAR(15),\n"
+ " mobile VARCHAR(12),\n"
+ " email VARCHAR(100)\n"
+ " )");
}
} catch (SQLException e) {
System.err.println(e.getMessage() + " --- setupDatabase");
} finally {
}
}
You have used 'name' as column name which is reserved keyword.
For your reference-
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
OR
Just put
DROP TABLE IF EXISTS tablename; before your CREATE TABLE statement.

Tomcat cannot find JDBC driver when connecting to DB [duplicate]

This question already has an answer here:
jdbc to MYSQL error: No suitable driver found for jdbc:mysql://localhost:3306/test?user='root'&password='' [duplicate]
(1 answer)
Closed 7 years ago.
I've put mysql driver in .../ROOT/WEB-INF/lib and Tomcat 8.0/lib but it has no effect. I'm using the following class to connect to DB:
package db;
import java.sql.*;
public class ConnectToDB implements AutoCloseable {
Connection con;
public ConnectToDB(String server, String database, String user,
String password) throws SQLException {
con = DriverManager.getConnection("jdbc:mysql://" + server + "/"
+ database, user, password);
}
#Override
public void close() throws SQLException {
con.close();
}
public Connection getConnection() {
return con;
}
}
The following classes are included in the Eclipse project:
1. src/nr3/model
package nr3.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import db.ConnectToDB;
public class MusikkHandler {
private ConnectToDB db;
private Connection con;
private String tableName;
private PreparedStatement pstmtGetRows;
public MusikkHandler(String server, String database, String user,
String password) throws SQLException {
db = new ConnectToDB(server, database, user, password);
con = db.getConnection();
tableName = "album";
}
public void close() throws SQLException {
db.close();
}
public ArrayList<Album> getRows(String genre) throws SQLException {
ArrayList<Album> list = new ArrayList<Album>();
pstmtGetRows = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE SJANGER = ?");
pstmtGetRows.setString(1, genre);
ResultSet rs = pstmtGetRows.executeQuery();
while (rs.next()) {
list.add(new Album(rs.getString(1), rs.getString(2), rs.getInt(3),
rs.getInt(4), rs.getString(5)));
}
rs.close();
pstmtGetRows.close();
return list;
}
}
-
package nr3.model;
public class Album {
private String tittel;
private String artist;
private int spor;
private int utgitt;
private String sjanger;
public Album (String artist, String tittel, int spor, int utgitt, String sjanger){
setArtist(artist);
setTittel(tittel);
setUtgitt(utgitt);
setSpor(spor);
setSjanger(sjanger);
}
public Album(){
this(null, null, 0, 0, null);
}
public void setTittel(String tittel){
this.tittel = tittel;
}
public void setArtist(String artist){
this.artist = artist;
}
public void setSpor(int spor) {
this.spor = spor;
}
public void setUtgitt(int utgitt) {
this.utgitt = utgitt;
}
public void setSjanger(String sjanger) {
this.sjanger = sjanger;
}
public String getTittel() {
return tittel;
}
public String getArtist() {
return artist;
}
public int getSpor() {
return spor;
}
public int getUtgitt() {
return utgitt;
}
public String getSjanger() {
return sjanger;
}
public String toString(){
return getTittel() + " (" + getArtist() + ")" + " Utgitt: "
+ getUtgitt();
}
}
2. src/nr3/servlets
package nr3.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nr3.model.Album;
import nr3.model.MusikkHandler;
public class MusikkValg extends HttpServlet {
private static final long serialVersionUID = 428937262021570370L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String genre = request.getParameter("sjanger");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
MusikkHandler mh;
out.println("<html>");
out.println("<head>");
out.println("<title>Musikk</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>MUSIKK-ANBEFALINGER</h1>");
out.println("<br/>");
out.println("<br/>");
out.println("<h3>Da bør du kanskje forsøke en av disse:</h3>");
out.println("<br/>");
out.println("<br/>");
try {
mh = new MusikkHandler(" ", " ", " ", " ");
for (Album a : mh.getRows(genre))
out.println("<p>" + a + "</p>");
} catch (SQLException e) {
e.printStackTrace(out);
}
out.println("</body>");
out.println("</html>");
}
}
Update: I've got the following error stacktrace in the browser:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost/pg3100 at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
db.ConnectToDB.(ConnectToDB.java:10) at
nr3.model.MusikkHandler.(MusikkHandler.java:20) at
nr3.servlets.MusikkValg.doGet(MusikkValg.java:39) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:618) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2381)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2370)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
First, you must register your driver at the beginning so DriverManager can user it when getting a connection. It might vary on the implementation.
DriverManager.registerDriver (new com.mysql.jdbc.Driver());
or
Class.forName("com.mysql.jdbc.Driver");
Then you can perform a getConnection() because you'll have a driver registered to be used by DriverManager.
Second: /webapps/ROOT/WEB-INF/lib is a different context and its libraries won't be available for your app unless you are setting the context path of your app as shown in this question. If you wanna add it, try placing your JDBC driver on /webapps/<yourapp>/lib first. Tomcat lib should work as well (but it's not nice when you distribute your app, might conflict with other apps deployed there, using different versions of the driver, etc.)
Third: When asking here, try to reduce your verifiable example to something readable. There's a lot of code which is not relevant to your problem. Reducing makes it easier to read your question and provide help.

In JavaFX how to add combobox with data in table view

I have tried a lot but not able to populate all values in the data base into my combo box table cell.
Controller.java
public class controller {
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
Statement st;
private ObservableList<Users> datas = FXCollections.observableArrayList();
public controller() {
}
#FXML
private TableView<Users> table;
#FXML
private TableColumn<Users, String> c1;
#FXML
private void editable() {
List<String> names = new ArrayList<String>();
try {
ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode")));
}
for (String name : names) {
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(name));
//not getting full items here
System.out.println("hell3" + name);// am getting full items here
}
table.setItems(null);
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class Users {
private StringProperty Itemc;
private Users(String Itemc) {
this.Itemc = new SimpleStringProperty(Itemc);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
}
}
table.fxml
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication47.controller">
<children>
<TableView fx:id="table" editable="true" layoutX="136.0" layoutY="58.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="335.0">
<columns>
<TableColumn fx:id="c1" prefWidth="333.0" text="Name" />
</columns>
</TableView>
</children>
</AnchorPane>
Main.java loader
public class Tableveiw extends Application {
private Stage primaryStage;
private AnchorPane pane;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
showPerson();
}
public void showPerson() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tableveiw.class.getResource("table.fxml"));
pane = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
Database Connection
public class GetConnection {
public Connection getConnection() throws Exception {
Connection con = null;
try {
System.out.println("MySQL Connect Example.");
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
// Accessing driver from the jar file
Class.forName(driver).newInstance();
// Creating a veriable for Connection Called conn
con = DriverManager.getConnection(url + dbName, "root", "");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String arg[]) {
GetConnection con = new GetConnection();
System.out.println("Connection" + con);
}
}
My problem with the code is that am not getting the full items in the database record to my c1 combobox table cell.Am only getting the last items of the database record in my comboboxtablecell.I have created array but still not helping .Why am not able to populate whole items in database into my combobox tablecell .Please help me with neccessary changes in the code.
This is Just basic functionality . when you duble click on cell combobox will visible then you can select value.to see direct Combobox you have write own TableCell class see this you ll understand. I hope this will help you. any ?s post a comment
private void editable() {
try {
ObservableList<String> names = FXCollections.observableArrayList();
ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(name));
table.setEditable(true);
table.getItems().clear();
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}

Read Time Out Exception in Cassandra using cassandra-driver-core

I am writing a Java application which reads the data from MySQL and stores it in Cassandra as Sqoop does not support a direct import to Cassandra. I am using Producer-Consumer framework to achieve the same due to high number of records (in millions) in MySQL. But I am getting ReadTimeOut Exception (com.datastax.driver.core.exceptions.DriverException: Timeout during read). I have one Producer class which reads the data from MySQL and puts it into one queue. There is one consumer class which reads the data from that queue and pushes it to Cassndra. There is one manager class which acts as a coordination bridge between these two classes.
Producer class :-
public class MySQLPrintJobProducer implements Runnable {
private BlockingQueue<PrintJobDAO> printerJobQueue = null;
private Connection conn = null;
public MySQLPrintJobProducer(BlockingQueue<PrintJobDAO> printerJobQueue) throws MySQLClientException {
this.printerJobQueue = printerJobQueue;
connect();
}
private void connect() throws MySQLClientException {
try {
Class.forName(MySQLClientConstants.MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection("jdbc:mysql://mysqlserverhose/mysqldb?user=mysqluser&password=mysqlpasswd");
} catch (ClassNotFoundException e) {
throw new MySQLClientException(ExceptionUtils.getStackTrace(e));
} catch (SQLException e) {
throw new MySQLClientException(ExceptionUtils.getStackTrace(e));
}
}
public void run() {
ResultSet rs = null;
Statement stmt = null;
PreparedStatement pStmt = null;
try {
stmt = conn.createStatement();
// Get total number of print jobs stored.
rs = stmt.executeQuery(MySQLClientConstants.PRINT_JOB_COUNT_QUERY);
int totalPrintJobs = 0;
if(rs != null) {
while(rs.next()) {
totalPrintJobs = rs.getInt(1);
}
}
// Determine the number of iterations.
int rowOffset = 1;
int totalIteration = ((totalPrintJobs / ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE) + 1);
pStmt = conn.prepareStatement(MySQLClientConstants.PRINT_JOB_FETCH_QUERY);
int totalRecordsFetched = 0;
// Iterate over to fetch Print Job Records in bathces and put it into the queue.
for(int i = 1; i <= totalIteration; i++) {
pStmt.setInt(1, rowOffset);
pStmt.setInt(2, ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE);
System.out.println("In iteration : " + i + ", Row Offset : " + rowOffset);
rs = pStmt.executeQuery();
synchronized (this.printerJobQueue) {
if(this.printerJobQueue.remainingCapacity() > 0) {
while(rs.next()) {
totalRecordsFetched = rs.getRow();
printerJobQueue.offer(new PrintJobDAO(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDate(4),
rs.getTimestamp(5), rs.getInt(6), rs.getInt(7), rs.getInt(8), rs.getInt(9),
rs.getInt(10), rs.getFloat(11), rs.getFloat(12), rs.getInt(13), rs.getFloat(14), rs.getInt(15),
rs.getDouble(16), rs.getDouble(17), rs.getDouble(18), rs.getDouble(19), rs.getDouble(20),
rs.getFloat(21)));
this.printerJobQueue.notifyAll();
}
System.out.println("In iteration : " + i + ", Records Fetched : " + totalRecordsFetched +
", Queue Size : " + printerJobQueue.size());
rowOffset += ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE;
} else {
System.out.println("Print Job Queue is full, waiting for Consumer thread to clear.");
this.printerJobQueue.wait();
}
}
}
} catch (SQLException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} catch (InterruptedException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} finally {
try {
if(null != rs) {
rs.close();
}
if(null != stmt) {
stmt.close();
}
if(null != pStmt) {
pStmt.close();
}
} catch (SQLException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
}
}
ExportManager.setProducerCompleted(true);
}
}
Consumer Class :-
public class CassandraPrintJobConsumer implements Runnable {
private Cluster cluster = null;
private Session session = null;
private BlockingQueue<PrintJobDAO> printerJobQueue = null;
public CassandraPrintJobConsumer(BlockingQueue<PrintJobDAO> printerJobQueue) throws CassandraClientException {
this.printerJobQueue = printerJobQueue;
cluster = Cluster.builder().withPort(9042).addContactPoint("http://cassandrahost").build();
}
public void run() {
int printJobConsumed = 0;
int batchInsertCount = 1;
if(cluster.isClosed()) {
connect();
}
session = cluster.connect();
PreparedStatement ps = session.prepare(CassandraClientConstants.INSERT_PRINT_JOB_DATA);
BatchStatement batch = new BatchStatement();
synchronized (this.printerJobQueue) {
while(true) {
if(!this.printerJobQueue.isEmpty()) {
for(int i = 1; i <= ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE; i++) {
PrintJobDAO printJob = printerJobQueue.poll();
batch.add(ps.bind(printJob.getJobID(), printJob.getUserID(), printJob.getType(), printJob.getGpDate(), printJob.getDateTimes(),
printJob.getAppName(), printJob.getPrintedPages(), printJob.getSavedPages(), printJob.getPrinterID(), printJob.getWorkstationID(),
printJob.getPrintedCost(), printJob.getSavedCost(), printJob.getSourcePrinterID(), printJob.getSourcePrinterPrintedCost(),
printJob.getJcID(), printJob.getCoverageC(), printJob.getCoverageM(), printJob.getCoverageY(), printJob.getCoverageK(),
printJob.getCoverageTotal(), printJob.getPagesAnalyzed()));
printJobConsumed++;
}
session.execute(batch);
System.out.println("After Batch - " + batchInsertCount + ", record insert count : " + printJobConsumed);
batchInsertCount++;
this.printerJobQueue.notifyAll();
} else {
System.out.println("Print Job Queue is empty, nothing to export.");
try {
this.printerJobQueue.wait();
} catch (InterruptedException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
}
}
if(ExportManager.isProducerCompleted() && this.printerJobQueue.isEmpty()) {
break;
}
}
}
}
}
Manager Class :-
public class ExportManager {
private static boolean isInitalized = false;
private static boolean producerCompleted = false;
private static MySQLPrintJobProducer printJobProducer = null;
private static CassandraPrintJobConsumer printJobConsumer = null;
private static BlockingQueue<PrintJobDAO> printJobQueue = null;
public static boolean isProducerCompleted() {
return producerCompleted;
}
public static void setProducerCompleted(boolean producerCompleted) {
ExportManager.producerCompleted = producerCompleted;
}
private static void init() throws MySQLClientException, CassandraClientException {
if(!isInitalized) {
printJobQueue = new LinkedBlockingQueue<PrintJobDAO>(ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE * 2);
printJobProducer = new MySQLPrintJobProducer(printJobQueue);
printJobConsumer = new CassandraPrintJobConsumer(printJobQueue);
isInitalized = true;
}
}
public static void exportPrintJobs() throws ExportException {
try {
init();
} catch (MySQLClientException e) {
throw new ExportException("Print Job Export failed.", e);
} catch (CassandraClientException e) {
throw new ExportException("Print Job Export failed.", e);
}
Thread producerThread = new Thread(printJobProducer);
Thread consumerThread = new Thread(printJobConsumer);
consumerThread.start();
producerThread.start();
}
}
TestNG class :-
public class TestExportManager {
#Test
public void testExportPrintJobs() {
try {
ExportManager.exportPrintJobs();
Thread.currentThread().join();
} catch (ExportException e) {
Assert.fail("ExportManager.exportPrintJobs() failed.", e);
} catch (InterruptedException e) {
Assert.fail("ExportManager.exportPrintJobs() failed.", e);
}
}
}
I have also made some configuration changes by following this link. Still I am getting following exception after inserting 18000 - 20000 records.
Exception in thread "Thread-2" com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.10.80
(com.datastax.driver.core.exceptions.DriverException: Timeout during read))
at com.datastax.driver.core.exceptions.NoHostAvailableException.copy(NoHostAvailableException.java:64)
at com.datastax.driver.core.DefaultResultSetFuture.extractCauseFromExecutionException(DefaultResultSetFuture.java:256)
at com.datastax.driver.core.DefaultResultSetFuture.getUninterruptibly(DefaultResultSetFuture.java:172)
at com.datastax.driver.core.SessionManager.execute(SessionManager.java:91)
at com.incendiary.ga.client.cassandra.CassandraPrintJobConsumer.run(CassandraPrintJobConsumer.java:108)
at java.lang.Thread.run(Unknown Source)
Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.10.80 (com.datastax.drive
r.core.exceptions.DriverException: Timeout during read))
at com.datastax.driver.core.RequestHandler.sendRequest(RequestHandler.java:100)
at com.datastax.driver.core.RequestHandler$1.run(RequestHandler.java:171)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
... 1 more
I am not able to figure out the actual reason for the issue. I could not find any exception in Cassandra system log. I am using Apache Cassandra 2.0.7 and cassandra-driver-core 2.0.1.
You can increase read time out in you driver side . By using withSocket method in this you have SocketOption class using that you can read time out .By default is read time out is 10 millisecond .