Skip to content
Andreas Rudolph edited this page Aug 16, 2021 · 5 revisions

How to use Idealista format

Reading JSON in Idealista format

The class org.openestate.io.idealista.IdealistaUtils provides a static read() function to read JSON data in Idealista format from a java.io.File, java.io.InputStream, java.io.Reader, or java.lang.String into a org.openestate.io.idealista.IdealistaRootElement.

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.openestate.io.idealista.IdealistaRootElement;
import org.openestate.io.idealista.IdealistaUtils;
import org.openestate.io.idealista.json.AbstractFeatures;
import org.openestate.io.idealista.json.BuildingFeatures;
import org.openestate.io.idealista.json.Customer;
import org.openestate.io.idealista.json.GarageFeatures;
import org.openestate.io.idealista.json.HomeFeatures;
import org.openestate.io.idealista.json.LandFeatures;
import org.openestate.io.idealista.json.NewDevelopment;
import org.openestate.io.idealista.json.OfficeFeatures;
import org.openestate.io.idealista.json.Operation;
import org.openestate.io.idealista.json.PremiseFeatures;
import org.openestate.io.idealista.json.Property;
import org.openestate.io.idealista.json.StorageFeatures;
import org.openestate.io.idealista.json.Typology;

public class IdealistaReadingExample {
    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            System.err.println("No file was specified!");
            System.exit(1);
        }

        // read file into a IdealistaRootElement
        IdealistaRootElement doc = IdealistaUtils.read(new File(args[0]));

        // convert IdealistaRootElement into a Customer object
        Customer customer = doc.getObject();

        System.out.println("processing customer " +
                "'" + customer.getReference() + "' " +
                "({" + customer.getName() + "})");

        // process properties
        if (customer.getProperties() != null) {
            for (Property property : customer.getProperties()) {
                // get property nr
                String objectNr = StringUtils.defaultIfBlank(
                        property.getReference(),
                        property.getCode());

                // get operation type
                Operation.Type operationType = (property.getOperation() != null) ?
                        property.getOperation().getType() : null;

                // get property type
                Enum objectType;
                AbstractFeatures features = property.getFeatures();
                if (features instanceof BuildingFeatures) {
                    BuildingFeatures building = (BuildingFeatures) features;
                    objectType = building.getType();
                } else if (features instanceof GarageFeatures) {
                    GarageFeatures garage = (GarageFeatures) features;
                    objectType = garage.getType();
                } else if (features instanceof HomeFeatures) {
                    HomeFeatures home = (HomeFeatures) features;
                    objectType = home.getType();
                } else if (features instanceof LandFeatures) {
                    LandFeatures land = (LandFeatures) features;
                    objectType = land.getType();
                } else if (features instanceof OfficeFeatures) {
                    OfficeFeatures office = (OfficeFeatures) features;
                    objectType = office.getType();
                } else if (features instanceof PremiseFeatures) {
                    PremiseFeatures premise = (PremiseFeatures) features;
                    objectType = premise.getType();
                } else if (features instanceof StorageFeatures) {
                    StorageFeatures storage = (StorageFeatures) features;
                    objectType = storage.getType();
                } else {
                    if (features == null) {
                        LOGGER.warn("Property type is not set!");
                    } else {
                        LOGGER.warn("Unknown property type '{}'!",
                                features.getClass().getName());
                    }
                    continue;
                }

                // print object information to console
                System.out.println("> found property '" + objectNr + "' " +
                        "(" + objectType + " / " + operationType + ")");
            }
        }

        // process new developments
        if (customer.getNewDevelopments() != null) {
            for (NewDevelopment newDevelopment : customer.getNewDevelopments()) {
                // get development nr
                String objectNr = StringUtils.defaultIfBlank(
                        newDevelopment.getReference(),
                        newDevelopment.getCode());

                // get typology types
                List<Enum> objectTypes = new ArrayList<>();
                if (newDevelopment.getTypologies() != null) {
                    for (Typology typology : newDevelopment.getTypologies()) {
                        AbstractFeatures features = typology.getFeatures();
                        if (features instanceof BuildingFeatures) {
                            BuildingFeatures building = (BuildingFeatures) features;
                            objectTypes.add(building.getType());
                        } else if (features instanceof GarageFeatures) {
                            GarageFeatures garage = (GarageFeatures) features;
                            objectTypes.add(garage.getType());
                        } else if (features instanceof HomeFeatures) {
                            HomeFeatures home = (HomeFeatures) features;
                            objectTypes.add(home.getType());
                        } else if (features instanceof LandFeatures) {
                            LandFeatures land = (LandFeatures) features;
                            objectTypes.add(land.getType());
                        } else if (features instanceof OfficeFeatures) {
                            OfficeFeatures office = (OfficeFeatures) features;
                            objectTypes.add(office.getType());
                        } else if (features instanceof PremiseFeatures) {
                            PremiseFeatures premise = (PremiseFeatures) features;
                            objectTypes.add(premise.getType());
                        } else if (features instanceof StorageFeatures) {
                            StorageFeatures storage = (StorageFeatures) features;
                            objectTypes.add(storage.getType());
                        } else {
                            if (features == null) {
                                LOGGER.warn("Property type is not set!");
                            } else {
                                LOGGER.warn("Unknown property type '{}'!",
                                        features.getClass().getName());
                            }
                        }
                    }
                }

                // print object information to console
                System.out.println("> found new development '" + objectNr + "' " +
                        "(" + StringUtils.join(objectTypes, " / ") + ")");
            }
        }
    }
}

See a full example at IdealistaReadingExample.java.

Accessing JSON data in Idealista format

The class org.openestate.io.idealista.json.Customer is equivalent to a root element in a Idealista document. For example the following code creates a Idealista document programmatically:

import com.thedeanda.lorem.Lorem;
import com.thedeanda.lorem.LoremIpsum;
import java.math.BigInteger;
import java.net.URI;
import java.util.Date;
import java.util.LinkedHashSet;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.openestate.io.idealista.json.Address;
import org.openestate.io.idealista.json.BathroomType;
import org.openestate.io.idealista.json.BuildingFeatures;
import org.openestate.io.idealista.json.ConditionedAirType;
import org.openestate.io.idealista.json.Contact;
import org.openestate.io.idealista.json.Customer;
import org.openestate.io.idealista.json.Description;
import org.openestate.io.idealista.json.HeatingType;
import org.openestate.io.idealista.json.HomeFeatures;
import org.openestate.io.idealista.json.Image;
import org.openestate.io.idealista.json.OfficeFeatures;
import org.openestate.io.idealista.json.Operation;
import org.openestate.io.idealista.json.Property;
import org.openestate.io.idealista.json.PropertyVisibilityType;

public class IdealistaWritingExample {
    private final static Lorem RANDOMIZER = new LoremIpsum();

    public static void main(String[] args) throws Exception {
        // create a customer root object with some example data
        Customer customer = new Customer();
        customer.setReference(RandomStringUtils.randomAlphanumeric(5));
        customer.setSendDate(new Date());
        customer.setCountry(randomValue(Customer.Country.values()));

        // add global customer contact
        customer.setContact(createContact());

        // append some example properties to the customer object
        customer.setProperties(new LinkedHashSet<Property>());
        int propertyCount = RandomUtils.nextInt(5, 10);
        for (int i = 0; i < propertyCount; i++) {
            customer.getProperties().add(createProperty());
        }

        // now make something useful with the object
    }

    /**
     * Create a {@link Contact} with some example data.
     *
     * @return created example object
     */
    private static Contact createContact() {
        Contact contact = new Contact();
        contact.setName(RANDOMIZER.getName());
        contact.setEmail(RANDOMIZER.getEmail());
        contact.setPrimaryPhonePrefix(RandomStringUtils.randomNumeric(2));
        contact.setPrimaryPhoneNumber(RandomStringUtils.randomNumeric(5, 10));
        contact.setSecondaryPhonePrefix(RandomStringUtils.randomNumeric(2));
        contact.setSecondaryPhoneNumber(RandomStringUtils.randomNumeric(5, 10));
        return contact;
    }

    /**
     * Create a {@link Property} with some example data.
     *
     * @return created example object
     */
    private static Property createProperty() {
        // create an example real estate for rent
        Property obj = new Property();

        obj.setCode(RandomStringUtils.randomAlphanumeric(5));
        obj.setReference(RandomStringUtils.randomAlphanumeric(5));
        obj.setVisibility(randomValue(PropertyVisibilityType.values()));

        // add address
        obj.setAddress(new Address());
        obj.getAddress().setPostalCode(RandomStringUtils.randomNumeric(5));
        obj.getAddress().setTown(RANDOMIZER.getCity());
        obj.getAddress().setCountry(randomValue(Address.Country.values()));

        // add contact
        obj.setContact(createContact());

        // add operation (sale / rent)
        obj.setOperation(new Operation());
        obj.getOperation().setType(randomValue(Operation.Type.values()));
        obj.getOperation().setPrice(BigInteger.valueOf(RandomUtils.nextLong(1000, 99999)));

        try {
            obj.setUrl(new URI("https://example.com/property-"
                    + obj.getCode() + ".html"));
        } catch (Exception ex) {
        }

        // add random number of images
        obj.setImages(new LinkedHashSet<Image>());
        int imageCount = RandomUtils.nextInt(5, 10);
        for (int i = 0; i < imageCount; i++) {
            obj.getImages().add(createImage(i));
        }

        // add random descriptions
        obj.setDescriptions(new LinkedHashSet<Description>());
        for (Description.Language lang : Description.Language.values()) {
            Description d = new Description();
            d.setLanguage(lang);
            d.setText(RANDOMIZER.getWords(RandomUtils.nextInt(100, 200)));
            obj.getDescriptions().add(d);
        }

        // add random property type
        // idealista supports more property types, but for the sake of readability
        // we're just showing three variations here
        switch (RandomUtils.nextInt(0, 3)) {
            case 0:
                obj.setFeatures(createPropertyBuilding());
                break;
            case 1:
                obj.setFeatures(createPropertyHome());
                break;
            case 2:
                obj.setFeatures(createPropertyOffice());
                break;
        }

        return obj;
    }

    /**
     * Create a {@link BuildingFeatures} property type with some example data.
     *
     * @return created example object
     */
    private static BuildingFeatures createPropertyBuilding() {
        // This is just a selection of attributes, supported for buildings.
        BuildingFeatures building = new BuildingFeatures();
        building.setType(randomValue(BuildingFeatures.Type.values()));
        building.setAreaConstructed(BigInteger.valueOf(RandomUtils.nextLong(50, 1000)));
        building.setAreaTradableMinimum(BigInteger.valueOf(RandomUtils.nextLong(50, 1000)));
        building.setBuiltYear(BigInteger.valueOf(RandomUtils.nextLong(1990, 2020)));
        building.setClassificationChalet(RandomUtils.nextBoolean());
        building.setClassificationCommercial(RandomUtils.nextBoolean());
        building.setClassificationHotel(RandomUtils.nextBoolean());
        building.setClassificationIndustrial(RandomUtils.nextBoolean());
        building.setClassificationOffice(RandomUtils.nextBoolean());
        building.setClassificationOther(RandomUtils.nextBoolean());
        building.setFloorsBuilding(BigInteger.valueOf(RandomUtils.nextLong(1, 10)));
        building.setLiftNumber(BigInteger.valueOf(RandomUtils.nextLong(1, 5)));
        building.setParkingSpacesNumber(BigInteger.valueOf(RandomUtils.nextLong(1, 10)));
        building.setPropertyTenants(RandomUtils.nextBoolean());
        building.setSecurityPersonnel(RandomUtils.nextBoolean());
        return building;
    }

    /**
     * Create a {@link HomeFeatures} property type with some example data.
     *
     * @return created example object
     */
    private static HomeFeatures createPropertyHome() {
        // This is just a selection of attributes, supported for homes.
        HomeFeatures home = new HomeFeatures();
        home.setType(randomValue(HomeFeatures.Type.values()));
        home.setAreaConstructed(BigInteger.valueOf(RandomUtils.nextLong(50, 1000)));
        home.setAreaPlot(BigInteger.valueOf(RandomUtils.nextLong(200, 2000)));
        home.setAreaUsable(BigInteger.valueOf(RandomUtils.nextLong(200, 2000)));
        home.setBuiltYear(BigInteger.valueOf(RandomUtils.nextLong(1990, 2020)));
        home.setBathroomNumber(BigInteger.valueOf(RandomUtils.nextLong(1, 5)));
        home.setBedroomNumber(BigInteger.valueOf(RandomUtils.nextLong(1, 5)));
        home.setBalcony(RandomUtils.nextBoolean());
        home.setChimney(RandomUtils.nextBoolean());
        home.setConditionedAir(RandomUtils.nextBoolean());
        home.setDoorman(RandomUtils.nextBoolean());
        home.setDuplex(RandomUtils.nextBoolean());
        home.setHeatingType(randomValue(HeatingType.values()));
        home.setLiftAvailable(RandomUtils.nextBoolean());
        home.setEquippedKitchen(RandomUtils.nextBoolean());
        home.setEquippedWithFurniture(RandomUtils.nextBoolean());
        home.setFloorsInTop(RandomUtils.nextBoolean());
        home.setOrientationEast(RandomUtils.nextBoolean());
        home.setOrientationNorth(RandomUtils.nextBoolean());
        home.setOrientationSouth(RandomUtils.nextBoolean());
        home.setOrientationWest(RandomUtils.nextBoolean());
        return home;
    }

    /**
     * Create a {@link OfficeFeatures} property type with some example data.
     *
     * @return created example object
     */
    private static OfficeFeatures createPropertyOffice() {
        // This is just a selection of attributes, supported for offices.
        OfficeFeatures office = new OfficeFeatures();
        office.setType(randomValue(OfficeFeatures.Type.values()));
        office.setAreaConstructed(BigInteger.valueOf(RandomUtils.nextLong(50, 1000)));
        office.setAreaUsable(BigInteger.valueOf(RandomUtils.nextLong(50, 1000)));
        office.setBuiltYear(BigInteger.valueOf(RandomUtils.nextLong(1990, 2020)));
        office.setAccessControl(RandomUtils.nextBoolean());
        office.setBathroomInside(RandomUtils.nextBoolean());
        office.setBathroomNumber(BigInteger.valueOf(RandomUtils.nextLong(0, 5)));
        office.setBathroomType(randomValue(BathroomType.values()));
        office.setConditionedAir(RandomUtils.nextBoolean());
        office.setConditionedAirType(randomValue(ConditionedAirType.values()));
        office.setEmergencyExit(RandomUtils.nextBoolean());
        office.setEmergencyLights(RandomUtils.nextBoolean());
        office.setEquippedKitchen(RandomUtils.nextBoolean());
        office.setExtinguishers(RandomUtils.nextBoolean());
        office.setFireDetectors(RandomUtils.nextBoolean());
        office.setFireDoors(RandomUtils.nextBoolean());
        office.setFloorsBuilding(BigInteger.valueOf(RandomUtils.nextLong(1, 10)));
        office.setSuspendedFloor(RandomUtils.nextBoolean());
        office.setOrientationEast(RandomUtils.nextBoolean());
        office.setOrientationNorth(RandomUtils.nextBoolean());
        office.setOrientationSouth(RandomUtils.nextBoolean());
        office.setOrientationWest(RandomUtils.nextBoolean());
        return office;
    }

    /**
     * Create an {@link Image} with some example data.
     *
     * @param order image position
     * @return created example object
     */
    private static Image createImage(int order) {
        Image image = new Image();
        image.setOrder(BigInteger.valueOf(order));
        image.setLabel(randomValue(Image.Label.values()));

        try {
            image.setUrl(new URI("https://example.com/image-" + order + ".jpg"));
        } catch (Exception ex) {
        }

        return image;
    }

    /**
     * Get a random value from an array.
     *
     * @param values array containing values to select from
     * @param <T>    type of contained values
     * @return randomly selected value
     */
    private static <T> T randomValue(T[] values) {
        return (values != null && values.length > 0) ?
                values[RandomUtils.nextInt(0, values.length)] :
                null;
    }
}

See a full example at IdealistaWritingExample.java.

Writing JSON in Idealista format

After a org.openestate.io.idealista.json.Customer object was created, it can be converted into a org.openestate.io.idealista.ImmobarItDocument with the static newDocument() function.

The class org.openestate.io.idealista.IdealistaRootElement provides a write() function, that finally writes the contents of the Customer object as JSON into a java.io.File, java.io.OutputStream or java.io.Writer.

import java.io.File;
import java.io.OutputStream;
import java.io.Writer;
import org.openestate.io.idealista.IdealistaRootElement;
import org.openestate.io.idealista.json.Customer;

public class IdealistaWritingExample {
    private final static boolean PRETTY_PRINT = true;

    /**
     * Convert a {@link Customer} to JSON and write it into a {@link File}.
     *
     * @param customer Java object representing the JSON root element
     * @param file     the file, where the document is written to
     * @throws Exception if the document can't be written
     */
    private static void write(Customer customer, File file) throws Exception {
        new IdealistaRootElement(customer)
                .write(file, PRETTY_PRINT);
    }

    /**
     * Convert a {@link Customer} to JSON and write it into an {@link OutputStream}.
     *
     * @param customer Java object representing the JSON root element
     * @param output   the stream, where the document is written to
     * @throws Exception if the document can't be written
     */
    private static void write(Customer customer, OutputStream output) throws Exception {
        new IdealistaRootElement(customer)
                .write(output, PRETTY_PRINT);
    }

    /**
     * Convert a {@link Customer} to JSON and write it into a {@link Writer}.
     *
     * @param customer Java object representing the JSON root element
     * @param output   the writer, where the document is written to
     * @throws Exception if the document can't be written
     */
    private static void write(Customer customer, Writer output) throws Exception {
        new IdealistaRootElement(customer)
                .write(output, PRETTY_PRINT);
    }

    /**
     * Convert a {@link Customer} to JSON and print the results to the console.
     *
     * @param customer Java object representing the JSON root element
     * @throws Exception if the document can't be written
     */
    private static void writeToConsole(Customer customer) throws Exception {
        System.out.println(
            new IdealistaRootElement(customer)
                .writeToString(PRETTY_PRINT)
        );
    }
}

See a full example at IdealistaWritingExample.java.