I'm ready to announce that started open project with sample application, having Java EE stack on backend (including Spring and build up with Gradle) and AngularJS on front-end part. Now it uses embedded HSQLDB storage, but will be migrated to MongoDB. Checkout: https://github.com/maxaus/ee-grad
вторник, 30 сентября 2014 г.
среда, 17 сентября 2014 г.
Printing grids in ExtJS
In many ExtJS applications grids have to be correctly printed, but as ExtJS has no such functionality out of the box, you should use some third-party or your own solution. One of the best start points is to use Ext.ux.Printer plugin. It can be used not only for grids, but also other components, but you need to define custom renderer classes for your component, see article http://edspencer.net/2009/07/28/extuxprinter-printing-for-any-ext/. After that printing from your code is very simple:
Ext.ux.Printer.print(MyApp.components.MyGrid);
четверг, 24 июля 2014 г.
Emoticons AngularJS directive
If you have ever developed web applications including social activity, like messaging, you definitely had a moment, when you need to add emoticons to your message board. Here is an example of AngularJS directive to convert symbols to emotional icons.
Emoticons map:
Directive:
In HTML:
Emoticons map:
angular.module("myApp").value('Emoticons', {
':-)': 'http://www.freesmileys.org/smileys/smiley-basic/biggrin.gif',
':)': 'http://www.freesmileys.org/smileys/smiley-basic/biggrin.gif',
':D': 'http://www.freesmileys.org/smileys/smiley-basic/laugh.gif',
':-D': 'http://www.freesmileys.org/smileys/smiley-basic/laugh.gif',
':-|': 'http://www.freesmileys.org/smileys/smiley-basic/mellow.gif',
':|': 'http://www.freesmileys.org/smileys/smiley-basic/mellow.gif',
':-p': 'http://www.freesmileys.org/smileys/smiley-basic/tongue.gif',
':p': 'http://www.freesmileys.org/smileys/smiley-basic/tongue.gif',
':-(': 'http://www.freesmileys.org/smileys/smiley-basic/sad.gif',
':(': 'http://www.freesmileys.org/smileys/smiley-basic/sad.gif'
});
Directive:
angular.module("myApp").directive("withEmoticons", function (Emoticons, $timeout) {
return {
link: function postLink(scope, element, attrs) {
scope.replaceEmoticons = function (text) {
var patterns = [];
var metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
// build a regex pattern for each defined property
for (var i in Emoticons) {
if (Emoticons.hasOwnProperty(i)) { // escape metacharacters
patterns.push('(' + i.replace(metachars, '\\$&') + ')');
}
}
// build the regular expression and replace
return text.replace(new RegExp(patterns.join('|'), 'g'), function (match) {
return Emoticons[match] ?
'
' :
match;
});
};
$timeout(function () {
element.html(scope.replaceEmoticons(element.html()));
});
scope.$watch(function () {
return element.html();
}, function onChange(newVal, oldVal) {
if (newVal !== oldVal) {
$timeout(function () {
element.html(scope.replaceEmoticons(element.html()));
});
}
});
}
};
});
In HTML:
{{message}}
пятница, 30 мая 2014 г.
Plain text AngularJS filter
Many times on different web projects there is an requirement to remove HTML tags from the text (that comes from some remote place and should be displayed on the web page). Here I will provide approach, how to do it through AngularJS filter. So, filter code itself:
And how it is being used on HTML page;
/**
* Filter removes HTML from given string value.
*/
angular.module("myApp").filter('plainText', function() {
return function(val) {
//remove html tags
var s1 = val.replace(/<\/?[^>]+(>|$)/g, "");
//translate special symbols
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt" : "<","gt" : ">"};
return ( s1.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
};
});
And how it is being used on HTML page;
{{htmlMessage.body | plainText}}
пятница, 5 июля 2013 г.
Exporting Excel spreadsheet from Spring MVC application.
Here I will provide solution for common situation, when you need to export some kind of Excel doc (e.g. report) from web application built on Spring MVC framework. It's made with help of Apache POI library, which generates spreadsheet.
In Spring config spring-excel-views.xml it should be declared like that:
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.web.servlet.view.document.AbstractExcelView;
/**
* @author Maxim Baev
*/
public class ExcelRecipeWishListView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map productMap = (Map) model.get("productMap");
//create a wordsheet
HSSFSheet sheet = workbook.createSheet("Product list");
HSSFRow header = sheet.createRow(0);
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
Cell headerCell1 = header.createCell(0);
headerCell1.setCellStyle(cellStyle);
headerCell1.setCellValue("Product");
Cell headerCell2 = header.createCell(1);
headerCell2.setCellStyle(cellStyle);
headerCell2.setCellValue("Quantity");
int rowNum = 1;
for (Map.Entry entry : productMap.entrySet()) {
//create the row data
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(entry.getKey());
row.createCell(1).setCellValue(entry.getValue());
}
response.setHeader("Content-Disposition", "attachment; filename=\"product_list.xls\"");
}
}
In Spring config spring-excel-views.xml it should be declared like that:
Then used in main config:
And finally on your controller:
@RequestMapping(value = "/xls_wish_list")
public ModelAndView exportWishListToExcel(HttpSession session) {
List recipes = null;
Map productMap = null;
if (session.getAttribute("recipeIds") != null) {
Set recipeIdSet = (Set) session.getAttribute("recipeIds");
List recipeIds = new ArrayList(recipeIdSet);
List searchCriteria = new ArrayList(1);
searchCriteria.add(new IdSearchCriterion(recipeIds));
recipes = recipeService.getRecipes(searchCriteria);
productMap = makeProductMap(recipes);
}
//return excel view
Map model = new HashMap(1);
model.put("productMap", productMap);
return new ModelAndView(new ExcelRecipeWishListView(), model);
}
вторник, 26 февраля 2013 г.
Spring MVC form validator example
Here I provide and example of custom validation of a form fields, made with Spring MVC framework.
import com.baev.cook365.model.Recipe;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Created by Maxim Baev.
*/
public class RecipeValidator implements Validator {
@Override
public boolean supports(Class aClass) {
return Recipe.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
Recipe recipe = (Recipe) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "recipe.title", "fill-in-the-name", "Is required");
}
}
пятница, 11 января 2013 г.
JSF custom converter
Example of rather simple JSF converter to transform string with separated by semicolon words to the list of strings. In my case it was useful for mailbox application for email address input field with multiple email addresses.
/**
* Custom converter to transform input string value to the list of strings.
*
* @author Maxim Baev
*/
@FacesConverter(value = "stringListConverter")
public class StringListConverter implements Converter {
private static final Logger LOGGER = LoggerFactory.getLogger(StringListConverter.class);
private static final String DELIMITER = ";";
private static final String WHITESPACE = " ";
/**
* {@inheritDoc}
*/
@Override
public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {
if (value == null || value.isEmpty()) {
return null;
}
try {
return Arrays.asList(value.replaceAll(WHITESPACE, StringUtils.EMPTY).split(DELIMITER));
} catch (Exception e) {
LOGGER.error("Failed to convert string to list", e);
throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to list", value)), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getAsString(final FacesContext context, final UIComponent component, final Object value) {
if (!(value instanceof List)) {
return null;
}
return StringUtils.join((List) value, DELIMITER + WHITESPACE);
}
}
Подписаться на:
Сообщения (Atom)