Spring Framework – file upload using ConversionService

Sometimes, when creating web application, we want to enable user to upload files to a server.

The uploaded file can be an image, document or any other regular file.
Developing our application using Spring should be relatively simple, so we need simple method for uploading files using this beautiful framework :-).

In our example I’ll use a Company entity, which among the others will contain an Image object with Data of the image and its name.

My Company entity looks like this:

@Entity
@Table
public class Company {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	@ManyToOne(cascade = CascadeType.ALL)
	private Address address;
	@NotEmpty
	private String name;
	@OneToOne(cascade = CascadeType.ALL)
	private Image image;
... accessors ommitted
}

As you can see I need company Address, Name and the Image.
In this example image is identified by name and data (content of image file), but you can do whatever you want with uploaded data, during conversion process.

On Spring Framework’s  documentation sites we can see a usage of custom editor support to convert file uploaded using HTML form into regular Java object.

I went in a different way and used ConversionService to easily convert file from HTTP POST request, which is more comfortable for me.
If you want to use ConversionService you’ll need to create a converter, which implements org.springframework.core.convert.converter.Converter interface.

Let’s create converter then:

...
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.multipart.MultipartFile;
...
public class MultipartFileToImageConverter implements Converter<MultipartFile, Image> {
	@Override
	public Image convert(final MultipartFile source) {
		final Image image = new Image();
                image.setData(source.getBytes());
		image.setName(source.getOriginalFilename());
		return image;
	}
}

We need to register our converter in conversion service, so in application context we add:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="converters">
		<set>
			<bean class="pl.greenpath.converter.MultipartFileToImageConverter">
		</set>
	</property>
</bean>

I use annotation-based configuration of controllers, so configuration of controller is pretty straightforward:

        @Autowired
        CompanyService _companyService;
        ...
	@RequestMapping(value = "", method = RequestMethod.POST)
	public String doEdit(@Valid final Company company, final Errors errors) {
		if (errors.hasErrors()) {
			return "admin/companies/edit";
		} else {
			_companyService.save(company);
			return "redirect:/admin/companies/" + company.getId();
		}
	}

Going this way we have company object with filled data from HTML form.
To obtain image data we just need to invoke e.g. company.getImage().getName();

The main advantage of this solution is its simplicity. You don’t need to create configuration of editors in your controller. All you need is to create a converter and register it in ConversionService. Spring will do all other stuff for you.

I hope it will help simplifying your web app ;-)

To-Read sites 4.0

I’ve just uploaded new version of To-Read sites extension into Opera Extensions portal.

By now extension is awaiting moderation and it should be available after 1st of January.

 

New version brings:

1. Sites synchronization which enables you share sites between many browsers.

I used Opera Link JS Api (thanks  Joel) to synchronize sites so all you need is My Opera account.

 

2. Turkish translation (thanks to Samet from operaturkiye.net).

 

All we need is to wait for moderation to be complete :)

Find To-Read sites on Opera Extensions portal.

 

 

 

To-Read Sites v.3 – introducing export/import feature.

I’ve just updated To-Read Sites to 3.0 version.

The new release brings export and import feature. Now you can easily save your sites to a file and move it to another Opera instance.

To use the new feature right-click on To-Read Sites extension button and go to “preferences”.

To-Read Sites preferences window.

You can download the new version here: https://addons.opera.com/addons/extensions/details/to-read-sites/

Enjoy :)

How to create multilingual Opera Extension

Opera supports multilingual extensions and creating such one is quite easy. Let’s start with config.xml file

<?xml version='1.0' encoding='utf-8'?>
<widget xmlns="http://www.w3.org/ns/widgets" id="extensions:to-read-sites" version="2.1-3">
	<name>To-Read sites</name>
	<description xml:lang="en">Temporary list of sites you want to 	visit later.</description>
	<description xml:lang="pl">Poręczna lista stron, które chcesz odwiedzić później.</description>
	<description xml:lang="ru">Список сайтов, которые вы хотите посетить позже.</description>
	<icon src="icon.png"/>
	<icon src="icon_16.png" width="16" height="16"/>
	<author href="http://www.greenpath.pl">Michał Borek</author>
	<access origin="*" subdomains="true"/>
</widget>

To translate config.xml values you need to add xml:lang attribute into particular nodes. You can apply this attribute into nodes as follows:

  • name
  • description
  • license

You can also define text flow direction by defining dir attribute, the same way as the one above:

  • ltr – left to right
  • rtl – right to left
  • lro – left to right override
  • rlo – right to left override

Another thing we must deal with is translating extension itself. Fortunately Opera provides locales folder for all files connected to translations.

Extension folder structure of extension.

All files that need to be translated should be put in specific subfolder in locales folder (pl for Polish, ru for Russian and en for English in our case). When you create a file in one of locales’ subfolder it will be automatically for specific language. Example:

<link rel="stylesheet" href="styles/style-translation.css"/>

Opera will try to find such file in one of locales’ folder and if there is no such file, the default one will be loaded (from root folder). For English it would be:  locales/en/styles/style-translation.css. To translate buttons’ labels you can use CSS content attribute as follows:

#addButton {
	content: "Add current";
}

To change another values (like anchor titles, error messages and so on) you can create translations files. I used popup.js to achieve this goal:

var tr = {
	addButtonLabel: "Add current page to list",
	deleteButtonLabel: "Delete site from the list",
	lockButtonLabel: "Lock site"
};

All you need is to use tr.* values instead of literal strings in your extension. I hope this article will simplify your Opera Extension development process. If you have any suggestions or questions, feel free to post a comment.

To-Read sites – minor update

I’ve just updated To-Read sites Opera extension removing an annoying bug (site is not being deleted from list) and making visual improvements:

  • I changed badge color, because it was annoying for some of you.
  • Sites list haven’t been centered (it looked odd) – it looks fine now.

To-Read sites 2.1-2

New version will be available on http://addons.opera.com shortly.

Many of this extension users asked me about syncing – it’s in plans. But I really have no time to do it now, but I hope I will finish that soon, please be patient :-).

OMeasure! 2.0 – available soon

I’ve just uploaded new version of OMeasure! plugin.

New version brings possibility to resize measuring area and few visual improvements.

I’ve changed HTML5 Canvas drawing used in v.1.0 to DOM based one and it’s easier to make detailed result.

OMeasure! 2.0 in action

New version should be available shortly via Opera Addons page.

OMeasure! – my new Opera Extension

Starting from this post I’m switching to English.

Yesterday Opera published my second extension – OMeasure!

OMeasure! is a simple tool for web developers which simplifies measuring of elements of web sites.

You can download OMeasure! here:

https://addons.labs.opera.com/addons/extensions/details/omeasure/1.0-2/

Known bugs:

Doesn’t work on https sites.

Opera Extensions – moje pierwsze rozszerzenie

Od wersji 11.0 Opera zacznie wspierać rozszerzenia (tzw. extensiony).
Dziś stworzyłem pierwsze rozszerzenie do Opery, które pozwala na dodawanie stron “do przeczytania później”.

Opera 11.0 zawiera jednak drobny błąd, więc funkcjonalność jest chwilowo ograniczona (opisane jest to poniżej).

Aby ominąć błąd należy przełączyć karty (dowolne 2 karty). Po zainstalowaniu wtyczki, najlepiej zresetować przeglądarkę (wyłączając też wszystkie karty).

Rozszerzenie tymczasowo można ściągnąć tutaj:  to-read-sites.1.0.oex

Nokia Maps – darmowe mapy od Nokii

Jakiś czas temu sprzedałem IPhona i wróciłem do Nokii. Zdecydowałem się na model E72, nie wiedząc nawet, że od niedawna Nokia udostępnia za darmo nawigację, a E72 ma wbudowany GPS.

Początkowo nie wierzyłem, że jest to możliwe.. myślałem “gdzieś musi być haczyk”. Ale nie! Od ok. miesiąca testuję nawigację i jest kapitalna.

Oferuje wszystko co pełnoprawna nawigacja (za kilkaset zł), a w porównaniu do AutoMapy, z której korzystałem jest naprawdę dokładna (Automapa chciała mnie wykąpać w jeziorze :)).

Miłym zaskoczeniem było dla mnie również powiadamianie o fotoradarach ;-)

Poniżej screen z nawigacji w użyciu (zaznaczę, że Internet nie jest w ogóle potrzebny. Cała mapa jest w środku).

Nokia Maps w użyciu.

Opera 10.50

Światło dzienne ujrzała nowa wersja przeglądarki Opera, oznaczona numerkiem 10.50 (zamiennie z 10.5 ;)).

Biorąc pod uwagę spowolnioniony rozwój i “rewolucyjność” kolejnych wersji Opery w przeciągu ostatniego roku, wersja 10.50 jest rewolucyjna.

Do głównych zalet zaliczyłbym:

  • Karty na pasku tytułu (Win7 style).
  • Niesamowita szybkość JavaScriptu (nowy silnik JS).
  • Lepsze uzupełnianie na pasku adresów.
  • Większa możliwość zmiany wyglądu (przyciski na dole ekranu itd.).
  • Lepsze wsparcie dla DragonFly (“Przegląd elementu”).
  • No i coś, czego nie było chyba tylko w Operze, Porno Browsing (ups. Private Browsing :)).

Deweloperzy Opery narzucili bardzo szybkie tempo, jeżeli chodzi o wydawanie kolejnych wersji alpha, beta i RC, co skutkowało szybkim wykrywaniem błędów i wypuszczeniem nowej Opery w tak krótkim czasie (pierwsza wersja alpha ujrzała światło dzienne na przełomie lat 2009/2010 .

Entuzjastą Opery jestem stosunkowo od niedawna, ale  mam nadzieję, że zostanę na długo. Czasem jeszcze muszę włączyć starego, poczciwego Firefoksa, ale fakt że w międzyczasie mogę zrobić sobie herbatę jakoś nie nastraja mnie pozytywnie :).

Link do strony Opery: http://my.opera.com/community/download.pl?ref=michalborek&p=opera_desktop.