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

Thursday, August 23, 2012

Exists via Criteria API

Parent class has List of Sons. (1:n)
        @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
        @Cascade( { CascadeType.SAVE_UPDATE, CascadeType.LOCK })
        @OrderBy("changeDate DESC")
Son has 1 Parent. (n:1)
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "parentoid", nullable = false)
FK is set on Son table to Parent and it is called PARENTOID.
How to get Parents that have at least 1 son?

select *
  from PARENT p
   where
       exists
            (select h.oid from SON h where p.oid = H.PARENTOID)

2 ways:
1) via Restrictions.isNotEmpty (easy)
DetachedCriteria crit= DetachedCriteria.forClass(Parent.class);
crit.add(Restrictions.isNotEmpty("sons"));

2) via Subqueries.exists - you can add more restrictions in subquery's WHERE clause
DetachedCriteria crit= DetachedCriteria.forClass(Parent.class);

DetachedCriteria subquery = DetachedCriteria.forClass(Son.class, "h");
subquery.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
subquery.setProjection(Projections.id());
subquery.add(Property.forName("parent").eqProperty(crit.getAlias() + ".oid"));
crit.add(Subqueries.exists(subquery));

Monday, June 18, 2012

CRON expressions


import java.text.ParseException;
import java.util.Date;
import org.quartz.CronExpression;

public class CronTester {
 public static void main(String[] args) throws ParseException {
  final String expression = "0 0/30 01-06 * * ?";
  final CronExpression cronExpression = new CronExpression(expression);
  Date date = new Date();
  for (int i = 0; i < 20; i++) {
   date = cronExpression.getNextValidTimeAfter(date);
   System.out.println(date);
  }
 }
}

http://en.wikipedia.org/wiki/Cron
http://www.cronmaker.com/

Tuesday, April 24, 2012

PECS - wildcards - generics

PECS - Pruducer extends, Consumer super

Only applies to input parameters.
Do not use wildcard type for return value - doesn't make it more flexible!

List<String> is a subtype of List<? extends Object>
List<Object> is a subtype of List<? super String>

eg.
pushAll(Collection<? extends E> src);
 - src is an E producer; you can push Long to Collection<Number>
popAll(Collection<? super E> dst);
 - dst is an E consumer; you can pop Numbers to Collection<Object>

Both produces and consumes use T.
Neither produces or consumes use ?.

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

Sort by 2 properties

There is list of articles that needs to be sorted by zone and then by name

List<Article> listaArtikala = articleManager.findByFilter(filter);
// sortiraj artikle po zoni
Collections.sort(listaArtikala, new Comparator<Article>()
{
@Override
public int compare(Article o1, Article o2)
{
return o1.getZone().getMark().compareTo(o2.getZone().getMark());
}
});

// razdvoji po zoni aktikle
Map<String, List<Article>> map = new TreeMap<String, List<Article>>();
for (Article a : listaArtikala)
{
String mark = a.getZone().getMark();
List<Article> tempList = map.get(mark);
if (tempList == null)
{
tempList = new ArrayList<Article>();
map.put(mark, tempList);
}
tempList.add(a);
}
listaArtikala.clear();

// sortiraj po imenu artikla
for (String mark : map.keySet())
{
List<Article> tempList = map.get(mark);
Collections.sort(tempList, new Comparator<Article>()
{
@Override
public int compare(Article o1, Article o2)
{
return o1.getName().compareTo(o2.getName());
}
});
listaArtikala.addAll(tempList);
}

Thursday, January 5, 2012

Reading Active Directory


Example of reading users e-mail address from AD:

public static void main(String[] args)
{
Hashtable env = new Hashtable(11);
env.put(Context.SECURITY_PRINCIPAL, "userName (CN)");
env.put(Context.SECURITY_CREDENTIALS, "pass");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://serverName:389/DC=domain1,DC=hr");

String users = "ou=Unit,ou=Organizational";
try
{
DirContext ctx = new InitialDirContext(env);

Attributes answer = null;
String[] attrIDs = { "mail" };//Specify the ids of the attributes to return
NamingEnumeration list = ctx.list(users);
while (list.hasMore())
{
NameClassPair nc = (NameClassPair) list.next();
System.out.println(nc.getName());
answer = ctx.getAttributes(nc.getName() + " , " + users, attrIDs);
for (NamingEnumeration ae = answer.getAll(); ae.hasMore();)
{
Attribute attr = (Attribute) ae.next();
System.out.println("attribute: " + attr.getID());
/* Print each value */
for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println(e.next()))
;
}
}
}
catch (NamingException e)
{
System.err.println(e);
}
}



Resources:
http://www.windowsnetworking.com/kbase/WindowsTips/Windows2000/AdminTips/ActiveDirectory/ActiveDirectoryNamingStandard.html
http://docs.oracle.com/javase/tutorial/jndi/ops/getattrs.html

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>