I would like to access a string variable from another class to put it into an SQlite DB but I get an error "cannot be resolved or not a field
Here is the code
timestamp.java
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.commons.io.FileUtils;
public class timestamp {
public static String doSomething() throws IOException {
File source = new File("C:/Users/India/Desktop/Test/Sub/Test.docx");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH-mm-ss-ms");
String ts=sdf.format(source.lastModified());
System.out.print(ts);
//String[] TimeStamp = source.lastModified().toString();
String name = source.getName();
String ext = name.substring(name.lastIndexOf("."));
name = name.substring(0, name.lastIndexOf("."));
String outFileName = name + " " + ts + ext;
//System.out.println(" new file name is " + outFileName);
File destination = new File("C:/Users/India/Desktop/Test", outFileName);
FileUtils.copyFile(source,destination);
return ts;
}
public static void main (String [] args) throws IOException
{ doSomething();}}
SQLiteJDBC.java
import java.io.IOException;
import java.sql.*;
public class SQLiteJDBC{
public static void InsertValues( String args[] ) throws IOException
{ timestamp t = new timestamp();
String var = t.ts;
System.out.println(t.ts);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
PreparedStatement prep1 = c.prepareStatement ("INSERT INTO ACTIONLOG VALUES (?,?, ?);") ;
prep1.setString(1, var);
prep1.addBatch();
c.setAutoCommit(false);
prep1.executeBatch();
c.setAutoCommit(true);
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
public static void main( String args[] ) throws IOException
{ InsertValues(args);
}
}
I am not able to access the ts string in the database class. I either get a NULL value or an error.
Thanks a lot in advance !
Since You are Trying to Access Local Variable from Another Class. better then that go ahead with global variable.update code like that only one line define after class
public class timestamp {
String ts;// Define Here (global variable )
}
You need to create an accessor method within the class and change 'ts' to a global variable. This way, when you instatiate this class, you can simply retrieve it using something like:
MyClass.getStringName();
where 'getStringName()' is something like:
public String getStringName()
{
return ts;
}
All of your variables are in class methods, not in class area.
In Class add variable String, not in class method.
Related
I don't know if I need more coffee, or my head is tired, but, I feel like an idiot :)
what am I doing wrong???
I want to call the methods within the class but I get complile errors.
Compilation failure: Compilation failure:
java:[35,1] error: illegal start of type
java:[35,21] error: <identifier> expected
java:[35,22] error: ';' expected
I can't execute this block in the class
//this is what doesn't work
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
} else {
this.loadRefDb(custkey);
}
}
my class
package com.ge.digital.fleet.dataservice.impl.processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
import com.ge.digital.fleet.dataservice.impl.db.RefDatabase;
public class RefReplicatedDataProcessor {
private static final Logger log = LoggerFactory.getLogger(RefReplicatedDataProcessor.class);
private RefDatabase refDb = null;
private DataSource dataSource;
private String custkey;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setCustkey(String custkey) {
this.custkey = custkey;
}
public void setRefDatabase(RefDatabase refDb) {
this.refDb = refDb;
}
//this is what doesn't work
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
} else {
this.loadRefDb(custkey);
}
}
public void loadRefDb(String custkey) throws SQLException {
log.info("Reference Replicated Data Processor :: start");
refDb.dropDb();
setAssociations(custkey);
refDb.replicationComplete();
log.info("Reference Replicated Data Processor :: Finish");
}
/***
* name: setAssociations(custkey)
* Loads/Builds the cache database with values found in mysql database
*
* returns a List of associations
* G1.DWATT,112-A-001_Gas_Turbine
* G1.ATID,112-A-001_Gas_Turbine
* G1.dvar, 112-A-001_Gas_Turbine
* ...
*/
public void setAssociations(String custkey) throws SQLException {
String reference = "";
String asset = "";
String dbname = "iprcmt1.fleet_associations"; //from old impl database - TODO new database impl
String query = "select reference, asset from " + dbname + " where custkey = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, custkey);
try (ResultSet rs = stmt.executeQuery()) {
if (! rs.next() ) {
log.info("SQL Warning ! No associations for key: " + custkey);
} else {
do {
reference = rs.getString(1);
asset = rs.getString(2);
log.info("SQL Associations reference: " + reference + " and asset: " + asset);
refDb.addRow(reference, asset);
} while (rs.next());
}
} catch (Exception ex) {
log.error("SQL Cannot Execute ResultSet Query!");
log.error(ex.getMessage());
}
} catch (Exception e) {
log.error("SQL Cannot Create DataSource Connection! Cannot Create Prepared Statement!");
log.error(e.getMessage());
}
}
}
maybe this ? :)
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
}
}else {
this.loadRefDb(custkey);
}
Your code is simply out of place. The code at "//this is what doesn't work" needs to be inside a method or constructor.
public RefReplicatedDataProcessor(){
//this is what didn't work
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
}
} else {
this.loadRefDb(custkey);
}
}
Perhaps you should run the split within a method
public void filter(){
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
} else {
this.loadRefDb(custkey);
}
}
}
I am working on a Get object as retrieved from a table in Habse. I want to dynamically retrieve all column values related to that get since I don't know the exact name of column families
val result1 = hTable.get(g)
if (!result1.isEmpty) {
//binaryEpisodes = result1.getValue(Bytes.toBytes("episodes"),Bytes.toBytes("episodes"))
//instead of above retrieve all values dynamically
}
Simple way :
get rawcells and knowing CF , columns information.
You have to do something like below example
public static void printResult(Result result, Logger logger) {
logger.info("Row: ");
for (Cell cell : result.rawCells()) {
byte[] family = CellUtil.cloneFamily(cell);
byte[] column = CellUtil.cloneQualifier(cell);
byte[] value = CellUtil.cloneValue(cell);
logger.info("\t" + Bytes.toString(family) + ":" + Bytes.toString(column) + " = " + Bytes.toString(value));
}
}
Hbase Admin way : Hbase client API was exposed by HbaseAdmin class like below...
Client would be like
package mytest;
import com.usertest.*;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListHbaseTablesAndColumns {
public static void main(String[] args) {
try {
HbaseMetaData hbaseMetaData =new HbaseMetaData();
for(String hbaseTable:hbaseMetaData .getTableNames(".*yourtables.*")){
for (String column : hbaseMetaData .getColumns(hbaseTable, 10000)) {
System.out.println(hbaseTable + "," + column);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use below class to Get HbaseMetaData..
package com.usertest;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.PageFilter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
public class HbaseMetaData {
private HBaseAdmin hBaseAdmin;
private Configuration hBaseConfiguration;
public HbaseMetaData () throws IOException {
this.hBaseConfiguration = HBaseConfiguration.create();
this.hBaseAdmin = new HBaseAdmin(hBaseConfiguration);
}
/** get all Table names **/
public List<String> getTableNames(String regex) throws IOException {
Pattern pattern=Pattern.compile(regex);
List<String> tableList = new ArrayList<String>();
TableName[] tableNames=hBaseAdmin.listTableNames();
for (TableName tableName:tableNames){
if(pattern.matcher(tableName.toString()).find()){
tableList.add(tableName.toString());
}
}
return tableList;
}
/** Get all columns **/
public Set<String> getColumns(String hbaseTable) throws IOException {
return getColumns(hbaseTable, 10000);
}
/** get all columns from the table **/
public Set<String> getColumns(String hbaseTable, int limitScan) throws IOException {
Set<String> columnList = new TreeSet<String>();
HTable hTable=new HTable(hBaseConfiguration, hbaseTable);
Scan scan=new Scan();
scan.setFilter(new PageFilter(limitScan));
ResultScanner results = hTable.getScanner(scan);
for(Result result:results){
for(KeyValue keyValue:result.list()){
columnList.add(
new String(keyValue.getFamily()) + ":" +
new String(keyValue.getQualifier())
);
}
}
return columnList;
}
}
package lucene;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.DateTools.Resolution;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Lucenetest {
//database connection
public static final String PATH = "C:/dbindex/index.txt";
private static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String CONNECTION_URL = "jdbc:sqlserver://WMDENTW1\\SQLEXPRESS:1433;" +
"database=FullTextDB;" +
"user=root;" +
"password=root123";
private static final String QUERY = "select FTID, ID, CLASSID, TEXT, PUBNOTICECONTENT, DOCUMENTCONTENT, contentSum_DE from METADATA_FULLTEXT";
public static void main(String[] args) throws Exception {
Lucenetest indexer = new Lucenetest();
//error here
***Directory indexDir = FSDirectory.open(new File(PATH).toPath());***
try {
// Index Writer
Class . forName ( JDBC_DRIVER ). newInstance ();
Connection conn = DriverManager.getConnection(CONNECTION_URL);
StandardAnalyzer analyzer = new StandardAnalyzer();
IndexWriterConfig config = new IndexWriterConfig ( analyzer );
IndexWriter index writer = new IndexWriter ( indexDir , config );
System.out.println("Indexing to directory '" + indexDir + "'...");
int indexedDocumentCount = indexer.indexDocs1(indexWriter, conn);
index writer . close ();
System.out.println(indexedDocumentCount + " records have been indexed successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
int indexDocs1(IndexWriter writer, Connection conn) throws Exception {
String sql = QUERY;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int i=0;
while (rs.next()) {
Document d = new Document();
d.add(new StringField("FTID", rs.getString("FTID"), StringField.Store.YES));
d.add(new StringField("ID", rs.getString("ID"), StringField.Store.YES));
d.add(new StringField("CLASSID", rs.getString("CLASSID"), StringField.Store.YES));
d.add(new StringField("TEXT", rs.getString("TEXT"), StringField.Store.YES));
d.add(new StringField("PUBNOTICECONTENT", rs.getString("PUBNOTICECONTENT"), StringField.Store.YES));
d.add(new StringField("DOCUMENTCONTENT", rs.getString("DOCUMENTCONTENT"), StringField.Store.YES));
d.add(new StringField("contentSum_DE", rs.getString("contentSum_DE"), StringField.Store.YES));
writer.addDocument(d);
i++;
}
return i;
}
private static void indexDocs(IndexWriter writer, Connection conn) {
// TODO Auto-generated method stub
}
}
I am getting an exception, Indexing to directory:
MMapDirectory#C:\dbindex lockFactory=org.apache.lucene.store.NativeFSLockFactory#4493d195'...
java.lang.IllegalArgumentException: value cannot be null at
org.apache.lucene.document.Field.(Field.java:238) at
org.apache.lucene.document.StringField.(StringField.java:61) at
lucene.Lucenetest.indexDocs1(Lucenetest.java:80) at
lucene.Lucenetest.main(Lucenetest.java:56)
Not really sure what I missed.
Where you have marked this exception occurring in your code doesn't make sense. That exception is being thrown within your IndexDocs1 method.
StringField and TextField will both throw an IllegalArgumentException if the value (or field name) are null. When importing from a nullable field in your database, you should check for null values and either skip the field, or replace it with a default value (using a default value is very useful if you want to be able to query for nulls).
Also: Your Directory should be a directory. The line:
Directory indexDir = FSDirectory.open(new File("C:/dbindex/index.txt").toPath());
will create a new directory called "index.txt", not a file. If such a file already exists, then that line will throw a FileAlreadyExistsException.
package com.demo.mongodb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
public class Driver {
private static DBCollection channelDBcollection;
public static void main(String[] args) throws IOException {
DB db = (new MongoClient("localhost",27017)).getDB("demo");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
boolean flag = false;
while(!flag) flag = autenticate(db, bufferedReader);
}
private static boolean autenticate(DB db, BufferedReader bufferedReader) throws IOException{
boolean flag = true;
System.out.println("User: ");
String user = bufferedReader.readLine();
System.out.println("Password: ");
String password = bufferedReader.readLine();
if(db.authenticate(user, password.toCharArray())){
DBCollection channDbCollection = db.getCollection("Channel");
String command = null;
while(true){
System.out.println("What do you want to do ? ");
command = bufferedReader.readLine();
if(command.equals("exit")) break ;
else if(command.equals("findALL")) findAll(channDbCollection);
else if(command.equals("insertJSON")) insertJSON(bufferedReader,channDbCollection);
}
}
else{
System.out.println("invalid user/password");
flag = false;
}
return flag;
}
private static void findAll(DBCollection dbCollection){
DBCursor dbCursor = channelDBcollection.find();
while(dbCursor.hasNext()) System.out.println(dbCursor.next());
}
private static void insertJSON(BufferedReader bufferedReader,DBCollection channDbCollection) throws IOException {
System.out.println("JSON: ");
channDbCollection.insert((DBObject) JSON.parse(bufferedReader.readLine()));
}
}
I make Database in MongoDB like :-
use demo
db.addUser("root","root")
While i executed application then while i enter for JSON , i found null pointer can someone help me to take out of this ?
in your
private static void findAll(DBCollection dbCollection){
DBCursor dbCursor = channelDBcollection.find();
while(dbCursor.hasNext()) System.out.println(dbCursor.next());
}
function, you use global variable channelDBcollection (which is null at the time of call) instead of parameter dbCollection (which is not used anywhere in the method);
what you think is "not null" is the local variable with confusing name "channDbCollection", but it's not used anywhere;
I suggest you to revise your approach to naming, using global variables and coding style in general.
I wrote a servlet file SignUp.java and a helper file Updater.java. SignUp gathers the user info from a form filled by the user. Then it sends the info to Updater so that Updater updates the table in the database using the info. But when I fill the form and click submit, nothing changes. The weird thing is that when I wrote a test file and used it to supply the Updater with some dummy values, the table was updated with those dummy values. -
SignUp.java
package com.onlineshopping.web;
import com.onlineshopping.model.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SignUp extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
String[] month = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
InfoHolder userInfo = new InfoHolder();
userInfo.name = req.getParameter("name");
userInfo.email = req.getParameter("email");
userInfo.date = Integer.parseInt(req.getParameter("date"));
userInfo.month = Arrays.asList(month).indexOf(req.getParameter("month")) + 1;
userInfo.year = Integer.parseInt(req.getParameter("year"));
userInfo.pwd = req.getParameter("pwd");
userInfo.subscribe = "n";
try
{
userInfo.subscribe = req.getParameter("subscribe");
}
catch(Exception e)
{}
Updater u = new Updater();
u.update(userInfo);
}
}
InfoHolder just holds the information.
Updater.java
package com.onlineshopping.model;
import java.io.*;
import java.sql.*;
import java.util.*;
public class Updater
{
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String CONNECTION = "jdbc:mysql://localhost/onlineshopping";
public void update(InfoHolder userInfo)
{
try
{
Class.forName(DRIVER);
Properties p = new Properties();
p.put("user","****");
p.put("password","****");
Connection c = DriverManager.getConnection(CONNECTION,p);
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT MAX(userid)+1 FROM user_info");
rs.next();
int id = rs.getInt(1);
PreparedStatement ps = c.prepareStatement("INSERT INTO user_info VALUES (?,?,?,?,?,?,?)");
ps.setInt(1,id);
ps.setString(2,userInfo.name);
ps.setString(3,userInfo.email);
ps.setInt(4,userInfo.date);
ps.setInt(5,userInfo.month);
ps.setInt(6,userInfo.year);
ps.setString(7,userInfo.subscribe);
ps.executeUpdate();
c.close();
}
catch(Exception e)
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("err", true));
out.println("Error: "+ e);
out.close();
}
catch(IOException e)
{}
}
}
}
test.java
import com.onlineshopping.model.*;
public class test
{
public static void main(String[] args)
{
Updater u = new Updater();
InfoHolder xyz = new InfoHolder();
xyz.name = "check";
xyz.email = "checkmail";
xyz.date = 1;
xyz.month = 1;
xyz.year = 2;
xyz.pwd = "pw";
xyz.subscribe = "n";
u.update(xyz);
}
}
The Updater class file keeps throwing - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. But when I run the test class file from the terminal the same Updater class runs smoothly.
Is there a problem with my CLASSPATH variable:
It has this value -
.:/usr/share/java/mysql.jar:/usr/share/java/mysql-connector-java-5.1.16.jar:/usr/lib/tomcat6/lib/servlet-api.jar:classes.
Please Help.
Try to copy mysql-connector-java-5.1.16.jar into /usr/lib/tomcat6/lib/