Skip to main content

the avatar of Efstathios Iosifidis

Μετατροπή αρχείου vdi του Virtual Box σε αρχείο raw img

Virtual Box αρχεία vdi σε img και αντίστροφα
Πολλοί φίλοι μου φοβούνται να εγκαταστήσουν μια διανομή Linux στον υπολογιστή τους. Πολλοί είναι οι λόγοι. Παλιά σίγουρα ήταν ότι δεν υπάρχουν προγράμματα. Τώρα νομίζω είναι ο φόβος της αποτυχίας στην εγκατάσταση και ίσως ότι αν τυχόν χαλάσει κάτι είτε στην εγκατάσταση είτε μετά, δεν θα βρουν τρόπο να το διορθώσουν. Στην ουσία, είτε windows, είτε Linux, η οδηγία είναι η αναζήτηση στο Internet μήπως κάποιος έχει αντιμετωπίσει το ίδιο πρόβλημα. Συνήθως, 90% θα βρεθεί ερώτηση με το ίδιο πρόβλημα και θα βρεθεί η λύση. Για να αποφύγουμε τον φόβο της "αποτυχίας", δυο είναι οι λύσεις.

ΕΠΙΛΟΓΗ 1: Η πιο εύκολη είναι να εγκαταστήσουν την διανομή σε Virtual Box (εικονική μηχανή).

ΠΛΕΟΝΕΚΤΗΜΑΤΑ:

  • Εγκατάσταση και δοκιμή (εγκατάσταση, κατατμήσεις, ρυθμίσεις κλπ) και αν γίνει κάποιο λάθος, διαγράφει ο χρήστης ένα αρχείο ενώ το host μηχάνημά με Windows ή MAC OSX δουλεύει κανονικά. Στην επόμενη δοκιμή απλά φροντίστε να μην κάνετε το ίδιο λάθος.

ΜΕΙΟΝΕΚΤΗΜΑΤΑ:

  • Περιορίζονται οι πόροοι (μνήμη, δίσκος) αφού χρειάζεται μνήμη και το host λειτουργικό σύστημα.
  • Το εικονικό λειτουργικό Linux μπορεί να έχει πρόσβαση στα αρχεία του host, μέσω ενός κοινόχρηστου φακέλου που θα δηλωθεί στο πρόγραμμα Virtual Box. Αντιθέτως μέσα από τα Windows δεν μπορεί κάποιος να έχει πρόσβαση στα αρχεία του εικονικού συστήματος Linux (έχει μόνο πρόσβαση στον κοινόχρηστο φάκελο).

ΕΠΙΛΟΓΗ 2: Η λίγο πιο δύσκολη λύση είναι η dual boot, δηλαδή να εγκατασταθούν στον ίδιο δίσκο, τόσο Windows όσο και Linux. Στην επιλογή αυτή θα εκτελείται ένα λειτουργικό σύστημα την φορά.

ΠΛΕΟΝΕΚΤΗΜΑΤΑ:

  • Kαι τα δυο λειτουργικά έχουν την απόλυτη επίδοση που μπορούν να έχουν όταν είναι σε λειτουργία.

ΜΕΙΟΝΕΚΤΗΜΑΤΑ:

  • Δεν υπάρχει πρόσβαση αρχείων από τα Windows στον δίσκο με το Linux (μόνο εάν έχει εγκατασταθεί πρόγραμμα). Η λύση δίνεται μόνο εάν δημιουργηθεί μια κατάτμηση NTFS όπου θα προσαρτείται τόσο στα Windows όσο και στο Linux και εκεί αποθηκεύονται τα αρχεία.
  • Δυσκολία για έναν αρχάριο να διαχειριστεί τις κατατμήσεις κατά την εγκατάσταση. Από τη στιγμή που αυτό λυθεί, μετά δεν υπάρχει κάποια δυσκολία.


Ίσως μια τρίτη επιλογή θα ήταν το Live ISO αλλά δεν κερδίζει κάποιος κάτι από αυτή την επιλογή. Δεν διατηρούνται ρυθμίσεις (υπάρχει η επιλογή του persistent storage αλλά προσωπικά δεν την εμπιστεύομαι).

ΠΡΟΒΛΗΜΑ

Θέλω να εγκαταστήσω Linux αλλά φοβάμαι επειδή δεν γνωρίζω. Θα εγκαταστήσω σε Virtual Box για να μάθω την διαδικασία.

Αυτή είναι η φράση που έχει χιλιοειπωθεί. Όταν πετύχουν την εγκατάσταση, μετά υπάρχει η "βαρεμάρα" να το στήσει κάποιος σε κανονικό μηχάνημα από την αρχή.

ΛΥΣΗ

Η λύση έρχεται να δοθεί εν μέρη με την μετατροπή του εικονικού λειτουργικού σε img όπου στη συνέχεια μπορεί να περαστεί σε κανονικό υπολογιστή. Εδώ θα δούμε πως γίνεται τόσο σε Windows, όσο και σε Linux (ουσιαστικά είναι η ίδια διαδικασία-εντολή).

WINDOWS

Σε Windows, ανοίξτε το τερματικό (cmd ή Command Line) και μετακινηθείτε στον κατάλογο:
cd "C:\Program Files\Oracle\VirtualBox"

Εδώ θα βρείτε το πρόγραμμα VBoxManage. Στη συνέχεια πρέπει να αντιγράψετε την παρακάτω εντολή:
VBoxManage clonehd --format RAW “C:\Users\stathis\VirtualBox VMs\opensuse\opensuse.vdi” “C:\Users\stathis\VirtualBox VMs\opensuse\opensuse.img”

Ας εξηγήσουμε λίγο το σενάριο. Στην παραπάνω εντολή υποθέτουμε ότι έχετε εγκαταστήσει openSUSE. Η εγκατάσταση έγινε μέσα στον φάκελο opensuse. Οπότε το όνομα του αρχείου που δημιουργήθηκε είναι opensuse.vdi. Προσέξτε λίγο και τον χρήστη (stathis). Πρέπει να δώσουμε την ακριβή διαδρομή που βρίσκεται το αρχείο vdi. Και επειδή σίγουρα θα έχει κενά κάπου, καλύτερα να χρησιμοποιήσετε και τα "".

Περιμένετε λίγο και θα έχετε έτοιμοι το αρχείο opensuse.img. Τι μπορείτε να κάνετε με αυτό; Μπορείτε να χρησιμοποιήσετε κάποιο live usb και να αντιγράψετε με την εντολή dd (ή άλλο εργαλείο) από ένα εξωτερικό μέσο στον δίσκο του υπολογιστή.

LINUX

Εδώ ίσως είναι ακόμα πιο εύκολα τα πράγματα. Ανοίξτε το τερματικό και μετακινηθείτε στον φάκελο με τα VM (VirtualBox VMs). Αφού το κάνετε αυτό, εκτελέστε την εντολή:
VBoxManage clonehd --format RAW ubuntu.vdi ubuntu.img

Στο σενάριο εδώ, έχουμε εγκαταστήσει ένα σύστημα με Ubuntu και θέλουμε να το μεταφέρουμε σε έναν υπολογιστή. Το αρχείο ubuntu.img το αντιγράφουμε σε ένα δίσκο και μετά με live usb και την εντολή dd το μεταφέρουμε σε υπολογιστή.

ΑΝΤΙΣΤΡΟΦΗ ΔΙΑΔΙΚΑΣΙΑ

Μπορείτε να κάνετε και την αντίστροφη διαδικασία. Εάν έχετε ένα πλήρως λειτουργικό σύστημα, μπορείτε να δημιουργήσετε ένα αρχείο img (με την εντολή dd). Στη συνέχεια μετατρέπετε το img σε vdi με την παρακάτω εντολή:
VBoxManage convertdd opensuse.img opensuse.vdi

Στη συνέχεια δημιουργούμε μια νέα εικονική μηχανή:
Δημιουργία εικονικής μηχανής στο Virtual Box
Σειρά έχει ο καθορισμός της μνήμης (8 είναι το μινιμουμ αλλά αν εσείς έχετε λιγότερη, προσαρμόστε ανάλογα):
Καθορισμός μνήμης στο Virtual Box
Τέλος η εισαγωγή του αρχείου vdi που δημιουργήσατε ως υπάρχοντας σκληρός δίσκος:
Εισαγωγή αρχείου vdi στο Virtual Box ως νέος σκληρός δίσκος
Περιμένετε λίγο μέχρι να το περάσει στην λίστα με τα εικονικά λειτουργικά που έχετε εγκατεστημένα. Τα στοιχεία του χρήστη θα είναι αυτά που είχατε κατά τη δημιουργία του img.

Εάν έχετε και εσείς κάποιον φίλο-γνωστό που φοβάται να εγκαταστήσει Linux ενώ το θέλει, ενημερώστε τον για τις παραπάνω διαδικασίες.
the avatar of openSUSE News

openSUSE Leap 15.3 Reaches Beta Build Phase

openSUSE Leap has entered into the beta release phase today for its 15.3 minor version.

This openSUSE Leap 15.3 version is a solidified release that focuses more on the building of the distribution rather than refreshing the distribution’s packages, but there are some significant changes to the distribution.

Many of the packages will remain the same as those in openSUSE Leap 15.2 with a bit of hardware enablement and security backports. An updated version of glibc brings some Power10 support and the Xfce desktop users will have the new 4.16 version. The distribution also gains adds s390x architecture.

The biggest change for this release is how Leap is built and its relationship with SUSE Linux Enterprise. Leap transitioned to a new way of building openSUSE Leap releases in the fall of 2020 through a prototype project called Jump. The Jump prototype was used as a proof of concept, but no longer exists; it did prove to work at building a distribution and bringing the code streams of both openSUSE Leap and SLE closer together. The proof of concept was implemented for building the release of openSUSE Leap 15.3 as seen in the beta release today. Building Leap on top of binary packages from SLE, which was part of the rationale for the Jump prototype, allows for easy development on a community release to be put into production on an enterprise release should the need arise.

The changes make the migration from openSUSE Leap 15.3 to SLE 15 Service Pack 3 practically instantaneous and there are no socket or virtual machine limitations. A little more than 50 packages are not identical with SLE, but these are mostly branding, patterns and openSUSE branding packages.

Entering this beta phase, testers are encouraged to test the migration from Leap to SLE. People testing the beta are encouraged to record their Leap Beta testing efforts on the following spreadsheet: https://docs.google.com/spreadsheets/d/1AGKijKpKiJCB616-bHVoNQuhWHpQLHPWCb3m1p6gXPc/edit#gid=801313279

Leap beta testers have an option to receive a T-shirt, so make sure to fill in all the proper information and bug reports to get one. Then send an email to ddemaio (at) opensuse.org with your address, size and name corresponding to the spreadsheet. Please make the subject title “beta test t-shirt”.

Bugs should be reported on openSUSE’s bugzilla and if any are found on SLE should be reported to SUSE’s bugzilla products for desktop, server and High Availability.

Leap has a rolling development model during both its Alpha and Beta phases. After the gold master and Public Availability of Leap is released, the rolling development model stops; the release then shifts into a supported release model with maintenance and security updates until its End of Life (EOL). Leap has an extended life cycle greater than 12 months per release. Leap ideal for desktop and server environments.

There are no concrete milestones in the Leap rolling development model. As bugs are fixed and new packages introduced or excluded, snapshots of the latest beta phase builds will be released once they pass openQA testing; this will take place over the next few months as the road map shows openSUSE Leap 15.3 will be have a Release Candidate in late April and the Gold Master on May 21, which will be follow by a public release on June 2. The documentation and translations deadline is May 14.

Architectures available for testing include x86_64, aarch64, PowerPC and s390x. People interested in armv7 and other architectures should read the announcement about openSUSE Step.

Those interested in beta testing images for openSUSE Leap 15.3 Windows Subsystem for Linux can contact the Leap release manager Luboš Kocman or the factory mailing list.

a silhouette of a person's head and shoulders, used as a default avatar

Lanzada la segunda actualización de Plasma 5.21

Tal y como estaba previsto en el calendario de lanzamiento de los desarrolladores, hoy martes 2 de marzo la Comunidad KDE ha comunicado que ha sido lanzada la segunda actualización de Plasma 5.21. Una noticia que aunque es esperada y previsible es la demostración palpable del alto grado de implicación de la Comunidad en la mejora continua de este gran entorno de escritorio de Software Libre.

Lanzada la segunda actualización de Plasma 5.21

No existe Software creado por la humanidad que no contenga errores. Es un hecho incontestable y cuya única solución son las actualizaciones. Es por ello que en el ciclo de desarrollo del software creado por la Comunidad KDE se incluye siempre las fechas de las actualizaciones.

Lanzada la segunda actualización de Plasma 5.21
Lanzada la segunda actualización de Plasma 5.21

De esta forma, el martes 2 de marzo ha sido lanzada la segunda actualización de Plasma 5.21, la cual solo trae (que no es poco) soluciones a los bugs encontrados en esta semana de vida del escritorio y mejoras en las traducciones. Es por tanto, una actualización 100% recomendable.

Más información: KDE

Las novedades básicas de Plasma 5.21

Os dejo las novedades más destacada de esta nueva versión son:

  • Nuevo lanzador de aplicaciones que presenta una interfaz de usuario de doble panel, mejoras en la navegación con el teclado y con el ratón, mejor accesibilidad y soporte para idiomas con escritura de derecha a izquierda.
  • Mejoras visuales en el tema por defecto de Plasma que disponen ahora de una combinación de colores renovada y lucen un nuevo estilo de barra de encabezado unificado con un aspecto limpio y refrescante.
  • Presentación de Breeze Crepúsculo («Twilight») nevo tema oficial disponible que combina lo mejor de los temas claros y oscuros.
  • Nueva interfaz de información del sistema llamdo Plasma System Monitor para monitorizar los recursos del sistema construido sobre Kirigami y un servicio de estadísticas del sistema llamado «KSystemStats».
  • Mejoras y avances importantes en Kwin con Wayland cuyo código de composición de KWin se ha refactorizado mejorando la latencia (tiempo de respuesta del escritorio) .
  • Nueva página para las «Preferencias del sistema»: las preferencias del cortafuegos de Plasma. Este módulo de configuración le permite ajustar y editar el cortafuegos de su sistema y constituye una interfaz gráfica para «UFW» y «firewalld».
a silhouette of a person's head and shoulders, used as a default avatar

Plasma Brezze oscuro especial para #openSUSE

Puedes “vestir” tu escritorio Plasma de KDE con un tema oscuro especialmente pensado para openSUSE

Los escritorios de nuestras distribuciones GNU/Linux están hechos para que los acomodemos a nuestro gusto hasta los más pequeños detalles. Y si hablamos de personalización, quizás el escritorio que gana en posibilidades es Plasma de la comunidad KDE.

La propia comunidad de KDE hizo un gran trabajo con el tema Breeze. Un tema de colores, Plasma, iconos, etc. que supusieron un gran salto visual en cuanto a diseño, con lo que había anteriormente.

Desde hace un tiempo, me decanté por temas oscuros en mi escritorio, por ser más cómodos para mis ojos, que el omnipresente blanco de los temas claros que causan más fatiga visual. Y utilizaba Plasma Breeze Dark.

Para aquellos que disfrutamos de estos temas oscuro, ahora tenemos otra opción más que podemos probar y dejar como opción predeterminada en nuestra distribución GNU/Linux openSUSE.

Se trata de openSUSE Breeze Dark Plasma Style, un estilo para Plasma de KDE inspirado en el trabajo de Breeze Dark. También está disponible un tema de colores llamado openSUSE Breeze Dark Plasma Scheme.

Todo esto le da un tono oscuro a tu openSUSE con el gran trabajo de Plasma Breeze pero añadiéndole unos toques verdes para que encajen con el color de openSUSE.

Por supuesto que no es exclusivo para openSUSE y que podrás utilizar en tu distribución de GNU/Linux, sea cual sea, siempre que utilices Plasma.

Estos dos aportes los ha realizado Nate, y ya está pensando en crear un tema global con estos elementos para que este disponible para KDE. Sería una buena idea que la comunidad de openSUSE los utilizara como temas predeterminados cuando se utilice el tema oscuro.

Para instalarlos, lo podemos hacer fácilmente desde los “Ajustes de sistema” de Plasma en el apartado de Aspecto → Estilo de Plasma o Aspecto → Colores y pulsando sobre el botón Obtener nuevos. Y filtrando por más recientes o buscándolos simplemente por sus nombres.

Como verás es muy sencillo de probar y quedarte con este nuevo aspecto a tu distribución si te gusta. Yo desde que se ha publicado me lo he quedado ¿y a ti te gusta?

Enlaces de interés

a silhouette of a person's head and shoulders, used as a default avatar
a silhouette of a person's head and shoulders, used as a default avatar
darix posted in English at

Jitsi: Turning off Automatic Gain Control

TL;DR

Operating systems let you customize the sensitivity of the microphone allowing you to suppress environmental noise such as keyboard strokes. Video conferences software unfortunately tends to override such settings using autogain making your customization void. While some video conferencing tools let you control autogain via the settings, Jitsi does not have such an option.

However, you can use https://your.jitsi.server/someroom#config.disableAGC=true when joining your Jitsi meetings to disable autogain and have more control over your microphone.

the avatar of YaST Team

Digest of YaST Development Sprint 118

It has been three weeks since the previous development report from the YaST Team. That’s one week more than our usual cadence, since most of the team was booked during four days in an internal SUSE workshop. But fear no more, we are back and loaded with news as usual. This time we bring:

  • Support to enable and configure SELinux during installation
  • A revamped interface for configuring wireless network devices
  • Usability improvements in several areas
  • A new “hidden level” in the installer with advanced tools ;-)

You may know that both the SUSE and openSUSE families of operating systems include container-oriented members, namely openSUSE MicroOS and SLE Micro. In order to make them even more awesome, we got the request to make possible to propose and configure the usage of Security-Enhanced Linux, more widely known as SELinux, during the (auto)installation. This is a complex change affecting several parts of YaST and various versions of (open)SUSE, but you can get a good overview in the description of this pull request which includes some screenshots that may be worth a thousand words. Right now, the feature may look different on each one of the distributions due to the different state of SELinux on them. While in SLE Micro the new setting is visible during installation and activated at its more restrictive level, in others it may look more permisive or even not be presented at all. We expect things to consolidate during the upcoming weeks.

And talking about things that take their time, for a long time we had wanted to improve the usability of the configuration of wireless network adapters. Finally we found the time to reorganize the corresponding tab in the YaST Network module, improving the mechanism to select a wireless network and automatically pre-filling as much information as possible. You can see the result in the following animation and in the detailed pull request with the usual before-and-after screenshots.

The new wireless configuration in action

That’s not the only usability improvements we implemented during this sprint. Now the Partitioner offers more useful information about file-systems that need to be unmounted in advance and presents a more sensible initial state for the collapsable branches in its tables. YaST Network permits to tweak the virt bridge interface during manual installation and reports AutoYaST errors more nicely. Last but not least in the usability field, we improved how long texts are managed and presented in most YaST pop-up dialogs.

If you are still not impressed with all the new things this sprint brought, we can give you a sneak peak on something we have been preparing lately to give power-users more… er… power. ;-) As you all know, YaST is already a pretty advanced installer offering many options. And it’s very configurable so it can be tweaked to behave differently depending on the distribution, the product or the system role selected by the user. But believe it or not, we still face situations in which we would like to configure the installer even more during its execution to overcome some obstacle found in a very special scenario or just for debugging purposes. How do we plan to do it? Meet the new YaST installation console, available through the even newer installer configuration screen!

While we dive into the beta phase of openSUSE Leap 15.3 and SLE-15-SP3, the YaST Team will focus during the next weeks in fixing the bugs found by the testers of those upcoming distributions, which implies we cannot give you a fixed date for the next development report, but it will be for sure during March. Meanwhile, stay tuned and do not hesitate to report any significant bug you can find in YaST or in openSUSE in general. See you soon(ish)!

a silhouette of a person's head and shoulders, used as a default avatar

Slimbook se convierte en patrocinador de KDE

Como buen blog sobre KDE me tengo que hacer eco de esta noticia, aunque no sea primicia y haya aparecido en otros sitios como MUy Linux.Y es que es importante para conocer un poco mejor como funciona la fundación KDE y cómo seguir constatando que poco a poco más y más empresas creen que la colaboración con el Software Libre es algo que beneficia a todos y todas. Así que congratula comentar que Slimbook se convierte en patrocinador de KDE, en otras palabras, una nueva voz con voto en el desarrollo del proyecto KDE… y una voz que es bastante conocida en este humilde blog.

Slimbook se convierte en patrocinador de KDE

El pasado jueves 25 de febrero de 2021 se anunció oficialmente que KDE tiene un nuevo patrocinador. Se trata de Slimbook una empresa que se dedica a ensamblar todo tipo de dispositivos (portátiles ligeros pero potentes, dispositivos All-in-One, portátiles gamers, torres espectaculares, minipcs, etc) 100% compatibles con los sistemas GNU/Linux. En el blog he hablado mucho de ellos, así que solo tenéis que seguir este enlace para conocerlos a fondo… solo añadiré que son más que una empresa.

Así que me llena de alegría conocer que Slimbook se convierte en un patrocionador del projecto de la Comunidad KDE aportando su visión empresarial al desarrollo de las tecnologías libres KDE, un paso más en la gran relación que ha tenido la empresa con la Comunidad y que ha tenido sus frutos en los KDE Slimbook.

Slimbook se convierte en patrocinador de KDE

Este anuncio ha llenado de satisfacción tanto al Presidente de KDE e.V. Aleix Pol y a Alejandro López, CEO de Slimbook, cuyo trabajo conjunto es el responsable de la aparición de los dispositivos antes mencionados.

De esta forma Aleix ha comentado que «la atención de Slimbook hacia los usuarios de FOSS como proveedor de hardware es muy importante para KDE y la comunidad en general. Para KDE, poder llegar más allá de la experiencia del software a soluciones tangibles y debidamente integradas ha sido un sueño hecho realidad. Trabajar juntos en las diferentes colaboraciones a lo largo de los años ha sido realmente emocionante, y esperamos seguir haciéndolo con Slimbook como patrocinador.»

Slimbook se convierte en patrocinador de KDE

Por otra parte, Alejandro López explicó que «Desde nuestros inicios en 2015, en SLIMBOOK nos esforzamos al máximo no solo por vender hardware de calidad compatible con GNU/Linux, sino también por contribuir y ayudar a los que hacen Software Libre y de Código Abierto.

Nuestra variedad de contribuciones van desde dar apoyo a grupos locales de desarrolladores, la realización de foros y tutoriales para ayudar a la comunidad Linux y compartir una visión común con KDE, para llegar al mercado con un dispositivo capaz de proporcionar al usuario final la mejor experiencia de Linux out-of-the-box disponible.

Slimbook se convierte en patrocinador de KDE

Pero nuestra misión no termina ahí y hay más de lo que parece. Nuestro principal objetivo es compartir nuestro conocimiento y experiencia, ayudarnos mutuamente y, por supuesto, dar a los usuarios de GNU/Linux lo mejor en excelencia de hardware de la misma manera que el equipo de KDE lo hace con su excelente experiencia de software.

Nos tomamos nuestro deber de apoyar a la Comunidad KDE con mucho orgullo, y nos sentimos honrados de ser Patronos de KDE».

De esta forma, Slimbook se une a otras compañías en su alianza con KDE: The Qt Company, SUSE, Google, Blue Systems, Canonical, Private Internet Access y enioka Haute Couture para continuar apoyando el Software Libre y el desarrollo de los proyectos KDE a través de KDE e.V.

Más información: KDE.News

the avatar of openSUSE News

Call for Papers Open for openSUSE Conference

The call for papers for the openSUSE Virtual Conference is open!

The call for papers is open until May 4. This leaves a little more than 60 days to submit a proposal. The dates of the conference are scheduled for June 18 - 20. Registration for the conference has also begun.

Presentations can be submitted for the following length of time:

  • Lightning Talks (15 mins)
  • Normal Talk (30 mins)
  • Long Talk (45 mins)
  • Workshop (1 hour)

The following tracks are listed for the conference:

  • Cloud and Containers
  • Community
  • Embedded Systems and Edge Computing
  • New Technologies
  • Open Source
  • openSUSE

The conference already has two sponsors with Fedora and SUSE. Companies interested in sponsoring the event can view the sponsorship prospectus on the project’s wiki page.

Volunteers who would like to help the Program Committee and/or the Organizing Team can email ddemaio@opensuse.org.

the avatar of Nathan Wolf

LCD Chalkboard Smart Sign, Raspberry Pi Powered

Whenever technology and art meet in a very useful product, I can’t help but get excited and think about the applications of where a thing can be used. Instructables, yet again provides another incredible idea for something you can build as a life enhancement. I find the notion of combining a chalk board and a … Continue reading LCD Chalkboard Smart Sign, Raspberry Pi Powered
a silhouette of a person's head and shoulders, used as a default avatar

Revisiting Html in Java

Some time ago I wrote a post about creating an embedded dsl for Html in Java. Sadly, it was based on an abuse of lambda name reflection that was later removed from Java.

I thought I should do a followup because a lot of people still visit the old article. While it’s no longer possible to use lambda parameter names in this way, we can still get fairly close. 

The following approach is slightly less concise. That said, it does have some benefits over the original:

a) You no longer need to have parameter name reflection enabled at compile time.

b) The compiler can check your attribute names are valid, and you can autocomplete them.

What does it look like? 

html(
   head(
       title("Hello Html World"),
       meta($ -> $.charset = "utf-8"),
       link($->{ $.rel=stylesheet; $.type=css; $.href="/my.css"; }),
       script($->{ $.type= javascript; $.src="//benjiweber.co.uk/some.js"; })
   ),
   body(
       div($-> $.cssClass = "article",
           a($-> $.href="https://benjiweber.com/",
               span($->$.cssClass="label", "Click Here"),
               img($->{$.src="//benjiweber.co.uk/htmldsl2.png"; $.width=px(25); $.height=px(25); })
           ),
           p(span("some text"), div("block"))
       )
   )
)

This generates the following html

 
   Hello Html World
   
   
   
 
 
   
Click Here

some text

block

You get nice autocompletion, and feedback if you specify inappropriate values:

You’ll also get a helping hand from the types to not put tags in inappropriate places:

Generating Code

As it’s Java you can easily mix other code to generate markup dynamically:

assertEquals(
       """
       
         
           
         
         
           

Paragraph one

Paragraph two

Paragraph three

""".trim(), html( head( meta($ -> $.charset = "utf-8") ), body( Stream.of("one","two","three") .map(number -> "Paragraph " + number) .map(content -> p(content)) ) ).formatted() );

And the code can help you avoid injection attacks by escaping literal values: 

assertEquals(
       """
       
         
           
         
         
           

<script src="attack.js"></script>

""".trim(), html( head( meta($-> $.charset = "utf-8") ), body( p("") ) ).formatted() );

How does it work?

There’s only one “trick” here that’s particularly useful for DSLs. Using the Parameter Objects pattern from my lambda type references post. 

The lambdas used for specifying the tag attributes are “aware” of their own types. And capable of instantiating the configuration they specify.

When we call 

meta($ -> $.charset="utf-8")

We make a call to 

default Meta meta(Parameters params, Tag... children) { … }

The lambda specifying the attribute config is structurally equivalent to the Parameters<Meta> type. This provides a get() function that instantiates an instance of Meta, and then passes the new instance to the lambda function to apply the config.

public interface Parameters extends NewableConsumer {
   default T get() {
       T t = newInstance();
       accept(t);
       return t;
   }
}

Under the hood the newInstance() method uses reflection to examine the SerializedLambda contents and find the type parameter (in this case “Meta”) before instantiating it.

You can follow the code or see the previous post which explains it in a bit more detail.

Add Mixins

It’s helpful to use interfaces as mixins to avoid having to have one enormous class with all the builder definitions. 

public interface HtmlDsl extends
   Html.Dsl,
   Head.Dsl,
   Title.Dsl,
   Meta.Dsl,
   Link.Dsl,
   Script.Dsl,
   Body.Dsl,
   Div.Dsl,
   Span.Dsl,
   A.Dsl,
   P.Dsl,
   Img.Dsl {}

Each tag definition then contains its own builder methods. We compose them together into a single HtmlDsl interface for convenience. This saves having to import hundreds of different methods. By implementing the Dsl interface a consumer gets access to all the builder methods.

Show me the code

It’s all on github. I’d start from the test examples. Bear in mind that it’s merely a port of the old proof of concept to a slightly different approach. I hope it helps illustrate the technique. It’s in no way attempting to be a complete implementation.

This approach can also be useful as an alternative to the builder pattern for passing a specification or configuration to a method. There’s another example on the type references article.

What else could you use this technique for?

The post Revisiting Html in Java appeared first on Benji's Blog.