Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

Thursday, August 9, 2018

HTTP Security Headers

Intro


HTTP security headers provide yet another layer of security by helping to mitigate attacks and security vulnerabilities.

When a user visits a site through his/her browser, the server responds with HTTP Response Headers. These headers tell the browser how to behave during communication with the site. These headers mainly comprise of metadata.

For example, by using the strict-transport-security you can force the browser to communicate solely over HTTPS.


HTTP Strict Transport Security (HSTS)


HTTP Strict Transport Security () is a web security policy mechanism which helps to protect websites against protocol downgrade attacks and cookie hijacking. It allows web servers to declare that web browsers (or other complying user agents) should only interact with it using secure HTTPS connections, and never via the insecure HTTP protocol.

A server implements an HSTS policy by supplying a header (Strict-Transport-Security) over an HTTPS connection (HSTS headers over HTTP are ignored).

Values

Value
Description
max-age=SECONDS
The time, in seconds, that the browser should remember that this site is only to be accessed using HTTPS.
includeSubDomains
If this optional parameter is specified, this rule applies to all of the site's subdomains as well.
preload
Google maintains a service that hardcodes your site as being HTTPS only into browsers. This way, a user doesn’t even have to visit your site: their browser already knows it should reject unencrypted connections. Getting off that list is hard, by the way, so only turn it on if you know you can support HTTPS forever on all your subdomains.

Example

Strict-Transport-Security: max-age=31536000 ; includeSubDomains

X-Frame-Options

X-Frame-Options response header improve the protection of web applications against Clickjacking. It declares a policy communicated from a host to the client browser on whether the browser must not display the transmitted content in frames of other web pages.

Clickjacking is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page.

Values

Value
Description
deny
No rendering within a frame.
sameorigin
No rendering if origin mismatch.
allow-from: DOMAIN
Allows rendering if framed by frame loaded from DOMAIN.

Example

X-Frame-Options: deny

X-XSS-Protection

This header enables the Cross-site scripting (XSS) filter in your browser.

XSS, is an attack where the attacker causes a page to load some malicious Javascript.

Values

Value
Description
0
Filter disabled.
1
Filter enabled. If a cross-site scripting attack is detected, in order to stop the attack, the browser will sanitize the page.
1; mode=block
Filter enabled. Rather than sanitize the page, when a XSS attack is detected, the browser will prevent rendering of the page.
1; report=report_URI
Filter enabled. The browser will sanitize the page and report the violation. This is a Chromium function utilizing CSP violation reports to send details to a URI of your choice.

Example

X-XSS-Protection: 1; mode=block

X-Content-Type-Options

Setting this header will prevent the browser from interpreting files as something else than declared by the content type in the HTTP headers.

This helps reduce the danger of drive-by downloads and helps treat the content the right way.

The X-Content-Type-Options headers instruct browsers to set the content type as instructed and never detect the type their own. You should apply this header, but double-check that you’ve set the content types correctly.

Values

Value
Description
nosniff
Will prevent the browser from MIME-sniffing a response away from the declared content-type.

Example

X-Content-Type-Options: nosniff

Content-Security-Policy (CSP)

Content Security Policy (CSP) gives you a language to define where the browser can load resources from. You can white list origins for scripts, images, fonts, stylesheets, etc. in a very granular manner. You can also compare any loaded content against a hash or signature.

A Content Security Policy (CSP) requires careful tuning and precise definition of the policy. If enabled, CSP has significant impact on the way browsers render pages (e.g., inline JavaScript disabled by default and must be explicitly allowed in policy). CSP prevents a wide range of attacks, including Cross-site scripting and other cross-site injections.

Example 

form samarait.hr where I have used Google fonts and analytics

Content-Security-Policy:

default-src 'none'; script-src 'self' https://www.googletagmanager.com https://www.google-analytics.com; style-src 'self' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self' https://www.google-analytics.com; frame-ancestors 'none'; upgrade-insecure-requests

Tuesday, March 13, 2018

Wiremock notes


WireMock is an HTTP mock server. At its core it is web server that can be primed to serve canned responses to particular requests (stubbing) and that captures incoming requests so that they can be checked later (verification).

It can be used as a library by any JVM application, or run as a standalone process either on the same host as the system under test or a remote server.

Example

I want to match part of the json, eg oib == ""
Request example:
{
                "oib": "",
                "status": "IN_PROGRESS",
}

For all request default stub is
  stubFor(post(urlMatching(".*/documentationStatusMock")).atPriority(10)
    .willReturn(aResponse()
    .withStatus(200)
    .withHeader("Content-Type", "application/json; charset=utf-8")
    .withBodyFile("documentationStatus/response.json")))

response.json

{
  "statusCode": 0,
  "statusName": "OK",
  "rowNumber": 18,
}

               
For error cases, when oib is empty:
  stubFor(post(urlMatching(".*/documentationStatusMock")).atPriority(1)
    .withRequestBody(matchingJsonPath("\$.oib", equalTo("")))
    .willReturn(aResponse()
    .withStatus(200)
    .withHeader("Content-Type", "application/json; charset=utf-8")
    .withBodyFile("documentationStatus/responseError.json")))
}

responseError.json

{
    "statusCode": -2,
    "statusName": "ERROR",
    "rowNumber": -1,
}


References

Wednesday, July 12, 2017

Angular notes

Angular 4 notes

Install Angular and create first project


  1. Install node.js (https://nodejs.org/en/)
  2. npm install -g @angular/cli
  3. ng new my-first-project
  4. cd my-first-project
  5. ng serve
  6. ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **

Check Node and NPM version 

$ node -v
$ npm -v

Typescript

Install typescript
$ npm install -g typescript
Compile ts file:
$ tsc app.ts

Directives overview

There are three kinds of directives in Angular:

Components—directives with a template. (most common)
Structural directives—change the DOM layout by adding and removing DOM elements. (change the structure of the view e.g. *ngIf)
Attribute directives—change the appearance or behavior of an element, component, or another directive. (are used as attributes of elements e.g. ngStyle)

Ref


Tuesday, August 9, 2016

Angular.JS notes

Notes

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.




A Directive is a marker on a HTML tag that tells Angular to run or reference some JavaScript code.
Controllers are where we define our app’s behavior by defining functions and values.
Modules – where our application components live
Expressions – how values get displayed within the page

AngularJS Example

index.html
<!DOCTYPE html>
<html ng-app="gemStore">
  <head>
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
  </head>
  
<body ng-controller="StoreController as store">
<div ng-repeat="product in store.products">
<h1>{{product.name}}</h1>
<h2> ${{product.price}}</h2>
<p> {{product.description}}</p>
<button ng-show="product.canPurchase">Add to Cart</button>
</div>
</body>
</html>

app.js
(function() {
var app = angular.module('gemStore', []);

app.controller('StoreController', function() {
// store data in the controller
this.products = gems;
});

var gems = [
{ name: 'Azurite', price: 2.95, description: 'Dobar za prodaju....', canPurchase : true },
{ name: 'Bloodstone', price: 5.95, description: 'Ne mozes kupiti', canPurchase : false },
{ name: 'Zircon', price: 3.95, description: 'ZZZZZZ', canPurchase : true }
];

})();

Ref


Wednesday, May 25, 2016

Tomcat notes

Configure tomcat to expose files from disk

In tomcat conf/server.xml add at the bottom before </Host>:

 <Context path="/results"
                 docBase="/opt/prov/rdisk/manufacturer_results"
                 debug ="99"
                 reloadable="true">
 </Context>


In you application properties you can define:

#where to save files
path_file=/opt/prov/rdisk/manufacturer_results/{0}_name.csv
#url to fetch file
url_file=http://machine:8080/results/{0}_error.csv

Tomcat exposes files found on those places on disk.
You can reach them via http.

Monday, March 23, 2015

Download file

Implemented using Spring MVC, rest service.

Display file on screen or download as attachment.

@Controller
public class FileController
{
private static final Logger log = LoggerFactory.getLogger(FileController.class);

@RequestMapping(value = "/file/{id}", method = RequestMethod.GET)
public void getFileViaAttachment(@PathVariable String id, HttpServletResponse response)
{
log.info("getFile " + id);
try
{

String content = "testing file download";
String fileName = "mojFileIzStringa.txt";
InputStream in = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));

IOUtils.copy(in, response.getOutputStream());

response.setContentType("application/text");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.flushBuffer();
}
catch (IOException e)
{
e.printStackTrace();
}
}

@RequestMapping(value = "/many", method = RequestMethod.GET)
public void getManyLinesViaAttachment(HttpServletResponse response)
{
log.info("getManyLines ");
try
{
String[] linesArrays = { "prva linija", "druga linija", "xxx linija" };
List<String> linesList = Arrays.asList(linesArrays);
String fileName = "mojFileSpunoLinija.csv";
IOUtils.writeLines(linesList, null, response.getOutputStream(), StandardCharsets.UTF_8);

response.setContentType("application/text");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.flushBuffer();
}
catch (IOException e)
{
e.printStackTrace();
}
}

// every line in new row
@RequestMapping(value = "/getFileAsItIs", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public String getFileAsItIs()
{
log.info("getFileAsItIs ");
String[] linesArrays = { "prva linija", "druga linija", "xxx linija" };
List<String> linesList = Arrays.asList(linesArrays);
StringBuilder sb = new StringBuilder();

for (String s : linesList)
{
sb.append(s).append(System.lineSeparator());
}

return sb.toString();
}
}

Thursday, May 22, 2014

Start/stop Tomcat from ANT

<project name="Stop/start Tomcat with local deploy">

<property name="tomcat.home" value="D:/apache-tomcat-7.0.47" />
<property name="project.name" value="samara-provisioning" />
<property name="dist.dir" value="dist/artefacts" />

<!-- deploy-local: delete and copy war -->
<target name="deploy-local" depends="tomcat-stop">

<delete>
<fileset dir="${tomcat.home}/webapps">
<include name="${project.name}.war" />
</fileset>
</delete>
<delete dir="${tomcat.home}/webapps/${project.name}" />

<copy todir="${tomcat.home}/webapps">
<fileset dir="${dist.dir}">
<include name="**/${project.name}.war" />
</fileset>
</copy>

<tstamp>
<format property="TODAY" pattern="HH:mm:ss:sss zzz"
locale="en" />
</tstamp>
<echo> Build Completed At: ${TODAY}</echo>

</target>

<!-- start tomcat, it depends on deploy-local -->
<target name="tomcat-start" depends="deploy-local">
<java classname="org.apache.catalina.startup.Bootstrap"
failonerror="true" fork="true">
<classpath
path="${tomcat.home}/bin/bootstrap.jar:${tomcat.home}/bin/tomcat-juli.jar" />
<jvmarg
value="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager" />
<jvmarg
value="-Djava.util.logging.config.file=${tomcat.home}/conf/logging.properties" />
<jvmarg value="-Dcatalina.home=${tomcat.home}" />
<jvmarg value="-Dcatalina.base=${tomcat.home}" />
<jvmarg value="-Djava.io.tmpdir=${tomcat.home}/temp" />
<arg line="start" />
</java>
</target>

<!--stopping tomcat , if it is found running -->
<target name="tomcat-stop" if="tomcat.running" depends="check-port">
<echo message="Tomcat is running...stopping it" />
<java classname="org.apache.catalina.startup.Bootstrap" fork="true">
<classpath
path="${tomcat.home}/bin/bootstrap.jar:${tomcat.home}/bin/tomcat-juli.jar" />
<jvmarg value="-Dcatalina.home=${tomcat.home}" />
<arg line="stop" />
</java>
</target>

<!-- Check whether Tomcat is running -->

<target name="check-port" description="Check whether Tomcat is running">
<echo message="Checking whether Tomcat is running" />
<condition property="tomcat.running">
<socket server="localhost" port="8080" />
</condition>
</target>

</project>


Ref:
http://techfindouts.blogspot.com/2013/08/how-to-restart-stopstart-tomcat-using.html
http://linuxclicks.blogspot.com/2011/04/java-ant-target-to-startstop-apache.html

Wednesday, April 3, 2013

Charts

Web

-using IceFaces 1.8.2 (JSF 1.2)

<ice:form id="chartPopUp">
<ice:panelPopup draggable="true" modal="true" rendered="#{activeBackingBean.chartPopUpVisible}">
  <f:facet name="header">
  <table width="100%">
  <tr>
  <td>
  <ice:outputText value="Grafički prikaz" />
  </td>
  <td align="right">
   
  <ice:commandButton id="closeOdabirButton" styleClass="xButton" actionListener="#{activeBackingBean.closeChartPopUpVisibleAction}" />
  </td>
  </tr>
  </table>
   </f:facet>

  <f:facet name="body">
  <ice:outputChart id="chart" type="pie2D" 

        chartTitle="#{activeBackingBean.title}" 
        colors="green, red" 
        data="#{activeBackingBean.chartData}" 
        labels="#{activeBackingBean.chartLabels}"/>
  </f:facet>
</ice:panelPopup>
</ice:form>

BackingBean

private int totalOkDPTs;
private int totalNotOkDPTs;

public String getChartData()
{
return totalOkDPTs + ", " + totalNotOkDPTs;
}
public String getTitle()

public String getChartLabels()


Result


Jasper report

- using iReport 3.6.2

Select colors:
Pie Chart - Properties - Series Colors ...

Data to display:
Right click Chart and select Chart Data - Details - Pie series
In this example I have 2 series

Parameters:
totalOkDPTsPercentage - String
totalNotOkDPTsPercentage - String
totalOkDPTsPercentageNumber - Double
totalNotOkDPTsPercentageNumber - Double

pieSeries definition:
keyExpression - what displays in bottom (bottom label)
valueExpression - used for calculating and displaying (Number)
labelExpression - label with arrow (String)

jrxml code:

<pieChart>
<chart isShowLegend="true">
<reportElement x="98" y="28" width="375" height="205"/>
<chartTitle>
<titleExpression><![CDATA["Grafički prikaz"]]></titleExpression>
</chartTitle>
<chartSubtitle/>
<chartLegend/>
</chart>
<pieDataset>
<pieSeries>
<keyExpression><![CDATA["Ispravnih DPK - " + $P{totalOkDPTsPercentageNumber} +"%"]]></keyExpression>
<valueExpression><![CDATA[$P{totalOkDPTsPercentageNumber}]]></valueExpression>
<labelExpression><![CDATA["Ispravnih DPK"]]></labelExpression>
</pieSeries>
<pieSeries>
<keyExpression><![CDATA["Pogrešnih DPK - " + $P{totalNotOkDPTsPercentageNumber} +"%"]]></keyExpression>
<valueExpression><![CDATA[$P{totalNotOkDPTsPercentageNumber}]]></valueExpression>
<labelExpression><![CDATA["Pogrešnih DPK"]]></labelExpression>
</pieSeries>
</pieDataset>
<piePlot>
<plot>
<seriesColor seriesOrder="0" color="#00FF33"/>
<seriesColor seriesOrder="1" color="#FF0033"/>
</plot>
<itemLabel color="#000000" backgroundColor="#FFFFFF"/>
</piePlot>
</pieChart>

Result


Stackedbar Chart

I have people and 2 values for them, OK and NOK

Result:
Add stackedbar chart:
- define series colors, Legend position

Define chart details:
- I have added 2 series since I have 2 values (OK and NOK)


The Series expression field is the name of the series. Its value can be any object that implements java.lang.Comparable. In most cases, the value of this field is a string.   --OK

The Category expression field is the label of each value in the chart. The value of this field is typically a string. In our example, each state is a different category, so we will use the state field ($F{state}) as our category expression.   --People's name

The Value expression field is a numeric value representing the value to be charted for a particular category. In our example, the number of aircraft in a particular state is the value we want to chart. Therefore, we use the implicit stateGroup_COUNT variable ($V{stateGroup_COUNT}) as our value expression. --OK in 1 serie and NOK in 2nd

The optional Label Expression field allows us to customize item labels in the chart.

Tuesday, February 5, 2013

Custom Converters

To make custom converter I found 4 ways of doing it:
  1. using Map in Bean object
  2. parsing Object to String
  3. using static Map
  4. defining inner class in backing bean

Using Map in Bean

In Bean class you need to have Map<key, Object>.
In converters getAsObject method you read object value from this map.

public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException
{
if (context == null) throw new NullPointerException("context");
if (component == null) throw new NullPointerException("component");
if (value == null || value.isEmpty()) return null;
// value je oid recorda

FacesContext ctx = FacesContext.getCurrentInstance();
ValueExpression vex = ctx.getApplication().getExpressionFactory().createValueExpression(ctx.getELContext(), "#{billViewBean}", BillViewBean.class);
BillViewBean view = (BillViewBean) vex.getValue(ctx.getELContext());

TowRecord record;
record = view.getRecordsMap().get(value);
if (record == null)
{

FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unknown value", "The record is unknown!");
throw new ConverterException(message);
}

return record;
}


public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException
{
if (context == null) throw new NullPointerException("context");
if (component == null) throw new NullPointerException("component");
if (value == null) return null;
if (!(value instanceof TowRecord))
{
log.error("Error converting TowRecord to String: Object is not an instance of TowRecord.");
throw new ConverterException("Object is not an instance of TowRecord.");
}

TowRecord record = (TowRecord) value;
return record.getOid();
}
    Ref: JSF 2.0 Cookbook: Using custom converters for h:selectOneMenu


Parsing Object to String

If using this approach you could be in problems with JPA.
Also if object if composed with many minor objects it can be heavy to parse to and from object.

public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException
{
if (value == null || value.isEmpty()) return null;

String[] attributes = StringUtils.delimitedListToStringArray(value, DELIMITER);

TowRecord record = new TowRecord(attributes[0], attributes[1], attributes[2]);
log.debug("Converter to object: " + record.getOid() + ", " + record.getNumber() + ", " + record.getRegistration().getLicensePlate());
return record;
}

public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException
{
if (value == null)
return null;
else if (!(value instanceof TowRecord))
{
log.error("Error converting TowRecord to String: Object is not an instance of TowRecord.");
throw new ConverterException("Object is not an instance of TowRecord.");
}
else
{
TowRecord record = (TowRecord) value;
String recordString = record.getOid() + DELIMITER + record.getNumber() + DELIMITER + record.getRegistration().getLicensePlate();

log.debug("Converted record to String " + recordString);
return recordString;
}
}

   Ref: Core JavaServer Faces  3rd Edition: Implementing Custom Converter Classes


Using static Map

You create class that will hold static maps, and from converter class you can easily access it.
Drawback is that you need to be careful how many object you can put in map.. memory issue.

public class MapHolder

{
private static Map<String, AbstractDOM> recordsMap = Collections.synchronizedMap(new HashMap<String, AbstractDOM>());

public static Map<String, AbstractDOM> getRecordsMap()
{
return recordsMap;
}
}

public class TowRecordsSTATICConverter implements Converter :
public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException
{
if (value == null || value.isEmpty()) return null;

return MapHolder.getRecordsMap().get(value);
}

public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException
{
if (value == null)
return null;
else if (!(value instanceof TowRecord))
{
log.error("Error converting TowRecord to String: Object is not an instance of TowRecord.");
throw new ConverterException("Object is not an instance of TowRecord.");
}
else
{
TowRecord record = (TowRecord) value;
return record.getOid();
}
}


Inner class in backing bean

using this approach you have access to Collection defined and populated in backing bean.

In this example you define:
private List<ReasonDPT> reasonList = new ArrayList<ReasonDPT>();
In xhtml you register converter as converter="#{backingBean.reasonDPTConverter}"

private class ReasonDPTConverter implements Converter
{

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
for (ReasonDPT o : reasonList)
{
if (o.getOid().equals(value)) return o;
}
return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
if (value == null) { return ""; }
return ((ReasonDPT) value).getOid();
}
}

Wednesday, January 23, 2013

DataTable -Multiple checkbox selection with ajax

Problem

You need to select few rows and then hit button to continue with logic. (using checkbox)
Button should be disabled if no entry is selected. (Ajax events)
When you press button you get popup window (dialog) that displays selected entries.

Solution


<h:form id="detailsForm">
<p:dialog id="detailsDlg" widgetVar="details" modal="true" resizable="false" width="900">

  <p:dataTable id="recordsTable" value="#{activeBackingBean.recordsDataModel}"
var="rec" selection="#{activeBackingBean.selectedRecords}"
  scrollable="#{activeBackingBean.recordsDataModel.rowCount gt 7 ? true : false}"
scrollHeight="200" scrollWidth="750"
  resizableColumns="false" >

<p:column selectionMode="multiple" width="35"/>

<p:ajax update="viewSelectedRecButton" event="toggleSelect
listener="#{activeBackingBean.recordsRowSelected}"/>
<p:ajax update="viewSelectedRecButton" event="rowSelectCheckbox"
listener="#{activeBackingBean.recordsRowSelected}"/>
<p:ajax update="viewSelectedRecButton" event="rowUnselectCheckbox"
listener="#{activeBackingBean.recordsRowSelected}"/>

<p:column headerText="Broj" width="200">
    #{rec.number}
    </p:column>

  <p:column headerText="Registracija" width="420">
    #{rec.registration.formatted}
    </p:column>

    <f:facet name="footer">
        <p:commandButton id="viewSelectedRecButton" value="SomeAction"
icon="ui-icon-search"
                               disabled="#{empty activeBackingBean.selectedRecords}"
               update=":detailsForm:displayMultiRec"
                              oncomplete="multiRecDialog.show();"/>
       </f:facet>  
        </p:dataTable>
    </p:dialog>


   <p:dialog id="multiDialog" header="Odabrani zapisnici" widgetVar="multiRecDialog"
          height="300" showEffect="fade" hideEffect="explode">
       <p:dataList id="displayMultiRec"
            value="#{activeBackingBean.selectedRecords}" var="selectedRecord">
        Broj: #{selectedRecord.number}, Rega: #{selectedRecord.registration.formatted}
      </p:dataList>
   </p:dialog>


Listener on ajax event is optional.

BackingBean:

private TowRecord[] selectedRecords;
private RecordsDataModel recordsDataModel;
public void recordsRowSelected(AjaxBehaviorEvent e)

public class RecordsDataModel extends ListDataModel<TowRecord> implements SelectableDataModel<TowRecord>

ajax events:
toggleSelect - toogle/untoggle all

References

http://www.primefaces.org/showcase/ui/datatableRowSelectionRadioCheckbox.jsf
http://stackoverflow.com/questions/12677924/primefaces-datatable-ajax-not-updating-any-component-except-itself


Monday, September 3, 2012

JavaScript - onkey events


When ENTER is pressed - it's like the user clicked Continue button.
When ESC is pressed popup form is closed, like Close button is pressed.


<ice:inputText id="licensePlate" value="#{activeBackingBean.selectedEntity.licensePlate}" required="true" maxlength="20" autocomplete="off"
onkeypress="if((event.which == 13)){document.getElementById('licencePlateForm:continueButton').focus();}"
onkeydown="if((event.which == 27)){document.getElementById('licencePlateForm:closeButton').click();}" onkeyup="checkChar('licencePlateForm:licensePlate', 'an');">
<f:validateLength minimum="3" maximum="20" />
</ice:inputText>

ESC is not picked up by onkeypress!






//Provjerava uneseni znak, moguce postaviti uvijet: n - broj, an - broj ili slovo, a - slovo, lwr - mala slova, upr - velika slova
//dodatni znakovi ako su postavljeni onda se uz uvjet jos omogucuju
//(ako je postavljen uvijet ne dopusta unos drugih znakova)
//Koristiti s onkeyup
function checkChar(elem, uvijet, dodatni){

var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyzšđčćž';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZŠĐČĆŽ';

var obj = document.getElementById(elem);
var znak = obj.value.substring(obj.value.length-1);

if(uvijet != null){
if(uvijet == 'n' && numb.indexOf(znak) == -1){
if(dodatni != null){
if(dodatni.indexOf(znak) == -1){
deleteLastChar(obj);
}
}
else{
deleteLastChar(obj);
}
}
else if(uvijet == 'an' && numb.indexOf(znak) == -1 && lwr.indexOf(znak) == -1 && upr.indexOf(znak) == -1){
if(dodatni != null){
if(dodatni.indexOf(znak) == -1){
deleteLastChar(obj);
}
}
else{
deleteLastChar(obj);
}
}
else if(uvijet == 'a' && lwr.indexOf(znak) == -1 && upr.indexOf(znak) == -1){
if(dodatni != null){
if(dodatni.indexOf(znak) == -1){
deleteLastChar(obj);
}
}
else{
deleteLastChar(obj);
}
}
else if(uvijet == 'lwr' && lwr.indexOf(znak) == -1){
if(dodatni != null){
if(dodatni.indexOf(znak) == -1){
deleteLastChar(obj);
}
}
else{
deleteLastChar(obj);
}
}
else if(uvijet == 'upr' && upr.indexOf(znak) == -1){
if(dodatni != null){
if(dodatni.indexOf(znak) == -1){
deleteLastChar(obj);
}
}
else{
deleteLastChar(obj);
}
}
}
}

//Brise zadnji znak zadanog document.element objekta
function deleteLastChar(obj){
if(obj.value != null){
obj.value = obj.value.substring(0,obj.value.length-1);
}
}

Monday, April 23, 2012

ResourceBundle

I need to read messages_hr.properties file that is in the classpath of web project.

1) Load properties file: 
ResourceBundle bridgeMsgBundle = ResourceBundle.getBundle("messages", new Locale("hr"));

2) Fomat text with parameters:
String text = MessageFormat.format(bridgeMsgBundle.getString("javax.faces.validator.LengthValidator.MAXIMUM"), 15);

In messages_hr.properties: 
javax.faces.validator.LengthValidator.MAXIMUM=* Maksimalan broj znakova je {0}.

Wednesday, January 11, 2012

Using java formatter on web

HTML will eat spaces.. use &nbsp
To get rightly aligned columns you need to use font that is monospaced!

Formatter formatter = null;
StringBuilder sb = new StringBuilder();
sb.append("%-").append(max).append(".").append(max).append("s");
String format = sb.toString();
for (Article a : listaArtikala)
{
// html pojede razmake - moras koristiti &nbsp i monospaced font (npr Courier)
sb = new StringBuilder();
formatter = new Formatter(sb);

formatter.format(format, a.getName() + ",");
formatter.format("%-14.14s", a.getArticlePeriod().getFormatted() + ",");
formatter.format("%-10.10s", CurrencyUtils.formatCurrency(a.getPrice()) + "kn");
if (log.isDebugEnabled()) log.debug(formatter.toString());


articleTypeSIList.add(new SelectItem(a.getOid(), formatter.toString().replace(" ", "&nbsp;")));
}

Wednesday, January 4, 2012

Primefaces and encoding (UTF-8)

From pom.xml

<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>3.0</version>
</dependency>

With Sun implementations special chars (šđčćž) are transformed to unreadable chars!!!
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.6</version>
</dependency>

It works well with Apache implementation:
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-impl</artifactId>
<version>2.1.5</version>
</dependency>

The index.xhtml page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h1>TESTING JSF and PRIMEFACES</h1>

<h:panelGrid columns="3">
<h:outputLabel for="lastName" value="Name: " />
<h:inputText id="lastName" value="#{userInputBean.name}"/>
<h:message for="lastName" styleClass="error" />
</h:panelGrid>

<br />
<h:outputText value="#{userInputBean.name}" />

<p:editor />
</h:form>
</h:body>
</f:view>
</html>

Wednesday, December 21, 2011

Dynamically load header message in column

In backing bean I have List vrsteAktivnosti and based on kratica property in my object I want to build header so it can easily be internationalized. Plus add sufix '_kratica' to property.
If for example kratica resolves to KR in my resource bundle I have key KR_kratica.

<ui:param name="kratica_3" value="#{aktivnostBean.vrsteAktivnosti.get(3).kratica}_kratica" />
<p:column headerText="#{msg[kratica_3]}">
...

Some expression language basics:
  • msg.someKey will look at message bundle for someKey
  • msg['someKey'] will look at message bundle for someKey
  • msg[someKey] will look at params to resolve property someKey
  • msg[aktivnostBean.vrsteAktivnosti.get(3).kratica] will look at objects property kratica and then look at msg bundle
  • msg[aktivnostBean.vrsteAktivnosti.get(3).kratica_kratica] will look at objects property kratica_kratica which does not exist, so use ui:param

Tuesday, November 8, 2011

Clearing JSF Form

On page you have form with input fields and button that can clear that fields.
Button is set to immediate since there is no need to do PROCESS_VALIDATIONS and UPDATE_MODEL_VALUES phases,
instead method is invoked in APPLY_REQUEST_VALUES phase.
First method can be used in JSF 1.x or 2.x, but second is based on AJAX event and is usable only in JSF 2.x
Better approach is with AJAX since there is no need to refresh whole page.

<h:commandButton value="Clear" id="clearButton">
<f:ajax event="click" render="@form" listener="#{myController.clearForm}" immediate="true" />
</h:commandButton>

public void clearForm(ActionEvent ae)
{
System.out.println("clearForm - via ActionEvent");
// clear bean values ...

// clear component values
UIComponent form = getContainingForm(ae.getComponent());
clearEditableValueHolders(form);
}

public void clearForm(AjaxBehaviorEvent ae)
{
System.out.println("clearForm - via AjaxBehaviorEvent");
// clear bean values ...

// clear component values
UIComponent form = getContainingForm(ae.getComponent());
clearEditableValueHolders(form);
}

private UIComponent getContainingForm(UIComponent component)
{
if (!(component.getParent() instanceof UIForm))
{
return getContainingForm(component.getParent());
}
else
{
System.out.println("getContainingForm: UIForm found");
return component.getParent();
}
}

private void clearEditableValueHolders(UIComponent form)
{
Iterator<UIComponent> iterator = form.getFacetsAndChildren();
while (iterator.hasNext())
{
UIComponent c = iterator.next();
if (c instanceof EditableValueHolder)
{
// Convenience method to reset this component's value to the un-initialized state.
((EditableValueHolder) c).resetValue();
}
clearEditableValueHolders(c);
}
}

Friday, July 22, 2011

Web -parameter transmission

(from jsf page to bean)

.xhtml:
<h:commandLink value="clickToTransfer" actionListener="#{activeBackingBean.methodName}" title="Hover effect">
<f:param name="myParam" value="TakeMe" />
</h:commandLink>

.java:
String parametar = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("myParam");

Ref:
4-ways-to-pass-parameter-from-jsf-page-to-backing-bean