Posty

Angularjs example MotoAds more advanced directive

Obraz
Another thing we will add to MotoAds demo application is a feature which allows us to comment each advert. A good idea would be to realize this as AngularJS directive. It will look like in the picture below. We can see all added comment to advert, click on Comment link activate the comment form with Preview, Send and Cancel buttons. The comment form we will realize as AngularJS directive. Before we start let's look at changed adverts.json , there is the additional comments field (array of comments): [ { "brandName": "Audi", "modelName": "A1", "year": 2011, "price": 35000, "imageUrl": "img/audi_a1_1.jpg", "countryName": "Germany", "regionName": "Bavaria", "comments" : [ "This car is awesome I want it\nBeatiful color\nFunny look", "Very cool vehicle\nJust perfect" ] } ] ]]...

Java ESL program for connecting to the FreeSWITCH

Next simple Java program using Event Socket interface to control FreeSWITCH. First you should read: Mod event socket on wiki freeswitch Java ESL Client on wiki freeswitch Next you should not forget to change event_socket.conf.xml (to allow connections from any host on the network): Now we can write simple java ESL program for connecting to the FreeSWITCH. MyEslEventListener.java package myeslevent; import java.util.Map; import java.util.Set; import org.freeswitch.esl.client.IEslEventListener; import org.freeswitch.esl.client.transport.event.EslEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyEslEventListener implements IEslEventListener { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Override public void eventReceived(EslEvent event) { log.info("eventReceived [{}]\n[{}]\n", event, getEventToLog(event)); } @Override public void backgroundJobResultReceived(EslEve...

Java program for connecting to the FreeSWITCH XML-RPC

I would like to show simple Java program which use XML-RPC interface to do some freeswitch commands. We should on freeswitch console load mod_xml_rpc: Worth checking out if it works, in web browser type: http://fshost8080/webapi/help If you see "FreeSWITCH help" it works. Next we download Apache XML-RPC library. Now we create Java program (using Apache XML-RPC): package fstest1; import java.net.URL; import java.util.Scanner; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; public class FsTest1 { public static void main(String[] args) { System.out.println("------ hello freeswitch -------\n"); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); XmlRpcClient client = new XmlRpcClient(); try { config.setServerURL(new URL("http://fshost:8080/RPC2")); config.setBasicUserName("freeswitch"); config.setBasicPassword("works"); ...

AngularJS example MotoAds with NodeJS and MongoDB

Obraz
I built MotoAds demo application in AngularJS but it did not have any server layer. Data was read directly from the json files. So I was decided to build the server side services. I know pretty well JEE and relational database, so I could use it. But I want to know something new so I chose NodeJS nad MongoDB. Thanks to this decision I got a full stack JavaScript application. It's incredible to use JavaScript to build the complete application. Now MotoAds demo application consists of: User interface in AngularJS and Bootstrap with full CRUD operations: add, read, edit and remove adverts. Server service layer was built in NodeJS with RESTful serrvices. To simplify the use of a NodeJS I used ExpressJS. Database: all data except the pictures are stored in MongoDB. So let's see how to add the CRUD operations in AngularJS with services in NodeJS with MongoDB. Step 1 We write in services.js access to our RESTful services: 'use strict'; var motoAdsServ...

AngularJS resource with JSONP

Obraz
Lately I struggled to get access to facebook by JSONP. I try to do it in AngularJS with factory and resource. I want to share with people my solution. Let's try to connect to the Facebook Graph. Firstly, we create index.html file with input graph.username , after type a value there is called getGraph() . The result of the calling this function is saved in $scope.result so we can display it. AngularJS resource with JSONP

AngularJS example MotoAds end-to-end tests

Obraz
E2E (end-to-end) tests result: Application folders tree: In previous post I showed how to write and run unit tests. Now, I will present how to test DOM manipulation or the wiring of our application. Angular Scenario Runner which simulates user interactions that will help us to do that. Recall adverts.html code which we should know to simulate user interaction: Adverts {{model.name}} Adverts search Country Region Year of production Filters: {{filter.brandName}} {{filter.modelName}} {{filter.country.name}} ...

AngularJS example MotoAds unit tests

Obraz
Unit tests result: Application folders tree: In Angular the controller is separated from the view so it is easy to add the unit tests to MotoAds application. Recall the controller code which will be tested ( controllers.js ): motoAdsApp.controller('AdvertsController', ['$scope', 'Brand', 'Country', 'Advert', function($scope, Brand, Country, Advert) { $scope.oneAtATime = true; $scope.brands = Brand.query(); $scope.countries = Country.query(); $scope.sortByCols = [{ "key": "year", "name": "Year" }, { "key": "price", "name": "Price" }]; $scope.adverts = []; var allAdverts = Advert.query(filterAdverts); $scope.filter = { brandName: null, modelName: null, country: null, region: null, yearFrom: null, yearTo: null }; $scope.isAnyFilter...

AngularJS example MotoAds more advanced than the tutorial on angularjs.org

Obraz
I have just been learning AngularJS and decided to build demo application that cover more techniques than the tutorial on angularjs.org . This application is only demo so it do not have complete server side, some features have the todos and there is not any test. This demo application is some kind of automotive adverts portal, so I called it MotoAds. It has two main features: List of adverts – includes an advanced filtering and sorting. Add advert – a form with some client side field validations. MotoAds application looks like this: Application folders tree: Root file index.html included external resource: bootstrap.css (2.3.2) angular.js, angular-resource.js (1.0.8) ui-bootstrap-tpls-0.6.0.js (0.6.0) and internal resource: app.css app.js services.js controllers.js Bootstrap angular application, add navigation and route templates In index.html we auto-bootstrap the angular application by defining directive ng-app : In app.js we define new...

AngularJS tutorial - my problems and solutions

Due to the fact that AngularJS gaining wider group of supporters and I decided to become familiar with its capabilities. So I started from AngularJS tutorial . At first I had to install: node.js, karma, git I already had (went smoothly). Step 0, Step 1 and almost finished Step 2 if no Section Tests, with whom I had a few problems - we are happy to share them, because maybe some of my suggestions will benefit and save some time. Let me just mention that I am acting in a Windows environment. Step 0, 1 success Step 2 problems Problem #1 The node.js console show me wrong path to Chrome: ERROR [launcher]: Cannot start Chrome Can not find the binary C:\Users\myuser\AppData\Local\Google\Chrome\Application\chrome.exe Please set env variable CHROME_BIN I set it at: set CHROME_BIN=C:\Program Files\Google\Chrome\Application\chrome.exe Of course, best to add it directly to the system environment variables. Problem #2 In file D:\angular-phonecat\test\unit\controlle...

Backbone.js in action

The last time JavaScript libraries, separating application code (as the MVC server's frameworks), are gaining on popularity. Below I will present a simple example implemented in backbone.js, which will show the possibility of the library and you will understand why it is worth to use it. Let's start by creating a directory empapp and put in it the index.html :

Attributes data-* in HTML5

Using HTML5 Web applications becomes a reality. Even the banks are starting to require users to use browsers that support this standard. An example is Getin Bank, which from May 1 recommends the use of new browsers (Firefox 12 +, Chrome 15 +, IE 9 +, Safari 5 +, Opera 10 +). Creating web application often have the need to create a javascript component (such as jQuery) in which we want to preserve its state. An example would be a simple text box that appears in the browser, and it is initiated by default: If user changes the value on userVal , and we want to add a button restores the default value of this field to defaultVal we have a problem. Of course, this can be done in several ways such as: variable in javascript, we need to ensure that the name of the variable to be unique create a hidden field and in this field store the default value However, HTML5 gives us new opportunities in this area. Namely allows you to define custom attributes in HTML elements - they ha...

Google Apps Script - and why do I need it?

The last time I needed a single spreadsheet (changing over time) from time to time to generate the statistics in the second sheet. Because of that, not only was about the cyclical generation, but the analysis was important for me that they are wrought in colors, bold - just easy to read. I would add that that these sheets are holding in Google Drive. I was able to rely on macros in MS Word, but I do not know them and do not hurry me to their knowledge. I thought it perfect for me in this situation would be JavaScript and intuition did not fail me. It turned out that the Google Cloud can access Google Apps Script, which written in help Google Apps Script is based upon JavaScript . Thus after a few moments I had the first version of my statistics, and the next sprint final release . And now a simple example that will bring the possibility of this tool. Start by creating a spreadsheet with the objective to calculate the profit from the sale of shares: Symbol Number Buy Sell Profi...

Unconscious use WebServices session

Real life ... programmer copied the definition of service in Service1WS to Service2WS , changed the name of the service, the name of the class and obtained a description of the service: He did not notice, however, that Service1WS contains a parameter that if Service2WS should not appear to have been: The result was that when the server traffic appeared to increase there was java.lang.OutOfMemoryError: Java heap space . The increases in traffic were no frequent so error occurred sporadically (sic!). During the tracking error, no one came up with the idea to look on cardinality of the Tomcat session (there are lots of them in heavy traffic). Only application profiling revealed that there are a lot of objects Axis'a session is indicated clue: enough to look at the number of sessions on Tomcat'cie, look for deploy.wsdd with the description Service2WS parameter, and see this thing was clear. Why were so many sessions for one client WS and one serve...

BigDecimal w GWT

Zawsze gdy testujemy jakiś framework wybieramy najprostszą drogę, co między innymi oznacza, iż korzystamy z takich typów danych jak: String i Integer . Niemniej jednak przychodzi czas kiedy musimy zmierzyć się z obsługą co najmniej kilku typów danych m.in. z typem zmiennoprzecinkowym. Doświadczenie nauczyło mnie, że jeżeli chodzi o Javę to najlepszym typem zmiennoprzecinkowym do wykonywania operacji arytmetycznych jest BigDecimal . Pewnie co niektórym nasuwa się pytanie - dlaczego nie double . Moją odpowiedzią będzie przykład zaczerpniety ze strony http://epramono.blogspot.com : Wynik na wyjściu: Upss... co za niemiła niespodzianka :( Nie o tym jednak zamierzam pisać moim głównym tematem jest GWT (wersja 1.4.60), a w zasadzie obsługa typu BigDecimal w GWT, której najogólniej rzecz ujmując po prostu nie ma. To oczywiście poważny problem... ale jest na to rozwiązanie: Wchodzimy na stronę: http://code.google.com/p/gwt-math/ . Ściągamy dwie biblioteki gwt-math-2.0.1.jar , gwt-math-se...

GWT - internacjonalizacja

Jeżeli docelową grupą użytkowników naszej aplikacji są ludzie o różnych narodowościach wówczas warto dostosować ją do obsługi wielu języków. Pierwszą rzeczą z którą przyjdzie się nam zmierzyć będzie tłumaczenie tekstów stałych. Samo tłumaczenie tekstów możemy pozostawić lingwistom, natomiast naszym zadaniem jest napisanie tak aplikacji, aby obsługa tych tekstów była możliwa i przy dodawaniu kolejnych tłumaczeń nie wymagała pracy programistycznej. Oczywiście każdy programista dość szybko poradziłby sobie z tym zagadnieniem wymyślając swój własny mechanizm, ale programista leniwy (czytaj: skuteczny ) przegrzebie dokumentację w celu znalezieniu mechanizmu, który już został wymyślony. Jak to wygląda w GWT... Podstawowym elementem, który umożliwi nam lokalizację tekstów stałych jest moduł zawarty w pakiecie com.google.gwt.i18n oferuje on kilka mechanizmów: Constants , Messages , ConstantsWithLookup , Dictionary , Localizable . Skoncentrujmy się jednak na dwóch podstawowych Constants i ...

Równy czy nierówny - oto jest pytanie

Ktoś kiedyś powiedział "mnie język w programowaniu nie przeszkadza"? Co mnie więcej oznacza, iż doświadczony programista, który miał do czynienia z kilkoma językami (np. C, Java) bez problemu powinien poradzić sobie z programowaniem w kolejnym języku (np. w C#). Jest w tym wiele prawdy, ale czy bez kompleksowej wiedzy z danego języka kod owego programisty będzie na pewno niezawodny? Rozważmy prosty przykład napisany w języku Java: Czy jest coś w tym przykładzie co mogłoby nas skłonić do refleksji - raczej nie. Oczywiste wydaje się, iż w pierwszym warunku zostanie wyświetlone na konsoli "rozne obiekty" , natomiast w drugim warunku "rowne obiekty" . Pierwszy warunek będzie spełniony tylko wtedy gdy będziemy mieli do czynienia ze zmiennymi, które wskazują dokładnie na ten sam obiekt. Drugi warunek to już porównanie wartości tych obiektów więc sprawa jest dość oczywista. Zmodyfikujmy ten przykład: Co się okazuje? Pierwszy warunek jest spełniony w efekcie...

Kreatory w GWT

W dystrybucji GWT znajdują się cztery skrypty cmd, które w największym skrócie można nazwać kreatorami. Każdy z nich jest wykorzystywany na różnym etapie tworzenia aplikacji. projectCreator GWT pozwala na łatwą integrację ze środowiskiem Eclipse, dlatego też jeżeli podczas tworzenia aplikacji programista zamierza korzystać z tego IDE, wówczas powinien użyć tego narzędzia. Kreator ten zakłada strukturę katalogów (wraz z plikami .project oraz .classpath) , która pozwoli łatwo zaimportować tworzoną aplikację jako projekt Eclipse. Wykonując komendę: Utworzona zostanie następująca struktura: applicationCreator Kreator ten pełni trzy funkcje: Wytwarza strukturę pakietów dla aplikacji. Generuje domyślne pliki HTML i Java spięte w prostym pliku module XML. Te pliki stanowią prostą aplikację od której można zacząć budowanie bardziej zaawansowanych funkcjonalności. Tworzy skrypty cmd, które pozwalają przekompilować i uruchomić aplikację w trybie hosted mode. Wykonując komendę (bez Ecl...