Thursday, June 20, 2013

PKI (public key infrastructure)

Public-key cryptography is a cryptographic technique that enables users to securely communicate on an insecure public network, and reliably verify the identity of a user via digital signatures.

Sender and receiver both have pair of private and public keys.

To send encrypted message sender is using reveiver's public key.
Prior to that he can encrypt signature using his private key.

Receiver needs to decrypt message using his private key.
To decrypt signature and to authenticate the sender he is using sender's public key.




Certificate Signing Requests (CSRs)
A CSR consists mainly of the public key of a key pair, and some additional information. Both of these components are inserted into the certificate when it is signed.

Whenever you generate a CSR, you will be prompted to provide information regarding the certificate. This information is known as a Distinguised Name (DN). An important field in the DN is the Common Name (CN), which should be the exact Fully Qualified Domain Name (FQDN) of the host that you intend to use the certificate with.


Ref:

Wednesday, May 8, 2013

Design Principles


  • Encapsulation is breaking your application into logical parts that have a clear boundary that allows an object to hide its data and methods from other objects.
  • Encapsulate what varies.
Information hiding (encapsulation) is important for many reasons, most of which stem from the fact that it decouples the modules that comprise a system, allowing them to be developed, tested, optimized, used, understood, and modified in isolation. This speeds up system development because modules can be developed in parallel. It eases the burden of maintenance because modules can be understood more quickly and debugged with little fear of harming other modules.

The rule of thumb is simple: make each class or member as inaccessible as possible.
  • Code to an interface rather than to an implementation (software is easier to extend).
  • Classes are about behaviour and functionality.
  • Open-Closed Principle (OCP) - classes should be open for extension (new functionality), and closed for modification. (keeps your software reusable, but still flexible) If you want to add new functionality you should extend the entity.
    • open for extension: new behaviour can be added to satisfy the new requirements 
    • close for modification: to extending the new behaviour are not required modify the existing code
  • Don't Repeat Yourself (DRY) - avoid duplicate code by abstracting out things that are common and placing those things in a single location. (DRY is about having each piece of information and behavior in your system in a single, sensible place)
  • Single Responsibility Principle (SRP) - every object in your system should have a single responsibility, and all the object's services should be focused on carrying out that single responsibility. 
    • Each class in your application should have only one reason to change. 
    • Cohesion is another name for SRP. 
    • High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility.
  • Liskov Substitution Principle (LSP) - subtypes must be substitutable for their base types. (ensures that you use inheritance correctly)
  • Delegation is when you hand over the responsibility for a particular task to another class or method. (If you need to use functionality in another class, but you don't want to change that functionality, consider using delegation instead of inheritance.)
  • Composition lets you choose a behavior from a family of behaviors, often via several implementations of an interface. (the composing object owns the behaviors it uses, and they stop existing as soon as the composing object does)
  • Aggregation is when one class is used as part of another class, but still exists outside of that other class.
  • Dependency inversion principle (DIP)
    • High level modules should not depend upon low-level modules. Both should depend upon abstractions.
    • Abstractions should never depend upon details. Details should depend upon abstractions.
Unlike method invocation, inheritance violates encapsulation. In other words, a subclass depends on the implementation details of its superclass for its proper function. The superclass’s implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched. As a consequence, a subclass must evolve in tandem with its superclass, unless the superclass’s authors have designed and documented it specifically for the purpose of being extended.
Instead of extending an existing class, give your new class a private field that references an instance of the existing class. This design is called composition because the existing class becomes a component of the new one. Each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the results. This is known as forwarding, and the methods in the new class are known as forwarding methods. The resulting class will be rock solid, with no dependencies on the implementation details of the existing class. Even adding new methods to the existing class will have no impact on the new class. 

The features in your system are what the system does (they reflect system's functionality).
Use cases show how the system is used. 
Features and use cases work together, but features are not always reflected in your use cases.

SOLID (single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion) is a mnemonic acronym introduced by Michael Feathers for the "first five principles" named by Robert C. Martin in the early 2000s that stands for five basic principles of object-oriented programming and design.


Ref: 


Head-First-Object-Oriented-Analysis-Design
Effective Java
10 Object Oriented Design Principles Java Programmer should know
YAGNI - Martin Fowler
Core Design Principles for Software Developers by Venkat Subramaniam
SOLID Principles : The Definitive Guide
The Principles of OOD (UncleBob)

Monday, May 6, 2013

Disk Helper


Utility class for saving, opening and zipping files.

public class DiskHelper
{

/**
* saveToDisk i openFile
*/
public static void printFileObject(FileObject fo)
{
File file = saveToDisk(fo, fo.getFilename());
openFile(file);
}

public static File saveToDisk(FileObject fo, String fileName)
{
String pdfSuffix = "";
if (!fileName.contains(".pdf"))
{
pdfSuffix = ".pdf";
}

File file = new File("c://tmp//" + fileName + pdfSuffix);

int i = 0;
while (file.exists())
{
i++;
file = new File("c://tmp//" + fileName.replace(".pdf", "") + "_" + i + ".pdf");
}

System.out.println("file.exists: " + file.exists());

OutputStream os;
try
{
os = new FileOutputStream(file);
os.write(fo.getContent());
os.flush();
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return file;

}

public static void openFile(File file)
{
StringBuilder sb = new StringBuilder();
sb.append("cmd.exe /C start ");
sb.append(file.getAbsolutePath());
System.out.println("openFile: " + sb);
try
{
Runtime.getRuntime().exec(sb.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}

private static int byteValue = 1024;

/**
* http://www.mkyong.com/java/how-to-compress-files-in-zip-format/
*/
public static void zipFile(String fileName, File... files)
{
byte[] buffer = new byte[1024];

try
{
File zipfile = new File("C:\\tmp\\" + fileName + ".zip");
FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(fos);

for (File file : files)
{
System.out.println("file.getName(): " + file.getName() + ", file.length(): " + file.length() / byteValue + " KB");
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(file.getAbsoluteFile());
System.out.println("file.getAbsoluteFile(): " + file.getAbsoluteFile());

int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}

in.close();
}

System.out.println("zipfile.getName(): " + zipfile.getName() + ", zipfile.length(): " + zipfile.length() / byteValue + " KB");

zos.closeEntry();
zos.close();

System.out.println("Done");

}
catch (IOException ex)
{
ex.printStackTrace();
}
}

public static void deleteFiles(File... files)
{
for (File file : files)
{
file.delete();
}
}

}



public class FileObject
{
private String filename;
private byte[] content;

public byte[] getContent()
{
return content;
}

public void setContent(byte[] content)
{
this.content = content;
}

public String getFilename()
{
return filename;
}

public void setFilename(String filename)
{
this.filename = filename;
}

}

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.

Thursday, March 14, 2013

Design patterns

Pattern - describes a solution to a common problem arising within a context by:
·       Naming a recurring design structure
·       Specifying design structure explicitly by identifying key class/object
·       Abstracting from concrete design elements, e.g., problem domain, form factor, vendor, etc.
·       Distilling & codifying knowledge gleaned by experts from their successful design experiences


Patterns:


  1. Builder
  2. Proxy
  3. Broker
  4. Command Processor
  5. Observer
  6. Layered Architecture
  7. Strategy
  8. Abstract Factory
  9. Wrapper Facade
  10. Reactor
  11. Acceptor-Connector
  12. Template Method Pattern


Ref:
The 23 Gang of Four Design Patterns .. Revisited
Pattern-Oriented Software Architectures for Concurrent and Networked Software
https://dzone.com/articles/java-design-pattern-simplified-part-1-of-django-se


Builder

is GoF Object Creational pattern.
Separate the construction of a complex object from its representation so that the same construction process can create different representations. 



Ref:
http://java.dzone.com/news/design-pattern-builder-pattern
https://en.wikipedia.org/wiki/Builder_pattern


http://java.dzone.com/articles/intro-design-patterns-prototype


Proxy

is GoF Object Structural pattern.
Intent: Provide a surrogate or placeholder for another object to control access to it
Applicability: Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide
Structure

Dynamics

Consequences
+ Decoupling client from object location
+ Simplify tedious & error-prone details
- Additional overhead from indirection
- May impose overly restrictive type system
- It’s not possible to entirely shield clients from networking & IPC



Broker

is POSA1 Architectural Pattern.
IntentConnect clients with remote objects by mediating invocations from clients to remote objects, while encapsulating the details of IPC or network communication
ApplicabilityApps need capabilities to support (potentially) remote communication, provide location transparency, handle faults, manage end-to-end QoS, & encapsulate low-level system details
Dynamics



Consequences
+ Location independence
+ Separation of concerns
+ Portability, modularity, reusability, etc.
- Additional time & space overhead
- May complicate debugging & testing



Command Processor

is POSA1 Design Pattern (it is similar to Command pattern in GoF book).
Intent: Encapsulate the request for a service as a command object
Applicability:
• Specify, queue, & execute service requests at different times
• Ensure service enhancements don’t break existing code
• Implement additional capabilities (such as undo/redo & persistence) consistently for all requests to a service
Structure & Dynamics

Consequences
+ Allow different users to work with service in different ways via commands
+ Client isn’t blocked for duration of command processing
– Additional programming to handle info passed with commands (cf. Broker)
– Supporting two-way operations requires additional patterns

The Command Processor pattern provides a relatively straightforward means for passing commands asynchronously between threads and/or processes in concurrent & networked software
In contrast, many implementations of Broker use synchronous (blocking) method invocations (Some brokers also support asynchronous method invocations)


Observer

is GoF Object Behavioral pattern (POSA1 book contains description of similar Publisher-Subscriber pattern)
Intent: Define a one-to-many dependency between objects so that when one object changes state, all dependents are notified & updated
Applicability:
• An abstraction has two aspects, one dependent on the other
• A change to one object requires changing untold others
• An object should notify unknown other objects
Structure 
Dynamics
Consequences
+ Modularity: subject & observers may vary independently
+ Extensibility: can define/add any # of observers
+ Customizability: different observers offer different views of subject
– Unexpected updates: observers don’t know about each other
– Update overhead: too many irrelevant updates


Layered Architecture

is POSA1 Design Pattern.

The Layered architectural pattern helps to structure applications that can be decomposed into groups of subtasks in which each group of subtasks Is at a particular level of abstraction.


Ref: http://posa1.blogspot.com/2008/05/layered-architecture-pattern.html


Strategy

(also known as the policy pattern) is a software design pattern, whereby an algorithm's behaviour can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

You can apply this pattern to a multitude of scenarios, such as validating an input with different criteria, using different ways of parsing, or formatting an input.
The strategy pattern consists of three parts:

  1. An interface to represent some algorithm (the interface Strategy)
  2. One or more concrete implementations of that interface to represent multiple algorithms (the concrete classes ConcreteStrategyA and ConcreteStrategyB)
  3. One or more clients that use the strategy objects

Ref: https://en.wikipedia.org/wiki/Strategy_pattern


Abstract Factory

provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

Ref: https://en.wikipedia.org/wiki/Abstract_factory_pattern


Wrapper Facade

is POSA 2 pattern - A Structural Pattern for Encapsulating Functions within Classes
Intent: Encapsulate low-level functions and data structures within more concise, robust, portable, and maintainable higher-level object-oriented class interfaces.




Benefits
Concise & robust higher-level OO programming interfaces
• Reduce the tedium & increase the type-safety of developing apps, which decreases certain types of accidental complexities
Portability & maintainability
• Shield app developers from non-portable aspects of lower-level APIs
Modularity, reusability, & configurability
• Creates cohesive & reusable class components that can be ‘plugged’ into other components in a wholesale fashion
• e.g., using OO language features like inheritance & parameterized types

Limitations
Loss of functionality
• Whenever a portable abstraction is layered on top of an existing API it’s possible to lose functionality
Performance degradation
• Performance can degrade if many forwarding function calls and/or indirections are made per wrapper façade method
Programming language & compiler limitations
• May be hard to define wrapper facades for certain languages due to a lack of language support or limitations with compilers



Known usages:
The Java Virtual Machine (JVM) and various Java foundation class libraries, such as AWT and Swing, provide a set of wrapper facades that encapsulate most of the lowlevel native OS system calls and GUI APIs.

Ref: https://en.wikipedia.org/wiki/Facade_pattern
       http://www.cs.wustl.edu/~schmidt/PDF/wrapper-facade.pdf


Reactor

-An Object Behavioral Pattern for Demultiplexing and Dispatching Handles for Synchronous Events
Intent: The Reactor design pattern handles service requests that are delivered concurrently to an application by one or more clients. Each service in an application may consist of serveral methods and is represented by a separate event handler that is responsible for dispatching service-specific requests. Dispatching of event handlers is performed by an initiation dispatcher, which manages the registered event handlers. Demultiplexing of service requests is performed by a synchronous event demultiplexer.


Acceptor-Connector

-An Object Creational Pattern for Connecting and Initializing Communication Services
Intent: The Acceptor-Connector design pattern decouples connection establishment and service initialization in a distributed system from the processing performed once a service is initialized. This decoupling is achieved with three components: acceptors, connectors, and service handlers. A connector actively establishes a connection with a remote acceptor component and initializes a service handler to process data exchanged on the connection. Likewise, an acceptor passively waits for connection requests from remote connectors, establishing a connection upon arrival of such a request, and initializing a service handler to process data exchanged on the connection. The initialized service handlers then perform application-specific processing and communicate via the connection established by the connector and acceptor components.

Template Method Pattern

The template method design pattern is a common solution when you need to represent the outline of an algorithm and have the additional flexibility to change certain parts of it. In other words, the template method pattern is useful when you ind yourself in a situation such as "I’d love to use this algorithm but I need to change a few lines so it does what I want."

A Template Method Pattern contains a method that provides the steps of the algorithm. It allows subclasses to override some of the methods.

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, December 10, 2012

Oracle XE


Change HTTP port

Default port is 8080!
start Run SQL Command Line
connect as sysdba
begin
dbms_xdb.sethttpport('80');
end;
/
select dbms_xdb.gethttpport from dual;
shutdown immediate;
startup


http://daust.blogspot.com/2006/01/xe-changing-default-http-port.html

Wednesday, November 7, 2012

Port forwarding /tunneling


From wiki

Port forwarding or port mapping is a name given to the combined technique of:
  1. translating the address and/or port number of a packet to a new destination 
  2. possibly accepting such packet(s) in a packet filter (firewall)
  3. forwarding the packet according to the routing table.

The destination may be a predetermined network port (assuming protocols like TCP and UDP, though the process is not limited to these) on a host within a NAT-masqueraded, typically private network, based on the port number on which it was received at the gateway from the originating host.
The technique is used to permit communications by external hosts with services provided within a private local area network.

Examples

Windows server
Kad dodje komunikacija prema 213.186.16.227:1433 preusmjeri to na 192.168.7.27:1433
netsh interface portproxy add v4tov4 
listenport=1433 listenaddress=213.186.16.227 
connectport=1433 connectaddress=192.168.7.27

Display all port forwards::
netsh interface portproxy show all

Delete:
netsh interface portproxy delete v4tov4 
listenport=1433 listenaddress=213.186.16.227 

For putty tunneling:
http://www.codemastershawn.com/library/tutorial/ssh.tunnel.php

Friday, September 21, 2012

Spring web security


in web.xml:

Define the filter and filter-mapping for Spring Security (single proxy filter):
<filter>
           <filter-name>springSecurityFilterChain</filter-name>
           <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
          <filter-name>springSecurityFilterChain</filter-name>
          <url-pattern>/*</url-pattern>
 </filter-mapping>

in the Application Context:

- using security namespace
<security:http access-denied-page="/denied.jsp" use-expressions="true">
<security:form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?login_error=true" />
<security:intercept-url pattern="/accounts/edit*" access="hasRole('ROLE_EDITOR')" />
<security:intercept-url pattern="/accounts/account*" access="hasAnyRole('ROLE_VIEWER','ROLE_EDITOR')" />
<security:intercept-url pattern="/accounts/**" access="isAuthenticated()" />
<security:logout/>
</security:http>

intercept-url are evaluated in the order listed (the first match will be used; specific matches should be put on top).
access-denied-page - user is logged in but it does not have appropriate role.
security:logout - Incorporates a logout processing filter.

<security:authentication-manager>  --configure authentication
<security:authentication-provider>
<security:password-encoder hash="md5" >
<security:salt-source system-wide="MySalt" or user-property=“id“ />
</security:password-encoder>
<security:user-service properties="/WEB-INF/users.properties" />
or use jdbc or ldap -user-service
<security:jdbc-user-service data-source-ref="dataSource"/>
</security:authentication-provider>
</security:authentication-manager>

Thursday, September 20, 2012

Spring best practices


  • DO NOT use version numbers with the Spring schema namespaces
  • Always use classpath:/ prefix for consist resource referencing
  • Always use a single XML config file to bootstrap the application or tests
  • Use the XML “id” attribute to identify a bean
  • Use Constructor injection to promote thread safety
  • Use Properties for configurable resources


Monday, September 17, 2012

Oracle functions

System functions

SYS_GUID()

SYS_GUID generates and returns a globally unique identifier (RAW value) made up of 16 bytes. On most platforms, the generated identifier consists of a host identifier, a process or thread identifier of the process or thread invoking the function, and a nonrepeating value (sequence of bytes) for that process or thread.

Ref: http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/functions153.htm

SYSDATE

SYSDATE returns the current date and time set for the operating system on which the database resides.

Ref: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions172.htm

Example:

insert into TABLE2 (oid, created) VALUES(sys_guid(), sysdate)

To_Date function

In Oracle/PLSQL, the to_date function converts a string to a date.
The syntax for the to_date function is:

to_date( string1, [ format_mask ], [ nls_language ] )

string1 is the string that will be converted to a date.
format_mask is optional. This is the format that will be used to convert string1 to a date.
nls_language is optional. This is the nls language used to convert string1 to a date.

Example:
to_date('1.9.2012','dd.mm.yyyy')
to_date('1.9.2012 23:59:59','dd.mm.yyyy HH24:mi:ss')

Between condition

The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates

SELECT *
FROM orders
WHERE order_date between to_date ('2003/01/01', 'yyyy/mm/dd')
AND to_date ('2003/12/31', 'yyyy/mm/dd');

is equal to 

WHERE order_date >= to_date('2003/01/01', 'yyyy/mm/dd')
AND order_date <= to_date('2003/12/31','yyyy/mm/dd');

Decode function

In Oracle/PLSQL, the decode function has the functionality of an IF-THEN-ELSE statement.
The syntax for the decode function is:

decode( expression , search , result [, search , result]... [, default] )

expression is the value to compare.
search is the value that is compared against expression.
result is the value returned, if expression is equal to search.
default is optional. If no matches are found, the decode will return default. If default is omitted, then the decode statement will return null (if no matches are found).

For Example:
You could use the decode function in an SQL statement as follows:

SELECT supplier_name,
decode(supplier_id, 10000, 'IBM',
10001, 'Microsoft',
10002, 'Hewlett Packard',
'Gateway') result
FROM suppliers;

The above decode statement is equivalent to the following IF-THEN-ELSE statement:

IF supplier_id = 10000 THEN
     result := 'IBM';
ELSIF supplier_id = 10001 THEN
    result := 'Microsoft';
ELSIF supplier_id = 10002 THEN
    result := 'Hewlett Packard';
ELSE
    result := 'Gateway';
END IF;

The decode function will compare each supplier_id value, one by one.
http://www.techonthenet.com/oracle/functions/decode.php

NVL Function

In Oracle/PLSQL, the NVL function lets you substitute a value when a null value is encountered.
The syntax for the NVL function is:

nvl( string1, replace_with )

string1 is the string to test for a null value.
replace_with is the value returned if string1 is null.

Example:

select nvl(commission, 0)
from sales;

This SQL statement would return 0 if the commission field contained a null value. Otherwise, it would return the commission field.
http://www.techonthenet.com/oracle/functions/nvl.php

Pseudocolumns (sequence)

sequence is a schema object that can generate unique sequential values. These values are often used for primary and unique keys. You can refer to sequence values in SQL statements with these pseudocolumns:



CURRVAL 

returns the current value of a sequence. 

NEXTVAL 

increments the sequence and returns the next value. 

Insert into table that has not-null sequence:

INSERT into terminal (terminal_id, terminal_sequence_number)
VALUES('someId', terminal_seq.NEXTVAL);

Get sequence current value:
SELECT empseq.currval FROM DUAL;

Ref
MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.

E.g. Return 2 results:

SELECT * FROM table_name WHERE ROWNUM <= 2;

Adding ORDER BY clause will not return proper data!
Solution is to use

SELECT * FROM ( your_query_here ) WHERE ROWNUM <= N.



Ref

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);
}
}