I'm trying to use this code. Which is an auto-complete field that use the database.
import java.util.Vector;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.database.Cursor;
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
public class AutoCompleteFieldDemo extends UiApplication
{
public static void main(String[] args)
{
AutoCompleteFieldDemo app = new AutoCompleteFieldDemo();
app.enterEventDispatcher();
}
public AutoCompleteFieldDemo()
{
pushScreen(new AutoCompleteFieldDemoScreen());
}
public static String[] getDataFromDB()
{
Vector names = new Vector();
try
{
Database db = DatabaseFactory.openOrCreate("database1.db");
Statement statement1 = db.createStatement("SELECT name FROM Directory_Items");
statement1.prepare();
statement1.execute();
Cursor c = statement1.getCursor();
Row r;
while(c.next())
{
r = c.getRow();
names.addElement(r.getString(0));
}
statement1.close();
db.close();
}
catch( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
String [] returnValues = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
returnValues[i] = (String) names.elementAt(i);
}
return returnValues;
}
static final class AutoCompleteFieldDemoScreen extends MainScreen
{
AutoCompleteFieldDemoScreen()
{
BasicFilteredList filterLst = new BasicFilteredList();
filterLst.addDataSet(1,getDataFromDB()
,"Names",BasicFilteredList.COMPARISON_IGNORE_CASE);
AutoCompleteField autoFld = new AutoCompleteField(filterLst);
add(autoFld);
}
I found it in here
The problem that I'm facing is, I can't find the database. I have created the database in the SD card and I put the name in the createOropen("myDataBase.db). But When I debug it jump to the exception. Any idea about why I'm having this problem.
Thank you so much!
Related
I want to display information that I have loaded in from 2 methods onto my TextArea. The methods I am trying to call and display are named loadFleet and loadCrew which are in the Fleet class. I only have it working to where it prints out to the console like so System.out.println(Enterprise). I am pretty new to Java and JavaFX, so any help would be greatly appreciated.
Here's my MainController file:
package application.controller;
import java.io.IOException;
import application.model.Fleet;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class MainController implements EventHandler<ActionEvent>{
#FXML TextField starshipname;
#FXML TextArea shipInfo;
#FXML Button shipEnter;
#Override
public void handle( ActionEvent event) {
/*try {
Fleet.loadFleet(null);
} catch (IOException e) {
shipInfo.setText(" Starship name not found! ");
e.printStackTrace();
}*/
Fleet Enterprise = new Fleet( "Bozeman" );
try {
Enterprise.loadFleet("data/fleet");
Enterprise.loadCrew("data/personnel");
System.out.println(Enterprise);
}catch( IOException e ) {
System.out.println( "Error loading the file - please check its location." );
e.printStackTrace();
}
}
}
And here's my Fleet class:
package application.model;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Fleet {
private String fleetName;
public ArrayList<Starship> ship;
private String fileName;
public Fleet( String name ) {
this.fleetName = name;
this.ship = new ArrayList<Starship>();
}
public String getFleetName() {
return this.fleetName;
}
public void setFleetName( String name ) {
this.fleetName = name;
}
public ArrayList<Starship> getStarship() {
return this.ship;
}
public void setStarship( ArrayList<Starship> ship ) {
this.ship = ship;
}
public String getFileName() {
return this.fileName;
}
public void setFileName( String fName ) {
this.fileName = fName;
}
public void addShip(Starship starAdd) {
this.ship.add(starAdd);
}
public void getStarshipsByName( Starship starName ) {
Starship starname;
}
public void loadFleet(String fileName)throws IOException {
try {
Scanner scan = new Scanner(new File("data/fleet.csv") );
while( scan.hasNextLine() ) {
String line = scan.nextLine();
String[] items = line.split(",");
Starship tmp = null;
tmp = new Starship( items[0], items[1], items[2]);
this.addShip(tmp);
}
scan.close();
}catch(IOException e) {
e.printStackTrace();
}
}
public void loadCrew(String fileName)throws IOException {
try {
Scanner scan = new Scanner(new File("data/personnel.csv") );
while( scan.hasNextLine() ) {
String line = scan.nextLine();
String[] items = line.split(",");
Crewmember tmp = null;
tmp = new Crewmember( items[0], items[1], items[2], items[3], items[4]);
for(int i = 0; i < this.ship.size(); ++i) {
if(this.ship.get(i).getStarShipRegistry().equals(items[3]))
this.ship.get(i).addCrew( tmp );
}
}
scan.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public String toString() {
String ret = " ";
for( int i = 0; i < this.ship.size(); i++)
{
ret += this.ship.get(i).toString();
}
return ret;
}
}
Please let me know what other classes or methods you would like for me to provide.
add data to shipInfo (your TextArea) by appending from foreach
loop of your list.
Quick sample code:
//instance of your ship object
StarShip myShip = StarShip();
//method to add data to your TextArea
private void showShipInfo(){
//getStarShip returns the list of ships
//same as the method on your Fleet class
myShip.getStarShip().forEach(starShip ->{
//add data to TextArea for each field of
//StarShip object you want to display
shipInfo.append(starShip.getName());
//shipInfo.append(starShip.get....());
//shipInfo.append(starShip.get....());
}
}
Note: only String values are allowed to be appended to TextArea!
Hope it helps!
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;
}
}
I get enclosing instance of type error in my java code and i don't know what is that error my java code is below
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class phase45 {
public class Vertex {
public Vertex(Integer na){ name = na;}
private Integer name ;
public Integer getname(){
return name;
}
ArrayList adjs = new ArrayList<Integer>();
}
public class graph {
// public Integer name ;
ArrayList Vertexes = new ArrayList<Vertex>();
public Vertex GetVertex(Integer name){
for(int i = 0; i < Vertexes.size(); i++){
if (((Vertex) Vertexes.get(i)).name == name)
return (Vertex) Vertexes.get(i);
}
return null;
}
public void AddVertex(Vertex V){
Vertexes.add(V);
}
}
public static void CreateGraph(File a , graph g) throws IOException{
String st1 , st2 , line;
Integer vs , es;
try {
BufferedReader br = new BufferedReader(new FileReader(a));
st1 = br.readLine();
st2 = br.readLine();
vs = Integer.parseInt(st1);
es = Integer.parseInt(st2);
while ((line = br.readLine()) != null) {
String[] splited = line.split("\\s+");
//Vertex vTemp = null;
Integer NameV = Integer.valueOf(splited[0]);
System.out.println("line + " + line);
//vTemp.name = NameV;
Vertex vTemp = new Vertex(NameV);
Integer AdjV = Integer.valueOf(splited[1]);
vTemp.adjs.add(AdjV);
if(g.GetVertex(NameV) == null)
g.AddVertex(vTemp);
else
g.GetVertex(NameV).adjs.add(AdjV);
}
System.out.println("vs : " + vs + " es "+ es);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
//try{
File file = new File("/Users/mehran/Desktop/filee.txt");
graph g = null;
System.out.println("hi boy");
CreateGraph(file , g);
//}catch(NullPointerException ee){;}
}
}
I get error in CreateGraph this line : Vertex vTemp = new Vertex(NameV);
and I can't understand why , please fix it?
You try to use a C++-Constructor.
In Java you have to write:
Vertex vTemp = new Vertex(NameV); // Class-names should start with a capital letter
The code you attached here compile fine for me. I tried to compile the class Vertex and found it OK.
I think the problem occurred when you try to create object of this class. Try to create Vetex object like this -
Vetex v = new Vertex(name);
Here's a little edit to your code (of course you can instantiate adjs anywhere in your methods)
package test;
import java.util.ArrayList;
public class vertex {
private Integer name ;
public vertex(Integer na){ name = na;}
public Integer getname(){
return name;
}
public static void main(String[] args) {
ArrayList adjs = new ArrayList<Integer>();
}
}
the code compiled, but didn't want to run because you didn't add the main method
I'm a rookie with Esper and I would like to get some help. I've already managed to use Esper with CSV files, but now I need to use Java objects as events sent through a socket and I can't find simple examples on the Internet to use as a guide.
Has anybody some simple examples to base on them?
Anyway, I let here the code I am trying to make work. Nothing happens when I run it, it seems the socket connection does not work.
The server class (it also contains the event class). It is suposed to send the events:
import java.io.* ;
import java.net.* ;
class Server {
static final int PORT=5002;
public Server( ) {
try {
ServerSocket skServer = new ServerSocket( PORT );
System.out.println("Listening at " + PORT );
Socket skClient = skServer.accept();
System.out.println("Serving to Esper");
OutputStream aux = skClient.getOutputStream();
ObjectOutputStream flux = new ObjectOutputStream( aux );
int i = 0;
while (i<10) {
flux.writeObject( new MeteoEvent(i,"A") );
i++;
}
flux.flush();
skClient.close();
System.out.println("End of transmission");
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new Server();
}
class MeteoEvent{
private int sensorId;
private String GeoArea;
public MeteoEvent() {
}
public MeteoEvent(int sensorid, String geoarea) {
this.sensorId = sensorid;
this.GeoArea = geoarea;
}
public int getSensorId() {
return sensorId;
}
public void setSensorId(int sensorId) {
this.sensorId = sensorId;
}
public String getGeoArea() {
return GeoArea;
}
public void setGeoArea(String geoArea) {
GeoArea = geoArea;
}
}
}
And the Esper-based class.
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.espertech.esper.client.Configuration;
import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPRuntime;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.UpdateListener;
import com.espertech.esper.event.map.MapEventBean;
import com.espertech.esperio.socket.EsperIOSocketAdapter;
import com.espertech.esperio.socket.config.ConfigurationSocketAdapter;
import com.espertech.esperio.socket.config.DataType;
import com.espertech.esperio.socket.config.SocketConfig;
public class Demo {
public static class CEPListener implements UpdateListener {
private String tag;
public CEPListener (String tag)
{
this.tag = tag;
}
public static void main(String[] args) throws IOException, InterruptedException {
Configuration configuration = new Configuration();
Map<String, Object> eventProperties = new HashMap<String, Object>();
eventProperties.put("sensorId", int.class);
eventProperties.put("GeoArea", String.class);
configuration.addEventType("MeteoEvent", eventProperties);
ConfigurationSocketAdapter socketAdapterConfig = new ConfigurationSocketAdapter();
SocketConfig socketConfig = new SocketConfig();
socketConfig.setDataType(DataType.OBJECT);
socketConfig.setPort(5002);
socketAdapterConfig.getSockets().put("MeteoSocket", socketConfig);
EPServiceProvider cepService = EPServiceProviderManager.getProvider("MeteoSocket",configuration);
EPRuntime cepServiceRT = cepService.getEPRuntime();
EPAdministrator cepAdmin = cepService.getEPAdministrator();
EsperIOSocketAdapter socketAdapter = new EsperIOSocketAdapter (socketAdapterConfig, "MeteoSocket");
socketAdapter.start();
EPStatement stmt = cepAdmin.createEPL("insert into JoinStream select * from MeteoEvent");
EPStatement outputStatementX = cepAdmin.createEPL("select * from JoinStream");
outputStatementX.addListener(new CEPListener("JS"));
cepService.initialize();
Object lock = new Object();
synchronized (lock)
{
lock.wait();
}
}
Thank you very much in advance if anyone takes some time trying to help me.
Problem solved! The Esper Dev list was very useful. I learned how to use Esper + sockets through the test classes located here
Best regards!
this is my nodefinder.java file
package com.acme.web.action.executer;
import java.sql.ResultSet;
import java.util.Map;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.ui.common.component.UIActionLink;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
public class NodeFinder {
// private static final String = null;
SearchParameters sp = new SearchParameters();
private NodeService nodeService;
private FileFolderService fileFolderService;
//geting the filefolder service
public FileFolderService getFileFolderService() {
return fileFolderService;
}
// setting the file folder service
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
// getting the node servise
public NodeService getNodeService() {
return nodeService;
}
// setting the node server
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void execute(ActionEvent event) {
ResultSet resultSet_s = null;
UIActionLink comp = (UIActionLink) event.getComponent();
Map<String, String> params = comp.getParameterMap();
String id = params.get("id1");
System.out.println("1");
NodeRef actionedUponNodeRef = new NodeRef(Repository.getStoreRef(), id);
String qry_s = "#cm\\:name:train";
System.out.println("2");
SearchParameters sp_s = new SearchParameters();
System.out.println("3");
sp_s.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
sp_s.setLanguage(SearchService.LANGUAGE_LUCENE);
sp_s.setQuery(qry_s);
System.out.println( "4" );
Node node = new Node(actionedUponNodeRef);
System.out.println("5");
resultSet_s = (ResultSet) Repository.getServiceRegistry(
FacesContext.getCurrentInstance()).getSearchService().query(
sp_s);
System.out.println("5.1");
if (resultSet_s != null) {
System.out.println("6");
System.out.println("Node value is::::" + node.getName());
}
}
}
Because you imported java.sql.ResultSet instead of an alfresco class/interface compatible to org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet
Look at that line ...(ResultSet) Repository.getServiceRegistry(..., then look at your exception and finally at your imports. There you will see that ResultSet is actually java.sql.ResultSet (which is indicated by your ClassCastException's message).
If you then look at the super classes or interfaces of org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet I'd say you won't find any java.sql.ResultSet. That's why you get that exception.