Adding columns to grid using Vaadin 8.0.7 - java

I want add column to grid, when i click to button ("backBtn"). Then i get the value from the textfield ("filterText"), and that will be the name of the new column. Who can help me? The code is from tutorial, but i need add the new feature here. Thanks ! You can find my code in attachment. Grid is in class "MyUI"
This is clas Customer
package my.vaadin.app;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Date;
/**
* A entity object, like in any other Java application. In a typical real world
* application this could for example be a JPA entity.
*/
#SuppressWarnings("serial")
public class Customer implements Serializable, Cloneable {
private Long id;
private String firstName = "";
private String datum = "";
private String lastName = "";
private LocalDate birthDate;
private CustomerStatus status;
private String email = "";
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Get the value of email
*
* #return the value of email
*/
public String getEmail() {
return email;
}
/**
* Set the value of email
*
* #param email
* new value of email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the value of status
*
* #return the value of status
*/
public CustomerStatus getStatus() {
return status;
}
/**
* Set the value of status
*
* #param status
* new value of status
*/
public void setStatus(CustomerStatus status) {
this.status = status;
}
/**
* Get the value of birthDate
*
* #return the value of birthDate
*/
public LocalDate getBirthDate() {
return birthDate;
}
/**
* Set the value of birthDate
*
* #param birthDate
* new value of birthDate
*/
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
/**
* Get the value of lastName
*
* #return the value of lastName
*/
public String getLastName() {
return lastName;
}
/**
* Set the value of lastName
*
* #param lastName
* new value of lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Get the value of firstName
*
* #return the value of firstName
*/
public String getFirstName() {
return firstName;
}
/**
* Set the value of firstName
*
* #param firstName
* new value of firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getDatum() {
return datum;
}
/**
* Set the value of firstName
*
* #param firstName
* new value of firstName
*/
public void setDatum(String datum) {
this.datum = datum;
}
public boolean isPersisted() {
return id != null;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this.id == null) {
return false;
}
if (obj instanceof Customer && obj.getClass().equals(getClass())) {
return this.id.equals(((Customer) obj).id);
}
return false;
}
#Override
public int hashCode() {
int hash = 5;
hash = 43 * hash + (id == null ? 0 : id.hashCode());
return hash;
}
#Override
public Customer clone() throws CloneNotSupportedException {
return (Customer) super.clone();
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
This is clas MyUI
package my.vaadin.app;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.swing.text.TableView;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.components.grid.HeaderCell;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of a html page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {#link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
#Theme("mytheme")
public class MyUI extends UI {
private CustomerService service = CustomerService.getInstance();
private Grid<Customer> grid = new Grid<>(Customer.class);
private TextField filterText = new TextField();
// private CustomerForm form = new CustomerForm(this);
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
Label tancore = new Label();
filterText.setPlaceholder("Meno ...");
//filterText.addValueChangeListener(e -> updateList());
//filterText.setValueChangeMode(ValueChangeMode.LAZY);
Button clearFilterTextBtn = new Button(FontAwesome.TIMES);
clearFilterTextBtn.setDescription("Clear the current name");
clearFilterTextBtn.addClickListener(e -> filterText.clear());
tancore.setCaption("TanCore s.r.o");
CssLayout filtering = new CssLayout();
filtering.addComponents(filterText, clearFilterTextBtn);
filtering.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
Button addCustomerBtn = new Button("Pridaj zamestnanca");
Button downloadXlsBtn = new Button("Stiahnuť ako .xls");
Button loginBtn = new Button("Prihlásiť sa");
// Button addEmplBtn = new Button("Pridaj");
Button backBtn = new Button("Vlož");
downloadXlsBtn.setVisible(false);
TextField name = new TextField();
PasswordField pass = new PasswordField();
// addEmplBtn.setVisible(false);
addCustomerBtn.setVisible(false);
backBtn.setVisible(false);
filtering.setVisible(false);
clearFilterTextBtn.setVisible(false);
filterText.setVisible(false);
addCustomerBtn.setStyleName(ValoTheme.BUTTON_PRIMARY);
//.setStyleName(ValoTheme.BUTTON_PRIMARY);
addCustomerBtn.setClickShortcut(KeyCode.ENTER);
backBtn.addClickListener(e -> {
//Here i want include the new data after click on the button
//grid.addColumn(filterText.getValue()); -> That it's not good, because after click the Java will Warning you
addCustomerBtn.setVisible(true);
backBtn.setVisible(false);
filtering.setVisible(false);
clearFilterTextBtn.setVisible(false);
filterText.setVisible(false);
});
addCustomerBtn.addClickListener(e -> {
addCustomerBtn.setVisible(false);
filtering.setVisible(true);
backBtn.setVisible(true);
clearFilterTextBtn.setVisible(true);
filterText.setVisible(true);
//addEmplBtn.setEnabled(true);
});
loginBtn.addClickListener(e -> {
if(name.getValue().equals("admin"))
{
if(pass.getValue().equals("admin"))
{
name.setVisible(false);
pass.setVisible(false);
loginBtn.setVisible(false);
addCustomerBtn.setVisible(true);
downloadXlsBtn.setVisible(true);
}
}
});
pass.setPlaceholder("Heslo ...");
name.setPlaceholder("Meno ...");
HorizontalLayout toolbar = new HorizontalLayout(name, pass, loginBtn,filtering, addCustomerBtn,backBtn,downloadXlsBtn);
// grid.setSelectionMode(SelectionMode.MULTI);
grid.setColumns("datum", "lastName","email","status");
// grid.setStyleName(ValoTheme.BUTTON_PRIMARY);
/*HeaderRow extraHeader = grid.prependHeaderRow();
HeaderCell joinedCell = extraHeader.join("datum", "lastName");
joinedCell.setText("Joined cell");*/
HorizontalLayout main = new HorizontalLayout(grid);
main.setSizeFull();
grid.setSizeFull();
// main.setExpandRatio(grid, 1);
grid.getColumn("datum").setWidth(100);
// grid.getColumn("datum").set
// grid.getColumn("datum").set
grid.getColumn("datum").setCaption("Dátum");
grid.getColumn("lastName").setCaption("Adam");
layout.addComponents(toolbar, main);
// fetch list of Customers from service and assign it to Grid
updateList();
setContent(layout);
// form.setVisible(false);
grid.asSingleSelect().addValueChangeListener(event -> {
//if (event.getValue() == null) {
// form.setVisible(false);
//} else {
// form.setCustomer(event.getValue());
//}
});
}
public void updateList() {
List<Customer> customers = service.findAll(filterText.getValue());
grid.setItems(customers);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
This is clas CustomerForm.java
package my.vaadin.app;
import com.vaadin.data.Binder;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Button;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;
public class CustomerForm extends FormLayout {
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField email = new TextField("Email");
private NativeSelect<CustomerStatus> status = new NativeSelect<>("Status");
private DateField birthdate = new DateField("Birthday");
private Button save = new Button("Save");
private Button delete = new Button("Delete");
private CustomerService service = CustomerService.getInstance();
private Customer customer;
private MyUI myUI;
private Binder<Customer> binder = new Binder<>(Customer.class);
public CustomerForm(MyUI myUI) {
this.myUI = myUI;
setSizeUndefined();
HorizontalLayout buttons = new HorizontalLayout(save, delete);
addComponents(firstName, lastName, email, status, birthdate, buttons);
status.setItems(CustomerStatus.values());
save.setStyleName(ValoTheme.BUTTON_PRIMARY);
save.setClickShortcut(KeyCode.ENTER);
binder.bindInstanceFields(this);
save.addClickListener(e -> this.save());
delete.addClickListener(e -> this.delete());
}
public void setCustomer(Customer customer) {
this.customer = customer;
binder.setBean(customer);
// Show delete button for only customers already in the database
delete.setVisible(customer.isPersisted());
setVisible(true);
firstName.selectAll();
}
private void delete() {
service.delete(customer);
myUI.updateList();
setVisible(false);
}
private void save() {
service.save(customer);
myUI.updateList();
setVisible(false);
}
}
This is clas CustomerService.java
package my.vaadin.app;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An in memory dummy "database" for the example purposes. In a typical Java app
* this class would be replaced by e.g. EJB or a Spring based service class.
* <p>
* In demos/tutorials/examples, get a reference to this service class with
* {#link CustomerService#getInstance()}.
*/
public class CustomerService {
private static CustomerService instance;
private static final Logger LOGGER = Logger.getLogger(CustomerService.class.getName());
private final HashMap<Long, Customer> contacts = new HashMap<>();
private long nextId = 0;
private CustomerService() {
}
/**
* #return a reference to an example facade for Customer objects.
*/
public static CustomerService getInstance() {
if (instance == null) {
instance = new CustomerService();
instance.ensureTestData();
}
return instance;
}
/**
* #return all available Customer objects.
*/
public synchronized List<Customer> findAll() {
return findAll(null);
}
/**
* Finds all Customer's that match given filter.
*
* #param stringFilter
* filter that returned objects should match or null/empty string
* if all objects should be returned.
* #return list a Customer objects
*/
public synchronized List<Customer> findAll(String stringFilter) {
ArrayList<Customer> arrayList = new ArrayList<>();
for (Customer contact : contacts.values()) {
try {
boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
|| contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
if (passesFilter) {
arrayList.add(contact.clone());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
}
Collections.sort(arrayList, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return (int) (o2.getId() - o1.getId());
}
});
return arrayList;
}
/**
* Finds all Customer's that match given filter and limits the resultset.
*
* #param stringFilter
* filter that returned objects should match or null/empty string
* if all objects should be returned.
* #param start
* the index of first result
* #param maxresults
* maximum result count
* #return list a Customer objects
*/
public synchronized List<Customer> findAll(String stringFilter, int start, int maxresults) {
ArrayList<Customer> arrayList = new ArrayList<>();
for (Customer contact : contacts.values()) {
try {
boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
|| contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
if (passesFilter) {
arrayList.add(contact.clone());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
}
Collections.sort(arrayList, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return (int) (o2.getId() - o1.getId());
}
});
int end = start + maxresults;
if (end > arrayList.size()) {
end = arrayList.size();
}
return arrayList.subList(start, end);
}
/**
* #return the amount of all customers in the system
*/
public synchronized long count() {
return contacts.size();
}
/**
* Deletes a customer from a system
*
* #param value
* the Customer to be deleted
*/
public synchronized void delete(Customer value) {
contacts.remove(value.getId());
}
/**
* Persists or updates customer in the system. Also assigns an identifier
* for new Customer instances.
*
* #param entry
*/
public synchronized void save(Customer entry) {
if (entry == null) {
LOGGER.log(Level.SEVERE,
"Customer is null. Are you sure you have connected your form to the application as described in tutorial chapter 7?");
return;
}
if (entry.getId() == null) {
entry.setId(nextId++);
}
try {
entry = (Customer) entry.clone();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
contacts.put(entry.getId(), entry);
}
/**
* Sample data generation
*/
public void ensureTestData() {
if (findAll().isEmpty()) {
for (int i = 31; i > 0; i--) {
Customer c = new Customer();
c.setDatum(i+".7");
save(c);
}
}
}
}
I want have this in my WebApp
This is actualy my WebApp

Related

TreeView of objects having child nodes that are fields of the object

I have an object with fields of varying datatypes:
public class MyObject{
private String field1;
private CustomObject field2;
private int field3;
...
}
I want to create a tree view of MyObject that will have multiple MyObject nodes, each with the fields (field1, field2, field3..etc) as children.
I know I can make a TreeView of Strings and populate it myself with an addNode(MyObject obj) method in which I would add the individual TreeItems I need. However, I did this with a TableView where I was able to bind a column with a field property. Such as:
TableView<MyObject> table;
TableColumn<MyObject, String> myColumn;
myColumn.setCellValueFactory(new PropertyValueFactory<>("field1"));
Is there any way to do something similar for a TreeView<MyObject>? Im not opposed to creating a subclass that extends TreeItem<?>
The ending result I'm looking for would be something like this:
--> First My Object
->field1: "Value at Field 1"
->field2: "Value at Field 2"
->field3: 3
--> Second My Object
->field1: "Value at Field 1"
->field2: "Value at Field 2"
->field3: 3
Pretty much any time you use a TreeView with different types in different nodes of the tree, you will need some casting and/or type checking somewhere.
One possible approach here is to subclass TreeItem to provide a field for the property you want to show, and then to use a TreeCell that shows the string value of that property.
Here's a very basic example of that:
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;
public class TreeViewWithProperties extends Application {
#Override
public void start(Stage primaryStage) {
List<SomeEntity> entities = Arrays.asList(
new SomeEntity("First object", "String value 1", 42),
new SomeEntity("Second object", "String value 2", 3)
);
TreeView<SomeEntity> tree = new TreeView<>();
tree.setShowRoot(false);
TreeItem<SomeEntity> treeRoot = new TreeItem<>();
tree.setRoot(treeRoot);
for (SomeEntity entity : entities) {
TreeItem<SomeEntity> item = PropertyTreeItem.baseItem(entity);
treeRoot.getChildren().add(item);
item.getChildren().add(new PropertyTreeItem<String>(entity, entity.getStringField()));
item.getChildren().add(new PropertyTreeItem<Integer>(entity, entity.getValue()));
}
tree.setCellFactory(tv -> new TreeCell<SomeEntity>() {
#Override
protected void updateItem(SomeEntity entity, boolean empty) {
super.updateItem(entity, empty);
PropertyTreeItem<?> item = (PropertyTreeItem<?>) getTreeItem();
if (empty) {
setText(null);
} else {
setText(item.getPropertyValue().toString());
}
}
});
Scene scene = new Scene(tree);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class PropertyTreeItem<T> extends TreeItem<SomeEntity> {
private final T propertyValue ;
public PropertyTreeItem(SomeEntity entity, T value) {
super(entity);
this.propertyValue = value ;
}
public static PropertyTreeItem<SomeEntity> baseItem(SomeEntity entity) {
return new PropertyTreeItem<>(entity, entity);
}
public T getPropertyValue() {
return propertyValue ;
}
}
public class SomeEntity {
private String name ;
private String stringField ;
private int value ;
public SomeEntity(String name, String stringField, int value) {
this.name = name;
this.stringField = stringField;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
#Override
public String toString() {
return name ;
}
}
public static void main(String[] args) {
launch(args);
}
}
Some variations on this are possible, of course. If you wanted to use JavaFX properties in the entity class, and be able to change those values externally to the tree, you could bind the text to the property in the cell instead of simply setting it.
Using some ideas from the link I posted under your question. This example uses a helper Class to create the TreeItems.
Main
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication128 extends Application
{
#Override
public void start(Stage primaryStage)
{
MyObject myObject1 = new MyObject("myObject1", "field 1 a", new CustomObject("customObject 1", 3), 5);
MyObject myObject2 = new MyObject("myObject2", "field 1 b", new CustomObject("customObject 2", 36), 10);
MyObject myObject3 = new MyObject("myObject3", "field 1 c", new CustomObject("customObject 3", 23), 8);
List<MyObject> list = new ArrayList();
list.add(myObject1);
list.add(myObject2);
list.add(myObject3);
List<TreeItem<String>> treeItemsContainer = new ArrayList();
for (MyObject object : list) {
ObjectToTreeView objectToTreeView = new ObjectToTreeView(object);
treeItemsContainer.add(objectToTreeView.getRootItem());
}
TreeItem<String> rootItem = new TreeItem();
rootItem.setExpanded(true);
rootItem.getChildren().addAll(treeItemsContainer);
TreeView treeView = new TreeView(rootItem);
Scene scene = new Scene(treeView, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
ObjectToTreeView Class <- a helper class
import javafx.scene.control.TreeItem;
/**
*
* #author blj0011
*/
public class ObjectToTreeView
{
private final TreeItem<String> rootItem = new TreeItem();
public ObjectToTreeView(MyObject myObject)
{
rootItem.setValue(myObject.getTitle());
rootItem.getChildren().add(new TreeItem(myObject.getField1()));
CustomObject customObject = myObject.getField2();
rootItem.getChildren().add(new TreeItem(customObject.getName()));
rootItem.getChildren().add(new TreeItem(customObject.getNumber()));
rootItem.getChildren().add(new TreeItem(myObject.getField3()));
}
/**
* #return the rootItem
*/
public TreeItem<String> getRootItem()
{
return rootItem;
}
}
MyObject Class
/**
*
* #author blj0011
*/
public class MyObject
{
private String title;
private String field1;
private CustomObject field2;
private int field3;
public MyObject(String title, String field1, CustomObject field2, int field3)
{
this.title = title;
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
/**
* #return the title
*/
public String getTitle()
{
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title)
{
this.title = title;
}
/**
* #return the field1
*/
public String getField1()
{
return field1;
}
/**
* #param field1 the field1 to set
*/
public void setField1(String field1)
{
this.field1 = field1;
}
/**
* #return the field3
*/
public int getField3()
{
return field3;
}
/**
* #param field3 the field3 to set
*/
public void setField3(int field3)
{
this.field3 = field3;
}
/**
* #return the field2
*/
public CustomObject getField2()
{
return field2;
}
/**
* #param field2 the field2 to set
*/
public void setField2(CustomObject field2)
{
this.field2 = field2;
}
}
CustomObject Class
/**
*
* #author blj0011
*/
public class CustomObject
{
private String name;
private int number;
public CustomObject(String name, int number)
{
this.name = name;
this.number = number;
}
/**
* #return the name
*/
public String getName()
{
return name;
}
/**
* #param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* #return the number
*/
public int getNumber()
{
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number)
{
this.number = number;
}
}
I ended up just creating a helper function by doing the following:
public TreeItem<String> createNode(MyObject obj) {
TreeItem<String> node = null;
if(obj != null) {
node = new TreeItem<String>("MyObject:" + obj.getId());
node.getChildren().add(new TreeItem<String>("Field1: "+ obj.getField1()));
node.getChildren().add(new TreeItem<String>("Field2: "+ obj.getField2()));
node.getChildren().add(new TreeItem<String>("Field3: "+ obj.getField3()));
}
}

I am getting BeanFactory error: NoSuchBeanDefinitionException and I can't figure out how to solve it

I was given the task to work on an existing AngularJS SPA (app B). This app uses code from another app (app B) to get information from the database. Both; app A and app B use the same database. the goal is to modify app B to get customers, Locations and Docks from a different database. My goal it to still use some of the same code that app A uses and to create new code for app B and then access the new database to get the information.
When I try to start the app (Eclipse Oxigen) I get an exception thrown by the BeanFactory.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'contextServiceImpl': Unsatisfied dependency expressed through field 'customersRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.csoln.lv.data.cld.dao.CustomersRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I suspect that the bean isn’t defined in the Spring Context but I don't know how to define it. I have tried the suggestions found on other posts and nothing works. I will post the code and relevant files next...
Keep in mind that I am pretty new on Spring, REstful Services, etc. I hope you can help me solving this error. Thank you in advance.
SERVICE FILE
package com.csoln.lv.service;
import java.util.List;
import java.util.Map;
import com.csoln.lv.cld.bo.CustomerBo;
import com.csoln.lv.cld.bo.DockBo;
import com.csoln.lv.cld.bo.LocationBo;
public interface ContextService {
public List<CustomerBo> getCustomersFiltered();
public Map<String, CustomerBo> getCustomerMapFiltered();
public CustomerBo getCustomer(Integer id);
public List<CustomerBo> getAllCustomers();
public List<CustomerBo> getCustomers();
public Map<String, CustomerBo> getCustomerMap();
public Map<Integer, CustomerBo> getCustomerMapById();
public List<LocationBo> getLocationsFiltered(CustomerBo customer);
public Map<String, LocationBo> getLocationMapFiltered(CustomerBo customer);
public Map<Integer, LocationBo> getLocationMapByIdFiltered(CustomerBo customer);
public LocationBo getLocation(Integer customerId, Integer id);
public List<LocationBo> getAllLocations(CustomerBo customer);
public List<LocationBo> getLocations(CustomerBo customer);
public List<DockBo> getDocksFiltered(LocationBo location);
public Map<String, DockBo> getDockMapFiltered(LocationBo location);
public Map<Integer, DockBo> getDockMapByIdFiltered(LocationBo location);
public DockBo getDock(Integer customerId, Integer locationId, Integer id);
public List<DockBo> getAllDocks(LocationBo location);
public List<DockBo> getDocks(LocationBo location);
public List<DockBo> getSubDocks(DockBo dock);
public Map<String, DockBo> getSubDockMap(DockBo dock);
public Map<Integer, DockBo> getSubDockMapById(DockBo dock);
}
SERVICE IMPL
package com.csoln.lv.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
// For Liveview
import com.csoln.lv.cld.bo.CustomerBo;
import com.csoln.lv.cld.bo.DockBo;
import com.csoln.lv.cld.bo.LocationBo;
import com.csoln.lv.data.cld.dao.CustomersRepo;
import com.csoln.lv.data.cld.dao.DocksRepo;
import com.csoln.lv.data.cld.dao.LocationsRepo;
import com.csoln.lv.data.dom.Customers;
import com.csoln.lv.data.dom.Docks;
import com.csoln.lv.data.dom.Locations;
import com.csoln.lv.data.id.DockId;
import com.csoln.lv.data.id.LocationId;
#Service
#SuppressWarnings("unchecked")
public class ContextServiceImpl implements ContextService {
private static Logger log = Logger.getLogger(ContextServiceImpl.class);
#Autowired
private CustomersRepo customersRepo;
#Autowired
private LocationsRepo locationsRepo;
#Autowired
private DocksRepo docksRepo;
private String customerPrefix = "C_";
private String locationPrefix = "L_";
private String dockPrefix = "D_";
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getCustomers()
*/
#Override
public List<CustomerBo> getCustomersFiltered() {
List<String> filter = this.getGrantedAuthorities(this.customerPrefix);
List<CustomerBo> customers = new ArrayList<>();
List<CustomerBo> clients = this.getCustomers(true);
if( clients != null && filter != null && clients.size() > 0 && filter.size() > 0 ) {
Stream<CustomerBo> stream = clients.stream().filter( entry -> filter.contains(entry.getId().toString()));
customers = stream.collect(Collectors.toList());
}
if( log.isDebugEnabled() ) {
log.debug(clients);
}
return customers;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getCustomerMap()
*/
#Override
public Map<String, CustomerBo> getCustomerMapFiltered() {
List<CustomerBo> customers = this.getCustomersFiltered();
Map<String, CustomerBo> clients = new HashMap<>();
if( customers != null && customers.size() > 0 ) {
customers.forEach(c -> clients.put(c.getAbbreviation(), c));
}
if( log.isDebugEnabled() ) {
log.debug(clients);
}
return clients;
}
/* (non-Javadoc)
* #see com.csoln.service.ContextService#getCustomer(java.lang.Integer)
*/
#Override
public CustomerBo getCustomer(Integer id) {
return new CustomerBo().toBo(this.customersRepo.findOne(id));
}
/* (non-Javadoc)
* #see com.csoln.service.ContextService#getCustomers()
*/
#Override
public List<CustomerBo> getAllCustomers() {
List<CustomerBo> customers = this.getCustomers(false);
return customers;
}
#Override
public List<CustomerBo> getCustomers() {
List<CustomerBo> customers = this.getCustomers(true);
return customers;
}
private List<CustomerBo> getCustomers(Boolean active) {
Example<Customers> example = null;
List<Customers> entities = null;
if( active ) {
Customers probe = new Customers();
probe.setActiveEntry(active);
example = Example.of(probe);
entities = this.customersRepo.findAll(example, new Sort(Direction.ASC, "shortName"));
} else {
entities = this.customersRepo.findAll(new Sort(Direction.ASC, "shortName"));
}
List<CustomerBo> customers = new ArrayList<>();
if( entities != null && entities.size() > 0 ) {
entities.forEach(c -> {
customers.add(new CustomerBo().toBo(c));
});
}
return customers;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getCustomerMapById()
*/
public Map<Integer, CustomerBo> getCustomerMapById() {
SortedMap<Integer, CustomerBo> clients = new TreeMap<>();
List<CustomerBo> customers = this.getAllCustomers();
if( customers != null && !customers.isEmpty() ) {
customers.forEach(c -> clients.put(c.getId(), c) );
}
if( log.isDebugEnabled() ) {
log.debug(clients);
}
return clients;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getCustomerMapByAbbreviation()
*/
#Override
public Map<String, CustomerBo> getCustomerMap() {
SortedMap<String, CustomerBo> clients = new TreeMap<>();
List<CustomerBo> customers = this.getAllCustomers();
if( customers != null && !customers.isEmpty() ) {
customers.forEach(c -> clients.put(c.getAbbreviation(), c));
}
if( log.isDebugEnabled() ) {
log.debug(clients);
}
return clients;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getLocations(com.csoln.web.bean.CustomerBean)
*/
#Override
public List<LocationBo> getLocationsFiltered(CustomerBo customer) {
List<String> filter = this.getGrantedAuthorities(this.locationPrefix + customer.getId() + "_");
List<LocationBo> locations = new ArrayList<>();
List<LocationBo> ls = this.getLocations(customer);
if( ls != null && !ls.isEmpty() ) {
locations = ls.stream().filter( l-> filter.contains(l.getId().toString())).collect(Collectors.toList());
Collections.sort(locations, (l1, l2) -> (l1.getId() < l2.getId())?1:0);
}
if( log.isDebugEnabled() ) {
}
return locations;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getLocationMap(com.csoln.web.bean.CustomerBean)
*/
#Override
public Map<String, LocationBo> getLocationMapFiltered(CustomerBo customer) {
Map<String, LocationBo> locations = new TreeMap<>();
List<LocationBo> locs = this.getLocationsFiltered(customer);
if( locs != null && !locs.isEmpty() ) {
locs.forEach(l -> locations.put(l.getAbbreviation(), l));
}
log.debug(locations);
return locations;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getLocationMapById(com.csoln.web.bean.CustomerBean, java.lang.String)
*/
#Override
public Map<Integer, LocationBo> getLocationMapByIdFiltered(CustomerBo customer) {
Map<Integer, LocationBo> locations = new TreeMap<>();
List<LocationBo> locs = this.getLocationsFiltered(customer);
if( locs != null && !locs.isEmpty() ) {
locs.forEach(l -> locations.put(l.getId(), l));
}
log.debug(locations);
return locations;
}
#Override
public LocationBo getLocation(Integer customerId, Integer id) {
LocationId locId = new LocationId(customerId, id);
return new LocationBo().toBo(this.locationsRepo.findOne(locId));
}
/* (non-Javadoc)
* #see com.csoln.service.ContextService#getLocations(com.csoln.common.bo.CustomerBo)
*/
#Override
// #Cacheable(cacheNames = "context", key="#root.target+#root.methodName+#customer")
public List<LocationBo> getAllLocations(CustomerBo customer) {
List<LocationBo> locations = this.getLocations(customer, false);
return locations;
}
#Override
public List<LocationBo> getLocations(CustomerBo customer) {
List<LocationBo> locations = this.getLocations(customer, true);
return locations;
}
private List<LocationBo> getLocations(CustomerBo customer, Boolean active) {
Locations probe = new Locations(customer.getId());
if( active ) {
probe.setActiveEntry(active);
}
List<Locations> entities = this.locationsRepo.findAll(Example.of(probe), new Sort(Direction.ASC, "shortName"));
List<LocationBo> locations = new ArrayList<>();
if( entities != null && entities.size() > 0 ) {
entities.forEach( l->{
locations.add(new LocationBo().toBo(l));
});
}
return locations;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getDocks(com.csoln.web.bean.LocationBean)
*/
#Override
public List<DockBo> getDocksFiltered(LocationBo location) {
List<String> filter = this.getGrantedAuthorities(this.dockPrefix + location.getCustomerId() + "_" + location.getId() + "_");
List<DockBo> docs = this.getDocks(location);
List<DockBo> docks = new ArrayList<>();
if( docs != null && filter != null && !docs.isEmpty() ) {
docks = docs.stream().filter( d-> filter.contains(d.getId().toString())).collect(Collectors.toList());
Collections.sort(docks, (d1, d2) -> (d1.getId() < d2.getId())?1:0);
}
if( log.isDebugEnabled() ) {
log.debug(docks);
}
return docks;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getDockMap(com.csoln.web.bean.LocationBean)
*/
#Override
public Map<String, DockBo> getDockMapFiltered(LocationBo location) {
Map<String, DockBo> docks = new TreeMap<>();
List<DockBo> dcks = this.getDocksFiltered(location);
if( dcks != null & !dcks.isEmpty() ) {
dcks.forEach(d -> docks.put(d.getAbbreviation(), d));
}
if( log.isDebugEnabled() ) {
log.debug(docks);
}
return docks;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getDockMapById(com.csoln.web.bean.LocationBean, java.lang.String)
*/
#Override
public Map<Integer, DockBo> getDockMapByIdFiltered(LocationBo location) {
Map<Integer, DockBo> docks = new TreeMap<>();
List<DockBo> dcks = this.getDocksFiltered(location);
if( dcks != null & !dcks.isEmpty() ) {
dcks.forEach(d -> docks.put(d.getId(), d));
}
if( log.isDebugEnabled() ) {
log.debug(docks);
}
return docks;
}
#Override
public DockBo getDock(Integer customerId, Integer locationId, Integer id) {
DockId dockId = new DockId(customerId, locationId, id);
return new DockBo().toBo(this.docksRepo.findOne(dockId));
}
/* (non-Javadoc)
* #see com.csoln.service.ContextService#getDocks(com.csoln.common.bo.LocationBo)
*/
#Override
// #Cacheable(cacheNames = "context", key="#root.target+#root.methodName+#location")
public List<DockBo> getAllDocks(LocationBo location) {
List<DockBo> docks = this.getDocksIfActive(location.getCustomerId(), location.getId(), false);
return docks;
}
#Override
public List<DockBo> getDocks(LocationBo location) {
List<DockBo> docks = this.getDocksIfActive(location.getCustomerId(), location.getId(), true);
return docks;
}
private List<DockBo> getDocksIfActive(Integer customerId, Integer locationId, Boolean active) {
List<DockBo> docks = new ArrayList<>();
List<Docks> entities = null;
Docks probe = new Docks(customerId, locationId);
if( active ) {
probe.setActiveEntry(active);
}
entities = this.docksRepo.findAll(Example.of(probe), new Sort(Direction.ASC, "shortName"));
List<DockBo> subdocks = new ArrayList<>();
if( entities != null && entities.size() > 0 ) {
entities.forEach( d-> {
subdocks.addAll(getSubDocks(new DockBo().toBo(d)));
docks.add(new DockBo().toBo(d));
});
}
subdocks.forEach(sd -> {
docks.remove(sd);
});
return docks;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getSubDocks(com.csoln.web.bean.DockBean)
*/
#Override
// #Cacheable(cacheNames = "context", key="#root.target+#root.methodName+#dock")
public List<DockBo> getSubDocks(DockBo dock) {
List<DockBo> docks = new ArrayList<>();
List<Docks> dcs = this.docksRepo.findSubDocksForDock(dock.getCustomerId(), dock.getLocationId(), dock.getId());
if( dcs != null ) {
dcs.forEach(d ->docks.add(new DockBo().toBo(d)));
}
return docks;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getSubDockMap(com.csoln.web.bean.DockBean)
*/
#Override
public Map<String, DockBo> getSubDockMap(DockBo dock) {
Map<String, DockBo> docks = new TreeMap<>();
List<DockBo> dcs = this.getSubDocks(dock);
if( dcs != null ) {
dcs.forEach(d ->docks.put(d.getAbbreviation(), d));
}
return docks;
}
/* (non-Javadoc)
* #see com.csoln.service.data.ContextService#getSubDockMapById(com.csoln.web.bean.DockBean, java.lang.String)
*/
#Override
public Map<Integer, DockBo> getSubDockMapById(DockBo dock) {
Map<Integer, DockBo> docks = new TreeMap<>();
List<DockBo> dcs = this.getSubDocks(dock);
if( dcs != null ) {
dcs.forEach(d ->docks.put(d.getId(), d));
}
return docks;
}
private List<String> getGrantedAuthorities(String prefix) {
List<String> filter = new ArrayList<>();
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
Stream<SimpleGrantedAuthority> filtered = authorities.stream().filter(a -> a.getAuthority().startsWith(prefix));
filtered.forEach(a -> filter.add(a.getAuthority().replace(prefix, "")));
log.debug("Filtered by User: " + filter);
return filter;
}
/**
* #return the customerPrefix
*/
public String getCustomerPrefix() {
return customerPrefix;
}
/**
* #param customerPrefix the customerPrefix to set
*/
public void setCustomerPrefix(String customerPrefix) {
this.customerPrefix = customerPrefix;
}
/**
* #return the locationPrefix
*/
public String getLocationPrefix() {
return locationPrefix;
}
/**
* #param locationPrefix the locationPrefix to set
*/
public void setLocationPrefix(String locationPrefix) {
this.locationPrefix = locationPrefix;
}
/**
* #return the dockPrefix
*/
public String getDockPrefix() {
return dockPrefix;
}
/**
* #param dockPrefix the dockPrefix to set
*/
public void setDockPrefix(String dockPrefix) {
this.dockPrefix = dockPrefix;
}
}
THE DAO
package com.csoln.lv.data.cld.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.csoln.lv.data.dom.Customers;
import com.csoln.data.repository.SyncRepository;
public interface CustomersRepo extends JpaRepository<Customers, Integer>, SyncRepository<Customers> {
public List<Customers> findByAbbreviationAndActiveEntryTrue(String abbreviation);
public List<Customers> findByIdInAndActiveEntryTrue(List<Integer> customerIds);
#Query("SELECT new Customers(id, abbreviation, shortName, longName) FROM Customers WHERE activeEntry = true ORDER BY abbreviation ASC")
public List<Customers> findDisplayInfo();
#Query("SELECT new Customers(id, abbreviation, shortName, longName) FROM Customers WHERE id IN :customerIds AND activeEntry = true")
public List<Customers> findDisplayInfoByIdIn(#Param("customerIds") List<Integer> customerIds);
#Query("SELECT new Customers(id, abbreviation, shortName, longName) FROM Customers WHERE abbreviation IN :abbreviations AND activeEntry = true")
public List<Customers> findDisplayInfoByAbbrIn(#Param("abbreviations") List<String> abbreviations);
}
CUSTOMERS
package com.csoln.lv.data.dom;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.domain.Persistable;
import com.csoln.data.common.AbstractAbbreviation;
import com.csoln.data.listener.SimpleSequenceId;
import com.csoln.data.listener.SimpleSequenceIdListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* #author eduardo.serrano
*
*/
#Entity
#Table(name = Customers.TABLE)
#EntityListeners(SimpleSequenceIdListener.class)
public class Customers extends AbstractAbbreviation implements Persistable<Integer>, SimpleSequenceId {
public static final String TABLE = "customers";
private static final long serialVersionUID = -8559335312619610990L;
#Id
private Integer id;
public Customers() {
super();
}
public Customers(Integer id, String abbreviation, String shortName, String longName) {
super();
this.id = id;
this.setAbbreviation(abbreviation);
this.setShortName(shortName);
this.setLongName(longName);
}
/**
* #return the id
*/
public Integer getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/* (non-Javadoc)
* #see org.springframework.data.domain.Persistable#isNew()
*/
#Override
#JsonIgnore
public boolean isNew() {
return this.id == null;
}
/* (non-Javadoc)
* #see com.csoln.data.common.AbstractAuditable#toString()
*/
#Override
public String toString() {
return new StringBuilder("\n\r\t\t" + this.getClass().getName() + " - ID: " + this.id + ", " +super.toString()).toString();
}
}
THE BO
package com.csoln.lv.cld.bo;
import com.csoln.lv.data.dom.Customers;
import com.csoln.bo.common.AuditableBo;
public class CustomerBo extends AuditableBo<CustomerBo, Customers> {
private static final long serialVersionUID = 6234658974110288240L;
private Integer id;
private String abbreviation;
private String code;
private String label;
private Boolean activeEntry;
public CustomerBo() {
super();
}
public CustomerBo(Integer id, String abbreviation, String code, String label) {
super();
this.id = id;
this.abbreviation = abbreviation;
this.code = code;
this.label = label;
}
/**
* #return the id
*/
public Integer getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* #return the abbreviation
*/
public String getAbbreviation() {
return abbreviation;
}
public CustomerBo setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
return this;
}
/**
* #return the code
*/
public String getCode() {
return code;
}
public CustomerBo setCode(String code) {
this.code = code;
return this;
}
/**
* #return the label
*/
public String getLabel() {
return label;
}
public CustomerBo setLabel(String label) {
this.label = label;
return this;
}
/**
* #return the activeEntry
*/
public Boolean getActiveEntry() {
return activeEntry;
}
/**
* #param activeEntry the activeEntry to set
*/
public void setActiveEntry(Boolean activeEntry) {
this.activeEntry = activeEntry;
}
#SuppressWarnings("unchecked")
#Override
public <B extends CustomerBo> B toBo(Customers domain) {
if( domain != null ) {
super.toBo(domain);
this.id = domain.getId();
this.abbreviation = domain.getAbbreviation();
this.code = domain.getShortName();
this.label = domain.getLongName();
this.activeEntry = domain.getActiveEntry();
}
return (B) this;
}
public Customers toDomain() {
Customers domain = new Customers();
domain = super.toDomain(domain);
domain.setId(id);
domain.setAbbreviation(abbreviation);
domain.setLongName(this.label);
domain.setShortName(this.code);
domain.setActiveEntry(activeEntry);
return domain;
}
#Override
public boolean equals(Object obj) {
boolean equals = false;
if( obj instanceof CustomerBo ) {
CustomerBo i = (CustomerBo)obj;
equals = (id == i.getId());
}
return equals;
}
#Override
public int hashCode() {
return 4000;
}
}
THE ERROR
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'contextServiceImpl': Unsatisfied dependency expressed through field 'customersRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.csoln.lv.data.cld.dao.CustomersRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.csoln.lv.data.cld.dao.CustomersRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
THE XML SPRING CONTEXT FILE
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config></context:annotation-config>
<bean class="com.csoln.context.CsolnContext" />
<import resource="classpath:/props-context.xml"/>
<import resource="classpath:/config/data-context.xml" />
<import resource="classpath:/config/livedock-data-context.xml" />
<import resource="classpath:/config/security-context.xml" />
<import resource="classpath:/config/cache-context.xml" />
<context:component-scan base-package="
com.csoln.lookup,
com.csoln.lv.service">
</context:component-scan>
<bean class="com.csoln.service.ContextServiceImpl" />
<bean class="com.csoln.service.CodeServiceImpl" />
<bean class="com.csoln.service.ReferenceServiceImpl" />
<bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider" />
</beans>
It's because your ComponentScan doesn't see the package where you declared your #Service. Post the Spring Context.
You are missing the #Repository annotation in CustomersRepo

json to table structure api in Java

I have been searching in internet for a while to get a API that convert json into tabular format. I don't have any code which I tried. Please direct me if you have any idea about it.
Eg : Json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
Output can be(with any separated)
rinu|14|91|99862656|true
rinu|14|91|675432|true
I don't want any ready-made stuff, If I get anything similar to this, I can re-write it.
You might need this:
JacksonRead.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonRead {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
Example example = mapper.readValue(new File("d:\\user.json"),
Example.class);
StringBuilder builder = new StringBuilder();
int i = 0;
for (Phone phone : example.getPhone()) {
builder.append(example.getName()).append("|");
builder.append(example.getAge()).append("|");
builder.append(phone.getCountryCode()).append("|")
.append(phone.getNumber()).append("|")
.append(example.getOtherDetails().get(i).getActive())
.append("|");
builder.append("\n");
}
File file = new File("d:\\user.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(builder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example.java
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
public class Example {
#JsonProperty("name")
private String name;
#JsonProperty("age")
private String age;
#JsonProperty("Phone")
private List<Phone> Phone = new ArrayList<Phone>();
#JsonProperty("OtherDetails")
private List<OtherDetail> OtherDetails = new ArrayList<OtherDetail>();
/**
*
* #return The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
/**
*
* #return The age
*/
#JsonProperty("age")
public String getAge() {
return age;
}
/**
*
* #param age
* The age
*/
#JsonProperty("age")
public void setAge(String age) {
this.age = age;
}
/**
*
* #return The Phone
*/
#JsonProperty("Phone")
public List<Phone> getPhone() {
return Phone;
}
/**
*
* #param Phone
* The Phone
*/
#JsonProperty("Phone")
public void setPhone(List<Phone> Phone) {
this.Phone = Phone;
}
/**
*
* #return The OtherDetails
*/
#JsonProperty("OtherDetails")
public List<OtherDetail> getOtherDetails() {
return OtherDetails;
}
/**
*
* #param OtherDetails
* The OtherDetails
*/
#JsonProperty("OtherDetails")
public void setOtherDetails(List<OtherDetail> OtherDetails) {
this.OtherDetails = OtherDetails;
}
#Override
public String toString() {
return "Example [name=" + name + ", age=" + age + ", Phone=" + Phone
+ ", OtherDetails=" + OtherDetails + "]";
}
}
Phone.java
import org.codehaus.jackson.annotate.JsonProperty;
public class Phone {
#JsonProperty("countryCode")
private Integer countryCode;
#JsonProperty("number")
private String number;
/**
*
* #return The countryCode
*/
#JsonProperty("countryCode")
public Integer getCountryCode() {
return countryCode;
}
/**
*
* #param countryCode
* The countryCode
*/
#JsonProperty("countryCode")
public void setCountryCode(Integer countryCode) {
this.countryCode = countryCode;
}
/**
*
* #return The number
*/
#JsonProperty("number")
public String getNumber() {
return number;
}
/**
*
* #param number
* The number
*/
#JsonProperty("number")
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Phone [countryCode=" + countryCode + ", number=" + number + "]";
}
}
OtherDetail.java
import org.codehaus.jackson.annotate.JsonProperty;
public class OtherDetail {
#JsonProperty("Active")
private Boolean Active;
/**
*
* #return The Active
*/
#JsonProperty("Active")
public Boolean getActive() {
return Active;
}
/**
*
* #param Active
* The Active
*/
#JsonProperty("Active")
public void setActive(Boolean Active) {
this.Active = Active;
}
#Override
public String toString() {
return "OtherDetail [Active=" + Active + "]";
}
}
user.json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
I tried the library json2flat with the json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
it gives a CSV like ::
rinu|14|91|99862656|
rinu|14|91|675432 |
rinu| | | |true
But if you tweak the json a little bit like ::
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656","Active":true},{"countryCode":91,"number":"675432","Active":true}]}
it gives the csv exactly as you require.
rinu|14|91|99862656|true
rinu|14|91|675432|true
Give it a try. After all the solution depends upon how the user wants to interpret the json.

How to fix Out of START_ARRAY token Error

Can anybody say where I am doing wrong. I have json like that
[{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"}]
And I parse to this class.
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonPropertyOrder({
"shards"
})
public class ShardsResponse extends Response{
#JsonProperty("shards")
private List<Shards> shards = new ArrayList<Shards>();
/**
*
* #return
* The shards
*/
#JsonProperty("shards")
public List<Shards> getShards() {
return shards;
}
/**
*
* #param shards
* The shards
*/
#JsonProperty("shards")
public void setShards(List<Shards> shards) {
this.shards = shards;
}
}
And Shards class is :
/**
*
* #return
* The locales
*/
#JsonProperty("locales")
public List<String> getLocales() {
return locales;
}
/**
*
* #param locales
* The locales
*/
#JsonProperty("locales")
public void setLocales(List<String> locales) {
this.locales = locales;
}
/**
*
* #return
* The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The hostname
*/
#JsonProperty("hostname")
public String getHostname() {
return hostname;
}
/**
*
* #param hostname
* The hostname
*/
#JsonProperty("hostname")
public void setHostname(String hostname) {
this.hostname = hostname;
}
/**
*
* #return
* The slug
*/
#JsonProperty("slug")
public String getSlug() {
return slug;
}
/**
*
* #param slug
* The slug
*/
#JsonProperty("slug")
public void setSlug(String slug) {
this.slug = slug;
}
}
So I'm using ObjectMapper.readValue(jsontext, responseclass)
JSONObject object = new JSONObject(JsonString);
JsonString = "";
Iterator<String> keys= object.keys();
while (keys.hasNext()){
String keyValue = (String)keys.next();
JsonString= JsonString+ object.getString(keyValue);
}
JsonString= JsonString.substring(1, JsonString.length()-1);
Object response = ObjectMapper.readValue(JsonString, ShardsResponse.class);
At the last I am getting out of START_ARRAY token. Please anybody tell me what's wrong.
Cause I'm trying so much things, but I never find the solution.
How can I fix it.
Your json string is correct, but not for the object you expect, as someone mentioned already, you need to use a List
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class ParseJson {
private static final String jsonString = "[{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"}]";
public static void parse() {
try {
TypeReference<List<Shards>> typeRef = new TypeReference<List<Shards>>() { };
ObjectMapper mapper = new ObjectMapper();
List<Shards> list = mapper.readValue(jsonString, typeRef);
for ( Shards s : list )
{
s.printDebug();
}
ShardsResponse sr = new ShardsResponse(list);
String srString = mapper.writeValueAsString(sr);
System.out.println("srString: " + srString );
TypeReference<ShardsResponse> typeRef2 = new TypeReference<ShardsResponse>() { };
ShardsResponse sr2 = mapper.readValue(srString, typeRef2);
sr2.printDebug();
} catch ( IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ParseJson.parse();
}
}
Edit:
If you expect a ShardsResponse back, your json string should look like this:
{"shards":[{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"}]}
Easiest way to figure out what the json will look like is to dump it out:
ShardsResponse sr = new ShardsResponse(list);
String srString = mapper.writeValueAsString(sr);
System.out.println("srString: " + srString );
Edit:
Adding additional Classes for clarity:
ShardsResponses.java
import java.util.ArrayList;
import java.util.List;
public class ShardsResponse {
private List<Shards> shards = new ArrayList<Shards>();
public ShardsResponse() { }
public ShardsResponse( List<Shards> shards)
{
this.shards = shards;
}
public List<Shards> getShards() {
return shards;
}
public void setShards(List<Shards> shards) {
this.shards = shards;
}
public void printDebug()
{
for ( Shards s : shards)
{
s.printDebug();
System.out.println("");
}
}
}
Shards.java:
import java.util.List;
public class Shards {
private List<String> locales;
private String name;
private String hostname;
private String slug;
private String region_tag;
public List<String> getLocales() {
return locales;
}
public void setLocales(List<String> locales) {
this.locales = locales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public void printDebug()
{
System.out.println("name: " + name);
System.out.println("hostname: " + hostname);
System.out.println("slug: " + slug);
System.out.println("region_tag: " + region_tag);
for ( String s : locales )
{
System.out.println("Locals: " + locales);
}
}
public String getRegion_tag() {
return region_tag;
}
public void setRegion_tag(String region_tag) {
this.region_tag = region_tag;
}
}
you have an jsonArray but you are trying to parse a jsonObject. change your method to return a list of objects instead of one object.

how to declare an arraylist collection class object

hi guys I have created a basket field in this browser class but, however I now need to declare this basket field in the browser class as arraylist collection class object but cant figure out how to do this, below is my code so far
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
List<Boolean> basketList = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
}
any answers or replies would be greatly appreciated
Try this out
List<Boolean> basketList = new ArrayList<Boolean>();
That must not be boolean as boolean is a primitive type not a collection of Objects.
what you need to do is:
ArrayList basket = new ArrayList();
Or if you need a collection of Boolean Objects (still not boolean) you can do:
ArrayList basket = new ArrayList();
A list of Boolean(s)?
java.util.List<Boolean> basketAl = new java.util.ArrayList<Boolean>();
And I urge you to add a toString method to your class
// Something like this...
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(iD).append(" ").append(email).append(" ");
sb.append(yearOfBirth).append(" ").append(memberID).append(" ");
sb.append(wineCase).append(" ").append(loggedIn).append(" ");
sb.append(website).append(" ").append(discount).append(" ");
sb.append(Basket);
return sb.toString();
}
It's a bit hard to tell what you're doing but declare this at the top of your class. Also, don't forget to import packages java.util.ArrayList and import java.util.List.
private List<Boolean> baskets = new ArrayList<Boolean>();
This will replace the previous declaration of:
private boolean Basket;

Categories

Resources