Mutiny Quarkus : Can you use Mutiny reactive programming in ArrayLists? - java

I'm trying to learn Reactive programming in quarkus and run into a problem. I want to make a simple employee system without any database, just the ArrayList with the Employees but in every article and video tutorial i watched and read , there were all using Databases.Is there a way to use Mutli and Uni in just an ArrayList and Is it worth it at all?
Thanks for your time

You can easily do something like:
public class Fruit {
public final String name;
public final String description;
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
}
#Path("/fruits")
public class FruitResource {
private final Set<Fruit> fruits = Set.of(new Fruit("Apple", "Winter fruit"), new Fruit("Pineapple", "Tropical fruit"));
#GET
public Uni<Set<Fruit>> list() {
return Uni.createFrom().item(fruits);
}
}
where all you are doing is returning a Set of Fruit objects via a Uni - no database or anything

Related

How to use autobean for converting json to java class in GWT

I have a class Person in gwt and I have sent an instance of Person with servlet converted using Gson from server to client. But in the client side seems I can't use Gson. From what I read in forums it seems that the best way is using AutoBeans to convert Json to object Person again.
However in AutoBeans I can only use an interface. I will appreciate if anyone can help me write it.
A json example I get from server and want to convert to Person class again:
{"name":"aaa","family":"fff","username":"uuu","age":20,"phones":[{"id":0,"phoneNumber":"0911111"}],"relatives":[null]}
public class Person implements Serializable {
private String name;
private String family;
private String username;
private int age;
private List<Phone> phones;
private List<Person> relatives;
public Person() {
}
public Person(String name, String family, String username, int age, List<Phone> phones, List<Person> relatives) {
this.name = name;
this.family = family;
this.username = username;
this.age = age;
this.phones = phones;
this.relatives = new ArrayList<Person>();
this.relatives = relatives;
}
public void addPhone(Phone p) {
phones.add(p);
}
public String getName() {
return this.name;
}
public String getFamily() {
return this.family;
}
public int getAge() {
return this.age;
}
public String getUsername() {
return this.username;
}
public List<Phone> getNumbers() {
return this.phones;
}
public List<Person> getRelatives() {
return this.relatives;
}
public String getAllNumbers() {
return Phone.convertPhonesToText(phones);
}
public static Person findPerson(List<Person> personList, String username) {
// .....
}
public static List<Person> convertTextToPersons(List<Person> personList, String personsText) {
// .....
}
public String convertPersonsToText() {
// ....
}
}
Yep, as commented by Tobika the other answer indicates that AutoBeans requires an Interface. AutoBeans feets better if you use it on both sides, client and server side and you define all your models as interfaces.
If you want to use your class models, you can use GWT Jackson which is pretty similar to AutoBeans but it uses your models, binding the json to your model (like other server side libraries; jackson, gson, etc):
https://github.com/nmorel/gwt-jackson
public static interface PersonMapper extends ObjectMapper<Person> {}
#Override public void onModuleLoad() {
PersonMapper mapper = GWT.create(PersonMapper.class);
String json = mapper.write(new Person("John", "Doe"));
GWT.log( json ); // > {"firstName":"John","lastName":"Doe"}
Person person = mapper.read(json);
GWT.log(person.getFirstName() + " " + person.getLastName());
}
Alternatively, you can use just plain GWT with JsInterop. This has many limitations but even with this limitation, it is a pretty good option. This is my favorite option if you can avoid inheritance in your DTOs. But this has the big advantage of being super lightweight (actually zero overhead mapping overhead and zero code overhead as it uses native parsing and no copies, accesing directly to the parsed json object). Limitations: cannot use inheritance, "broken type system" (all X instanceof SomeDtoType returns always true as all DTOs are of type Object wich makes sense because we are actually using the parsed JSON), cannot use collections only native arrays (but thanks to java8 Stream this should not be a problem, whatever you want to do with start with Stream.of(arr)), and only Double and Boolean boxed types supported (not supported any fancy type like Date or BigInteger, not supported long/Long...).
#JsType(isNative=true, package=GLOBAL, name="Object") final class Person {
// you can use getter/setter but as this class is final DTO adds no value
public String firstName; public String lastName; public Phome[] numbers;
// you can add some helper methods, don't forget to skip serialization!
public final #JsOverlay #JsonIgnore List<Phone> getNumberList() {
return Stream.of(numbers).collect(Collectors.toList());
}
}
#JsType(isNative=true, package=GLOBAL, name="Object) final class Phone {
public String number;
}
#JsMethod(namespace = "JSON") public static native <T> T parse(String text);
#Override public void onModuleLoad() {
Person person = parse("{\"firstName\":\"John\",\"lastName\":\"Doe\"}");
GWT.log(person.firstName + " " + person.lastName);
}
These simple and limited DTOs are more a DTO scheme than a type. But has a big advantage, this DTOs works out of the box with most of the server side parsers. Jackson and GSON will encode and parse without any configuration.

AWS DynamoDB - save a JSON Array to a table (Java/Android)

How do you save a JSON Array as an item attribute? AWS documentation is the absolute worst thing ever - it contradicts itself, a lot of things are either redundant or only partially explained, some things aren't explained at all - I don't know how anyone manages to use it.
Anyway, suppose I have a table called Paths, and a path has a name, an ID, and a list of LatLngs (formatted as a JSON Array)
In the class definition for this table, I have
#DynamoDBTable(tableName = "Paths")
public class Path {
private String id;
private String name;
private JSONArray outlineJSON;
with getters and setters like
#DynamoDBRangeKey(attributeName = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
which works fine for strings, booleans and numbers, and the object saves successfully to the table.
AWS documentation mentions JSON several times, and says it can handle lists, but it doesn't explain how to use lists or give any examples.
I used #DynamoDBHashKey for the id, #DynamoDBRangeKey for name, and #DynamoDBAttribute for other strings, numbers or booleans, and I tried it here
#DynamoDBAttribute(attributeName = "outline")
private JSONArray getOutlineJSON() {
return outlineJSON;
}
private void setOutlineJSON(JSONArray outlineJSON) {
this.outlineJSON = outlineJSON;
}
It successfully saved the object but without the array.
How do I save the array? I can't find an explanation anywhere. I think #DynamoDBDocument might have something to do with it, but all the documentation on the subject gives unrelated examples, and I can't find any using a list like my in situation.
EDIT: For now, I have a working solution - I can easily convert my lists to JSONArrays and then convert those to Strings, and vice-versa.
You can define your class to be something like
#DynamoDBTable(tableName = "Paths")
public class Path {
private String id;
private String name;
private LatLang latLangs;
#DynamoDBHashKey(attributeName="id")
public String getId() { return id;}
public void setId(String id) {this.id = id;}
#DynamoDBRangeKey(attributeName = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBDocument
public static class LatLang{
public String lat;
public String lang;
}
}

Java Class Misuse - Best Practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm fairly certain that I am not doing something class related correctly.
I am using a class to create a set of variables (like a javascript object sort of maybe but not really).
I am using it as shown bellow (a basic example)
public class myScript {
public static void main(String[] args) {
Client warehouse = new Client();
Contacts warehouseContactsA = new Contacts();
Contacts warehouseContactsB = new Contacts();
warehouse.idno = 1;
warehouse.name = "warehouse";
warehouse.desc = "I don't exist";
warehouseContactsA.client_idno = 1;
warehouseContactsA.email = "emailAAA#place.com"
warehouseContactsB.client_idno = 1;
warehouseContactsB.email = "emailBBB#place.com"
insertIntoDB(warehouse,
warehouseContactsA,
warehouseContactsB);
}
public static void insertIntoDB(Client warehouse,
Contacts warehouseContactsA,
Contacts warehouseContactsB) {
// code to insert into database here
}
private class Client {
int idno;
String name;
String desc;
}
private class Contacts {
int client_idno;
String email;
}
}
Is there any reason to not use classes this way and if so is there a simpler way to store/manage data that doesn't require a class?
Creating inner classes is probably going to create pitfalls for you. When you don't define them as static then they require an implicit reference back to the outer class, which your code doesn't need, it will only get in the way and cause obscure errors. Maybe you're doing this so you can compile only one class and avoid having a build script? Simple build scripts that use gradle are trivial (not like the bad old days when we used ant), so that shouldn't be an issue. It would be better to move your persistent entities out into separate files.
What you're doing with database connections and transactions is not clear. Generally it's bad to try to do each insert in its own transaction, if only because each transaction has overhead and it increases the time the inserts need to run. Typically you'd want to process the inserts in batches.
Mainly, though, if you're writing a script, use a scripting language. Groovy could be a good choice here:
you wouldn't need an outer class for the procedural script part
you can define multiple public classes in one file
Groovy includes a groovy.sql api for simplifying JDBC code.
import java.util.Arrays;
import java.util.List;
public final class WarehouseRepository {
public static void main(String[] args) {
WarehouseRepository repository = new WarehouseRepository();
Client warehouse = new Client(1, "warehouse", "I don't exist");
Contacts warehouseContactsA = new Contacts(1, "emailAAA#place.com");
Contacts warehouseContactsB = new Contacts(1, "emailBBB#place.com");
repository.insertIntoDB(warehouse, Arrays.asList(warehouseContactsA, warehouseContactsB));
}
public void insertIntoDB(Client warehouse, List<Contacts> contacts) {
// code to insert into database here
}
}
final class Client {
private final int id;
private final String name;
private final String desc;
public Client(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc = desc;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
}
final class Contacts {
private final int clientName;
private final String email;
public Contacts(int clientName, String email) {
this.clientName = clientName;
this.email = email;
}
public int getClientName() {
return clientName;
}
public String getEmail() {
return email;
}
}
Some things to notice:
Try to name the classes with their intentions and some Java conventions. For example, a class doing database operations are usually referred as repository
Unless required, make classes and variables final.
Make fields private, and if they are must have, then make them constructor parameters, instead of public or getter/setters.
If there can be multiple contacts associated with client, then it would be great idea to make List<Contact> as field in client.
I would use Map<String,String> for storing attributes.
Where I would store String and ints as Strings and parse them back when they needed.
hope it helps
Yes, that is a good-enough representation.
No, it's not ideal. There are a couple things you can change to improve the situation:
Visibility option 1: make things private with accessors
You can make things more OO-idiomatic by having your "bean" classes (i.e. objects with data storage purpose only, no logic) fields private, and then having public accessors to mask the inner representation:
public class Client {
private int id;
public int getId() { return this.id; }
public void setId(int id) { this.id = id; }
}
Visibility option 2: make your beans immutable
Another option is to make it so that your beans are immutable (so that you can pass them around in a multi-threaded environment nonchalantly) and also guarantee that they are properly initialized and no one writes to them in an illegal state (for example deleting/zeroing the id but not the rest of the data):
public class Client {
public final int id;
public Client(int id) { this.id = id; }
}
Finally, if you have things that may or may not be there (such as description "I don't exist"), I recommend using Optional types, rather than just String types.

Set and HashSet Java

I'm relatively new to the Java language and have a project I'm doing for school in which I have a Book class that has the normal setters/getters, constructors, and overrides for this class, nothing complicated. I have to change it so I can get multiple authors by utilizing Set and HashSet. The question I have is how would I go about doing this? So far, and correct me if I'm wrong, I have this
import java.util.*;
public class Book{
private Set<String> authorSet;
private String isbn;
public Book(){
authorSet = null;
isbn = null;
}
public Book(String isbn, Set<String> authorSet){
this.isbn = isbn;
Set<String> s = new HashSet<String>();
// Do I do anything else here?
}
public String getIsbn(){
return isbn;
}
public void setIsnb(String isbn){
this.isbn = isbn;
}
public Set<String> getAuthorSet(Set<String> newAuthorSet{
return newAuthorSet;
}
public void setAuthorSet(Set<String> newAuthorSet){
this.authorSet = newAuthorSet;
}
Before moving on to the overrides, I want to make sure I get this properly. I've tried to look for similar examples so I can see what's going on, but I haven't had much luck as of yet. I'm sure it's very simple, but I'm just starting to learn the language. Thanks for the help
First of all, in your default constructor, get rid of
authorSet = null;
and instead initialize your authorSet variable to a new HashSet. The reason for this is that you want to create the authorSet container regardless of whether any authors are added to begin with.
You'll probably want a constructor that takes just an isbn String. Also consider a constructor that takes isbn String and a variable number of Author Strings.
Ah, I missed this:
public Book(String isbn, Set<String> authorSet){
this.isbn = isbn;
Set<String> s = new HashSet<String>();
// Do I do anything else here?
}
Not good as you ignore both the parameter and the field! Instead, assign the set parameter to the existing field as you would with any other field.
public Book(String isbn, Set<String> authorSet){
this.isbn = isbn;
this.authorSet = authorSet;
}
Then give your class an addAuthor(String author) method. Better for you to code this since this is homework. I really don't think that there's a whole lot more that you need with regards to this problem.
I'd have taken away the default constructor. Also, why would you need to set the authorSet? Wouldn't it better to just add and remove from it? Also why would you need to set the isbn. Could you instead just take it in the constructor, as I don't think you'd ever have to change it. How about something like this?
import java.util.HashSet;
import java.util.Set;
public class Book {
private final Set<String> authorSet;
private final String isbn;
public Book(String isbn) {
this.isbn = isbn;
this.authorSet = new HashSet<>();
}
public String getIsbn() {
return isbn;
}
public Set<String> getAuthorSet() {
return authorSet;
}
public void addAuthor(String author) {
authorSet.add(author);
}
public void removeAuthor(String author) {
authorSet.remove(author);
}
}
For extra points, the practice of returning your actual collection (set) implementation can allow a caller to muck with your internals. Thus, this is a little hazardous:
public Set<String> getAuthorSet() {
return authorSet;
}
safer:
public Set<String> getAuthorSet() {
return Collections.unmodifiableSet(authorSet);
}
Similarly if you had need to accept a new set in your API, but did not want to trust the caller to not later violate your representation, then you might do this:
public void setAuthorSet(Set<String> newAuthorSet) {
authorSet = new HashSet<String>(newAuthorSet);
}

What's the most object-oriented way to design an address book?

I am asking myself how to design an object-oriented address book in Java.
Let's say a contact can have several contact details, like addresses, phone numbers and e-mail addresses.
One way to implement this would be to give every contact an ArrayList for every type. But there must be a better and more object-oriented solution. What is it?
The most OOP suggestion I can give you is to create a class for every item/piece of information. For example:
public abstract class ContactInfo { /* ... */ }
public class Address extends ContactInfo { /* ... */ }
public class PhoneNumber extends ContactInfo { /* ... */ }
public class EmailAddress extends ContactInfo { /* ... */ }
public class Contact {
private String name;
private Set<ContactInfo> info;
// ...
}
and finally,
public class AddressBook {
List<Contact> contacts;
// ...
}
This may or may not be overkill for your specific case, but as a thought experiment, it's the way to go. It obviously takes care of the literal part of OOP — using objects — but also lays groundwork for encapsulation, abstraction and inheritance, which are closely related principles.
You're on the right track. The only thing I would do differently would be to use a List interface instead of an ArrayList collection to reference the contacts' attribute collections. This is advice based on the code-to-interfaces rule-of-thumb as described in this article and many others.
I don't think that's particularly un-object oriented. If your domain is such that a Person can have zero or more EmailAddresses, then you've almost exactly described the situation to use a list.
The only alternative approach I can think of would be to have fields such as
WorkEmail
PersonalEmail
OtherEmail1
OtherEmail2
OtherEmail3
but in my opinion that's worse, because:
You simply cannot support more than five email addresses (well, you could add more fields, but that increases the pain of the latter points and still imposes some finite limit.)
You're implying some extra semantics than may be present (what if the same address is used for work and personal? What if neither applies, can you just fill the Other ones? What if you don't know the purpose?)
You now have to test each field manually to see which is null, which is going to involve a non-trivial amount of duplication in Java. You can't use nice features like the enhanced-for loop to apply the same block to every email address, and you can't trivially count how many addresses there are
The list of properties that a Person has is now much less clean. I suppose you could package these properties into an EmailContactDetails class or something, but now you've got an extra level of indirection (more conceptual complexity) for no real gain.
So, if a person has a possibly-empty, unbounded list of email addresses, what's wrong with representing that as a list?
You can also use a Map, and then get specific values e.g. via myMap.get("emailAdress1") or iterate over the whole map like you would do with a list via myMap.entrySet().
One simple way to handle most of the use cases can be like this
public class AddressBook {
private Map<String, Contact> contacts;
AddressBook(){
contacts = new HashMap<String, Contact>();
}
public boolean addContact(Contact contact) {
if(contacts.containsKey(contact.getName())) {
System.out.println("Already exists");
return false;
}
contacts.put(contact.getName(), contact);
return true;
}
public boolean updateContact(Contact contact) {
contacts.put(contact.getName(), contact);
return true;
}
}
class Contact{
private String name;
private String email;
private String phone;
private Address address;
public Contact(String name) {
this.name = name;
}
public Contact(String name, String email, String phone, Address address) {
this.name = name;
this.email = email;
this.phone = phone;
this.address = address;
}
// getters and setters
#Override
public String toString() {
return "name is "+name+" and address is "+address;
}
}
class Address{
private String street1;
private String street2;
private String city;
private int zipcode;
public Address() {}
// getters and setters
#Override
public String toString() {
return "street1 is "+street1+" and zipcode is "+zipcode;
}
}

Categories