Monthly Archives: April 2013

Finding the most common element in array

arrays
Here is another way to find the most common element in array.
Just for comparison with Fruz implementation http://fruzenshtein.com/exercise-1/

package com.firetrot.fruz;

import java.util.Arrays;

public class Fruz {

    public static void main(String[] args) {
        int[] arr = { 1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2 };
        System.out.println("Input:  " + Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println("Sorted: " + Arrays.toString(arr));

        int valueName = arr[0];
        int valueCount = 1;

        int tmpCount = 1;
        for (int i = 1; i < arr.length; i++) {
            int prev = arr[i - 1];
            int curr = arr[i];

            // If equals - just increase counter
            if (curr == prev) {
                tmpCount++;
            }

            // If not equals or end of array - make processing
            if (curr != prev || i == arr.length - 1) {
                if (tmpCount > valueCount) {
                    valueName = prev;
                    valueCount = tmpCount;
                }
                // Reset counter
                tmpCount = 1;
            }
        }

        System.out.println("Name: " + valueName);
        System.out.println("Count: " + valueCount);
    }
}

The output:

Input: [1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2]
Sorted: [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 8, 9, 9]
Name: 3
Count: 6

The advantage is no need reason to hold a map of digit – count. So, less memory usage occurs.

SOLID principle in OOP design

solid
Just to remember the issue.

SOLID is:

SRP -Single responsibility principle
A class should have only a single responsibility.

OCP – Open/closed principle
“Software entities … should be open for extension, but closed for modification”.

LSP – Liskov substitution principle
“Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”.

ISP – Interface segregation principle
“Many client-specific interfaces are better than one general-purpose interface.”

DIP – Dependency inversion principle
One should “Depend upon Abstractions. Do not depend upon concretions.”

Source link

Web

JQuery ajax request

ajax
Next example demonstarates Login method:

var backEndpath = '/backend';

function unparam(p) {
  // http://stackoverflow.com/questions/1131630/javascript-jquery-param-inverse-function/4764403#4764403
  var ret = {}, seg = p.replace(/^.*\?/,'').split('&'), len = seg.length, i = 0, s;
  for (;i<len;i++) {
    if (!seg[i]) {
      continue;
    }
    s = seg[i].split('=');
    ret[s[0]] = s[1];
  }
  return ret;
}

function doLogin() {
  var data = unparam($.param( $('form input,textarea,select') ));
  data['operation_name'] = 'login';
  data['formatter'] = 'json';
  $.ajax({
      url: '/user',
      type: 'POST',
      data: data,
      success: function(data) {
        try {
          //alert(data);
          event = JSON.parse(data);
          if (event.is_error == 'true') {
            $('#login_result').html(event.message).show();
          }
          else {
            $(location).attr('href', backEndpath);
          }
        } catch(e) {
        alert(e);
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus + ': ' + errorThrown);
      }
  });
  return false;
}

Method unparam converts all form fields to array.

Getting bundle from java code

Bundle

If you use a bunle file SomeUI.properties in resource folder in JSF (or any web app), to access it from java code is next:

import java.util.ResourceBundle;

public abstract class AbstractBean {
  private static final String SOMEUI_BUNDLE_NAME = "SomeUI";
  private static final ResourceBundle SOMEUI_BUNDLE = 
    ResourceBundle.getBundle(SOMEUI_BUNDLE_NAME);

  private static final String SOME_KEY = SOMEUI_BUNDLE.getString("some_key");
}

SOME_KEY will contain some value.

Sql queries under transaction in Groovy

trans
When you wish to perform some sql queries in transaction, use withTransaction method:

this.class.classLoader.rootLoader.addURL(
  new URL("file:///$jbossPath/lib/ojdbc6.jar"))
Sql sql = Sql.newInstance("ds.url", "ds.user.name", 
  "ds.user.password", "oracle.jdbc.driver.OracleDriver")

sql.withTransaction {
  sql.eachRow("SELECT * FROM USERS") {
    sql.executeUpdate("update USERS set PASSWORD = ? where USER_ID = ?", 
      ["123456", it.USER_ID])
  }
}

Hashing password in Java and Groovy

hash
If you have to get a hash from string, you can use next:

In java:

public static String getPasswordHash(String value) {
  byte[] bytesOfPassword = value.getBytes("UTF-8");
  MessageDigest md = MessageDigest.getInstance("SHA-256");
  md.update(bytesOfPassword);
  byte[] bytesOfEncryptedPassword = md.digest();
  return new String(bytesOfEncryptedPassword);
}

In Groovy (with Base64 encoding!):

def sha256Hash = { text ->
  java.security.MessageDigest.getInstance("SHA-256") 
    .digest(text.getBytes("UTF-8")).encodeBase64().toString()
}