I am trying to create an object that is then serialized and written to file but regardless of what I try, a blank object is always written to file instead.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class FileIO implements Serializable {
private static final long serialVersionUID = 1L;
private VIAModel viaModel1;
private VIAView viaView1 = new VIAView();
private VIAController viaContr = new VIAController();
public void setVIAModelFromFile() throws IOException, ClassNotFoundException, EOFException {
boolean endOfFile = false;
FileInputStream fstream = new FileInputStream("viaModel.ser");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
}
inputFile.close();
}
public void setToFile() throws IOException {
viaContr = viaView1.getController();
viaModel1.setEventList(viaContr.getVIAMod().getEventList());
System.out.println(viaModel1.getEventList().getListOfEvents());
FileOutputStream fstream = new FileOutputStream("viaModel.ser");
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
try {
outputFile.writeObject(viaModel1);
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException ioe) {
System.out.println("Error.");
ioe.printStackTrace();
}
}
public VIAModel getVIAModel() {
return viaModel1;
}
public void setVIAModel(VIAModel viamod) {
this.viaModel1 = viamod;
}
}
The object being written has serializable on all objects inside and objects unable to be serialized have been manually serialized. The system.out.print shows the object with the information entered in the program, but this information doesn't appear in the .ser file at all and so only a blank object is read later.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javafx.beans.property.SimpleStringProperty;
public class Events implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5596571541918537611L;
private transient SimpleStringProperty name = new SimpleStringProperty("");
private transient SimpleStringProperty date = new SimpleStringProperty("");
private transient SimpleStringProperty duration = new SimpleStringProperty("");
private transient SimpleStringProperty type = new SimpleStringProperty("");
private transient SimpleStringProperty location = new SimpleStringProperty("");
private transient SimpleStringProperty category = new SimpleStringProperty("");
// private Lecturer conductor;
private transient SimpleStringProperty price = new SimpleStringProperty("");
private transient SimpleStringProperty minPartic = new SimpleStringProperty("");
private transient SimpleStringProperty maxPartic = new SimpleStringProperty("");
private boolean isFinalized = false;
// ArrayList<Members> eventMembList = new ArrayList<>();
public Events(String name, String date, String duration, String type, String location, String category,
/* Lecturer conductor, */ String price, String minPartic, String maxPartic, boolean isFinalized) {
setName(name);
setDate(date);
setDuration(duration);
setType(type);
setLocation(location);
setCategory(category);
setPrice(price);
setMinPartic(minPartic);
setMaxPartic(maxPartic);
this.isFinalized = isFinalized;
}
public Events() {
this("","","","","","","","","",false);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getDate() {
return date.get();
}
public void setDate(String date) {
this.date.set(date);
}
public String getDuration() {
return duration.get();
}
public void setDuration(String duration) {
this.duration.set(duration);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getLocation() {
return location.get();
}
public void setLocation(String location) {
this.location.set(location);
}
public String getCategory() {
return category.get();
}
public void setCategory(String category) {
this.category.set(category);
}
public String getPrice() {
return price.get();
}
public void setPrice(String price) {
this.price.set(price);
}
public String getMinPartic() {
return minPartic.get();
}
public void setMinPartic(String minPartic) {
this.minPartic.set(minPartic);
}
public String getMaxPartic() {
return maxPartic.get();
}
public void setMaxPartic(String maxPartic) {
this.maxPartic.set(maxPartic);
}
public boolean isFinalized() {
return isFinalized;
}
public void setFinalized(boolean isFinalized) {
this.isFinalized = isFinalized;
}
public void finalizeEvent() {
this.isFinalized = true;
}
// public void addMemToEvent(Members member) {
// eventMembList.add(member);
// }
public String toString() {
return this.name + "\n" + this.date+ "\n" + this.duration+ "\n" + this.type+ "\n" + this.location+ "\n" + this.category+ "\n" + this.price+ "\n" + this.minPartic+ "\n" + this.maxPartic+ "\n" + this.isFinalized;
}
public void readExternal(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
name = new SimpleStringProperty((String) in.readObject());
date = new SimpleStringProperty((String) in.readObject());
duration = new SimpleStringProperty((String) in.readObject());
type = new SimpleStringProperty((String) in.readObject());
location = new SimpleStringProperty((String) in.readObject());
category = new SimpleStringProperty((String) in.readObject());
price = new SimpleStringProperty((String) in.readObject());
minPartic = new SimpleStringProperty((String) in.readObject());
maxPartic = new SimpleStringProperty((String) in.readObject());
}
public void writeExternal(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(name.get());
out.writeObject(date.get());
out.writeObject(duration.get());
out.writeObject(type.get());
out.writeObject(location.get());
out.writeObject(category.get());
out.writeObject(price.get());
out.writeObject(minPartic.get());
out.writeObject(maxPartic.get());
}
}
Changing SimpleStringProperty to String seems to work perfectly and eliminates all of the issues involved with serializing, which is something that I don't have the knowledge to correct.
in your below code you will end up reading only the last object make sure you are reading correct contents from input file. Did you tried populating a new VIAModel object and then writing it to the file
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
It is exactly as I said. You have
public class Events implements Serializable
and a whole series of transient fields, and also
public void readExternal(ObjectInputStream in)
and
public void writeExternal(ObjectOutputStream out)
These methods are never called. There is nothing in the Object Serialization Specification about either of these method signatures.
If you want this class to be serialized, you need to either remove transient throughout, if SimpleStringProperty is Serializable, and remove these methods, or make it extends Externalizable, and fix the resulting compilation errors.
What you can't do is just make up your own semantics and signatures and then wonder why Java doesn't implement them.
Related
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();
}
}
I recently mapped a field of a class with a custom hibernate UserType.
this is my custom user type
package service.dao.hibernate;
import java.io.IOException;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.SimpleType;
import com.google.common.base.Objects;
public abstract class JSONUserType implements UserType { //ParameterizedType, Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final ObjectMapper Mapper;
private static final String CLASS_TYPE = "classType";
private static final String TYPE = "type";
private static final int[] SQL_TYPES = new int[] { Types.LONGVARCHAR,
Types.CLOB, Types.BLOB };
private Class classType;
private int sqlType = Types.LONGVARCHAR; // before any guessing
static {
Mapper = new ObjectMapper();
Mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
#Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return this.deepCopy(cached);
}
#Override
public Object deepCopy(Object value) throws HibernateException {
Object copy = null;
if (value != null) {
try {
return Mapper.readValue(Mapper.writeValueAsString(value),
this.classType);
} catch (IOException e) {
throw new HibernateException("unable to deep copy object", e);
}
}
return copy;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
try {
return Mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new HibernateException("unable to disassemble object", e);
}
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y) {
return true;
} else if (x == null || y == null) {
return false;
} else {
return x.equals(y);
}
}
#Override
public int hashCode(Object x) throws HibernateException {
return null == x ? 0 : x.hashCode();
}
#Override
public boolean isMutable() {
return true;
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
Object obj = null;
if (!rs.wasNull()) {
if (this.sqlType == Types.CLOB || this.sqlType == Types.BLOB) {
byte[] bytes = rs.getBytes(names[0]);
if (bytes != null) {
try {
obj = Mapper.readValue(bytes, createJavaType(Mapper));
} catch (IOException e) {
throw new HibernateException(
"unable to read object from result set", e);
}
}
} else {
try {
String content = rs.getString(names[0]);
if (content != null) {
obj = Mapper.readValue(content, createJavaType(Mapper));
}
} catch (IOException e) {
throw new HibernateException(
"unable to read object from result set", e);
}
}
}
return obj;
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, this.sqlType);
} else {
if (this.sqlType == Types.CLOB || this.sqlType == Types.BLOB) {
try {
st.setBytes(index, Mapper.writeValueAsBytes(value));
} catch (JsonProcessingException e) {
throw new HibernateException(
"unable to set object to result set", e);
}
} else {
try {
st.setString(index, Mapper.writeValueAsString(value));
} catch (JsonProcessingException e) {
throw new HibernateException(
"unable to set object to result set", e);
}
}
}
}
#Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return this.deepCopy(original);
}
// #Override
// public Class returnedClass() {
// return this.classType;
// }
#Override
public int[] sqlTypes() {
return SQL_TYPES;
}
// #Override
// public void setParameterValues(Properties params) {
// String classTypeName = params.getProperty(CLASS_TYPE);
// try {
// this.classType = ReflectHelper.classForName(classTypeName,
// this.getClass());
// } catch (ClassNotFoundException cnfe) {
// throw new HibernateException("classType not found", cnfe);
// }
// String type = params.getProperty(TYPE);
// if (type != null) {
// this.sqlType = Integer.decode(type).intValue();
// }
// }
/**
* By default we are expecting to use a simple object / not a collection (Set, List)
*
* #param mapper : instance jackson object mapper
*
* #return A jackson JavaType to specify wich object represent the json string representation
*
*/
public JavaType createJavaType (ObjectMapper mapper){
return SimpleType.construct(returnedClass());
}
}
this is the specific user type
package model.common;
import service.dao.hibernate.JSONUserType;
public class DocumentInfoType extends JSONUserType {
#Override
public Class returnedClass() {
return DocumentInfo.class;
}
}
Here is my entity with custom type field
package model.common;
import model.SimpleAuditedEntity;
import model.lk.DocumentMode;
import model.lk.DocumentType;
import service.dao.hibernate.JSONUserType;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import java.sql.Timestamp;
/**
* The persistent class for the documents database table.
*
*/
#Entity
#Table(name = "documents")
#NamedQuery(name = "Document.findAll", query = "SELECT d FROM Document d")
public class Document extends SimpleAuditedEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "content_type")
private String contentType;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type")
private DocumentType documentType;
#Column
private Timestamp created;
#Column
private String description;
#Column
private String filename;
#Column
private String name;
#Column
private String ref;
#Type(type = "model.common.DocumentInfoType")
#Column
private DocumentInfo info;
public Document() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getContentType() {
return this.contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Timestamp getCreated() {
return this.created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFilename() {
return this.filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return this.ref;
}
public void setRef(String ref) {
this.ref = ref;
}
/**
* #return the documentType
*/
public DocumentType getDocumentType() {
return documentType;
}
/**
* #param documentType
* the documentType to set
*/
public void setDocumentType(DocumentType documentType) {
this.documentType = documentType;
}
public DocumentMode getDocumentMode() {
return this.documentType != null ? DocumentMode
.getType(this.documentType.getId()) : DocumentMode.UNDEFINED;
}
/**
* #return the info
*/
public DocumentInfo getInfo() {
return info;
}
/**
* #param info the info to set
*/
public void setInfo(DocumentInfo info) {
this.info = info;
}
}
The problem is when I launch the application I get immediately the exception
Caused by: org.hibernate.MappingException: property mapping has wrong number of columns: model.common.Document.info type: model.common.DocumentInfoType
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:497) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.mapping.RootClass.validate(RootClass.java:270) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.cfg.Configuration.validate(Configuration.java:1360) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1851) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
Any idea about? I've mapped all the columns and I've tried many modifications but nothing!
Thanks in advance
You return an array of SQLTypes from JSONUserType.sqlTypes() that contains 3 elements:
private static final int[] SQL_TYPES = new int[] { Types.LONGVARCHAR,
Types.CLOB, Types.BLOB };
This tells hibernate that your type maps to 3 columns.
You should choose one of the types only.
See the javadoc for UserType.sqlTypes():
Return the SQL type codes for the columns mapped by this type
public class DateObj extends Date implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String fName;
private String sName;
private String days;
private String country;
private boolean fitIn;
public DateObj(String id,String fName, String sName, String country, String days) {
this.id = id;
this.fName = fName;
this.sName = sName;
this.days = days;
this.country = country;
}
#Override
public boolean equals(Object obj) {
DateObj dateObj = (DateObj) obj;
System.out.println("method Call");
return getfName().equals(dateObj.getfName());
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String toString(){
return fName;
}
#Override
public int hashCode() {
return fName.hashCode();
}
}
==========================================================================================
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
public class DataSaveTo {
private ArrayList<DateObj> listData = new ArrayList<DateObj>();
File file = new File("data3.csv");
public static void main(String[] args) {
DataSaveTo dataExperiment = new DataSaveTo();
dataExperiment.go();
}
public void go() {
loadData();
TreeSet<DateObj> data = new TreeSet<DateObj>();
data.addAll(listData);
// ObjComparInt comparId = new ObjComparInt();
// ObjectComparable comparObj = new ObjectComparable();
// Collections.sort(listData, comparId);
saveData();
// System.out.println(listData);
}
public void saveData() {
try {
File file = new File("dataNoDupl.csv");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(DateObj obj : listData){
bw.write(obj.getId()+";"+obj.getfName()+";"+obj.getsName()+";"+obj.getCountry()+";"+obj.getDays()+"\n ");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception in save Data method: "+ e);
}
}
public void loadData() {
FileReader fr;
try {
fr = new FileReader(file);
String s = null;
String[] tokens;
BufferedReader br = new BufferedReader(fr);
while((s=br.readLine())!=null){
tokens = s.split(",");
createDateObj(tokens);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("Exception in LoadData method"+e);
} catch (IOException e) {
System.out.println("Exception in LoadData method 2nd catch"+e);
e.printStackTrace();
}
}
private void createDateObj(String[] tokens) {
DateObj obj = new DateObj(tokens[4],tokens[0],tokens[2],tokens[3],tokens[1]);
listData.add(obj);
System.out.println(obj.hashCode()+"--"+obj.getfName()+"--"+obj.getsName());
}
// Name comparator
public class ObjectComparable implements Comparator<DateObj>{
#Override
public int compare(DateObj obj, DateObj obj1) {
return obj.getfName().compareTo(obj1.getfName());
}
}
// ID comparator
public class ObjComparInt implements Comparator<DateObj>{
#Override
public int compare(DateObj ob, DateObj ob1){
return Integer.parseInt(ob.getId()) - Integer.parseInt(ob1.getId());
}
}
}
I want HashSet to call equal method, because of overriden hashCode. And after equals compare,I want to remove duplicates in mine Collection I am passing into the hashSet.
HashSet<DateObj> data = new HashSet<DateObj>();
data.addAll(listData);
In console it prints me out, true (because of sys.out in equals method) but it does not do anything. I styl have duplicates.
With having same fName does not get same hash Value. As you consider sName also while generating hash code.
When you are putting the objects into your HashSet, hash code is generated and your hash code implementation generates hash code according to your fName and sName. On the other hand you are matching only fName in your equal method and get true printed!
First Define when you want to consider your objects same. Use those criteria to match in equals method and also consider them in hashCode method also. Because if two objects are equal, their hash code must to be equal!
The Java documentation of hashCode() states that:
If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
Your implementation is breaking this rule, and you need to change either the implementation of hashCode() or equals() to fulfill it.
You probably want to update equals():
#Override
public boolean equals(Object obj){
if (obj == null || !(obj instanceof DateObj)) {
return false;
}
DateObj dateObj = (DateObj) obj;
return getfName().equals(dateObj.getfName()) && getsName().equals(dateObj.getsName());
}
i have created a package SimpleCustomer and used it in SimpleCustomerService file.I have generated .class file for SimpleCustomer where as when i am compiling SimpleCustomerService file it is given errors .i couldn't resolve my error.i am new to java.thanks in advance
my package file is:
package com.adobe.objects;
import java.util.Date;
public class SimpleCustomer
{
private int customerId;
private String customerName;
private String customerAddress;
private String customerType;
private Date entryModifiedDate;
public int getCustomerId()
{
return this.customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return this.customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return this.customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getCustomerType() {
return this.customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public void setEntryModifiedDate(Date entryModifiedDate) {
this.entryModifiedDate = entryModifiedDate;
}
public Date getEntryModifiedDate() {
return this.entryModifiedDate;
}
}
and my file which uses this package is:
package com.adobe.services;
import com.adobe.objects.SimpleCustomer;
import java.util.ArrayList;
import java.util.Date;
public class SimpleCustomerService
{
public static void main(String args[])
{
}
ArrayList<SimpleCustomer> getAllCustomers()
{
ArrayList customers = null;
try
{
int numberOfCustomers = 20;
SimpleCustomer customer = null;
customers = new ArrayList();
for (int loopCounter = 1; loopCounter <= numberOfCustomers; loopCounter++)
{
customer = new SimpleCustomer();
customer.setCustomerId(loopCounter);
customer.setCustomerName("Customer " + loopCounter);
customer.setCustomerType("Organization " + loopCounter);
customer.setCustomerAddress("Road # " + loopCounter + ", Bangalore, India");
customer.setEntryModifiedDate(new Date());
customers.add(customer);
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return customers;
}
}
my error is:
illegal start of expression :public ArrayList getAllCustomers()
error 2: error ;excepted :public ArrayList getAllCustomers()
the first error is at public and second error is at getALlCustomers()
thanks in advance.
It seems you are trying to embed a method in your main method, which is i belive causing the error:
public static void main(String args[])
{
ArrayList<SimpleCustomer> getAllCustomers()
{
Not sure why you want to do it, but it is not permissible. You should move your getAllCustomers mehthod out of main method and see if it helps!
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
java.net.MalformedURLException: no protocol: "localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
Malformed URL exception when reading data from url containing localhost.
Actually my program is as below
package bll.sap;
import java.net.MalformedURLException;
import utility.PropertyUtility;
public class GetActiveData
{
public static void main(String[] args) {
String sapURL = "";
try {
sapURL = PropertyUtility.getSapURL();
//Get Summary Data
SapDataSync sapDataSync = new SapDataSync();
//sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=false");
sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=E13F42EC5E38");
}
catch(MalformedURLException me)
{
me.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AND
package bll.sap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import utility.Utility;
import com.google.code.morphia.Datastore;
import dal.GetMorphiaDB;
public class SapDataSync
{
private void saveSapTransaction(List<TransactionUnit> sapTransaction){
GetMorphiaDB morphia;
try {
morphia = GetMorphiaDB.getInstance();
Datastore ds = morphia.getDs();
ds.save(sapTransaction);
}catch (Exception e) {
e.printStackTrace();
}
}
private void createSapTransaction(String transactionJson){
JSONObject jsonObj = JSONObject.fromObject(transactionJson);
JSONArray transactionUnits = jsonObj.getJSONArray("TRANSACTION");
List<ActiveUnit> transactionList = new ArrayList<ActiveUnit>();
for(int i = 0; i < transactionUnits.size() ; i++){
JSONObject jsn = transactionUnits.getJSONObject(i);
JSONObject jsnFeed = transactionUnits.getJSONObject(i);
ActiveUnit transactionUnit = new ActiveUnit(
jsn.getString("listEditions"),
jsn.getString("listPackage"),
//Double.parseDouble(jsn.getString("YIELD")),
//Double.parseDouble(jsn.getString("QUANTITY")),
//Double.parseDouble(jsn.getString("VALUE")),
jsn.getString("referenceID")
//jsn.getString("PRICEGROUP"),
//jsn.getString("PAGE"),
//Utility.getCalendarTime(jsn.getString("PUBDATE"), "dd-MM-yyyy"),
//jsn.getString("CLIENTNAME"),
//jsn.getString("CLIENTCODE"),
// new Date().getTime(),
//jsn.getString("BOOKINGUNITNAME"),
//jsn.getString("BCCNAME"),
//jsn.getString("PAGENAME"),
// jsn.getString("PRICEGROUPNAME"),
// jsn.getString("ORDER"),
// jsn.getString("PAGE_LH_RH")
);
transactionList.add(transactionUnit);
System.out.println(transactionList);
}
System.out.println(transactionList.size());
if (transactionList.size() > 0) {
//saveSapTransaction(transactionList);
}
}
public void readTransactionJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
createSapTransaction(sb.toString());
} finally {
is.close();
}
}
}
AND
package bll.sap;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
#Entity("SapTransaction")
public class ActiveUnit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private ObjectId id;
private Long tilCreationDate;
private String clientName;
private String clientCode;
private String listEditions;
private Long date;
private String listPackage;
private String bookingUnitName;
private String referenceID;
private String bccName;
private String page;
private String pageName;
private String priceGroup;
private String pgName;
private Double yield;
private Double qty;
private Double value;
private String order;
private String pageType;
public ActiveUnit() {
}
public ActiveUnit(String listEdtions, String listPackage, /*Double yield,
Double qty, Double value,*/ String referenceID /*, String priceGroup,
String page, Long date,String clientName,
String clientCode,Long tilCreationDate,String bookingUnitName,String bccName,String pageName,String pgName,String order,String pageType*/) {
this.listEditions = listEdtions;
this.listPackage = listPackage;
//this.yield = yield;
//this.qty = qty;
//this.value = value;
this.referenceID = referenceID;
//this.priceGroup = priceGroup;
//this.page = page;
//this.date = date;
//this.clientName = clientName;
//this.clientCode = clientCode;
//this.tilCreationDate = tilCreationDate;
//this.setBookingUnitName(bookingUnitName);
//this.bccName = bccName;
//this.pageName = pageName;
//this.pgName = pgName;
//this.order = order;
//this.pageType = pageType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientCode() {
return clientCode;
}
public void setClientCode(String clientCode) {
this.clientCode = clientCode;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getId() {
return id;
}
public void setTilCreationDate(Long tilCreationDate) {
this.tilCreationDate = tilCreationDate;
}
public Long getTilCreationDate() {
return tilCreationDate;
}
public String getreferenceID() {
return referenceID;
}
public void setreferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getPriceGroup() {
return priceGroup;
}
public void setPriceGroup(String priceGroup) {
this.priceGroup = priceGroup;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getListEditions() {
return listEditions;
}
public void setVertical(String listEditions) {
this.listEditions = listEditions;
}
public String getListPackage() {
return listPackage;
}
public void setListPackage(String listPackage) {
this.listPackage = listPackage;
}
public Double getYield() {
return yield;
}
public void setYield(Double yield) {
this.yield = yield;
}
public Double getQty() {
return qty;
}
public void setQty(Double qty) {
this.qty = qty;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public void setBookingUnitName(String bookingUnitName) {
this.bookingUnitName = bookingUnitName;
}
public String getBookingUnitName() {
return bookingUnitName;
}
public String getBccName() {
return bccName;
}
public void setBccName(String bccName) {
this.bccName = bccName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPgName() {
return pgName;
}
public void setPgName(String pgName) {
this.pgName = pgName;
}
#Override
public String toString() {
String unit = "{ " +
//"ClientCode: " + this.clientCode+
//",TILCreation Date: " + new Date(this.tilCreationDate)+
//",ClientName: "+ this.clientName+
"listEditions: " + this.listEditions+
",listPackage: "+ this.listPackage+
//",BookingUnitName: "+ this.bookingUnitName+
//",Yield: " + this.yield+
//",QTY: " + this.qty+
//",Value: " + this.value+
",referenceID: " + this.referenceID+
//",Price Group: " + this.priceGroup+
//",BCCName: " + this.bccName+
//",PageName: " + this.pageName+
//",PriceGroupName: " + this.pgName+
//",Page: " + this.page+
//",PageType: " + this.pageType+
//",Order: " + this.order+
//",PublishDate: " + new Date(this.date) +
" }";
return unit;
}
public void setOrder(String order) {
this.order = order;
}
public String getOrder() {
return order;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getPageType() {
return pageType;
}
}
First, make sure you have the protocol set for your request.
Second, make sure that the String containing the URL is URL-encoded. I.e. the URL doesn't have any spaces and other special characters - these should be encoded (space is %20 etc).
Given that the two above are met, your program should not throw an exception from the java.net.URL class.
Looking at the exception above, you'll just have to set the protocol (http://), but do make sure that you encode your URL address strings properly or else you'll get exceptions from other parts of your program.
Also, adding http:// to the following string will also result in a MalformedURLException:
"localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38 as your URL would contain special characters (" in this case) which would need to be encoded.
To provide a valid URL you should make sure that the quotes are stripped from your URL's server and path segments areas:
localhost/uatpw/ActiveTransaction?isx=E13F42EC5E38. Prepeding http:// to this will result in a valid URL.
You are missing the protocol (e.g. http://) in front of localhost.
The welformed URL could be http://localhost/uatpw/ActiveTransaction
This is not a question. What are you trying to do?
But otherwise, "localhost/uatpw/ActiveTransaction" is not a valid URL. An url must start with a protocol (http, https, ftp, etc.).
You should try with:
http://localhost/uatpw/ActiveTransaction