I created a java class which return a DB connection object. But it is returning the null value at the caller method. When i am running the code in debug mode it is not going to the method itself. Need suggestions.
package com.cisco.installbase.hiveconnector;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
public class CreateConnection {
private static Connection instance = null;
static final String drivername = "org.apache.hive.jdbc.HiveDriver";
private CreateConnection() {
try {
Class.forName(drivername);
// instance =
// DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/",
// "phodisvc", "B1GD4T4dev");
// for hive 1 use this ------> instance =
// DriverManager.getConnection("thrift://hddev-c01-edge-02:9083");
instance = DriverManager.getConnection("thrift://hddev-c01-edge-02:9083");
System.out.println("get instance"+instance);
Constants.setFlag(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Constants.setFlag(false);
} catch (SQLException e) {
e.printStackTrace();
Constants.setFlag(false);
}
}
public static Connection getInstance() {
Constants.setFlag(true);
return instance;
}
}
Below is the code which is calling the getInstance() method
package com.cisco.installbase.hiveconnector;
import java.util.Date;
public class MainApp {
private static final String hiveDB = ReadProperties.getInstance().getProperty("hive_db");
private static final String logTable = ReadProperties.getInstance().getProperty("IB_log_table");
private static final String dataGovernanceLogTable = ReadProperties.getInstance().getProperty("SR_DG_table");
private static final String dataGovernanceMasterTable = ReadProperties.getInstance()
.getProperty("SR_DG_master_table");
private static final String count_xxccs_ds_sahdr_core = "select count(*) from " + hiveDB + "."
+ "xxccs_ds_sahdr_core";
private static final String count_mtl_system_items_b = "select count(*) from " + hiveDB + "."
+ "mtl_system_items_b";
private static final String count_xxccs_scdc_product_profile = "select count(*) from " + hiveDB + "."
+ "xxccs_scdc_product_profile";
private static final String count_xxccs_ds_cvdprdline_detail = "select count(*) from " + hiveDB + "."
+ "xxccs_ds_cvdprdline_detail";
private static final String count_xxccs_ds_instance_detail = "select count(*) from " + hiveDB + "."
+ "xxccs_ds_instance_detail";
private static int currentJobID = 0;
private static Date startTime = null;
private static Date stopTime = null;
private static int runTime = 0;
static CommonDBUtilities commonDB = new CommonDBUtilities();
static ShellUtilities shellUtilities = new ShellUtilities();
static SqoopUtility sqoop = new SqoopUtility();
public static void main(String[] args) {
MainApp.startTimeLogger();
System.out.println("Started the Job");
}
public static void startTimeLogger() {
// getting the Job ID and the start time for the log table
if (Constants.isFlag()) {
currentJobID = commonDB.getMaximumJobID();
startTime = commonDB.getTime();
MainApp.importTables();
System.out.println("executing startTimeLogger");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while logging method name startTimeLogger()");
System.out.println("executing startTimeLogger failed");
}
}
public static void importTables() {
// Delete target directory before running the sqoop imports
if (Constants.isFlag()) {
shellUtilities.DeleteDirectory(Constants.getMtlSystems());
shellUtilities.DeleteDirectory(Constants.getProductLine());
shellUtilities.DeleteDirectory(Constants.getInstanceDetail());
shellUtilities.DeleteDirectory(Constants.getProductLine());
shellUtilities.DeleteDirectory(Constants.getHeaderCore());
// Run the sqoop imports to load the data from oracle to hive
sqoop.runSqoop();
MainApp.getCounts();
System.out.println("executing importTables");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while running sqoop import method name importTables()");
System.out.println("executing importTables failed");
}
}
public static void getCounts() {
// Get the record counts for all the IB tables pulled
if (Constants.isFlag()) {
commonDB.getCounts(count_xxccs_ds_instance_detail);
commonDB.getCounts(count_xxccs_ds_cvdprdline_detail);
commonDB.getCounts(count_xxccs_scdc_product_profile);
commonDB.getCounts(count_mtl_system_items_b);
commonDB.getCounts(count_xxccs_ds_sahdr_core);
MainApp.stopTimeLogger();
System.out.println("executing getCounts");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while getting counts method name getCounts()");
System.out.println("executing getCounts failed");
}
}
public static void stopTimeLogger() {
// Get the stop time or end time
if (Constants.isFlag()) {
stopTime = commonDB.getTime();
MainApp.runTimeLogger();
System.out.println("executing stopTimeLogger");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while end logging method name stopTimeLogger()");
System.out.println("executing stopTimeLogger failed");
}
}
public static void runTimeLogger() {
// Get the run time or total time taken
if (Constants.isFlag()) {
runTime = (int) (stopTime.getTime() - startTime.getTime()) / 1000 * 60 * 60 * 24;
MainApp.onSuccess();
MainApp.logGovernance();
System.out.println("executing runTimeLogger");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while runtime logging method name runTimeLogger()");
System.out.println("executing runTimeLogger failed");
}
}
public static void logGovernance() {
// IB Data governance
if (Constants.isFlag()) {
String dataGovernance = "Insert into table " + hiveDB + "." + dataGovernanceLogTable
+ " select Data_Asset_Reference,File_Name,Origin_System,Transfer_System," + startTime
+ ",Column_Reference,Element_Reference,Rule_Priority,Delete_By_Date,Classification,Geographic_Inclusion,Geographic_Restriction,Group_Inclusion,Group_Restriction,Reserved from "
+ hiveDB + "." + dataGovernanceMasterTable;
commonDB.InsertToTable(dataGovernance);
System.out.println("executing logGovernance");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed",
"Load failed while inserting into datagovernance method name logGovernance()");
System.out.println("executing logGovernance failed");
}
}
public static void onFailure() {
// Write to log on Failure
String insertOnFailure = "insert into table " + hiveDB + "." + logTable + " select " + currentJobID + ","
+ stopTime + "," + runTime + "," + "FAILED from " + hiveDB + "." + "dual" + " limit 1; ";
commonDB.InsertToTable(insertOnFailure);
JobMailer.PostMail("IB Load Failed", "Load failed");
System.out.println("executing onFailure");
}
public static void onSuccess() {
// Write to log on Success
String insertOnSuccess = "insert into table " + hiveDB + "." + logTable + " select " + currentJobID + ","
+ stopTime + "," + runTime + "," + "SUCCESS from " + hiveDB + "." + "dual" + " limit 1; ";
commonDB.InsertToTable(insertOnSuccess);
JobMailer.PostMail("IB Load Successfully completed", "Load completed");
System.out.println("executing onSuccess");
}
}
private static Connection instance = null;
static final String drivername = "org.apache.hive.jdbc.HiveDriver";
public static Connection getInstance() {
if(instance==null){
try {
Class.forName(drivername);
instance = DriverManager.getConnection("thrift://hddev-c01-edge-02:9083");
Constants.setFlag(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Constants.setFlag(false);
} catch (SQLException e) {
e.printStackTrace();
Constants.setFlag(false);
}
}
return instance;
}
Your implementation of sigleton is wrong.
You never call the constructor. This is th correct way to implement a singleton.
public static Connection getInstance() {
if (instance==null){
instance = new CreateConnection();
}
Constants.setFlag(true);
return instance;
}
You never call the constructor CreateConnection() (besides, this shouldn't be a constructor anyway, rather a utility method returning a Connection).
Related
I want to take base64 screenshot for all the passed and failed screenshots with testNG, below is my code.
private static ExtentReports extent;
private static Platform platform;
private static String reportFileName = "ExtentReports-Version3-Test-Automaton-Report.html";
private static String macPath = System.getProperty("user.dir")+ "/TestReport";
private static String windowsPath = System.getProperty("user.dir")+ "\TestReport";
private static String macReportFileLoc = macPath + "/" + reportFileName;
private static String winReportFileLoc = windowsPath + "\" + reportFileName;
public static ExtentReports getInstance() {
if (extent == null)
createInstance();
return extent;
}
//Create an extent report instance
public static ExtentReports createInstance() {
platform = getCurrentPlatform();
String fileName = getReportFileLocation(platform);
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
extent = new ExtentReports();
extent.setSystemInfo("Author", "Gladson Antony");
extent.setSystemInfo("Browser", Browser);
extent.setSystemInfo("OS", OSName);
extent.setSystemInfo("OS Version", OSVersion);
extent.setSystemInfo("OS Architecture", OSArchitecture);
extent.setSystemInfo("OS Bit", OSBit);
extent.setSystemInfo("JAVA Version",System.getProperty("java.version"));
extent.attachReporter(htmlReporter);
return extent;
}
//Select the extent report file location based on platform
private static String getReportFileLocation (Platform platform) {
String reportFileLocation = null;
switch (platform) {
case MAC:
reportFileLocation = macReportFileLoc;
createReportPath(macPath);
System.out.println("ExtentReport Path for MAC: " + macPath + "\n");
break;
case WINDOWS:
reportFileLocation = winReportFileLoc;
createReportPath(windowsPath);
System.out.println("ExtentReport Path for WINDOWS: " + windowsPath + "\n");
break;
default:
System.out.println("ExtentReport path has not been set! There is a problem!\n");
break;
}
return reportFileLocation;
}
//Create the report path if it does not exist
private static void createReportPath (String path) {
File testDirectory = new File(path);
if (!testDirectory.exists()) {
if (testDirectory.mkdir()) {
System.out.println("Directory: " + path + " is created!" );
} else {
System.out.println("Failed to create directory: " + path);
}
} else {
System.out.println("Directory already exists: " + path);
}
}
//Get current platform
private static Platform getCurrentPlatform () {
if (platform == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
platform = Platform.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
platform = Platform.LINUX;
} else if (operSys.contains("mac")) {
platform = Platform.MAC;
}
}
return platform;
}
Below is my listerner class where I take screenshot for each passed test case using Base64 format.
private static ExtentReports extent = ExtentManager.createInstance();
private static ThreadLocal test = new ThreadLocal();
public synchronized void onStart(ITestContext context) {
System.out.println("Test Suite started!");
}
public synchronized void onFinish(ITestContext context) {
System.out.println(("Test Suite is ending!"));
extent.flush();
}
public synchronized void onTestStart(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " started!"));
ExtentTest extentTest = extent.createTest(result.getMethod().getMethodName(),
result.getMethod().getDescription());
test.set(extentTest);
}
public synchronized void onTestSuccess(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " passed!"));
test.get().pass("Test passed");
try {
test.get().pass(result.getTestClass().getName() + "." + result.getMethod().getMethodName(),
MediaEntityBuilder.createScreenCaptureFromBase64String(TestBase.addScreenshot()).build());
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(result.getThrowable());
try {
test.get().fail(result.getTestClass().getName() + "." + result.getMethod().getMethodName(),
MediaEntityBuilder.createScreenCaptureFromBase64String(TestBase.addScreenshot()).build());
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void onTestSkipped(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " skipped!"));
test.get().skip(result.getThrowable());
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
System.out.println(("onTestFailedButWithinSuccessPercentage for " + result.getMethod().getMethodName()));
}
Thanks in advance for the favour!!
I have written a small program in Java (eclipse) to run R using JRI (rjava). All paths are set. The problem is that while I can run numeric functions (like add), I can't run a string function like cat. (please excuse any errors; I did Java coding for the first time yesterday).
package com.trial.ss;
import org.rosuda.JRI.Rengine;
public class RScriptConnection {
public Rengine getRScriptEngine() throws Exception {
Rengine engine = null;
try {
engine = Rengine.getMainEngine();
if (engine == null) engine = new Rengine(new String[] {
"--vanilla"
},
false, null);
/* if (!engine.waitForR()) {
System.out.println("Unable to load R");
return null;
} else*/
System.out.println("Connected to R");
String rScriptSourceFile = "source('" + RScriptConstant.RS_FILE_LOCATION + "',verbose=TRUE)";
engine.eval(rScriptSourceFile);
System.out.println("loading RScript file || completed");
//return engine;
} catch(Exception ex) {
System.out.println("Exeption while connecting to REngine " + ex.getMessage());
//throw new Exception("Error while creating REngine in RScriptConnection:getRScriptEngine()");
}
return engine;
}
public static void main(String[] args) {
String libpath = System.getProperty("java.library.path");
System.out.println("##############libpath=" + libpath);
// System.out.println("Method to be called in RScript=" + "Add(x1 = " + 10 + ", x2 = " + 20 + ", x3 = " + 30 + ", x4 = " + 50 + ")");
RScriptConnection rScriptConnection = new RScriptConnection();
try {
Rengine rEngine = rScriptConnection.getRScriptEngine();
String Value1 = "\"Advisory\"";
String Value2 = "\"Assurance\"";
double svalue = rEngine.eval("(1+2)").asDouble();
System.out.println("mvalue=" + svalue);
System.out.println("method to be called in RScript is " + "cat(" + Value1 + "," + Value2 + ")");
String value = rEngine.eval("cat(" + Value1 + "," + Value2 + ")").asString();
System.out.println(value);
rEngine.end();
} catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please help me understand why my string function like cat doesn't work.
Here is the output I am currently getting:
##############libpath=C:\Users\myname\Documents\R\win-library\3.3\rJava\jri\x64
Connected to R
loading RScript file || completed
mvalue=3.0
method to be called in RScript is cat("Advisory","Assurance")
null
Why am I getting null in the end? I should get Advisory Assurance
Bellow is an example of how to show R output into Java. You basically have to implement RMainLoopCallbacks.
import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import java.util.logging.Logger;
public class Runner {
private static Logger log = Logger.getLogger("Runner");
static class LoggingConsole implements RMainLoopCallbacks {
private Logger log;
LoggingConsole(Logger log) {
this.log = log;
}
public void rWriteConsole(Rengine re, String text, int oType) {
log.info(String.format("rWriteConsole: %s", text));
}
public void rBusy(Rengine re, int which) {
log.info(String.format("rBusy: %s", which));
}
public void rShowMessage(Rengine re, String message) {
log.info(String.format("rShowMessage: %s", message));
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
return null;
}
public String rChooseFile(Rengine re, int newFile) {
return null;
}
public void rFlushConsole(Rengine re) {
}
public void rLoadHistory(Rengine re, String filename) {
}
public void rSaveHistory(Rengine re, String filename) {
}
}
Rengine engine = new Rengine(new String[] {"--no-save"}, false, new LoggingConsole(log));
...
// Use the engine somewhere to evaluate a R method and see the output
engine.eval(rScriptSourceFile);
}
I am writing an Android application that queries a database with 170,000 dictionary words. (It has 31 columns: _id, word, sortedWord, length, and count_A, count_B, count_C, ... count_Z)
Here is the code for my Dictionary database helper
public class DictionaryDbHelper extends SQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.rabbitfighter.wordsleuth/databases/";
// Database name
private static String DB_NAME = "dictionary.db";
// Database, and context
private SQLiteDatabase myDataBase;
private final Context myContext;
// Table name
public static final String TABLE_NAME = "dictionary";
// Table columns
public static final String UID = "_id";
// Word
public static final String COLUMN_NAME_WORD = "word";
// Length
public static final String COLUMN_NAME_WORD_LENGTH = "length";
// For all the letters, A-Z.
public static final String COLUMN_NAME_COUNT_A = "count_A";
public static final String COLUMN_NAME_COUNT_B = "count_B";
public static final String COLUMN_NAME_COUNT_C = "count_C";
public static final String COLUMN_NAME_COUNT_D = "count_D";
public static final String COLUMN_NAME_COUNT_E = "count_E";
public static final String COLUMN_NAME_COUNT_F = "count_F";
public static final String COLUMN_NAME_COUNT_G = "count_G";
public static final String COLUMN_NAME_COUNT_H = "count_H";
public static final String COLUMN_NAME_COUNT_I = "count_I";
public static final String COLUMN_NAME_COUNT_J = "count_J";
public static final String COLUMN_NAME_COUNT_K = "count_K";
public static final String COLUMN_NAME_COUNT_L = "count_L";
public static final String COLUMN_NAME_COUNT_M = "count_M";
public static final String COLUMN_NAME_COUNT_N = "count_N";
public static final String COLUMN_NAME_COUNT_O = "count_O";
public static final String COLUMN_NAME_COUNT_P = "count_P";
public static final String COLUMN_NAME_COUNT_Q = "count_Q";
public static final String COLUMN_NAME_COUNT_R = "count_R";
public static final String COLUMN_NAME_COUNT_S = "count_S";
public static final String COLUMN_NAME_COUNT_T = "count_T";
public static final String COLUMN_NAME_COUNT_U = "count_U";
public static final String COLUMN_NAME_COUNT_V = "count_V";
public static final String COLUMN_NAME_COUNT_W = "count_W";
public static final String COLUMN_NAME_COUNT_X = "count_X";
public static final String COLUMN_NAME_COUNT_Y = "count_Y";
public static final String COLUMN_NAME_COUNT_Z = "count_Z";
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DictionaryDbHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/* ------------------------ */
/* --- Override Methods --- */
/* ------------------------ */
/**
* On creation
* #param db - the database
*/
public void onCreate(SQLiteDatabase db) {
//Nothing to do here
}
/**
* On upgrade
* #param db - the database
* #param oldVersion - the old database version int
* #param newVersion - the new database version int
*/
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "Database " + db + " version " + oldVersion + " upgraded to " + newVersion);
}
/**
* On downgrade
* #param db - the database
* #param oldVersion - the old database version int
* #param newVersion - the new database version int
*/
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "Database " + db + " version " + oldVersion + " downgraded to " + newVersion);
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
if(checkDataBase()){
//do nothing - database already exist
Log.i(TAG, "Database already exists... Nothing to do.");
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
Log.i(TAG, "Successfully copied database");
} catch (IOException e) {
Log.i(TAG, "Error copying");
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database doesn't exist yet.
Log.i(TAG, "Database doesn't exist yet");
}
// Check for null db
if(checkDB != null){
checkDB.close();
Log.i(TAG, "Closed dict database");
}
// Return null or not null
return checkDB != null;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null) {
Log.i(TAG, "Closing dictionary database");
myDataBase.close();
}
super.close();
}
/* -------------------------- */
/* --- Database retrieval --- */
/* -------------------------- */
/**
* Get the Anagrams in the database
* #return the number of anagrams
*/
public ArrayList<Result> getMatches(
// Params. Yeah, I know...
int count_A, int count_B, int count_C, int count_D, int count_E, int count_F,
int count_G, int count_H, int count_I, int count_J, int count_K, int count_L,
int count_M, int count_N, int count_O, int count_P, int count_Q, int count_R,
int count_S, int count_T, int count_U, int count_V, int count_W, int count_X,
int count_Y, int count_Z, int count_WILDCARDS
) {
// Get the database helper to get access to everything...
SQLiteDatabase db = this.getWritableDatabase();
// List to hold matches
ArrayList<Result> resultList = new ArrayList<>();
// Here are the columns we care about in our search
String[] columns = {
UID,
COLUMN_NAME_WORD,
COLUMN_NAME_WORD_LENGTH,
COLUMN_NAME_COUNT_A,
COLUMN_NAME_COUNT_B,
COLUMN_NAME_COUNT_C,
COLUMN_NAME_COUNT_D,
COLUMN_NAME_COUNT_E,
COLUMN_NAME_COUNT_F,
COLUMN_NAME_COUNT_G,
COLUMN_NAME_COUNT_H,
COLUMN_NAME_COUNT_I,
COLUMN_NAME_COUNT_J,
COLUMN_NAME_COUNT_K,
COLUMN_NAME_COUNT_L,
COLUMN_NAME_COUNT_M,
COLUMN_NAME_COUNT_N,
COLUMN_NAME_COUNT_O,
COLUMN_NAME_COUNT_P,
COLUMN_NAME_COUNT_Q,
COLUMN_NAME_COUNT_R,
COLUMN_NAME_COUNT_S,
COLUMN_NAME_COUNT_T,
COLUMN_NAME_COUNT_U,
COLUMN_NAME_COUNT_V,
COLUMN_NAME_COUNT_W,
COLUMN_NAME_COUNT_X,
COLUMN_NAME_COUNT_Y,
COLUMN_NAME_COUNT_Z,
};
String[] selectionArgs = null;
// The selection (WHERE ...)
String selection =
COLUMN_NAME_COUNT_A +"<="+ count_A + " AND " +
COLUMN_NAME_COUNT_B +"<="+ count_B + " AND " +
COLUMN_NAME_COUNT_C +"<="+ count_C + " AND " +
COLUMN_NAME_COUNT_D +"<="+ count_D + " AND " +
COLUMN_NAME_COUNT_E +"<="+ count_E + " AND " +
COLUMN_NAME_COUNT_F +"<="+ count_F + " AND " +
COLUMN_NAME_COUNT_G +"<="+ count_G + " AND " +
COLUMN_NAME_COUNT_H +"<="+ count_H + " AND " +
COLUMN_NAME_COUNT_I +"<="+ count_I + " AND " +
COLUMN_NAME_COUNT_J +"<="+ count_J + " AND " +
COLUMN_NAME_COUNT_K +"<="+ count_K + " AND " +
COLUMN_NAME_COUNT_L +"<="+ count_L + " AND " +
COLUMN_NAME_COUNT_M +"<="+ count_M + " AND " +
COLUMN_NAME_COUNT_N +"<="+ count_N + " AND " +
COLUMN_NAME_COUNT_O +"<="+ count_O + " AND " +
COLUMN_NAME_COUNT_P +"<="+ count_P + " AND " +
COLUMN_NAME_COUNT_Q +"<="+ count_Q + " AND " +
COLUMN_NAME_COUNT_R +"<="+ count_R + " AND " +
COLUMN_NAME_COUNT_S +"<="+ count_S + " AND " +
COLUMN_NAME_COUNT_T +"<="+ count_T + " AND " +
COLUMN_NAME_COUNT_U +"<="+ count_U + " AND " +
COLUMN_NAME_COUNT_V +"<="+ count_V + " AND " +
COLUMN_NAME_COUNT_W +"<="+ count_W + " AND " +
COLUMN_NAME_COUNT_X +"<="+ count_X + " AND " +
COLUMN_NAME_COUNT_Y +"<="+ count_Y + " AND " +
COLUMN_NAME_COUNT_Z +"<="+ count_Z;
String groupBy = null;
String having = null;
String orderBy = null;
// Query the database
Cursor cursor = db.query(
TABLE_NAME, // Table name
columns, // Columns
selection, // Selection
selectionArgs, // Selection arguments
groupBy, // Group by...
having, // having
orderBy // Order by
);
while (cursor.moveToNext()) {
int columnResult = cursor.getColumnIndex(COLUMN_NAME_WORD);
// Add the result to the list to return
resultList.add(new Result(cursor.getString(columnResult)));
}
cursor.close();
// Return the list
return resultList;
}
}//EOF
And here is where I query the Dictionary in another class:
How can I query for wildcards given my current setup? I am new to sql, so any suggestions would be greatly appreciated... I am looking for a parameter for the WHERE clause to allow for up to 2 wildcards, each of which could be anything from A-Z.
Here is an example of how i'm doing a lookup now, from my search service:
DictionaryDbHelper helper = DictionaryDbHelper(this);
ArrayList<Result> matches = helper.getMatches(
this.getQuery().getCount_A(), this.getQuery().getCount_B(),
this.getQuery().getCount_C(), this.getQuery().getCount_D(),
this.getQuery().getCount_E(), this.getQuery().getCount_F(),
this.getQuery().getCount_G(), this.getQuery().getCount_H(),
this.getQuery().getCount_I(), this.getQuery().getCount_J(),
this.getQuery().getCount_K(), this.getQuery().getCount_L(),
this.getQuery().getCount_M(), this.getQuery().getCount_N(),
this.getQuery().getCount_O(), this.getQuery().getCount_P(),
this.getQuery().getCount_Q(), this.getQuery().getCount_R(),
this.getQuery().getCount_S(), this.getQuery().getCount_T(),
this.getQuery().getCount_U(), this.getQuery().getCount_V(),
this.getQuery().getCount_W(), this.getQuery().getCount_X(),
this.getQuery().getCount_Y(), this.getQuery().getCount_Z(),0 // wildcards not in use yet
)
In my app I need to add string vallues to the file(.property file, if it is important). and user enter this values in gwt GUI. Here is it's important part:
final Button submit = new Button("Submit");
addButton(submit);
submit.addSelectionListener(new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
keyWord.selectAll();
regexp.selectAll();
if (keyWord.getValue() != null){
setKeyWord(customerId, keyWord.getValue());
keyWord.setValue("");
}
if (regexp.getValue() != null){
setRegExp(customerId, regexp.getValue());
regexp.setValue("");
}
}
});
}
private void setKeyWord(final String customerId, final String keyword){
final AsyncCallback<String> callbackItems = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("unable to add " + caught.toString());
}
public void onSuccess(final String x) {
Window.alert(x);
}
};
serverManagementSvc.setKeyWords(customerId, keyword, callbackItems);
}
private void setRegExp(final String customerId, final String regexp){
final AsyncCallback<String> calbackItems = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
Window.alert("unable to add " + throwable.toString());
}
#Override
public void onSuccess(String s) {
Window.alert(s);
}
};
serverManagementSvc.setRegExp(customerId, regexp, calbackItems);
}
So I need to use Asunccallback to call methods which are in the "server part".
here are these methods:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords" + "," + word));
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps" + "," + regexp));
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
all interfaces are present.
when I run my code And press "submit" button in gui I see that both asynccallback failured(Window.alert, as you can see, shows "null pointer exception" despite of the fact that values which I send to methods are not null). why can it be? can you suggest me something?
UPD here is error which is shown by firebug:
uncaught exception: java.lang.ClassCastException
function W8(){try{null.a()}catch(a){return a}}
the problem is solved: there were a simple mistake in the code. I've closed brackets at the wrong place:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords") + "," + word);
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps") + "," + regexp);
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
I recommend that you recompile the GWT code using
-style PRETTY
and then check that firebug output again; it may give you a better clue, compared to your updated uncaught exception.
Next, I suggest you run it in the eclipse debugger, and set breakpoints in both the client and server code, and then you can inspect the variables and step through the code.
I try to connect to a custom Bluetooth device using BlueCove. I can pair the device, but when I try to search for services I always get SERVICE_SEARCH_DEVICE_NOT_REACHABLE in serviceSearchCompleted() and no services are discovered. If I try the same thing outside Java (in Windows), the PC bluetooth device discovers and can connect (using COM21, COM22, ...) to the SPP service on my device.
What am I doing wrong?
I also tried to do the service search after the device discovery is ended. Same issue.
Please find below my code.
Many thanks in advance for any idea on how to solve this,
Adrian.
public class Test {
private static Logger LOG = Logger.getLogger(Test.class.getName());
private static final String NAME = "XXXX";
private static final String PIN = "1234";
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003), new UUID(0x1101)};
private LocalDevice localDevice;
private DiscoveryAgent discoveryAgent;
private DiscoveryListener discoveryListener = new GDiscoveryListener();
private Map<Integer, RemoteDevice> searchForServices = new HashMap<Integer, RemoteDevice>();
private Collection<ServiceRecord> servicesDiscovered = new HashSet<ServiceRecord>();
private Object lock = new Object();
private CountDownLatch waitForDevices;
protected void connect() {
try {
localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
LOG.info("Local Device: " + localDevice.getFriendlyName()
+ "(" + localDevice.getBluetoothAddress() + ")");
discoveryAgent = localDevice.getDiscoveryAgent();
LOG.finest("Start discovering devices");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoveryListener);
try {
synchronized(lock) {
lock.wait();
}
if (searchForServices.size() > 0) {
waitForDevices = new CountDownLatch(searchForServices.size());
waitForDevices.await();
}
}
catch (InterruptedException e) {
LOG.log(Level.WARNING, "Error waiting to terminate discovery", e);
}
LOG.finest(servicesDiscovered.size() + " services discovered");
LOG.finest("Device discovery completed");
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Error initializing Bluetooth", e);
}
}
private class GDiscoveryListener implements DiscoveryListener {
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
try {
String name = rd.getFriendlyName(false);
boolean isMine = NAME.equals(name);
LOG.info("Discovered: " + name + "(" + rd.getBluetoothAddress() + ")"
+ (isMine ? "" : " - ignoring"));
if (!isMine)
return;
if (!rd.isAuthenticated()) {
LOG.finest("Try to pair with " + name
+ " PIN: " + PIN);
boolean paired = RemoteDeviceHelper.authenticate(rd, PIN);
LOG.info("Pair with " + name + (paired ? " succesfull" : " failed"));
}
int transID = discoveryAgent.searchServices(null, UUIDS, rd, discoveryListener);
searchForServices.put(transID, rd);
LOG.finest("Searching for services for " + name + " with transaction " + transID);
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), e);
} catch (IOException e) {
LOG.log(Level.WARNING, "Error connecting ", e);
} catch (Throwable t) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), t);
}
}
public void inquiryCompleted(int respCode) {
synchronized(lock) {
lock.notify();
}
switch (respCode) {
case DiscoveryListener.INQUIRY_COMPLETED :
LOG.fine("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
LOG.fine("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
LOG.fine("INQUIRY_ERROR");
break;
default :
LOG.fine("Unknown Response Code - " + respCode);
break;
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String rd = searchForServices.get(transID).getBluetoothAddress();
//searchForServices.remove(transID);
switch (respCode) {
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
LOG.fine(rd + ": The service search completed normally");
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
LOG.fine(rd + ": The service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch(int)");
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
LOG.warning(rd + ": An error occurred while processing the request");
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
LOG.info(rd + ": No records were found during the service search");
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
LOG.warning(rd + ": The device specified in the search request could not be reached or the local device could not establish a connection to the remote device");
break;
default:
LOG.warning(rd + ": Unknown Response Code - " + respCode);
break;
}
if (waitForDevices != null)
waitForDevices.countDown();
}
public void servicesDiscovered(int transID, ServiceRecord[] srs) {
LOG.info("Services discovered in transaction " + transID + " : " + srs.length);
for (ServiceRecord sr : srs) {
LOG.info(sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
servicesDiscovered.add(sr);
}
}
}
public static void main(String[] args) {
new Test().connect();
}
}
I had the same problem while connecting to a Bluetooth earpiece. Like you I was also searching for more than one service at a time and It always returned SERVICE_SEARCH_DEVICE_NOT_REACHABLE. So, I tried searching for only one service and it worked. So, try modifying your code as:
...
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003)}