so i have a three class video store GUI and it is supposed to save records of videos in stock. however it saves the video objects using serialization but for some reason ,even though i am not getting any errors, only the numerical values are making it through..
notice how the leftmost three columns and the rightmost column are all empty. this is because they are meant to have strings in them, and yet they dont...
as i said im not getting any errors so this truly confuses me.
constructor of VideoStore.java(the GUI class):
public VideoStore() {
initComponents();
model = (DefaultTableModel)displayVideos.getModel();
try{
BinaryFile = new BinaryFile();
BinaryFile.load();
}
catch(Exception e){
}
for(int j = 1; j < BinaryFile.videosList.size(); j ++) {
Video load = (Video)BinaryFile.videosList.get(j);
String tempName = load.getVideoName();
String tempProd = load.getProducer();
String tempRat = load.getRating();
String tempGenre = load.getGenre();
short tempNum = load.getVidNum();
float tempPrice = load.getvideoPrice();
try {
Object[] row = {ID, tempName, tempProd, tempGenre, tempPrice, tempNum, tempRat};
model.addRow(row);
} catch(Exception e){
}
ID++;
}
}
and then the BinaryFile class that i use to handle the .ser file:
public void load(){
try
{
FileInputStream fileIn = new FileInputStream("/Users/hanaezz/Desktop/output.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
videosList = (ArrayList)in.readObject();
in.close();
fileIn.close();
} catch(Exception i)
{
i.printStackTrace();
return;
}
}
public static void adderoo(Video v) {
videosList.add(v);
}
finally, the video class that is in the ArrayList:
private static String videoName;
private static String producer;
private static String rating;
private static String genre;
private short videoNumber;
private float videoPrice;
Static variabled are NOT serialized, you should put:
private String videoName;
private String producer;
private String rating;
private String genre;
private short videoNumber;
private float videoPrice;
in your video class.
The only static variable you should put in a Serializable class is serialVersionUID (which is used by the serialization and deserialization process). As in:
private static final long serialVersionUID = 1L;
Related
I have a problem with CsvToBeanBuilder from opencsv. I have a class:
public class TransferNetworkRawData {
#CsvBindByName
private String jurisdiction;
#CsvBindByName
private String currency;
#CsvBindByName
private String transfernetwork;
#CsvBindByName
private String display;
public TransferNetworkRawData() {
}
// getters and setters
}
And a service (FYI: TransferNetworkDataFetcher is just an interface with one method getTransferNetworkData(). I am creating this class in such manner, because I want the data to be loaded on application startup without having to read the file every time a request for this data comes.
#Component
public class CsvTransferNetworkDataFetcher implements TransferNetworkDataFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(CsvTransferNetworkDataFetcher.class);
private static final char SEPARATOR = ';';
private List<TransferNetworkRawData> transferNetworkRawData = new ArrayList<>();
public CsvTransferNetworkDataFetcher(ResourceLoader resourceLoader) {
try {
Resource resource = resourceLoader.getResource("classpath:" + "csv/transferNetworks.csv");
CSVReader reader = new CSVReaderBuilder(new FileReader(resource.getFile())).build();
transferNetworkRawData = new CsvToBeanBuilder(reader)
.withType(TransferNetworkRawData.class)
.withSeparator(SEPARATOR)
.build()
.parse();
} catch (IOException exception) {
LOGGER.error("File not found! " + exception.getMessage());
}
}
#Override
public List<TransferNetworkRawData> getTransferNetworkData() {
return transferNetworkRawData;
}
}
The CSV file looks like this (the file has 28 sets of data + header, so 28 objects in general)
jurisdiction;currency;transfernetwork;display
US;AAVE;ETHEREUM;TRUE
US;BAT;ETHEREUM;TRUE
EU;BCAP;ETHEREUM;TRUE
And a test:
#SpringBootTest
class CsvTransferNetworkDataFetcherTest {
#Autowired
private CsvTransferNetworkDataFetcher transferNetworkDataFetcher;
#Test
void shouldReturnTransferNetworkList() {
List<TransferNetworkRawData> transferNetworkDataList = transferNetworkDataFetcher.getTransferNetworkData();
System.out.println(transferNetworkDataList); // just for breakpoint
}
}
Running this test shows some unexpected results, as getTransferNetworkData() is returning a list of 28 TransferNetworkRawData objects, but all the values (jurisdiction, currency, transfernetwork and display) in all those 28 objects are null, so it seems that the file is loaded correctly but the data isn't correctly read from it...
I have no idea what am I missing here...
I'm facing with exactly the same issue in my source code. I just change this annotation #CsvBindByName for #CsvBindByPosition(position = #)
Your new model should be:
public class TransferNetworkRawData {
#CsvBindByPosition(position = 0)
private String jurisdiction;
#CsvBindByPosition(position = 1)
private String currency;
#CsvBindByPosition(position = 2)
private String transfernetwork;
#CsvBindByPosition(position = 3)
private String display;
public TransferNetworkRawData() {
}
// getters and setters
}
I am trying to override the #AdminPresentation of the following attribute defined in ProductImpl:
#Column(name = "DISPLAY_TEMPLATE")
#AdminPresentation(friendlyName = "ProductImpl_Product_Display_Template",
group = GroupName.Advanced)
protected String displayTemplate;
Currently, it is displayed as a text field by default as there is no fieldType attribute provided. But I want to display a dropdown select menu with predefined values such as Product and Plan. Here is what I've tried so far:
I've created a class DisplayTemplateType that implements BroadleafEnumerationType and defined PLAN and PRODUCT enums. Here is the code of that class:
public class DisplayTemplateType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 7761108654549553693L;
private static final Map<String, DisplayTemplateType> TYPES = new LinkedHashMap<String, DisplayTemplateType>();
public static final DisplayTemplateType PLAN = new DisplayTemplateType("PLAN", "PLAN");
public static final DisplayTemplateType PRODUCT = new DisplayTemplateType("PRODUCT", "PRODUCT");
public static DisplayTemplateType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public DisplayTemplateType() {
//do nothing
}
public DisplayTemplateType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
#Override
public String getType() {
return type;
}
#Override
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
// equals() and hashCode() implementation is removed for readability
}
Then in applicationContext-admin.xml file, I have added the following override properties:
<mo:override id="blMetadataOverrides">
<mo:overrideItem ceilingEntity="org.broadleafcommerce.core.catalog.domain.Product">
<mo:field name="displayTemplate">
<mo:property name="explicitFieldType" value="BROADLEAF_ENUMERATION"/>
<mo:property name="broadleafEnumeration" value="com.community.core.domain.DisplayTemplateType"/>
</mo:field>
</mo:overrideItem>
</mo:override>
But it didn't change anything. Am I missing something here?
Finally, after trying many things, I came up with a workaround. Instead of going with the XML based approach, I had to extend the ProductImpl class to override #AdminPresentation of its attributes. But for extending I needed to define an #Entity and as a result, I needed to create a useless table to bind to that entity. I know this is not the perfect approach but I couldn't find any better solution for this. Here is my code, so that someone might get help from it in the future:
#Entity
#Immutable
#AdminPresentationMergeOverrides({
#AdminPresentationMergeOverride(name = "displayTemplate", mergeEntries = {
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.FIELDTYPE, overrideValue = "BROADLEAF_ENUMERATION"),
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.BROADLEAFENUMERATION, overrideValue = "com.community.core.domain.DisplayTemplateType"),
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE, overrideValue = "REQUIRED"),
#AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.DEFAULTVALUE, overrideValue = "PLAN")
})
})
public class CustomProduct extends ProductImpl {
private static final long serialVersionUID = -5745207984235258075L;
}
This is how it is displayed now:
I am trying to read a csv file into JavaRDD. In order to do that, I wrote the code below:
SparkConf conf = new SparkConf().setAppName("NameOfApp").setMaster("spark://Ip here:7077");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<CurrencyPair> rdd_records = sc.textFile(System.getProperty("user.dir") + "/data/data.csv", 2).map(
new Function<String, CurrencyPair>() {
public CurrencyPair call(String line) throws Exception {
String[] fields = line.split(",");
CurrencyPair sd = new CurrencyPair(Integer.parseInt(fields[0].trim()), Double.parseDouble(fields[1].trim()),
Double.parseDouble(fields[2].trim()), Double.parseDouble(fields[3]), new Date(fields[4]));
return sd;
}
}
);
My data file looks like this:
1,0.034968,212285,7457.23,"2019-03-08 18:36:18"
Here, in order to check that if my data loaded correctly or not, I tried to print some of them:
System.out.println("Count: " + rdd_records.count());
List<CurrencyPair> list = rdd_records.top(5);
System.out.println(list.toString());
But I had following error at both system out lines. I tried each of them alone as well rather than printing count and list at the same time.
Caused by: java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field org.apache.spark.rdd.MapPartitionsRDD.f of type scala.Function3 in instance of org.apache.spark.rdd.MapPartitionsRDD
My custom object looks like this:
public class CurrencyPair implements Serializable {
private int id;
private double value;
private double baseVolume;
private double quoteVolume;
private Date timeStamp;
public CurrencyPair(int id, double value, double baseVolume, double quoteVolume, Date timeStamp) {
this.id = id;
this.value = value;
this.baseVolume = baseVolume;
this.quoteVolume = quoteVolume;
this.timeStamp = timeStamp;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public double getBaseVolume() {
return baseVolume;
}
public void setBaseVolume(double baseVolume) {
this.baseVolume = baseVolume;
}
public double getQuoteVolume() {
return quoteVolume;
}
public void setQuoteVolume(double quoteVolume) {
this.quoteVolume = quoteVolume;
}
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
}
So I could not figured out what is wrong here. What am I doing wrong?
Edit: It works well when I write local instead of my own spark master IP. But I need to run this on my own IP. So what can be wrong with my master node?
The issue is probably the anonymous class definition new Function<String, CurrencyPair>() { which forces Spark to try to serialize the parent class as well. Try a lambda instead:
rdd_records.map(
(Function<String, CurrencyPair>) line -> {
...
Note: You could read the file as a CSV instead and use the dataset API with a bean encoder to skip the manual parsing completely.
So i'm trying to add items (which have to be static) to an ArrayList using this class template:
AllEventInformationStatic.java:
public class AllEventInformationStatic {
public static int id;
public static String name;
public static String type;
public static String date;
public static String desc;
public static String location;
public AllEventInformationStatic(int id, String name, String type, String date, String desc, String location)
{
AllEventInformationStatic.id = id;
AllEventInformationStatic.name = name;
AllEventInformationStatic.type = type;
AllEventInformationStatic.date = date;
AllEventInformationStatic.desc = desc;
AllEventInformationStatic.location = location;
}
}
AllEventResponseStatic.java:
public class AllEventResponseStatic {
public static ArrayList<AllEventInformationStatic> events;
}
And here is the iteration to fill the ArrayList:
AllEventResponseStatic.events = new ArrayList<AllEventInformationStatic>();
for (int i = 0; i < allEventResponse.events.size(); i++)
{
AllEventResponseStatic.events.
add(new AllEventInformationStatic(42, "bowling",
"event", "11/12/2015",
"enjoy it", "paris"));
String name = AllEventResponseStatic.events.get(0).name;
}
String name_bis = AllEventResponseStatic.events.get(0).name;
So the variable name display "bowling" but name_bis is Null.
it seems like it just clear the whole arraylist after the iteration and I have don't know why..
If you have any idea where the problem is?
Assuming you mean allEventResponseStatic in loop condition and not allEventResponse.
AllEventResponseStatic.events = new ArrayList<AllEventInformationStatic>();
After this call the size of list is zero so loop is never called. Hence you get null on index 0 after the loop
for (int i = 0; i < allEventResponseStatic.events.size(); i++)
{
AllEventResponseStatic.events.
add(new AllEventInformationStatic(42, "bowling",
"event", "11/12/2015",
"enjoy it", "paris"));
String name = AllEventResponseStatic.events.get(0).name;
}
Also, please research what static keyword does, as it is useless here and causes far bigger problems in your code.
Given that i have an arrayList of company objects. I want to shuffle the objects inside listcompanies. listcompanies has a list of object companies inside it. I want to shuffle the company objects inside the listcompanies arraylist.
This is my company object
public class Company {
private String id;
private String companyName;
private String currentTaskId;
private String task1_id;
private String task1_url;
private String task1_title;
private String task1_description;
private String task1_type;
private String task2_id;
private String task2_url;
private String task2_title;
private String task2_description;
private String task2_type;
private String task3_id;
private String task3_url;
private String task3_title;
private String task3_description;
private String task3_type;
private String task4_id;
private String task4_url;
private String task4_title;
private String task4_description;
private String task4_type;
private String task5_id;
private String task5_url;
private String task5_title;
private String task5_description;
private String task5_type;
}
This is how i store data:
//create a company ArrayList
ArrayList<Company> listcompanies = new ArrayList<>();
for(int i = 0 ; i < 60 ; i ++){
//Initialise a new company per iteration
Company company = new Company();
//store data
company.setcompanyName("Name: " + i);
company.setcompanycurrentTaskId(i+"");
listcompanies.add(company);
}
I tried doing this to shuffle listcompanies but it didn't work.
// I TRIED doing this for sorting the listcompanies
long seed = System.nanoTime();
Collections.shuffle(listcompanies, new Random(seed));
// nothing happened it did not sort the list of companies
My question was a little confusing. Though i already figured it out the shuffle method randomises the data when it's included in the arraylist. Thus it was random all along.