ClassNotFoundException with readObject() method - java

I'm trying to read objects from a file in the Internet. I have been given the object class, which is this:
import java.io.Serializable;
public class Sulearvuti extends Arvuti implements Serializable {
private static final long serialVersionUID = 1L;
//isendiväli
private int aku;
//konstruktor
public Sulearvuti(String tootja, String mudel, String lisainfo,
int järjekorraNumber, int raskusaste, boolean kiirtellimus, int aku)
throws ValeRaskusAsteErind {
super(tootja, mudel, lisainfo, järjekorraNumber, raskusaste,
kiirtellimus);
this.aku = aku;
}
// meetod toString, kasutama ülemklassi meetodit
public String toString() {
return "Sülearvuti [aku=" + aku + ", " + super.toString() + "]";
}
// meetodi ülekatmine
double parandamiseAeg(){
return this.getRaskusaste()*2;
}
}
Now when I'm trying to read the objects (Sulearvuti), I get ClassNotFoundException. This is the piece of code :
ObjectInputStream ois =
new ObjectInputStream (
new URL("http://www.ut.ee/~marinai/sulearvutid.dat")
.openConnection()
.getInputStream());
int arv=ois.readInt();
Sulearvuti sülearvuti=(Sulearvuti)ois.readObject();
There's no problem with the Integer, but it won't recognize the class. I've been desperate for the past hour or so...
Also here's the code for the superclass "Arvuti":
import java.io.Serializable;
public class Arvuti implements Serializable, Comparable<Arvuti> {
private String tootja;
private String mudel;
private String lisainfo;
private int jrnumber;
private int vea_raskusaste;
private boolean kiirtellimus;
String getTootja() {
return tootja;
}
String getMudel() {
return mudel;
}
String getLisainfo() {
return lisainfo;
}
int getJrnumber() {
return jrnumber;
}
int getVea_raskusaste() {
return vea_raskusaste;
}
boolean isKiirtellimus() {
return kiirtellimus;
}
void setTootja(String tootja) {
this.tootja = tootja;
}
void setMudel(String mudel) {
this.mudel = mudel;
}
void setLisainfo(String lisainfo)throws WindowsXPErind {
this.lisainfo = lisainfo;
if(lisainfo.contains("WindowsXP"))throw new WindowsXPErind();
}
void setJrnumber(int jrnumber) {
this.jrnumber = jrnumber;
}
void setVea_raskusaste(int vea_raskusaste)throws ValeRaskusAsteErind {
if(vea_raskusaste<1 || vea_raskusaste>10) throw new ValeRaskusAsteErind();
this.vea_raskusaste = vea_raskusaste;
}
void setKiirtellimus(boolean kiirtellimus) {
this.kiirtellimus = kiirtellimus;
}
Arvuti(String tootja, String mudel, String lisainfo, int jrnumber,
int vea_raskusaste, boolean kiirtellimus)throws ValeRaskusAsteErind {
try{
setTootja( tootja);
setMudel(mudel);
setJrnumber(jrnumber);
setVea_raskusaste(vea_raskusaste);
setKiirtellimus(kiirtellimus);
setLisainfo(lisainfo);
}
catch (WindowsXPErind e){
System.out.println("WindowsXPErind");
setVea_raskusaste(vea_raskusaste+2);
}
}
double parandamiseAeg(){
return getVea_raskusaste()*1.5;
}
public String toString() {
return "Arvuti [tootja=" + tootja + ", mudel=" + mudel + ", lisainfo="
+ lisainfo + ", järjekorranumber=" + jrnumber + ", vea raskusaste="
+ vea_raskusaste + ", kiirtellimus=" + kiirtellimus
+ ", parandamise aeg=" + parandamiseAeg() + "]";
}
public int compareTo(Arvuti arvuti){
if(this.isKiirtellimus()==true && arvuti.isKiirtellimus()==false) return -1;
else if(this.isKiirtellimus()==false && arvuti.isKiirtellimus()==true) return 1;
else{
if(this.getJrnumber()<arvuti.getJrnumber())return -1;
else if(this.getJrnumber()>arvuti.getJrnumber())return 1;
else return 0;
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type ClassNotFoundException
at Peaklass.main(Peaklass.java:36)

You are missing some classes contained in the .dat file. Lookout for the classname shown in the classnotfound exception.
It is not sufficient to have the "Sulearvuti", you also need "Arvuti" (superclass) and "ValeRaskusAsteErind" (Exception) in your classpath.
BTW the language looks very funny to me, what language is this ?

Is "Sulearvuti" class on the classpath of the application trying to deserialize the object?

Related

java main method wont compile because it cannot find a symbol to create an object [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
im relatively new to java since im attending my first year at university.
currently we are doing OOP in class and i have the following problem:
i am creating a "Train", but when i try to compile it , it gives the following error:
https://i.gyazo.com/2d4f3ccc68f45419a9439ab9adb1a499.png[1]
which is really confusing to me because i have tried to run the main method in eclipse's console and it ran just fine.
my waggon class:
package sheet08;
//a)
public class Waggon {
private int SitzGesamt, SitzReserviert, SitzFrei ;
private int Klasse;
private String Doppelwagen;
private int WCbesetzt, WCfrei , WCdefekt;
private String WaggonHinten;
//b)
//Getter & Setter
public int getSitzGesamt() {
return SitzGesamt;
}
public void setSitzGesamt(int sitzGesamt) {
SitzGesamt = sitzGesamt;
}
public int getSitzReserviert() {
return SitzReserviert;
}
public void setSitzReserviert(int sitzReserviert) {
SitzReserviert = sitzReserviert;
}
public int getSitzFrei() {
return SitzFrei;
}
public void setSitzFrei(int sitzFrei) {
SitzFrei = sitzFrei;
}
public int getKlasse() {
return Klasse;
}
public void setKlasse(int klasse) {
Klasse = klasse;
}
public String getDoppelwagen() {
return Doppelwagen;
}
public void setDoppelwagen(String doppelwagen) {
Doppelwagen = doppelwagen;
}
public int getWCbesetzt() {
return WCbesetzt;
}
public void setWCbesetzt(int wCbesetzt) {
WCbesetzt = wCbesetzt;
}
public int getWCfrei() {
return WCfrei;
}
public void setWCfrei(int wCfrei) {
WCfrei = wCfrei;
}
public int getWCdefekt() {
return WCdefekt;
}
public void setWCdefekt(int wCdefekt) {
WCdefekt = wCdefekt;
}
public String getWaggonHinten() {
return WaggonHinten;
}
public void setWaggonHinten(String waggonHinten) {
WaggonHinten = waggonHinten;
}
//default Constructor
public Waggon() {
}
//Constructor
public Waggon(int sitzGesamt, int sitzReserviert, int sitzFrei, int klasse, String doppelwagen, int wCbesetzt,
int wCfrei, int wCdefekt, String waggonHinten) {
super();
SitzGesamt = sitzGesamt;
SitzReserviert = sitzReserviert;
SitzFrei = sitzFrei;
Klasse = klasse;
Doppelwagen = doppelwagen;
WCbesetzt = wCbesetzt;
WCfrei = wCfrei;
WCdefekt = wCdefekt;
WaggonHinten = waggonHinten;
}
// e)
public String toString(){
String strSitzGesamt = String.valueOf(SitzGesamt);
String strSitzReserviert = String.valueOf(SitzReserviert);
String strSitzFrei = String.valueOf(SitzFrei);
String strKlasse = String.valueOf(Klasse);
String strWCbesetzt = String.valueOf(WCbesetzt);
String strWCfrei = String.valueOf(WCfrei);
String strWCdefekt = String.valueOf(WCdefekt);
return strSitzGesamt + "-" + strSitzReserviert + "-" + strSitzFrei + "-" + strKlasse + "-" + Doppelwagen + "-" + strWCbesetzt + "-" +
strWCfrei + "-" + strWCdefekt + WaggonHinten;
}
}
my "Train" class:
package sheet08;
public class Train {
int Baureihe;
String Antriebsart;
int PS;
int Höchstgeschwindigkeit;
int WaggonDahinter;
//Getter&Setter
public int getBaureihe() {
return Baureihe;
}
public void setBaureihe(int baureihe) {
Baureihe = baureihe; //this.baurihe = baureihe
}
public String getAntriebsart() {
return Antriebsart;
}
public void setAntriebsart(String antriebsart) {
Antriebsart = antriebsart;
}
public int getPS() {
return PS;
}
public void setPS(int pS) {
PS = pS;
}
public int getHöchstgeschwindigkeit() {
return Höchstgeschwindigkeit;
}
public void setHöchstgeschwindigkeit(int höchstgeschwindigkeit) {
Höchstgeschwindigkeit = höchstgeschwindigkeit;
}
public int getWaggonDahinter() {
return WaggonDahinter;
}
public void setWaggonDahinter(int waggonDahinter) {
WaggonDahinter = waggonDahinter;
}
//default Constructor
public Train() {
}
//Constructor
public Train(int baureihe, String antriebsart, int pS, int höchstgeschwindigkeit, int waggonDahinter) {
super();
Baureihe = baureihe;
Antriebsart = antriebsart;
PS = pS;
Höchstgeschwindigkeit = höchstgeschwindigkeit;
}
//e)
public String toString(){
String strBaureihe = String.valueOf(Baureihe);
String strPS = String.valueOf(PS);
String strHöchstgeschwindigkeit = String.valueOf(Höchstgeschwindigkeit);
return strBaureihe + "-" + Antriebsart + "-" + strPS + "-" + strHöchstgeschwindigkeit;
}
}
and the main method itself :
package sheet08;
import java.util.Random;
public class Test {
public static void main( String[] args ) {
Random WCkaputt = new Random();
int WCdefekt = WCkaputt.nextInt(100)+1;
System.out.println("Die Toilette ist zu " + WCdefekt + " % kaputt");
Train t1 = new Train (412, "elektrisch", 13500, 250, 1);
Waggon w1 = new Waggon(50, 24, 3, 1, "doppelstock", 0, 0, 0, "1 Waggon dahinter"); //keine Angabe über die WC-Anzahl
Waggon w2 = new Waggon(100, 12, 64, 2, "doppelstock", 0, 0, 0, "1 Waggon dahinter");
Waggon w3 = new Waggon(100, 32, 11, 2, "doppelstock", 0, 0, 0, "1 Waggon dahinter");
Waggon w4 = new Waggon(50, 17, 3, 1, "doppelstock", 0, 0, 0, " kein Waggon dahinter");
System.out.println(t1);
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
System.out.println(w4);
//cannot find symbol Train & Waggon
//Variable als Train1 im typ train abspeichern
}
}
i compiled both the waggon and train class, got no errors there and i simply cant figure out why my main method doesnt find the symbol.
id appreciate any tips as im stuck at this error since yesterday!
You forgot the import statement in the class that contains main method.
import sheet08.Train;
import sheet08.Waggon;
From your screenshot, it looks like you have the three source files in the directory 'sheet08', and they are all in the package 'sheet08'. But your compile command is also being run from the same directory.
You need to "cd .." and compile from the parent directory, "src".
Your code will then run using "java sheet08.Test"
Think of it this way: the package (and directory) are a relative path from where you are running the java commands. When you identify a file as in a package, Java expects that file to be in a relative path from it equivalent to that package: in your case, your files are in package "sheet08", and so the relative path to them must be a directory "sheet08/".
This is why, when running the code, you need to identify the package: just as when referring to the file, you have to identify which directory it is in.

How do I load and save an arrayList<String> into a text class in java?

I am trying to implement a save and load function in my program that saves an arrayList to a textfile and then can later load all of the past lists I have saved and print them out. I am currently using these two methods:
public static void save(Serializable data, String fileName) throws Exception {
try (ObjectOutputStream oos = new ObjectOutputStream((Files.newOutputStream(Paths.get(fileName))))) {
oos.writeObject(data);
}
}
public static Object load(String fileName) throws Exception {
try (ObjectInputStream oos = new ObjectInputStream((Files.newInputStream(Paths.get(fileName))))) {
return oos.readObject();
}
}
As well as a class that represents a list as serializable data.
The problem with this is that it won't save the data after I terminate the program, and when it loads data it prints it with a great deal of extra text besides the list I want it to return. Is there a better or easier way of doing this?
I once had a same problem. So I will show you how to do it ...
Be the below Level class is what is to be saved:
public class Level implements Serializable {
private int level = 1;
private int star;
private int point;
// Constructor
public Level() {
}
public void setLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
public void setStar(int stars) {
this.star = stars;
}
public int getStar() {
return star;
}
public void setPoint(int points) {
this.point = points;
}
public int getPoint() {
return point;
}
#Override
public String toString() {
return "Level-" + level + " " +
(star > 1 ? star + " stars": star + " star") + " " +
(point > 1 ? point + " points" : point + " point") + "\n";
}
}
We will save the list into this file:
private static final String FILENAME = "data.level";
This is the List of our objects:
List<Level> mLevels;
Call this method to save the list into the file:
private void save() {
if(mLevels.isEmpty()) {
return;
}
try
{
ObjectOutputStream oos = new ObjectOutputStream(mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE));
oos.writeObject(mLevels);
}
catch (IOException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Use this method to load the list from saved file. Notice, we cast the list of our object with this (List<Level>) ois.readObject(); in the method:
private void load() {
try
{
ObjectInputStream ois = new ObjectInputStream(mContext.openFileInput(FILENAME));
mLevels = (List<Level>) ois.readObject();
}
catch (IOException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
catch (ClassNotFoundException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(mLevels == null) {
mLevels = new ArrayList<>();
//Toast.makeText(mContext,"List created",Toast.LENGTH_SHORT).show();
}
}
By now, you should get the idea of how to save your own list.

Printing textdata from toString - Java

I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?
This is how my toString looks like:
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
Full code:
import java.util.*;
import java.io.*;
public class Codes {
public static void main(String[] args) {
List<Codes2> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
Codes2 personObj = new Codes2(personName, userNameGenerator);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++){
String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
for(int j = 0; j < regionSplit.length; j++){
newStrSet.add(regionSplit[j]);
}
}
for (String p: newStrSet) {
System.out.printf("%s -> ", p);
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.getPersonName());
}
}
System.out.println();
}
}
}
Java Class:
public class Codes2 implements Comparable<Codes2> {
private String personName;
private String userNameGenerator;
public Codes2(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
#Override
public int compareTo(Codes2 o) {
return getUserNameGenerator().compareTo(o.getUserNameGenerator());
}
public int compare(Object lOCR1, Object lOCR2) {
return ((Codes2)lOCR1).userNameGenerator
.compareTo(((Codes2)lOCR2).userNameGenerator);
}
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
}
Everything looks right in your code.
I think you should just call the method when you are trying to print it out:
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.toString());
}
}
This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.
Try:
#Override
public String toString() {
return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}

wrapper class is it a design pattern

i'm new to design pattern , and now i'm working on an open ware code : so i'm trying to understand the architecture of the code : layers , used design pattern ...
So i found the a package containing classes named EntityWrapper.java here's an example :
The wrapper class :
package org.objectweb.salome_tmf.api.data;
/**
* #author marchemi
*/
public class ActionWrapper extends DataWrapper{
String awaitedResult;
int orderIndex;
int idTest;
/**
* #return Returns the orderIndex.
*/
public int getOrderIndex() {
return orderIndex;
}
/**
* #param orderIndex The orderIndex to set.
*/
public void setOrderIndex(int orderIndex) {
this.orderIndex = orderIndex;
}
/**
* #return Returns the waitedResult.
*/
public String getAwaitedResult() {
return awaitedResult;
}
/**
* #param waitedResult The waitedResult to set.
*/
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
/**
* #return Returns the idTest.
*/
public int getIdTest() {
return idTest;
}
/**
* #param idTest The idTest to set.
*/
public void setIdTest(int idTest) {
this.idTest = idTest;
}
}
The entity class:
package org.objectweb.salome_tmf.data;
import java.io.File;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import org.objectweb.salome_tmf.api.Api;
import org.objectweb.salome_tmf.api.ApiConstants;
import org.objectweb.salome_tmf.api.Util;
import org.objectweb.salome_tmf.api.data.ActionWrapper;
import org.objectweb.salome_tmf.api.data.FileAttachementWrapper;
import org.objectweb.salome_tmf.api.data.ParameterWrapper;
import org.objectweb.salome_tmf.api.data.SalomeFileWrapper;
import org.objectweb.salome_tmf.api.data.UrlAttachementWrapper;
import org.objectweb.salome_tmf.api.sql.ISQLAction;
public class Action extends WithAttachment {
static ISQLAction pISQLAction = null;
private String awaitedResult;
public String getAwaitedResult() {
return awaitedResult;
}
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
private int orderIndex;
private Hashtable parameterHashTable;
private Test pTest = null;
public Action(Test pTest, String name, String description) {
super(name, description);
awaitedResult = "";
orderIndex = 0;
parameterHashTable = new Hashtable();
this.pTest = pTest;
if (pISQLAction == null){
pISQLAction = Api.getISQLObjectFactory().getISQLAction();
}
}
public Action(ActionWrapper pAction, Test pTest) {
this(pTest, pAction.getName(), pAction.getDescription());
awaitedResult = pAction.getAwaitedResult();
orderIndex = pAction.getOrderIndex();
idBdd = pAction.getIdBDD();
}
public Action(Action pAction, Test pTest) {
this(pTest, pAction.getNameFromModel(), pAction.getDescriptionFromModel());
awaitedResult = pAction.getAwaitedResultFromModel();
} // Fin du constructeur Action/1
protected void reloadBaseFromDB() throws Exception {
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
ActionWrapper pActionWrapper = pISQLAction.getActionWrapper(idBdd);
awaitedResult = pActionWrapper.getAwaitedResult();
orderIndex = pActionWrapper.getOrderIndex();
name = pActionWrapper.getName();
description = pActionWrapper.getDescription();
}
public void reloadFromDB(boolean base, Hashtable paramsInModel, boolean attach)
throws Exception {
int transNuber = -1;
try {
transNuber = Api.beginTransaction(101, ApiConstants.LOADING);
if (base){
reloadBaseFromDB();
}
reloadUsedParameterFromDB(paramsInModel);
if (attach){
reloadAttachmentDataFromDB(false);
}
Api.commitTrans(transNuber);
} catch (Exception e){
Api.forceRollBackTrans(transNuber);
throw e;
}
}
public void clearCache() {
/* TODO ClearAttachement */
}
/******************************************************************************/
/** ACCESSEURS ET
MUTATEURS ***/
/******************************************************************************/
public String getAwaitedResultFromModel() {
return awaitedResult;
}
public void setAwaitedResultInModel(String string) {
awaitedResult = string;
}
public int getOrderIndexFromModel() {
return orderIndex;
}
public void setOrderIndex(int i) {
orderIndex = i;
}
public Test getTest(){
return pTest;
}
/////////////////////////////// Basic Operation /////////////////////////
/* Used by Manuel Test */
void addInDB(Test pTest) throws Exception {
//boolean needUpdate = false;
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
if (!pTest.isInBase()){
throw new Exception("Test " + pTest.getNameFromModel() + " is not in BDD");
}
int id = pISQLAction.insert(pTest.getIdBdd(), name, description, awaitedResult);
setIdBdd(id);
orderIndex = pISQLAction.getActionWrapper(id).getOrder();
/*if (orderIndex != rowCount){
needUpdate = true;
}
return needUpdate;*/
Project.pCurrentProject.notifyChanged( ApiConstants.INSERT_ACTION ,this);
}
/* Used by Manuel Test */
void addInModel(Test pTest){
this.pTest = pTest;
}
/* Used by Manuel Test */
void addInDBAndModel(Test pTest)throws Exception {
//boolean res;
addInDB(pTest);
addInModel(pTest);
//return res;
}
public void updateInDB(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.update(idBdd, newActionName, newActionDesc, newActionResAttendu );
Project.pCurrentProject.notifyChanged( ApiConstants.UPDATE_ACTION ,this, new String(name), newActionName);
}
public void updateInModel(String newActionName, String newActionDesc, String newActionResAttendu) {
setNameInModel(newActionName);
updateDescriptionInModel(newActionDesc);
setAwaitedResultInModel(newActionResAttendu);
}
public void updateInDBAndModel(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
updateInDB(newActionName, newActionDesc, newActionResAttendu);
updateInModel(newActionName, newActionDesc, newActionResAttendu);
}
public void updateInDBAndModel(String newName, String newDesc) throws Exception {
updateInDB(newName, newDesc, awaitedResult);
updateInModel(newName, newDesc, awaitedResult);
}
public void updateOrderInDBAndModel(boolean inc) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
orderIndex = pISQLAction.updateOrder(idBdd, inc);
}
/* Used by Manuel Test */
void deleteInDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.delete(idBdd);
Project.pCurrentProject.notifyChanged( ApiConstants.DELETE_ACTION ,this);
}
/* Used by Manuel Test */
void deleteInModel(){
pTest=null;
parameterHashTable.clear();
clearAttachInModel();
}
/* Used by Manuel Test */
void deleteInDBAndModel() throws Exception {
deleteInDB();
deleteInModel();
}
//////////////// PARAMETERS ////////////////////////
public void setParameterHashSetInModel(HashSet set) {
parameterHashTable.clear();
for (Iterator iter = set.iterator(); iter.hasNext();) {
Parameter param = (Parameter)iter.next();
parameterHashTable.put(param.getNameFromModel(), param);
}
}
public void setParameterHashtableInModel(Hashtable table) {
parameterHashTable.clear();
parameterHashTable = table;
}
public Hashtable getCopyOfParameterHashTableFromModel(){
Hashtable copyParameter = new Hashtable();
Enumeration enumKey = parameterHashTable.keys();
while (enumKey.hasMoreElements()){
Object key = enumKey.nextElement();
copyParameter.put(key, parameterHashTable.get(key));
}
return copyParameter;
}
public void reloadUsedParameterFromDB(Hashtable parametersInModel) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] paramActionArray = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < paramActionArray.length; i++) {
Parameter param = null;
ParameterWrapper pParameterWrapper = paramActionArray[i];
if (parametersInModel != null){
param = (Parameter)parametersInModel.get(pParameterWrapper.getName());
if (param == null){
param = new Parameter(pParameterWrapper);
}
}
setUseParamInModel(param);
}
}
public void setUseParamInModel(Parameter pParam) {
parameterHashTable.put(pParam.getNameFromModel(), pParam);
if (pTest != null) {
if (pTest.getUsedParameterFromModel(pParam.getNameFromModel()) == null){
pTest.setUseParamInModel(pParam);
}
}
}
public void setUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.addUseParam(idBdd,paramId);
}
public void setUseParamInDBAndModel(Parameter pParam) throws Exception {
//DB
setUseParamInDB(pParam.getIdBdd());
//model
setUseParamInModel(pParam);
}
public void deleteUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteParamUse(idBdd, paramId);
}
public void deleteUseParamInDBAndModel(Parameter pParam) throws Exception {
deleteUseParamInDB(pParam.getIdBdd());
deleteUseParamInModel(pParam);
}
public void deleteUseParamInModel(Parameter pParam) {
// Clean Action
String newDesc = null ;
if (getDescriptionFromModel()!=null)
newDesc = clearStringOfParameter(getDescriptionFromModel(), pParam);
String newResult = null;
if (getAwaitedResultFromModel()!=null)
newResult = clearStringOfParameter(getAwaitedResultFromModel(), pParam);
description = newDesc;
awaitedResult = newResult;
Object o= parameterHashTable.remove(pParam.getNameFromModel());
Util.log("[Action->deleteUseParamInModel] Delete Use Parameter " + pParam + ", in Action " + name + " res is " +o);
}
public Parameter getParameterFromModel(String name) {
Enumeration paramList = parameterHashTable.elements();
while (paramList.hasMoreElements()){
Parameter param = (Parameter)paramList.nextElement();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public Parameter getParameterFromDB(String name) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = getParameterHashSetFromDB();
for (Iterator iter = result.iterator(); iter.hasNext(); ) {
Parameter param = (Parameter)iter.next();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public HashSet getParameterHashSetFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = new HashSet();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Vector getParameterVectorFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
Vector result = new Vector();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Hashtable getParameterHashSetFromModel() {
return parameterHashTable;
}
////////////// ATTACHEMENT ///////////////////////
public void addAttachementInDB (Attachment attach )throws Exception {
if (attach instanceof FileAttachment) {
addAttachFileInDB((FileAttachment) attach);
} else {
addAttachUrlInDB((UrlAttachment) attach);
}
}
void addAttachFileInDB(FileAttachment file) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
File f = file.getLocalFile();
int id = pISQLAction.addFileAttach(idBdd,new SalomeFileWrapper(f),file.getDescriptionFromModel());
file.setIdBdd(id);
}
void addAttachUrlInDB(UrlAttachment url) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
int id = pISQLAction.addUrlAttach(idBdd, url.getNameFromModel(),url.getDescriptionFromModel());
url.setIdBdd(id);
}
public void deleteAttachementInDB(int attachId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteAttachment(idBdd, attachId);
}
public void deleteAttachementInDBAndModel(Attachment attach)throws Exception {
deleteAttachementInDB(attach.getIdBdd());
deleteAttachmentInModel(attach);
}
public Vector getAttachFilesFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
FileAttachementWrapper[] fawArray = pISQLAction.getAllAttachFile(idBdd);
Vector result = new Vector();
for(int i = 0; i < fawArray.length; i++) {
result.add(fawArray[i]);
}
return result;
}
public Vector getAttachUrlsFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
UrlAttachementWrapper[] uawArray = pISQLAction.getAllAttachUrl(idBdd);
Vector result = new Vector();
for(int i = 0; i < uawArray.length; i++) {
result.add(uawArray[i]);
}
return result;
}
//////// PROTECTED //////////////
protected String clearStringOfParameter(String prtString, Parameter pParam) {
String result = prtString;
result = result.replaceAll("[$]" + pParam.getNameFromModel() + "[$]", "");
return result;
}
public static boolean isInBase(Test pTest, String actionName) {
try {
int id = pISQLAction.getID(pTest.getIdBdd(), actionName);
if (id > 0){
return true;
}
return false;
} catch (Exception e) {
}
return false;
} // Fin de la methode isInBase/1
public boolean existeInBase() throws Exception {
if (!isInBase()) {
return false;
}
return pISQLAction.getID(pTest.getIdBdd(), name) == idBdd;
}
}
So what is the utility of the wrapper class , is it a kind of design pattern ?
I can not see, what ActionWrapper wraps, for me is just implementation of DataWrapper interface.
There 3 "kinds" of wrappers design patterns:
Facade design pattern = take a lot of classes/interfaces, do some logic inside and get out small interface. For example "Car start" encapsulate inside: open car, put key, set DVD, correct chair, ignition.
Decorator design pattern = take some class with behavior and make ability to add behaviors in run time. for example, instead of do class CarWithLCDWithDVDWithTurbo you can do: new LCDDecorator(new DVDDecorator(TurboDecorator(new car)));
Adapter design pattern = take some new interface and adapt it to some known interface.
The fact that something ends with the Wrapper word doesn´t make it a wrapper. To be a wrapper it has to wrap something. This is, it has to encapsulate one or more components, probably a whole third-party API.
There are different types of wrappers as #zzfima says. And yes, proxy could be a wrapper in some cases and also bridges could be.
Your code doesn´t encapsulate any other component and then, it is not a wrapper (at least for me)
call something "wrapper" doesn't make it a wrapper. Basically it needs to encapsulate something or wrap something, whatever you call it

Trouble with a small library-management program

I'm having major trouble piecing this together. I have basic read and write functionality. What I need is for the input from file 'Books.txt' to be checked so that:
ISBN is valid
CopyNumber, Year and Statistics should be numeric
Title, Author and Publisher must contain values
BorrowDate must be a valid date
ReturnDate if available must be a valid date
LibraryCardNumber if available must be numeric.
If a book is not borrowed the two last fields are nonexistent.
2 sample rows from 'Books.txt':
9780140455168#2#The Twelve Caesars#Suetonius#Penguin Classics#2007#3#101009#101030#5478
9780141188607#1#Claudius the God#Robert Graves#Penguin Classics#2006#2#080123
Error lines should be written to 'ErrorLines.txt' with an error-message, e.g. Wrong ISBN. Error-free books should be written to 'NewBooks.txt' sorted by name of author.
Here's what I've got so far. I'm not looking for a complete solution, because I obviously have a looong way to go, but if someone would be so kind as to give me some pointers, I'd be extremely grateful! And yes, it's homework :D
Do I need to make a try loop to validate the input...?
The Library class:
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Library {
public void readFromFile (String filename) throws IOException {
String inLine;
File inFile;
inFile = new File("Books.txt");
BufferedReader fIn = new BufferedReader(new FileReader(inFile));
inLine = fIn.readLine();
while (inLine != null) {
inLine = fIn.readLine();
aBookList.add(inLine + "\n");
}
fIn.close();
}
public void writeToFile (String fileName) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write("???"); //Dont know what to put here...
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing file.");
} finally {
bw.close();
}
}
public static boolean isISBN13Valid(isbn) {
int check = 0;
for (int i = 0; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1));
}
for (int i = 1; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1)) * 3;
}
check += Integer.valueOf(isbn.substring(12));
return check % 10 == 0;
}
}
And here's the Book class:
import java.util.*;
import java.io.*;
public class Book {
Book b = new Book();
private static ArrayList<String> aBookList = new ArrayList<String>();
private String Isbn;
private int CopyNumber;
private String Title;
private String Author;
private String Publisher;
private int Year;
private int Statistics;
private String BorrowDate;
private String ReturnDate;
private int LibraryCardNumber;
public void bookInfo (String nIsbn, int nCopyNumber, String nTitle, String nAuthor, String nPublisher, int nYear,
int nStatistics, String nBorrowDate, String nReturnDate, int nLibraryCardNumber) {
Isbn = nIsbn;
CopyNumber = nCopyNumber;
Title = nTitle;
Author = nAuthor;
Publisher = nPublisher;
Year = nYear;
Statistics = nStatistics;
BorrowDate = nBorrowDate;
ReturnDate = nReturnDate;
LibraryCardNumber = nLibraryCardNumber;
}
public void bookInfo (String Row) {
StringTokenizer sT = new StringTokenizer(Row);
Isbn = sT.nextToken("#");
CopyNumber = Integer.parseInt(sT.nextToken("#") );
Title = sT.nextToken("#");
Author = sT.nextToken("#");
Publisher = sT.nextToken("#");
Year = Integer.parseInt(sT.nextToken("#") );
Statistics = Integer.parseInt(sT.nextToken("#") );
BorrowDate = sT.nextToken("#");
ReturnDate = sT.nextToken("#");
LibraryCardNumber = Integer.parseInt(sT.nextToken("#") );
}
public void setIsbn(String nIsbn) {
Isbn = nIsbn;
}
public void setCopynumber(int nCopyNumber) {
CopyNumber = nCopyNumber;
}
public void setTitle(String nTitle) {
Title = nTitle;
}
public void setAuthor(String nAuthor) {
Author = nAuthor;
}
public void setPublisher(String nPublisher) {
Publisher = nPublisher;
}
public void setYear(int nYear) {
Year = nYear;
}
public void setStatistics(int nStatistics) {
Statistics = nStatistics;
}
public void setBorrowDate(String nBorrowDate) {
BorrowDate = nBorrowDate;
}
public void setReturnDate(String nReturnDate) {
ReturnDate = nReturnDate;
}
public void setLibraryCardNumber(int nLibraryCardNumber) {
LibraryCardNumber = nLibraryCardNumber;
}
public String getAll () {
String s = " ";
return (Isbn + s + CopyNumber + s + Title + s + Author + s + Publisher + s +
Year + s + Statistics + s + BorrowDate + s + ReturnDate + s +
LibraryCardNumber);
}
public void showAll () {
String t = "\t";
System.out.println(Isbn + t + CopyNumber + t + Title + t + Author + t +
Publisher + t + Year + t + Statistics + t +
BorrowDate + t + ReturnDate + t + LibraryCardNumber);
}
}
And finally there's the Main class with main method:
public class Main<aBookList> implements Comparable<aBookList> {
public static void main(String [] args) throws Exception {
new Library().readFromFile("Books.txt");
new Library().writeToFile("NewBooks.txt");
new Library().writeToFile("ErrorLines.txt");
}
#Override
public int compareTo(aBookList o) {
return 0;
}
}
as it is homework, i will point you direction, not give you code
1) you have lot of mess here, ie i'm not sure why you have compare in your main class? instead of creating getAll method in bookInfo(which is named against java nameing convention) just override toString method
2) why do you have list of strings? read a line, convert this into book, if book is valid add it to your list, otherwise report an error
3) move your isISBN13Valid method to book
4) write to file -> loop through your list, and save each element into file by bw.write(book.toString()),
5) create second method createErrorFile, then each error what you will have add into your error list, and after you call that method, you will sace each element into given file, it is not perfetc solution, better will be if you add error to file each time when it occur.
6) create one instance of library in your main method, and just call on it all your method, and avoid using static fields in your project(sometimes you must, but if you don;t need, just avoid them)
7) names for method import/ export i think sounds nicer than read from file read from file

Categories

Resources