Java error "cannot find symbol" when using a constructor - java

This is the class and it's constructor that I made. No problems while compiling.
public class Usuario
{
private String usuario="a";
private String contrasena="a";
private String nombre="a";
private String apellido="a";
private int dni=0;
private int edad=0;
public Usuario (String usuario, String contrasena, String nombre, String apellido, int dni, int edad)
{
this.usuario=usuario;
this.contrasena=contrasena;
this.nombre=nombre;
this.apellido=apellido;
this.dni=dni;
this.edad=edad;
}
And this is my main code where I use the constructor.
public class userTest
{
public static void main (String args[])
{
Usuario philip;
philip=new Usuario (user987, pass123, Philip, Fry, 11000111, 21);
}
}
When compiling this part, the javac shows that error.

philip=new Usuario (user987, pass123, Philip, Fry, 11000111, 21);
The first 4 parameters are not defined.
If you are attempting to pass String values to the constructor, then the code should be:
philip= new Usuario ("user987", "pass123", "Philip", "Fry', 11000111, 21);

Related

How work with immutable object in mongodb and lombook without #BsonDiscriminator

I tried to work with immutable objects in MongoDB and Lombok. I found a solution to my problem but it needs to write additional code from docs but I need to used Bson annotations and create a constructor where describes fields via annotations. But if I user #AllArgsConstructor catch exception: "Cannot find a public constructor for 'User'" because I can't use default constructor with final fields. I think i can customize CodecRegistry correctly and the example will work correctly but I couldn't find solution for it in docs and google and Stackoverflow.
Is there a way to solve this problem?
#Data
#Builder(builderClassName = "Builder")
#Value
#BsonDiscriminator
public class User {
private final ObjectId id;
private final String name;
private final String pass;
private final String login;
private final Role role;
#BsonCreator
public User(#BsonProperty("id") final ObjectId id,
#BsonProperty("name") final String name,
#BsonProperty("pass") final String pass,
#BsonProperty("login") final String login,
#BsonProperty("role") final Role role) {
this.id = id;
this.name = name;
this.pass = pass;
this.login = login;
this.role = role;
}
#AllArgsConstructor
public enum Role {
USER("USER"),
ADMIN("ADMIN"),
GUEST("GUEST");
#Getter
private String value;
}
public static class Builder {
}
}
Example for MongoDB where I create, save and then update users:
public class ExampleMongoDB {
public static void main(String[] args) {
final MongoClient mongoClient = MongoClients.create();
final MongoDatabase database = mongoClient.getDatabase("db");
database.drop();
final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
final MongoCollection<User> users = database.getCollection("users", User.class).withCodecRegistry(pojoCodecRegistry);
users.insertMany(new ExampleMongoDB().getRandomUsers());
System.out.println("Before updating:");
users.find(new Document("role", "ADMIN")).iterator().forEachRemaining(
System.out::println
);
System.out.println("After updating:");
users.updateMany(eq("role", "ADMIN"), set("role", "GUEST"));
users.find(new Document("role", "GUEST")).iterator().forEachRemaining(
System.out::println
);
}
public List<User> getRandomUsers() {
final ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 15; i++) {
users.add(
User.builder()
.login("log" + i)
.name("name" + i)
.pass("pass" + i)
.role(
(i % 2 == 0) ? User.Role.ADMIN : User.Role.USER
).build()
);
}
return users;
}
}
This should work (it worked for me):
#Builder(builderClassName = "Builder")
#Value
#AllArgsConstructor(onConstructor = #__(#BsonCreator))
#BsonDiscriminator
public class User {
#BsonId
private final ObjectId _id;
#BsonProperty("name")
private final String name;
#BsonProperty("pass")
private final String pass;
#BsonProperty("login")
private final String login;
#BsonProperty("role")
private final Role role;
}
Then in lombok.config add these (in your module/project directory):
lombok.addLombokGeneratedAnnotation=true
lombok.anyConstructor.addConstructorProperties=true
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonProperty
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonId
Also piece of advice, keep _id if you are going to use automatic conversion to POJOs using PojoCodec, which will save a lot of trouble.

How to override the #AdminPresentation for existing attributes [Broadleaf Commerce]

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:

JAVA: Trying to get a list by two objects that I have created but got an error

This is my code, and the errors are in lstA.add(objPintura); lstB.add(objPintura2);... in "add":
import java.util.ArrayList;
import java.util.List;
public class ListaObj {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> lstA = new ArrayList<String>();
ArrayList<String> lstB = new ArrayList<String>();
ConceptosLista objPintura = new ConceptosLista("1781", "", "PUERTA TRA.I. PINTURA SUSTITUCION", 407.25, "0", "HYP", 0);
lstA.add(objPintura);
ConceptosLista objPintura2 = new ConceptosLista("1781", "", "PUERTA TRA.I. PINTURA SUSTITUCION", 300.20, "0", "HYP", 0);
lstB.add(objPintura2);
}
}
This is what the error says:
The method add(String) in the type ArrayList is not applicable
for the arguments (ConceptosLista)
And this is also my class:
public class ConceptosLista {
private String posicion;
private String numeroParte;
private String descripcion;
private double monto;
private String cambioPrecio;
private String concepto;
private double montoConvenio;
public ConceptosLista(String posicion, String numeroParte, String descripcion, double monto, String cambioPrecio,
String concepto, double montoConvenio) {
this.posicion = posicion;
this.numeroParte = numeroParte;
this.descripcion = descripcion;
this.monto = monto;
this.cambioPrecio = cambioPrecio;
this.concepto = concepto;
this.montoConvenio = montoConvenio;
}
}
I've been trying a lot and haven't had any solution, I think is perhaps the kind of variables I use in my class like double .
thank you so much.
lstA is a List<String>, so it contains String objects, not ConceptosLista objects. If you want listA to contain ConceptosLista objects, change it to this:
ArrayList<ConceptosLista> lstA = new ArrayList<ConceptosLista>();

2 session object java ee null exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm beginner with Java EE, when I try to transfer an object between a JSP and a Servlet I use a session.
For an homework, I have to create an e-commerce website.
I just have this in my jsp:
HttpSession sess = request.getSession();
Panier pan = new Panier();
sess.setAttribute("panier", pan);
sess.setAttribute("produit", produits.get(0));
produits is an arraylist of "produit" object.
In my Servlet:
HttpSession sess = request.getSession();
Panier pan = (Panier) sess.getAttribute("panier");
Produit p1 = (Produit) sess.getAttribute("prod");
When I'm here, all works cause I can display the good attributes of the object pan or p1. But, when I use my method "ajouterProduit" (addProduct in English), a savage null pointer exception appears.
My class "Produit":
public class Produit implements java.io.Serializable{
private String nom;
private int prix;
public Produit(String name, int price){
this.nom = name;
this.prix = price;
}
public void setNom(String n){
this.nom = n;
}
public void setPrix(int p){
this.prix = p;
}
public String getNom(){
return this.nom;
}
public int getPrix(){
return this.prix;
}
}
My class "Panier" (basket in english):
public class Panier implements Serializable{
private List<Produit> panier;
private static int montant = 0;
public Panier(){
panier = new ArrayList<>();
}
public void ajouterProduit(Produit p1){
panier.add(p1);
montant = montant + p1.getPrix();
}
public void ajouterProduit(Produit p1, Produit p2){
panier.add(p1);
montant = montant + p1.getPrix();
panier.add(p2);
montant = montant + p2.getPrix();
}
public void ajouterProduit(Produit p1, Produit p2,Produit p3){
panier.add(p1);
montant = montant + p1.getPrix();
panier.add(p2);
montant = montant + p2.getPrix();
panier.add(p3);
montant = montant + p3.getPrix();
}
public List<Produit> getPanier(){
return panier;
}
public int getMontantTotal(){
return montant;
}
}
Thanks in advance for help ! ;)
You add your "produit" like so:
sess.setAttribute("produit", produits.get(0));
But you retrieve it like so:
Produit p1 = (Produit) sess.getAttribute("prod");
"prod" and "produit" are 2 different session names. Your "produit" is not in "prod" session.
You store your product in the produit session, but you retrieve it from a prod session, which does not exist.
p1 is, therefore, null.

How do I find and count how many spaces of a particular type here?

I have these codes:
public class CentroImpl implements Centro {
//Atributos
private String nombre;
private String direccion;
private Integer numeroPlantas;
private Integer numeroSotanos;
public Set<Espacio> espacio;
//Constructor
public CentroImpl(String nombre, String direccion, Integer numeroPlantas, Integer numeroSotanos){
checkPlantas(numeroPlantas);
checkSotanos(numeroSotanos);
this.nombre = nombre;
this.direccion = direccion;
this.numeroPlantas = numeroPlantas;
this.numeroSotanos = numeroSotanos;
this.espacio = new TreeSet<Espacio>();
}
#Override
public Set<Despacho> getDespachos() {
}
getDespacho is supposed to go through the list of 'Espacios' (places) in a building (centro) and tell me how many of them are Despachos (offices). As you can see in Espacio class there is a type defined.
public class EspacioImpl implements Espacio {
//Atributos
private TipoEspacio tipo;
private String nombre;
private Integer planta;
private Integer aforo;
//Constructores
public EspacioImpl(TipoEspacio tipo, String nombre, Integer planta, Integer aforo) {
checkerAforo(aforo);
this.nombre = nombre;
this.planta = planta;
this.aforo = aforo;
this.tipo = tipo;
}
But I have not learned yet how to access it, and I haven't been able to find anything understandable around. Thank you for your help.
Assuming Despacho extends Espacio and TipoEspacio is enum:
#Override
public Set<Despacho> getDespachos() {
Set<Despacho> despachos = new HashSet<Despacho>();
for (Espacio e : espacio) {
// Not sure, depends on the definition of TipoEspacio
if (e.getTipo() == TipoEspacio.DESPACHO && e instanceof Despacho) {
despachos.put((Despacho)e);
}
}
return despachos;
}
This answer assumes that you have a collection of EspacioImpls called espacios, and that the enum name for a Despacho is Despacho. You then have to do something with numDespachos (like return it). This also assumes that EspacioImpl has a method called getTipo. You need this because the tipo member is private, and so it cannot be accessed outside the class without having a getter.
int numDespachos = 0;
for(EspacioImpl e : espacios)
{
if(e.getTipo() == TipoEspacio.Despacho)
++numDespachos;
}

Categories