I'm working on this program which is supposed to deserialize objects from an XML using the first thread, stream it through pipes to the second thread, which will then sort it and output the results.
The thing is I get exceptions when running it, saying both read and write ends are dead.
When I try to debug though, it works fine, which makes me think it's because of faulty synchronization. Confusing, since I thought the pipes were supposed to handle that aspect. Can anyone help me figure out what I'm doing wrong and point me in the right direction ?
Here's the code for the runnable:
(the relevant parts are near the end)
package domAPI;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ParserRunnable implements Runnable {
List<Employee> myEmpls;
Document dom;
PipedInputStream pin;
PipedOutputStream pout;
ObjectInputStream in;
ObjectOutputStream out;
int threadNr;
// private final Object sending = new Object();
// private final Object receiving = new Object();
public ParserRunnable(){
myEmpls = new ArrayList<Employee>();
}
public ParserRunnable(PipedOutputStream ws, int threadNr){
myEmpls = new ArrayList<Employee>();
pout = ws;
try {
out = new ObjectOutputStream(pout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.threadNr = threadNr;
}
public ParserRunnable(PipedInputStream rs, int ThreadNr){
myEmpls = new ArrayList<Employee>();
pin = rs;
try {
in = new ObjectInputStream(pin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.threadNr = threadNr;
}
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse("persons.xml");
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument(){
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName("Employee");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the employee element
Element el = (Element)nl.item(i);
//get the Employee object
Employee e = getEmployee(el);
//add it to list
myEmpls.add(e);
}
}
}
/**
* I take an employee element and read the values in, create
* an Employee object and return it
* #param empEl
* #return
*/
private Employee getEmployee(Element empEl) {
//for each <employee> element get text or int values of
//name ,id, age and name
String name = getTextValue(empEl,"Name");
int id = getIntValue(empEl,"Id");
int age = getIntValue(empEl,"Age");
String type = empEl.getAttribute("type");
//Create a new Employee with the value read from the xml nodes
Employee e = new Employee(name,id,age,type);
return e;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <employee><name>John</name></employee> xml snippet if
* the Element points to employee node and tagName is name I will return John
* #param ele
* #param tagName
* #return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
* #param ele
* #param tagName
* #return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}
/**
* Iterate through the list and print the
* content to console
*/
private void printData(){
System.out.println("No of Employees '" + myEmpls.size() + "'.");
Iterator<Employee> it = myEmpls.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
private void sortByAge(){
Collections.sort(myEmpls);
}
public void run() {
if (out != null){
parseXmlFile();
parseDocument();
writeToStream();
}
if (in != null){
readStream();
sortByAge();
printData();
}
// since i'm using the same class for both the producer and consumer thread
// here, the code above functions as kind of a switch between these 2
// modes of operation, by checking which pipe is initialized.
}
public void writeToStream(){
try{
out.writeObject(myEmpls);
out.flush();
out.close();
pout.flush();
pout.close();
}catch (Exception e) {
System.out.println("ErrorWS:" + e);
}
}
public void readStream(){
try{
myEmpls = (List<Employee>) in.readObject();
in.close();
pin.close();
}catch (Exception e) {
System.out.println("ErrorRS:" + e);
}
}
}
Here's the runner code :
package domAPI;
import java.io.*;
public class Launcher {
public static void main(String[] args){
Thread t1,t2;
try{
PipedOutputStream pos1 = new PipedOutputStream();
PipedInputStream pis2 = new PipedInputStream(pos1);
t1 = new Thread(new ParserRunnable(pos1,1));
t2 = new Thread(new ParserRunnable(pis2,1));
t1.start();
t2.start();
}catch (Exception e) {
System.out.println("Error:" + e);
}
}
}
My code might be pretty tricky to understand. Feel free to bombard me with questions, I'll be available. Also, most of the XML parsing code is originated from here : http://totheriver.com/learn/xml/xmltutorial.html#2
I'll just leave the XML here as well, if need be:
<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
<Employee type="permanent">
<Name>Seagull</Name>
<Id>3674</Id>
<Age>34</Age>
</Employee>
<Employee type="contract">
<Name>Robin</Name>
<Id>3675</Id>
<Age>25</Age>
</Employee>
<Employee type="permanent">
<Name>Crow</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Personnel>
The exception I get :
ErrorRS:java.io.IOException: Write end dead
No of Employees '0'.
ErrorWS:java.io.IOException: Read end dead
I did some test code and I can reproduce the issue you're facing. But I don't see this problem IF the ObjectOutputStream and ObjectInputStream is instantiated in their respective threads. For example.
public void run() {
if (pout != null){
parseXmlFile();
parseDocument();
writeToStream();
}
if (pin != null){
readStream();
sortByAge();
printData();
}
}
public void writeToStream(){
try{
out = new ObjectOutputStream(pout);
out.writeObject(myEmpls);
out.flush();
out.close();
pout.flush();
pout.close();
}catch (Exception e) {
System.out.println("ErrorWS:" + e);
}
}
public void readStream(){
try{
in = new ObjectInputStream(pin);
myEmpls = (List<Employee>) in.readObject();
in.close();
pin.close();
}catch (Exception e) {
System.out.println("ErrorRS:" + e);
}
}
You will need to remove the instantiation of ObjectOutputStream and ObjectInputStream from the ParserRunnable constructor.
Related
I get soap xml response and convert to String. String (xml) Example:
<Details>
<row>
<item>
<name>account</name>
<value>45687447</value>
</item>
<item>
<name>number</name>
<value>896541</value>
</item>
</row>
<row>
<item>
<name>account</name>
<value>2669874</value>
</item>
<item>
<name>number</name>
<value>063641</value>
</item>
</row>
</Details>
Now i parsing the String like this:
public ObjectNode ParseXml(String xml) {
Parsing parsing = ParsingFactory.getInstance().create();
Document document = parsing.xml().document(xml);
Parser<ObjectNode> parser = parsing.obj("//Details")
.attribute("row", parsing.obj("//row")
.attribute("account", "//item[name/text() = 'account']/value")
.attribute("number", "//item[name/text() = 'number']/value")).build();
ObjectNode result = parser.apply(document);
return result;
}
But problem is the, i take only one row, like this:
{
"row": {
"account": "2669874",
"number": "063641",
}
}
If i have 10 rows, but i get only one row. How i can get all rows?
I'm parsing from .xml file which you can easily change and have log on this files too.
package java_testiranja;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* #author blac
*/
public class Java_testiranja {
/**
* #param xml
* #param args the command line arguments
*/
private List<Employee> myEmpls = new ArrayList<Employee>();
public static void main(String[] args) throws IOException, ParserConfigurationException {
Java_testiranja domParser = new Java_testiranja();
domParser.parseXmlFile();
}
private void parseXmlFile() throws IOException, ParserConfigurationException {
// get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
Document dom = db.parse("employee.xml");
parseDocument(dom);
printData();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument(Document dom) {
// get the root element
Element docEle = dom.getDocumentElement();
// get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("item");
int stevilor = nl.getLength();
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
// get the employee element
Element el = (Element) nl.item(i);
// get the Employee object
Employee e = getEmployee(el);
// add it to list
myEmpls.add(e);
}
}
}
/**
* I take an employee element and read the values in, create an Employee object and return it
*/
private Employee getEmployee(Element empEl) {
// for each <employee> element get text or int values of
// name ,id, age and name
String name = getTextValue(empEl, "name");
int id = getIntValue(empEl, "value");
//int age = getIntValue(empEl, "Age");
//String type = empEl.getAttribute("type");
// Create a new Employee with the value read from the xml nodes
Employee e = new Employee(name, id);
return e;
}
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private int getIntValue(Element ele, String tagName) {
// in production application you would catch the exception
return Integer.parseInt(getTextValue(ele, tagName));
}
private void printData() {
Iterator<Employee> it = myEmpls.iterator();
while (it.hasNext()) {
System.out.println("{" + "\n" + "\"row\": {");
System.out.println(" "+it.next().toString());
System.out.println(" "+it.next().toString());
System.out.println(" }" + "\n" + "}");
}
}
}
And the Employee class is like:
package java_testiranja;
/**
*
* #author blac
*/
public class Employee {
private String name;
private int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "\""+name+"\": " + "\""+id+"\""+",";
}
}
I tried your .xml file and get the result:
{
"row": {
"account": "45687447",
"number": "896541",
}
}
{
"row": {
"account": "2669874",
"number": "63641",
}
}
I just saved .xml file as Employee.xml and called it. You can simply save this results...
Regards,
Blaz
I am making a Library System in Java, I am able to add new books, view and save them. However, I now want to search them using a Search window box. The saved data is located in a txt file. I would like to search for specific fields. I am thinking of implementing a linear search method, but am not too sure how to do it.
package bcu.storer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import bcu.model.Book;
public class BookStorer {
public void StoreBooks(ArrayList<Book> booksList) throws IOException
{
FileWriter fw = new FileWriter(".\\data\\books.txt");
BufferedWriter bw = new BufferedWriter(fw);
try {
for (int i = 0; i < booksList.size(); i++)
{
String content = "";
Book book = booksList.get(i);
content += book.getIsbn()+"::";
content += book.getTitle()+"::";
content += book.getAuthor()+"::";
content += book.getPublisher()+"::";
content += book.getPudDate()+"::";
content += book.getStatus()+"\n";
bw.write(content);
}
System.out.println("Complete storing all books!");
} catch (IOException ae) {
ae.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is the code which stores the book information to the TXT file, I would like to access this data in the search results.
I'm not sure if that's what you want. I help it helps you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
private static final String FILENAME = "pathToFile";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
Array[String] tmpBook = sCurrentLine.split("::");
Book myBook = new Book(tmpBook(0),tmpBook(1),tmpBook(2), tmpBook(3), tmpBook(4), tmpBook(5))
/*Check here if is the book you are looking for*/
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This will read the file, line by line, and will get all the lines that match the search criteria.
This map provides the position (column) of each of the fields in the Book object.
private static Map<String, Integer> fieldToPositionMap = ImmutableMap.<String, Integer>builder()
.put("Isbn", 0)
.put("Title", 1)
.put("Author", 2)
.put("Publisher", 3)
.put("PudDate", 4)
.put("Status", 5)
.build();
Note: I have used GoogleGuava's ImmutableMap to construct the map, but you can build it in a traditional way.
The search method takes the name of the field and the value that you want to search for (eg, Isbn=ABC or Publisher=XYZ) and returns all the rows (as Book objects) that match the criteria.
public List<Book> search(String fieldName, String fieldValue) {
try {
return Files.lines(Paths.get("/path/to/txt/file")) //reads a file line by line
.filter(line -> {
String[] blocks = line.split("::");
//filter (choose) a row if value of the searched field equals the provided value
return blocks[fieldToPositionMap.get(fieldName)].equals(fieldValue);
})
.map(this::deserialize) //convert the line to a Book object
.collect(Collectors.toList()); //collect the result
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//To convert a row from the file to a Book instance
private Book deserialize(String line) {
String [] blocks = line.split("::");
Book book = new Book();
book.setIsbn(blocks[0]);
book.setTitle(blocks[1]);
book.setAuthor(blocks[2]);
book.setPublisher(blocks[3]);
book.setPudDate(blocks[4]);
book.setStaus(blocks[5]);
}
Note: You might have to handle cases when a row does not have all fields
I have 2 class files in my simple project - sorry another newbee here!
But I get a compilation error on the last part where I am trying to print the hopefully stored configuration settings from a file for my project that will be referred to throughout the project.
The file is just rows of values like this 'ButtonConfig,8,V,NULL,bunny,mpg'
I basically want to be able to used the contents of this arraylist to dynamicly set up the configuration of a Raspberry pi GPO pins i.e. for the above values button attached to GPO pin 8 will play video (V) "<..other value...>_bunny.mpg"
Any help greatly appreciated - just telling me why I can't access the getExtension method would be nice!
Contents of first java file is -
package bpunit;
public class ButtonConfig {
private String keyword;
private String gponumber;
private String buttontype;
private String language;
private String filename;
private String extension;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
...............
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
The second contains this -
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List buttonList = new ArrayList();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
You have to add the parameterized type ButtonConfig to your ArrayList. It ends up being List<ButtonConfig> instead of just List.
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
The reason why the compilation is failing is because when you add an object to the ArrayList it is upcast as an object of the class Object. Now when you extract it you simply have to typecast it back to the original type. so all you have to do is this :
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
ButtonConfig buttonObject =(ButtonConfig)buttonListToPrint.get(i);
System.out.println(buttonObject.getExtension());
}
}
Or as mentioned in the comments and answers above you could use generics and create an List of type ButtonConfig
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
and pass it in the function printButtonList
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
I can't seem to find sample code for constructing a Berkeley DB in Java and inserting records into it. Any samples? And I do not mean the Berkeley DB Java Edition either.
http://www.oracle.com/technology/documentation/berkeley-db/db/programmer_reference/BDB_Prog_Reference.pdf
Chapter 5
If you download db-5.0.21.NC.zip you will see plenty of samples.
Here is one that seems to do what you want
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2004, 2010 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
// File: ExampleDatabaseLoad.java
package db.GettingStarted;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
public class ExampleDatabaseLoad {
private static String myDbsPath = "./";
private static File inventoryFile = new File("./inventory.txt");
private static File vendorsFile = new File("./vendors.txt");
// DatabaseEntries used for loading records
private static DatabaseEntry theKey = new DatabaseEntry();
private static DatabaseEntry theData = new DatabaseEntry();
// Encapsulates the databases.
private static MyDbs myDbs = new MyDbs();
private static void usage() {
System.out.println("ExampleDatabaseLoad [-h <database home>]");
System.out.println(" [-i <inventory file>] [-v <vendors file>]");
System.exit(-1);
}
public static void main(String args[]) {
ExampleDatabaseLoad edl = new ExampleDatabaseLoad();
try {
edl.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleDatabaseLoad: " + dbe.toString());
dbe.printStackTrace();
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
e.printStackTrace();
} finally {
myDbs.close();
}
System.out.println("All done.");
}
private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbs.setup(myDbsPath);
System.out.println("loading vendors db....");
loadVendorsDb();
System.out.println("loading inventory db....");
loadInventoryDb();
}
private void loadVendorsDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List vendors = loadFile(vendorsFile, 8);
// Now load the data into the database. The vendor's name is the
// key, and the data is a Vendor class object.
// Need a serial binding for the data
EntryBinding dataBinding =
new SerialBinding(myDbs.getClassCatalog(), Vendor.class);
for (int i = 0; i < vendors.size(); i++) {
String[] sArray = (String[])vendors.get(i);
Vendor theVendor = new Vendor();
theVendor.setVendorName(sArray[0]);
theVendor.setAddress(sArray[1]);
theVendor.setCity(sArray[2]);
theVendor.setState(sArray[3]);
theVendor.setZipcode(sArray[4]);
theVendor.setBusinessPhoneNumber(sArray[5]);
theVendor.setRepName(sArray[6]);
theVendor.setRepPhoneNumber(sArray[7]);
// The key is the vendor's name.
// ASSUMES THE VENDOR'S NAME IS UNIQUE!
String vendorName = theVendor.getVendorName();
try {
theKey = new DatabaseEntry(vendorName.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
// Convert the Vendor object to a DatabaseEntry object
// using our SerialBinding
dataBinding.objectToEntry(theVendor, theData);
// Put it in the database.
myDbs.getVendorDB().put(null, theKey, theData);
}
}
private void loadInventoryDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List inventoryArray = loadFile(inventoryFile, 6);
// Now load the data into the database. The item's sku is the
// key, and the data is an Inventory class object.
// Need a tuple binding for the Inventory class.
TupleBinding inventoryBinding = new InventoryBinding();
for (int i = 0; i < inventoryArray.size(); i++) {
String[] sArray = (String[])inventoryArray.get(i);
String sku = sArray[1];
try {
theKey = new DatabaseEntry(sku.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
Inventory theInventory = new Inventory();
theInventory.setItemName(sArray[0]);
theInventory.setSku(sArray[1]);
theInventory.setVendorPrice((new Float(sArray[2])).floatValue());
theInventory.setVendorInventory((new Integer(sArray[3])).intValue());
theInventory.setCategory(sArray[4]);
theInventory.setVendor(sArray[5]);
// Place the Vendor object on the DatabaseEntry object using our
// the tuple binding we implemented in InventoryBinding.java
inventoryBinding.objectToEntry(theInventory, theData);
// Put it in the database. Note that this causes our secondary database
// to be automatically updated for us.
myDbs.getInventoryDB().put(null, theKey, theData);
}
}
private static void parseArgs(String args[]) {
for(int i = 0; i < args.length; ++i) {
if (args[i].startsWith("-")) {
switch(args[i].charAt(1)) {
case 'h':
myDbsPath = new String(args[++i]);
break;
case 'i':
inventoryFile = new File(args[++i]);
break;
case 'v':
vendorsFile = new File(args[++i]);
break;
default:
usage();
}
}
}
}
private List loadFile(File theFile, int numFields) {
List records = new ArrayList();
try {
String theLine = null;
FileInputStream fis = new FileInputStream(theFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((theLine=br.readLine()) != null) {
String[] theLineArray = splitString(theLine, "#");
if (theLineArray.length != numFields) {
System.out.println("Malformed line found in " + theFile.getPath());
System.out.println("Line was: '" + theLine);
System.out.println("length found was: " + theLineArray.length);
System.exit(-1);
}
records.add(theLineArray);
}
fis.close();
} catch (FileNotFoundException e) {
System.err.println(theFile.getPath() + " does not exist.");
e.printStackTrace();
usage();
} catch (IOException e) {
System.err.println("IO Exception: " + e.toString());
e.printStackTrace();
System.exit(-1);
}
return records;
}
private static String[] splitString(String s, String delimiter) {
Vector resultVector = new Vector();
StringTokenizer tokenizer = new StringTokenizer(s, delimiter);
while (tokenizer.hasMoreTokens())
resultVector.add(tokenizer.nextToken());
String[] resultArray = new String[resultVector.size()];
resultVector.copyInto(resultArray);
return resultArray;
}
protected ExampleDatabaseLoad() {}
}
There are a number of good Getting Started Guides for Oracle Berkeley DB Java Edition. They are included in the documentation set. You'll find example code in the documentation. If you're new to Oracle Berkeley DB Java Edition that's the right place to start. There are other examples in the download package as well.
I'm the product manager for Oracle Berkeley DB, I hope this addressed your question. If not please let me know how else I can help you.
I'm having a bit of problem with an example I'm currently testing. For some reason, the execution blocks when writing at oos.writeObject(new SimpleObject());, despite that fact that the pipe should transfer the data across, even (I'd assume) if it had to do it in smaller operations due to a small pipe size. Anyway, the example succeeds when the pipe size is larger than the object, and fails when the pipe size is smaller than the object. If anyone could shed some light on this, it'd be much appreciated.
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.ByteBuffer;
import org.apache.mina.filter.codec.serialization.ObjectSerializationInputStream;
import org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream;
public class ObjTest4 {
public static void main(String[] args) {
System.out.println("exec1");
int objectsToSend = 10;
int objectsRecvd = 0;
try {
System.out.println("exec2");
PipedOutputStream pos = new PipedOutputStream();
ObjectSerializationOutputStream oos = new ObjectSerializationOutputStream(pos);
PipedInputStream pis = new PipedInputStream(pos, 500);
ObjectSerializationInputStream ois = new ObjectSerializationInputStream(pis);
oos.setMaxObjectSize(2000);
ois.setMaxObjectSize(2000);
while (objectsRecvd < objectsToSend) {
System.out.println("exec3");
oos.writeObject(new SimpleObject());
System.out.println("exec3.1");
oos.flush();
System.out.println("exec3.2");
System.out.println("oisavail: " + ois.available());
Object o = ois.readObject();
if (o != null) {
objectsRecvd++;
System.out.println("o: " + o);
} else {
System.out.println("recvd null");
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
and the class for the object being serialised:
package objtest;
import java.io.Serializable;
import java.util.EnumSet;
public class SimpleObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String moo = "moo";
public EnumSet<EnumTest> set = EnumSet.of(EnumTest.Test);
public String moo2 = "moo2";
public String moo3 = "moo3";
public String moo4 = "moo4_";
{
for (int i = 0; i < 8; i++) {
moo4 += moo4;
}
}
/**
*
*/
public SimpleObject() {
// TODO Auto-generated constructor stub
}
/**
* #return the moo
*/
public String getMoo() {
return moo;
}
/**
* #param moo the moo to set
*/
public void setMoo(String moo) {
this.moo = moo;
}
}
Cheers,
Chris
Sorry, I found the problem -- the Java documentation says not to use piped streams from a single thread, as it may deadlock the thread:
Attempting to use both objects from a
single thread is not recommended, as
it may deadlock the thread.