db4o - weird characters when retrieving objects - java

import java.io.File;
import com.db4o.Db4o;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;
public class Student {
private String name;
public AlumnoBDOO(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ObjectContainer bd = Db4oEmbedded.openFile("students.db4o");
try {
Student s1 = new Student("Carl");
bd.store(s1)
showStudents(bd);
} catch (Exception e) {
e.printStackTrace();
} finally {
bd.close();
}
}
public static void showResult(ObjectSet rs){
System.out.println("Retrieved "+rs.size()+" objects");
while(rs.hasNext()){
System.out.println(rs.next());
}
}
public static void showStudents(ObjectContainer bd){
Query query = bd.query();
query.constrain(Student.class);
query.descend("name");
ObjectSet rs = query.execute();
showResult(rs);
}
}
I just simply want to store a Student in the db4o database but when I want to retrieve all of them it outputs like this:
Student#61070a02
I'm using Eclipse Juno and db40 v.8.0 which I already added as external jar.
Why am I getting those weird characters instead of "Carl"?

That is not weired, but the default implementation of the toString() method. To get meaningfull information you should override this method in your Student class.

Related

How to return Value after ifPresent Check

I am trying to return empName if its present Or else Empty String
But i am unable to return .
After ifPresent its not allowing me to return value , please help need with the syntax .
This is my Structure
import java.util.List;
public class EmployeeData {
private List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
This is my Employee class
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Test Program
import java.util.Collections;
import java.util.Optional;
public class Test {
public static void main(String args[]) {
EmployeeData empData = new EmployeeData();
}
public String getEmpName(EmployeeData empData)
{
Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().findFirst().ifPresent(
return emp->emp.getName();
)).orElse{
return "";
}
}
}
If you want any name of one of the employees you need to map to their name, then use findFirst and orElse.
The ifPresent is to consume the data and only if their is a data : here you want to return and do something if not present
public String getEmpName(EmployeeData empData) {
return Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().filter(Objects::nonNull)
.map(Employee::getName).findFirst().orElse("");
}

Eclipse Junit writing tests correctly for getters and setters

I need to write Junit tests in Eclipse and I wanted to know if I am on the right track. I have an Allergey.java and TestAllergey.java. I heard you are not supposed to do tests for getters and setters but it is a requirement and I have no choice. I also did a test for the toString method and am curious if I did that correctly. All the tests passed.
Thanks
package medical.com.medicalApplication.model;
/**
* This class represent the Allergy model in the application
*
*/
public class Allergey {
private String name;
public Allergey(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Allergy " + name;
}
}
package medicalApplication.model;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import medical.com.medicalApplication.model.Allergey;
public class AllergeyTest {
private Allergey allergy;
#Before
public void setUp() throws Exception {
allergy = new Allergey("Peanut");
}
#Test
public void testGetName() {
String expectedValue = allergy.getName();
String actualValue = "Peanut";
assertTrue(expectedValue.equals(actualValue));
}
#Test
public void testSetName() {
String expectedValue = "Peanut";
allergy.setName(expectedValue);
String actualValue = allergy.getName();
assertTrue(expectedValue.equals(actualValue));
}
#Test
public void testToString() {
assertTrue(allergy.toString().equals("Allergy " + allergy.getName()));
}
}

XMLEncoder not writing object data when class fields are private

I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData()
{
methods = new ArrayList<>();
}
public void setName(String cName)
{
name = cName;
}
public String getName()
{
return name;
}
public void setMethods(String mName)
{
methods.add(mName);
}
public ArrayList<String> getMethods()
{
return methods;
}
}
String fileName = cObj.getName() + ".xml";
XMLEncoder enc=null;
try{
enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData() {
methods = new ArrayList<>();
}
public void setName(String cName) {
name = cName;
}
public String getName() {
return name;
}
public void addMethod(String mName) {
methods.add(mName);
}
public void setMethods(ArrayList<String> m)
{
methods.addAll(m);
}
public ArrayList<String> getMethods() {
return methods;
}
public static void main(String[] args) {
ClassData cObj = new ClassData();
cObj.setName("This_is_name");
cObj.addMethod("m1");
String fileName = cObj.getName() + ".xml";
XMLEncoder enc = null;
try {
enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
} catch (FileNotFoundException fileNotFound) {
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
}
}

How to get properties of an object stored in ArrayList using Java

I want to print all student objects' properties(name, subject, registrationNo) stored in a ArrayList object.
student details are getting from a database and insert them into student objects.
Then these student objects are insert into the ArrayList.
Finally I want to print these student object properties one by one as follows.
Followings are my codes.
DBconn.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBconn {
static Connection conn;
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/student_database", "root", "");
} catch (SQLException ex) {
}
} catch (ClassNotFoundException ex) {
}
return conn;
}
}
Student.java
public class Student {
private String name;
private String RegistrationNo;
private String course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegistrationNo() {
return RegistrationNo;
}
public void setRegistrationNo(String RegistrationNo) {
this.RegistrationNo = RegistrationNo;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
StudentList.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentList {
public static ArrayList getStudentList() {
ArrayList list = new ArrayList();
String sql = "SELECT * FROM student";
try {
Statement stm = DBconn.getConnection().createStatement();
ResultSet rs = stm.executeQuery(sql);
while (rs.next()) {
Student student = new Student();
student.setName(rs.getString(1));
student.setCourse(rs.getString(2));
student.setRegistrationNo(rs.getString(3));
list.add(student);
}
} catch (SQLException ex) {
}
return list;
}
}
ViewStudent.java
public class ViewStudent {
public static void main(String[] args) {
int size = StudentList.getStudentList().size();
for (int i = 0; i < size; i++) {
System.out.println(StudentList.getStudentList().get(i));
//I want to get all student's name,subject and registrationNo
}
}
}
Thanks.
Simply give Student a public String toString() method override, one that returns a String holding all key properties, and then this will work fine:
System.out.println(StudentList.getStudentList().get(i));
Instead of System.out.println(StudentList.getStudentList().get(i));, you should access the student's properties and print it out.
Student s = (Student) StudentList.getStudentList().get(i);
System.out.println(s.getName());
System.out.println(s.getCourse());
System.out.println(s.getRegistrationNo());

Import csv's into data stax cassandra through spark (Java Api)

Is there a way to import csv into cassandra through spark's java api without creating a pojo class for the csv. I am able to insert the csv by creating a pojo class like below , Is there any way to do so without creating pojo class for the csv programatically using spark java api.
My csv looks like this
Name,Age,bg,sex
ammar,67,ab+,M
nehan,88,b+,M
moin,99,m+,M
arbaaz,67,a+,M
...
And the program is below.
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import com.cassandra.insertion.MergeGeneSymDataInsertion;
import com.cassandra.insertion.MergeGeneSymDataInsertion.HgIpsenGeneSym;
import com.publicdata.task.PublicDataInsertion.PublicData;
import static com.datastax.spark.connector.japi.CassandraJavaUtil.*;
public class InsertCsv {
static JavaSparkContext ctx = null;
static boolean isHeader = true;
public static void main(String[] args) {
try {
ctx = new JavaSparkContext(new SparkConf().setMaster("local[4]")
.setAppName("TestCsvInserion"));
insertCsv(ctx);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void insertCsv(JavaSparkContext ctx) {
JavaRDD<String> testfileRdd = ctx
.textFile("/home/syedammar/Pilot Project /test.csv");
JavaRDD<Bats> batsclassRdd = testfileRdd
.map(new Function<String, Bats>() {
#Override
public Bats call(String line) throws Exception {
// TODO Auto-generated method stub
if(!isHeader){
String[] words=StringUtils.split(line, ",");
String name = words[0];
String age = words[1];
String bg = words[2];
String sex = words[3];
return new Bats(name, age, bg, sex);
}
else
{
isHeader=false;
return null;
}
}
}).filter(new Function<Bats, Boolean>() {
#Override
public Boolean call(Bats obj) throws Exception {
// TODO Auto-generated method stub
return obj!=null;
}
}).coalesce(1);
javaFunctions(batsclassRdd).writerBuilder("test", "bats", mapToRow(Bats.class)).saveToCassandra();
}
public static class Bats {
public Bats() {
// TODO Auto-generated constructor stub
}
private String name;
private String age;
private String bg;
public Bats(String name, String age, String bg, String sex) {
super();
this.name = name;
this.age = age;
this.bg = bg;
this.sex = sex;
}
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getBg() {
return bg;
}
public void setBg(String bg) {
this.bg = bg;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
}
Yes you can do that. I found it while browsing... please refer -
How to Parsing CSV or JSON File with Apache Spark
There are two approaches, follow Procedure for approach B
POJO classes are not required for the approach B, but POJO classes would make your code easier to read if you are using Java
Hope this will help.

Categories