Batch update for a CRUD spring-boot application every second - sql

I have a spring boot application in which i edit a employee database with CRUD operations received from Postman.
My problem is that in this case i need to access the database with multiple threads, or with batches.
I decided to do a batch update.
This is my DAO in which i make the crud operations with sql connections.
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
public EmployeeDaoImpl(NamedParameterJdbcTemplate template) {
this.template = template;
}
private static int maxCreateBatch = 50;
private static int maxUpdateBatch = 50;
private static int maxDeleteBatch = 50;
NamedParameterJdbcTemplate template;
#Override
public List<Employee> findAll() {
return template.query("select * from employee", new EmployeeRowMapper());
}
#Override
public void insertEmployee(Employee emp) {
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://10.10.45.147:5432/db", "db",
"pass");
PreparedStatement ps = conn.prepareStatement("insert into employee(employeeId, employeeName ) values(?,?)");
int i = 1, j = 0;
ps.setString(i++, emp.getEmployeeId());
ps.setString(i++, emp.getEmployeeName());
ps.addBatch();
j++;
i = 1;
if (j == maxCreateBatch) {
ps.executeBatch();
j = 0;
}
} catch (SQLException e) {
System.out.println("Connection failure");
e.printStackTrace();
}
}
#Override
public void updateEmployee(Employee emp) {
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://10.10.45.147:5432/db", "db",
"pass");
PreparedStatement ps = conn.prepareStatement("update employee set employeeName=? where employeeId=?");
int i = 1, j = 0;
ps.setString(i++, emp.getEmployeeName());
ps.setString(i++, emp.getEmployeeId());
ps.addBatch();
i = 1;
j++;
if (j == maxUpdateBatch) {
ps.executeBatch();
j = 0;
}
} catch (SQLException e) {
System.out.println("Connection failure");
e.printStackTrace();
}
}
#Override
public void executeUpdateEmployee(Employee emp) {
final String sql = "update employee set employeeName=:employeeName where employeeId=:employeeId";
Map<String, Object> map = new HashMap<String, Object>();
map.put("employeeId", emp.getEmployeeId());
map.put("employeeName", emp.getEmployeeName());
template.execute(sql, map, new PreparedStatementCallback<Object>() {
#Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
#Override
public void deleteEmployee(Employee emp) {
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://10.10.45.147:5432/db", "db",
"pass");
PreparedStatement ps = conn.prepareStatement("delete from employee where employeeId=?");
int j = 0;
ps.setString(1, emp.getEmployeeId());
ps.addBatch();
j++;
if (j == maxDeleteBatch) {
ps.executeBatch();
j = 0;
}
} catch (SQLException e) {
System.out.println("Connection failure");
e.printStackTrace();
}
}
}
This is my simple controller
#RestController
#RequestMapping("/postgressApp")
public class ApplicationController {
#Resource
EmployeeService employeeService;
#GetMapping(value = "/employeeList")
public List<Employee> getEmployees() {
return employeeService.findAll();
}
#PostMapping(value = "/createEmp")
public void createEmployee(#RequestBody Employee emp) {
employeeService.insertEmployee(emp);
}
#PutMapping(value = "/updateEmp")
public void updateEmployee(#RequestBody Employee emp) {
employeeService.updateEmployee(emp);
}
#PutMapping(value = "/executeUpdateEmp")
public void executeUpdateEmployee(#RequestBody Employee emp) {
employeeService.executeUpdateEmployee(emp);
}
#DeleteMapping(value = "/deleteEmpById")
public void deleteEmployee(#RequestBody Employee emp) {
employeeService.deleteEmployee(emp);
}
}
As you can see i have a preparedStatement for each operation and i add avery operation to a batch.
In this moment, all get sent to the database only when the batch limit is reached.
**But my problem is : ** i need to sent every one of those batches to the database every second.
How do i do that ? Cause i cant call the bathes outside of their methods.

Related

Kafka consumer receive null value when sending customer object

So i want to implement application which reads data from json format files. And I have created customer object for the data in json. And I want to send these object through kafka topic. So far i have successfully send String message to producer to consumer. But when i try to send object, in the consumer side, when I do .value().toString(). I got null value. The following is the code I have used:
This is producer:
public class MyProducer {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.put("bootstrap.servers", "kafka.kafka-cluster-shared.non-prod-5-az-scus.prod.us.walmart.net:9092");
properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer", "xxxxxxxxx.KafkaJsonSerializer");
properties.put("acks", "1");
properties.put("retries", "2");
properties.put("batch.size", "16384");
properties.put("linger.ms", "1");
properties.put("buffer.memory", "33554432");
KafkaProducer<String, pharmacyData> kafkaProducer = new KafkaProducer<String, pharmacyData>(
properties);
String topic = "insights";
//try {
Gson gson = new Gson();
Reader reader = Files.newBufferedReader(Paths.get("......./part.json"));
List<pharmacyData> pdata = new Gson().fromJson(reader, new TypeToken<List<pharmacyData>>() {}.getType());
//pdata.forEach(System.out::println);
reader.close();
//} catch (Exception e) {
//e.printStackTrace();
//}
for (pharmacyData data : pdata) {
kafkaProducer.send(new ProducerRecord<String, pharmacyData>(topic, data), new Callback() {
#Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
if (e == null) {
System.out.println(recordMetadata.partition() + "--" + recordMetadata.serializedValueSize());
} else {
e.printStackTrace();
}
}
});
}
kafkaProducer.close();
}
}
This is the customer object class:
public class pharmacyData {
private String load_date;
private String store_nbr;
private String state;
private String pmp_flag;
private String zero_flag;
private String submit_ts;
public pharmacyData(String load_date, String store_nbr, String state, String pmp_flag, String zero_flag, String submit_ts) {
this.load_date = load_date;
this.store_nbr = store_nbr;
this.state = state;
this.pmp_flag = pmp_flag;
this.zero_flag = zero_flag;
this.submit_ts = submit_ts;
}
public String getLoad_date() {
return load_date;
}
public void setLoad_date(String load_date) {
this.load_date = load_date;
}
public String getStore_nbr() {
return store_nbr;
}
public void setStore_nbr(String store_nbr) {
this.store_nbr = store_nbr;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPmp_flag() {
return pmp_flag;
}
public void setPmp_flag(String pmp_flag) {
this.pmp_flag = pmp_flag;
}
public String getZero_flag() {
return zero_flag;
}
public void setZero_flag(String zero_flag) {
this.zero_flag = zero_flag;
}
public String getSubmit_ts() {
return submit_ts;
}
public void setSubmit_ts(String submit_ts) {
this.submit_ts = submit_ts;
}
#Override
public String toString() {
return "pharmacyData{" +
"load_date='" + load_date + '\'' +
", store_nbr='" + store_nbr + '\'' +
", state='" + state + '\'' +
", pmp_flag='" + pmp_flag + '\'' +
", zero_flag='" + zero_flag + '\'' +
", submit_ts='" + submit_ts + '\'' +
'}';
}
}
this is the customer Serializer:
public class KafkaJsonSerializer implements Serializer {
private Logger logger = LogManager.getLogger(this.getClass());
#Override
public void configure(Map map, boolean b) {
}
#Override
public byte[] serialize(String s, Object o) {
byte[] retVal = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
retVal = objectMapper.writeValueAsBytes(o);
} catch (Exception e) {
logger.error(e.getMessage());
}
return retVal;
}
#Override
public void close() {
}
}
This is the customer Deserializer:
public class KafkaJsonDeserializer implements Deserializer {
#Override
public void configure(Map map, boolean b) {
}
#Override
public Object deserialize(String s, byte[] bytes) {
ObjectMapper mapper = new ObjectMapper();
pharmacyData pdata = null;
try {
pdata = mapper.readValue(bytes, pharmacyData.class);
} catch (Exception e) {
e.printStackTrace();
}
return pdata;
}
#Override
public void close() {
}
}
This is consumer:
public class MyConsumer {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("bootstrap.servers", "kafka.kafka-cluster-shared.non-prod-5-az-scus.prod.us.walmart.net:9092");
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
properties.put("value.deserializer", "xxxxxxxx.KafkaJsonDeserializer");
properties.put("group.id", "consumer-group-1");
properties.put("enable.auto.commit", "true");
properties.put("auto.commit.interval.ms", "1000");
properties.put("auto.offset.reset", "earliest");
properties.put("session.timeout.ms", "30000");
KafkaConsumer<String, pharmacyData> consumer = new KafkaConsumer<>(properties);
String topic = "insights";
consumer.subscribe(Collections.singletonList(topic));
while (true) {
ConsumerRecords<String, pharmacyData> consumerRecords = consumer.poll(100);
for (ConsumerRecord<String, pharmacyData> consumerRecord : consumerRecords) {
System.out.println(consumerRecord.key() + "--" + consumerRecord.toString());
//System.out.println(consumerRecord.offset() + "--" + consumerRecord.partition());
}
}
}
}
Can someone please help me with the issues? Thank you very much!
Problem solved:
The solution of this issue just add a default constructor as below:
public pharmacyData() {
}
See this page for more details.

Headless Exception

I would like to ask for a solution to my problem:
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from
fulfilling this request.
exception
java.awt.HeadlessException
note The full stack traces of the exception and its root causes are available
in the GlassFish Server Open Source Edition 4.1.1 logs.
GlassFish Server Open Source Edition 4.1.1
There are a few tables in the database, but when I need to get records from the table "Student", it keeps showing this error.
domain file :
package domain;
import java.io.Serializable;
import java.util.Objects;
public class Student implements Serializable {
private String studID;
private String studName;
private int studIC;
private String gender;
private String address;
private int contactNo;
public Student(){}
public Student(String studID){
this.studID = studID;
}
public Student(String studID, String studName, int studIC, String gender, String address, int contactNo){
this.studID = studID;
this.studName = studName;
this.studIC = studIC;
this.gender = gender;
this.address = address;
this.contactNo = contactNo;
}
public String getStudID(){
return studID;
}
public void setStudID(String studID){
this.studID = studID;
}
public String getStudName(){
return studName;
}
public void setStudName(String studName){
this.studName = studName;
}
public int getStudIC(){
return studIC;
}
public void setStudIC(int studIC){
this.studIC = studIC;
}
public String getGender(){
return gender;
}
public void setGender(String gender){
this.gender = gender;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public int getContactNo(){
return contactNo;
}
public void setContactNo(int contactNo){
this.contactNo = contactNo;
}
}
da file :
package da;
import domain.Student;
import java.sql.*;
import javax.swing.*;
public class StudentDA {
private String host = "jdbc:derby://localhost:1527/hostelDB";
private String user = "nbuser";
private String password = "nbuser";
private String tableName = "Student";
private Connection conn;
private PreparedStatement stmt;
public StudentDA(){
createConnection();
}
public void addRecord(Student student) {
String insertStr = "INSERT INTO " + tableName + " VALUES(?, ?, ?, ?, ?, ?)";
try {
stmt = conn.prepareStatement(insertStr);
stmt.setString(1, student.getStudID());
stmt.setString(2, student.getStudName());
stmt.setInt(3, student.getStudIC());
stmt.setString(4, student.getGender());
stmt.setString(5, student.getAddress());
stmt.setInt(6, student.getContactNo());
stmt.executeUpdate();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
public Student getRecord(String studID) {
String queryStr = "SELECT * FROM " + tableName + " WHERE StudentID = ?";
Student student = null;
try {
stmt = conn.prepareStatement(queryStr);
stmt.setString(1, studID);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
student = new Student(studID, rs.getString("StudentName"), rs.getInt("StudentIC"), rs.getString("Gender"), rs.getString("Address"), rs.getInt("ContactNo"));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
return student;
}
private void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection(host, user, password);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
private void shutDown() {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
}
servlet :
String studID = request.getParameter("studID");
Student stud = studDA.getRecord(studID);
out.println(stud);

Pusher with Service application on Android dose not bind events

I had a problem with Pusher with Service application on Android.
When I using pusher on Application or Activity then It's working.
But I move it to Service and register with application in manifress like:
<service android:name=".services.PusherServices"/>
It's not working.
When i startService Pusher connected success with authorization, but It's not bind events when I call method for register Channel.
PusherServices.java
package vn.hemlock.winkle.pancake.services;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.pusher.client.Pusher;
import com.pusher.client.PusherOptions;
import com.pusher.client.channel.PrivateChannel;
import com.pusher.client.channel.PrivateChannelEventListener;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionState;
import com.pusher.client.connection.ConnectionStateChange;
import com.pusher.client.util.HttpAuthorizer;
import net.windjs.android.utils.Encrypt;
import net.windjs.android.utils.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import vn.hemlock.winkle.pancake.abstracts.ChatEvents;
import vn.hemlock.winkle.pancake.contracts.ServicesURI;
import vn.hemlock.winkle.pancake.ui.Conversation;
import vn.hemlock.winkle.pancake.ui.Message;
import vn.hemlock.winkle.pancake.ui.Page;
/**
* Created by me866chuan on 5/4/15.
*/
public class PusherServices extends Service {
private String LOG_TAG = "Pusher Services";
private boolean pusherOn = false;
public final String PUSHER_KEY = "...";
private String userToken = "";
private String userID = "";
private final IBinder mBinder = new LocalBinder();
public boolean isPusherOn() {
return pusherOn;
}
public void setPusherOn(boolean pusherOn) {
this.pusherOn = pusherOn;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
#Override
public IBinder onBind(Intent intent) {
setUserID(intent.getStringExtra("userId"));
setUserToken(intent.getStringExtra("userToken"));
startPusher();
startService(intent);
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
Log.e(LOG_TAG, "OFF");
stopService(intent);
return true;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pusher.disconnect();
}
private Pusher pusher;
public void startPusher() {
HashMap<String, String> hash = new HashMap<>();
Log.e(LOG_TAG, "Token: "+getUserToken());
hash.put("authorization", getUserToken());
HttpAuthorizer authorizer = new HttpAuthorizer(ServicesURI.PUSHER_AUTHORIZER);
authorizer.setHeaders(hash);
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
pusher = new Pusher(PUSHER_KEY, options);
pusher.connect(new ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange change) {
Log.e(LOG_TAG, "State changed to " + change.getCurrentState() +
" from " + change.getPreviousState());
if(change.getCurrentState().toString().toUpperCase().equals("CONNECTED") || change.getCurrentState().toString().toUpperCase().equals("CONNECTING")){
setPusherOn(true);
}
else setPusherOn(false);
}
#Override
public void onError(String message, String code, Exception e) {
Log.e(LOG_TAG, "There was a problem connecting: " + message);
}
}, ConnectionState.ALL);
}
PrivateChannel userChannel;
public void userListenChanel(final Activity activity) {
if (pusher == null) return;
userChannel = pusher.subscribePrivate("private-" + Encrypt.stringMD5(getUserID()));
userChannel.bind("fetch_accounts", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
if (activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ChatEvents.getInstance().onNewPage(new Page((new JSONObject(data)).getJSONObject("page")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e(LOG_TAG, "USER FETCH FAIL: " + s);
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e(LOG_TAG, "USER FETCH SUCCESS: " + s);
}
});
}
PrivateChannel pageChannel;
private String idPageChannelListen;
public void pageListenChanel(final Activity activity, String pageId) {
if (pusher == null) return;
idPageChannelListen = pageId;
Log.e(LOG_TAG, "Channel page: "+"private-" + Encrypt.stringMD5(pageId));
pageChannel = pusher.subscribePrivate("private-" + Encrypt.stringMD5(pageId));
pageChannel.bind("realtime_updates", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Real time update with data: " + data);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject finalJsonObject = jsonObject;
if(activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (finalJsonObject == null) return;
try {
if (finalJsonObject.has("message")) ChatEvents.getInstance().onNewMessage(new Message(finalJsonObject.getJSONObject("message")));
else if (finalJsonObject.has("conversation")) ChatEvents.getInstance().onNewConversation(new Conversation(finalJsonObject.getJSONObject("conversation")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e(LOG_TAG, "Real time update failed: " + s);
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e(LOG_TAG, "Real time update successed: " + s);
}
});
pageChannel.bind("fetch_conversations", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
if(activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ChatEvents.getInstance().onNewConversation(new Conversation((new JSONObject(data)).getJSONObject("conversation")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
}
#Override
public void onSubscriptionSucceeded(String s) {
}
});
pageChannel.bind("fetch_comments", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
}
#Override
public void onSubscriptionSucceeded(String s) {
}
});
}
public void removeLisnterPage(String pageId) {
if (pusher != null) pusher.unsubscribe("private-" + Encrypt.stringMD5(pageId));
idPageChannelListen = "";
}
public void reconnectPusher() {
if (pusher != null) {
pusher.disconnect();
pusher.connect();
}
}
public void disconnectPusher() {
if (pusher != null) pusher.disconnect();
}
public String getIdPageChannelListen() {
return idPageChannelListen;
}
public class LocalBinder extends Binder {
public PusherServices getService() {
// Return this instance of LocalService so clients can call public methods
return PusherServices.this;
}
}
}

How to convert my Database class to Singleton

I'm a beginner in java and i'm practicing Singleton.
I'm trying to figure out how to convert my Database class to Singleton.
Also, part of my issue is how to use the Database class without passing the properties in the constructor.
public class Database {
public static final String DB_DRIVER_KEY = "db.driver";
public static final String DB_URL_KEY = "db.url";
public static final String DB_USER_KEY = "db.user";
public static final String DB_PASSWORD_KEY = "db.password";
private static Logger LOG = Logger.getLogger(Database.class.getName());
private static final Database theInstance = new Database();
private static Connection connection;
private static Properties properties;
private Database() {
}
public static void init(Properties properties) {
if (Database.properties == null) {
LOG.debug("Loading database properties from db.properties");
Database.properties = properties;
}
}
public static Connection getConnection() throws SQLException {
if (connection != null) {
return connection;
}
try {
connect();
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
return connection;
}
private static void connect() throws ClassNotFoundException, SQLException {
String dbDriver = properties.getProperty(DB_DRIVER_KEY);
LOG.debug(dbDriver);
Class.forName(dbDriver);
System.out.println("Driver loaded");
connection = DriverManager.getConnection(properties.getProperty(DB_URL_KEY),
properties.getProperty(DB_USER_KEY), properties.getProperty(DB_PASSWORD_KEY));
LOG.debug("Database connected");
}
/**
* Close the connections to the database
*/
public void shutdown() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
}
/**
* Determine if the database table exists.
*
* #param tableName
* #return true is the table exists, false otherwise
* #throws SQLException
*/
public static boolean tableExists(String tableName) throws SQLException {
DatabaseMetaData databaseMetaData = getConnection().getMetaData();
ResultSet resultSet = null;
String rsTableName = null;
try {
resultSet = databaseMetaData.getTables(connection.getCatalog(), "%", "%", null);
while (resultSet.next()) {
rsTableName = resultSet.getString("TABLE_NAME");
if (rsTableName.equalsIgnoreCase(tableName)) {
return true;
}
}
} finally {
resultSet.close();
}
return false;
}
/**
* #return the theinstance
*/
public static Database getTheinstance() {
return theInstance;
}
}
Well this little bit change into your existing class to make you understand.
public class Database {
public static final String DB_DRIVER_KEY = "db.driver";
public static final String DB_URL_KEY = "db.url";
public static final String DB_USER_KEY = "db.user";
public static final String DB_PASSWORD_KEY = "db.password";
private static Logger LOG = Logger.getLogger(Database.class.getName());
private static Database theInstance;
private static Connection connection;
private static Properties properties;
private Database() {
}
public static void init(Properties properties) {
if (Database.properties == null) {
LOG.debug("Loading database properties from db.properties");
Database.properties = properties;
}
}
public static Connection getConnection() throws SQLException {
if (connection != null) {
return connection;
}
try {
connect();
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
return connection;
}
private static void connect() throws ClassNotFoundException, SQLException {
String dbDriver = properties.getProperty(DB_DRIVER_KEY);
LOG.debug(dbDriver);
Class.forName(dbDriver);
System.out.println("Driver loaded");
connection = DriverManager.getConnection(
properties.getProperty(DB_URL_KEY),
properties.getProperty(DB_USER_KEY),
properties.getProperty(DB_PASSWORD_KEY));
LOG.debug("Database connected");
}
/**
* Close the connections to the database
*/
public void shutdown() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
}
/**
* Determine if the database table exists.
*
* #param tableName
* #return true is the table exists, false otherwise
* #throws SQLException
*/
public static boolean tableExists(String tableName) throws SQLException {
DatabaseMetaData databaseMetaData = getConnection().getMetaData();
ResultSet resultSet = null;
String rsTableName = null;
try {
resultSet = databaseMetaData.getTables(connection.getCatalog(),
"%", "%", null);
while (resultSet.next()) {
rsTableName = resultSet.getString("TABLE_NAME");
if (rsTableName.equalsIgnoreCase(tableName)) {
return true;
}
}
} finally {
resultSet.close();
}
return false;
}
/**
* #return the theinstance
*/
public static Database getInstance() {
if(theInstance == null){
theInstance = new Database();
}
return theInstance;
}
}

calling alarm from a service

I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()