Archive for the 'Java' Category

 

Basic REST web service example ..

May 08, 2015 in Java, REST, Web, WebServices

From: http://getj2ee.over-blog.com/article-tutorial-rest-with-spring-mvc-and-maven-97283997.html

[java]

@Controller // –> Declare a Spring MVC Controller

@RequestMapping(“/computer”) // –> Map an URI with a controller or a method

@PathVariable // –> Read a variable in an Uri and assign this value to a java variable

@RequestBody // –> Declare a Pojo class to map the http request body

@ResponseBody // –> Declare a Pojo class to generate Json content to return to the http client

// Declaration as this class as a controller
@Controller

// Declaration that this controller handles requests on uri */computer
@RequestMapping(“/computer”)

public class ComputerController {

// Stores computers
private static final ComputerStorage computerStorage = new ComputerStorage();

// Declare a method that handle all GET request on */computer
@RequestMapping(method = RequestMethod.GET)

// Return a list of computer to the http client
@ResponseBody public List getComputers() {
return computerStorage.getAll();
}
}

[/java]

How to use PriorityQueue

Apr 03, 2015 in Algorithms, Java

From http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue

[java]

// TestPQ.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class TestPQ {
public static void main(String[] args) {
Comparator comparator = new StringLengthComparator();
PriorityQueue queue =
new PriorityQueue(10, comparator);
queue.add(“short”);
queue.add(“very long indeed”);
queue.add(“medium”);
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}

[/java]

[java]

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() – y.length(),
// which would be more efficient.
if (x.length() < y.length()) { return -1; } if (x.length() > y.length()) {
return 1;
}
return 0;
}
}

[/java]

Merge two sorted arrays in Java

Oct 09, 2013 in Algorithms, Java

. . .

From: based on http://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array

[java]

public class m2a {

public static int[] merge(int[] a, int[] b) {

int[] ma = new int[a.length + b.length];
int ax = 0, bx = 0, mx = 0;
while (ax < a.length && bx < b.length) {
if (a[ax] < b[bx]) {
ma[mx++] = a[ax++];
}
else {
ma[mx++] = b[bx++];
}
}

while (ax < a.length) {
ma[mx++] = a[ax++];
}

while (bx < b.length) {
ma[mx++] = b[bx++];
}

return ma;
}

public static void main(String[] args) {
m2a om2a = new m2a();
int a[] = {1, 3, 5, 7};
int b[] = {3, 4, 6, 9};
int ma[] = om2a.merge(a, b);
for ( int mx = 0 ; mx < ma.length ; mx++ ) {
System.out.print(ma[mx] + ” “);
}
System.out.println();
}

}

[/java]

More compact, from same post, newer answer ..

[java]

public class m2a {

public static int[] merge(int[] aa, int[] ba) {

int[] ma = new int[aa.length + ba.length];
int ax = 0, bx = 0, mx = 0;

while (ax < aa.length && bx < ba.length) {
if (aa[ax] < ba[bx])
ma[mx++] = aa[ax++];
else
ma[mx++] = ba[bx++];
}

while (ax < aa.length)
ma[mx++] = aa[ax++];

while (bx < ba.length)
ma[mx++] = ba[bx++];

return ma;
}

public static void main(String[] args) {
m2a om2a = new m2a();
int a[] = {1, 3, 5, 7};
int b[] = {3, 4, 6, 9};
int ma[];

ma = om2a.merge(a, b);
for ( int mx = 0 ; mx < ma.length ; mx++ ) {
System.out.print(ma[mx] + ” “);
}
System.out.println();
}

}

[/java]

Creating Java Exception getStackTrace() as a string

Dec 17, 2012 in Java, language

[java]

public class t1 {
public static void main(String[] args) {
final Throwable t = new IllegalArgumentException(“hi!”);

StringBuffer sb = new StringBuffer();
for (int tx = 0 ; tx < t.getStackTrace().length ; tx ++ ) { sb.append(t.getStackTrace()[tx] ); sb.append("\n"); } System.out.println(sb); } } [/java] or, simpler: [java] System.out.println("STACK: [[" + java.util.Arrays.toString(Thread.currentThread().getStackTrace() ).replace(",", "\n") + "]]" ); [/java] . . .

Java.util.regex Example

Jun 27, 2012 in Java, JavaUsage

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegExp1 {
    private static final Pattern snRegExpPattern = Pattern.compile("^[A-Za-z0-9-_]+");

    public static void main(String []args) {
        checkMatch( "ab.de" );

        checkMatch( "abde" );

        checkMatch( "gh+ij" );

        checkMatch( "kl_mn" );

        checkMatch( "op-qr" );

        checkMatch( "st93uv" );

        checkMatch( "st93uv&" );

    }

    private static void checkMatch(String name) {
        Matcher reMatcher = snRegExpPattern.matcher(name);
        if (! reMatcher.matches() ) {
            System.out.println("Error on " + name);
        }
        else {
            System.out.println("OK on " + name);
        }
    }
}

Expected output :

Error on ab.de
OK on abde
Error on gh+ij
OK on kl_mn
OK on op-qr
OK on st93uv
Error on st93uv&

jMock resources..

Aug 04, 2011 in Java

http://www.jmock.org

http://www.jmock.org/articles.html

http://www.jmock.org/cheat-sheet.html

http://www.jmock.org/cookbook.html

http://www.jmock.org/yoga.html

http://www.jmock.org/mocking-classes.html

This article explains how the mock setup class works
(I have been looking for this for at least 5 hours over 2 days..)

http://dancing-devil.blogspot.com/2011/04/mocking-java-system-class-and.html

To mock System.class and override the currentTimeMillis() method, do this:

Note: this works for protected methods.


Mockit.setUpMock(new MockSystem());

...

@MockClass(realClass = System.class)
public class MockSystem {
    @Mock
    public long currentTimeMillis() {
        ....
        return ....;
    }
}

To redefine methods using another way, including mocking static methods, use this:

public void setUp() throws Exception {
    super.setUp();
    Mockit.redefineMethods(MyClass.class, MockMyClass.class);
    ...
}

....

public static class MockMyClass {
    @Mock
    public static Something doSomething(...) {
        return Something ...;
    }
}

Creating a wlfullclient.jar for JDK 1.6 client applications..

Jul 30, 2010 in Java, Weblogic

From http://download.oracle.com/docs/cd/E12840_01/wls/docs103/client/jarbuilder.html

Use the following steps to create a wlfullclient.jar file for a JDK 1.6 client application:

1.Change directories to the server/lib directory.

cd WL_HOME/server/lib

2. Use the following command to create wlfullclient.jar in the server/lib directory:

java -jar wljarbuilder.jar

3.You can now copy and bundle the wlfullclient.jar with client applications.

4.Add the wlfullclient.jar to the client application’s classpath.

EJB container interface..

Jun 07, 2010 in EJB, JBoss, Weblogic

  1. ejbCreate, ejbPostCreate
  2. ejbLoad, ejbStore
  3. ejbActivate, ejbPassivate

Reversing a singly-linked list in Java .. iterative and recursive methods ..

Dec 27, 2009 in Algorithms, Java

From http://www.java2blog.com/2014/07/how-to-reverse-linked-list-in-java.html

[java]

public void reverse(ListNode head) {
ListNode curr = head;
ListNode prev = null;
ListNode next = null;

while (curr != null) {
next = curr.next;
curr.next = prev; // reverse link to previous
prev = curr;
curr = next;
}

return prev;
}

[/java]

Recursive method:

[java]
public ListNode reverseList(ListNode head) {
// from: http://www.java2blog.com/2014/07/how-to-reverse-linked-list-in-java.html
if ( head == null || head.next == null )
return head;

ListNode rlist = reverseList(head.next);
head.next.next = head;
head.next = null;

return rlist;
}
[/java]

. . .

Breadth first search traversal algorithm..

Dec 02, 2009 in Algorithms, Java

http://en.allexperts.com/q/Computer-Science-3197/Bread-First-Search-Algorithm.htm


BFS(G, s)
 for each vertex u in V - { s } do
   u.color = white
   u.dist = infinity  // ''dist'' is distance from s
   u.pred = nil       // ''pred'' is predecessor
 s.color = gray
 s.dist = 0
 s.pred = nil
 Q = { s }            // ''Q'' is a FIFO queue
 while Q not empty do
   u = Q.head         // get element on top of queue
   for each v in neighbors(u) do  // visit every node u has an edge to
     if v.color == white then
       v.color = gray
       v.dist = u.dist + 1
       v.pred = u
       Q.enqueue(v)   // add v to back of queue
   Q.dequeue          // pop u off top of queue
   u.color = black

And a bit more Java-ish..

[java]

BFS(root) {
cn = root;

s.push(cn.getValue()); // Save node value on stack
cn.setValue(-1); // mark node visited
q.enqueue(cn);

while(! q.isEmpty() ) {
cn = q.dequeue();
foreach v in cn.getChildren() {
if (v.getValue() != -1) {
// This node not visited yet
s.push(v.getValue()); // save node value on stack
v.setValue(-1); // mark node visited
q.enqueue(v);
}
}
}

}

[/java]

And even simpler..

[java]

BFS(root) {
cn = root;

cn.visit(); // mark node visited
q.enqueue(cn);

while(! q.isEmpty() ) {
cn = q.dequeue();

foreach v in cn.getChildren() {
if ( ! v.visited() ) {
// This node not visited yet
v.visit(); // mark node visited
q.enqueue(v);
}
}
}

}

[/java]