Titan Key with given name does not exist - titan

I create two indexes but when I want to invoke vertex.setProperties(), my program prompts with "given name does not exist.". Below is my code:
initDB
public void tstInitHBase() {
Configuration conf = new BaseConfiguration();
conf.setProperty("storage.backend", "hbase");
conf.setProperty("storage.hostname", "192.168.22.209");
conf.setProperty("storage.port", "2181");
conf.setProperty("storage.tablename", "social_map");
conf.setProperty("cache.db-cache", "true");
conf.setProperty("cache.db-cache-clean-wait", "20");
conf.setProperty("cache.db-cache-time", "180000");
conf.setProperty("cache.db-cache-size", "0.5");
GraphDatabaseConfiguration graphconfig = new GraphDatabaseConfiguration(conf);
try {
graphconfig.getBackend().clearStorage();
} catch (StorageException e) {
e.printStackTrace();
throw new RuntimeException("Techvalley:ERROR 清空数据库失败");
}
TitanGraph graph = TitanFactory.open(conf);
graph.makeKey("PKID").dataType(String.class).indexed(Vertex.class).unique(UniquenessConsistency.LOCK).make();
graph.makeKey("CN_NAME").dataType(String.class).indexed(Vertex.class).make();
graph.makeKey("EDGE_PEERS_WEIGHT").dataType(Long.class).indexed(Edge.class).make();
graph.commit();
}
Insert Data with pig
//objList structure is like (uuid,cn_name,gender,..)
vertex = tx.getVertex(DataType.toString(objList.get(0)));
if (vertex == null) {
logger.info("create node");
vertex = tx.addVertex(DataType.toString(objList.get(0)));
vertex.setProperty(flied[0], DataType.toString(objList.get(0)));
}
/**
*
* */
for (int i = 1; i < flied.length; i++) {
switch (DataType.findType(objList.get(i))) {
case DataType.NULL:
logger.info("cache" + flied[i] + " " + DataType.toString(objList.get(i)));
ElementHelper.setProperties(vertex, flied[i],DataType.toString(objList.get(i)));
break;
case DataType.CHARARRAY:
logger.info("cache" + flied[i] + " " + DataType.toString( objList.get(i)));
ElementHelper.setProperties(vertex, flied[i],DataType.toString(objList.get(i)));
break;
default:
break;
}
}
When I execute ElementHelper.setProperties(vertex,flied[i],DataType.toString(objList.get(i))); my program always returns 'Key with given name does not exist'.
Any ideas?

Find out the offending property key by wrapping ElementHelper.setProperties in try/catch and logging/printing the property key name. Then add it to the graph.makeKey set.

Related

How to set auto-increment the numbers in mysql workbench with a character prefix by using netbeans

How to increment the numbers in mysql with a character prefix using netbeans
A1-01
A1-02
A1-03
AND
A2-01
A2-02
A2-02
I had try this as below mentioned
try {
Class.forName("com.mysql.cj.jdbc.Driver");
sqlConne = DriverManager.getConnection(dataConn, username, password);
st = sqlConne.createStatement();
for (int i = 0; i < model.getRowCount(); i++) {
int id = Integer.valueOf(model.getValueAt(i, 0).toString());
String Status = jTextField_status.getText();
String zonevalue = jTextField1.getText();
String space = jTextField2.getText();
String updateQuery = "UPDATE master_data SET status='" + Status + "', zone_spacevalue='" + transfer_zonename.concat(zonevalue) + "' WHERE s_no = " + id;
st.addBatch(updateQuery);
int insertResult = st.executeUpdate(updateQuery);
if (insertResult > 0) {
insertedResult++;
}
}
int[] updatedRow = st.executeBatch();
System.out.println(updatedRow.length);
catch (SQLException ex) {
Logger.getLogger(assign_data.class.getName()).log(Level.SEVERE, null, ex);
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
and i want that zone wise allocation item with autoincrement number like warehouse allocation system

android cardview only show the last result the right amount of times

i'm new to android and java.
i made a cardview and populated it with a simple loop like so:
private ArrayList<DataObject> getTheData(){
ArrayList res = new ArrayList<DataObject>();
for (int index = 0; index < 5; index++){
DataObject obj = new DataObject("shit","happen");
res.add(index,obj);
}
return res;
}
it worked. now i created a database and want to populate it with this data. so i have this:
public ArrayList<DataObject> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList res = null;
try {
res = new ArrayList<DataObject>();
String selectQuery = "SELECT * FROM quotes a LEFT JOIN authors b ON b.author_id=a.quote_author";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Log.d("CHECKDB",cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")));
Log.d("CHECKDB2",cursor.getString(cursor.getColumnIndex("quote_text")));
DataObject obj = new DataObject(
cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")),
cursor.getString(cursor.getColumnIndex("quote_text"))
);
res.add(obj);
} while (cursor.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
return res;
}
the log show all the results, but when i run the app i get the last result the right amount of times. in this case 4 quotes in my database, so i see 4 but the last one 4 times.
please , since i'm new to it, good explanations will be appreciated.
the issue was that my dataobject attributes were set to static

PostgreSQL JDBC query: Include .sql file using \i [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Running a .sql script using MySQL with JDBC
I have an SQL script file which contains 40-50 SQL statements. Is it possible to run this script file using JDBC?
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* #param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* #param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
I use this bit of code to import sql statements created by mysqldump:
public static void importSQL(Connection conn, InputStream in) throws SQLException
{
Scanner s = new Scanner(in);
s.useDelimiter("(;(\r)?\n)|(--\n)");
Statement st = null;
try
{
st = conn.createStatement();
while (s.hasNext())
{
String line = s.next();
if (line.startsWith("/*!") && line.endsWith("*/"))
{
int i = line.indexOf(' ');
line = line.substring(i + 1, line.length() - " */".length());
}
if (line.trim().length() > 0)
{
st.execute(line);
}
}
}
finally
{
if (st != null) st.close();
}
}
Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:
public void executeSqlScript(Connection conn, File inputFile) {
// Delimiter
String delimiter = ";";
// Create scanner
Scanner scanner;
try {
scanner = new Scanner(inputFile).useDelimiter(delimiter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// Loop through the SQL file statements
Statement currentStatement = null;
while(scanner.hasNext()) {
// Get statement
String rawStatement = scanner.next() + delimiter;
try {
// Execute statement
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
if (currentStatement != null) {
try {
currentStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
currentStatement = null;
}
}
scanner.close();
}
Just read it and then use the preparedstatement with the full sql-file in it.
(If I remember good)
ADD: You can also read and split on ";" and than execute them all in a loop.
Do not forget the comments and add again the ";"
You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.
I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.
You can read the script line per line with a BufferedReader and append every line to a StringBuilder so that the script becomes one large string.
Then you can create a Statement object using JDBC and call statement.execute(stringBuilder.toString()).

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;

Getting FormPanel's field values

I'm having problems with getting the value of the fields coming from a FormPanel. Theonly thing I get is the image included in the form here is the servlet code, I'm using Apache Commons:
// Create a new file upload handler
ServletFileUpload upload1 = new ServletFileUpload();
// Parse the request
FileItemIterator iter;
try {
iter = upload1.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I have seen this post but it didn't really explain what to do
Like #Colin Alworth said, the name property must be set for each field!
TextBox lastName = new TextBox();
lastName.setName("LastName");