import java.util.HashSet;
public class LCS {
private int [][] LCS_Matrix(String oldStr, String newStr) {
int m[][] = new int[oldStr.length() + 1][newStr.length() + 1];
for (int i = 1; i <= oldStr.length(); i++) {
for (int j = 1; j <= newStr.length(); j++) {
char c1 = oldStr.charAt(i - 1);
char c2 = newStr.charAt(j - 1);
if (c1 == c2) {
m[i][j] = m[i - 1][j - 1] + 1;
} else {
m[i][j] = Math.max(m[i - 1][j], m[i][j - 1]);
}
}
}
return m;
}
private HashSet<String> backTraceAll(int[][] m, String oldStr, String newStr, int i, int j) {
if (i == 0 || j == 0) {
HashSet<String> a = new HashSet<>();
a.add("");
return a;
} else if (oldStr.charAt(i - 1) == newStr.charAt(j - 1)) {
HashSet<String> a = new HashSet<>();
HashSet<String> b = backTraceAll(m, oldStr, newStr, i - 1, j - 1);
for (String g : b) {
a.add(g + oldStr.charAt(i - 1));
}
return a;
} else {
HashSet<String> a = new HashSet<>();
if (m[i][j - 1] >= m[i - 1][j])
a.addAll(backTraceAll(m, oldStr, newStr, i, j - 1));
if (m[i - 1][j] >= m[i][j - 1])
a.addAll(backTraceAll(m, oldStr, newStr, i - 1, j));
return a;
}
}
public void process(String oldStr, String newStr) {
int [][] LCSMatrix = LCS_Matrix(oldStr, newStr);
HashSet<String> hs = backTraceAll(LCSMatrix, oldStr, newStr, oldStr.length(), newStr.length());
System.out.println("List of Longest Common Subsequence:");
for(String s : hs)
System.out.println(s);
}
public static void main(String[] args) {
new LCS().process("abc512238gh", "abc523278gh");
}
}
Category Archives: Java
BTree in Java
btreeNode.java
import java.util.Vector;
public class btreeNode {
private Vector<Integer> values = new Vector<>();
private Vector<btreeNode> nodes = new Vector<>();
private btreeNode parent = null;
public btreeNode() {
}
public btreeNode(btreeNode p, Vector<Integer> v, Vector<btreeNode> vb) {
parent = p;
values = v;
nodes = vb;
vb.forEach(x -> x.parent = this);
}
btreeNode findNodeToInsert(int v) {
if (isNodeALeaf())
return this;
if (nodes.size() > 0) {
if (v < values.firstElement()) {
return nodes.firstElement().findNodeToInsert(v);
} else if (v > values.lastElement()) {
return nodes.lastElement().findNodeToInsert(v);
} else {
for (int i = 0; i < values.size() - 1; i++) {
if (v > values.elementAt(i) && v < values.elementAt(i + 1)) {
return nodes.elementAt(i + 1).findNodeToInsert(v);
}
}
}
}
return null;
}
btreeNode traverseRight() {
if(isNodeALeaf()) {
return this;
}
return nodes.lastElement().traverseRight();
}
btreeNode findNodeValue(int v) {
for (int i = 0; i < values.size(); i++) {
if (v == values.elementAt(i))
return this;
if (isNodeALeaf())
continue;
if (v < values.firstElement()) {
return nodes.firstElement().findNodeValue(v);
} else if (v > values.lastElement()) {
return nodes.lastElement().findNodeValue(v);
} else if (i + 1 < values.size() &&
v > values.elementAt(i) &&
v < values.elementAt(i + 1)) {
return nodes.elementAt(i + 1).findNodeValue(v);
}
}
return null;
}
public boolean findValue(int v) {
return findNodeValue(v) != null ? true : false;
}
void overflow() throws Exception {
if (values.size() < 5)
return;
if (values.size() >= 5) {
splitNode();
if (parent != null) {
parent.insert(values.firstElement());
int index = parent.getIndexOfNode(this);
if (index < 0)
throw new Exception("Index is out of bound");
parent.removeNode(index);
parent.addAllNodes(index, nodes);
nodes.forEach(x -> x.parent = parent);
}
}
if (parent != null) {
parent.overflow();
}
}
void transferNodeFromLeft(int i, btreeNode leftNode) {
int val1 = parent.valueAt(i - 1);
values.add(0, val1);
int val2 = leftNode.getLastValue();
leftNode.removeLastValue();
parent.setValueAt(i - 1, val2);
if(parent.nodeAt(i - 1).isNodeALeaf() == false) {
btreeNode node1 = parent.nodeAt(i - 1).removeLastNode();
nodes.add(0, node1);
node1.parent = this;
}
}
void transferNodeFromRight(int i, btreeNode rightNode) {
int val1 = parent.valueAt(i);
values.add(val1);
int val2 = rightNode.removeFirstValue();
parent.setValueAt(i, val2);
if(parent.nodeAt(i + 1).isNodeALeaf() == false) {
btreeNode node1 = parent.nodeAt(i + 1).removeFirstNode();
nodes.add(node1);
node1.parent = this;
}
}
void mergeNodeToLeft(int i, btreeNode leftNode) {
int val = parent.removeValue(i - 1);
parent.removeNode(this);
values.add(0, val);
leftNode.mergeNodes(this);
}
void mergeNodeToRight(int i, btreeNode rightNode) {
int val = parent.removeValue(i);
parent.removeNode(rightNode);
values.add(val);
mergeNodes(rightNode);
}
void underflow() throws Exception {
if(parent == null)
return;
if(values.size() > 1)
return;
int i = parent.getIndexOfNode(this);
if (i < 0)
throw new Exception("Index is out of bound");
if (i == 0) {
btreeNode rightNode = parent.nodeAt(i + 1);
int rightSize = rightNode.valueSize();
if(rightSize == 2) {
mergeNodeToRight(i, rightNode);
setRoot();
}
else {
transferNodeFromRight(i, rightNode);
}
}
else if(i == parent.nodeSize() - 1) {
btreeNode leftNode = parent.nodeAt(i - 1);
int leftSize = leftNode.valueSize();
if(leftSize == 2) {
mergeNodeToLeft(i, leftNode);
leftNode.setRoot();
}
else {
transferNodeFromLeft(i, leftNode);
}
}
else {
btreeNode leftNode = parent.nodeAt(i - 1);
btreeNode rightNode = parent.nodeAt(i + 1);
int leftSize = leftNode.valueSize();
int rightSize = rightNode.valueSize();
if (leftSize > rightSize) {
transferNodeFromLeft(i, leftNode);
} else if (leftSize < rightSize) {
transferNodeFromRight(i, rightNode);
} else {
mergeNodeToLeft(i, leftNode);
}
}
if(parent != null && parent.valueSize() == 1)
parent.underflow();
}
void setRoot() {
if(parent.valueSize() == 0) {
parent.values = values;
parent.nodes = nodes;
nodes.forEach(x -> x.parent = parent);
parent.parent = null;
}
}
void mergeNodes(btreeNode n2) {
values.addAll(n2.values);
nodes.addAll(n2.nodes);
nodes.forEach(x -> x.parent = this);
}
public void insert(int v) {
int i = 0;
for (; i < values.size(); i++) {
if (values.elementAt(i) > v) {
break;
}
}
values.add(i, v);
}
public void splitNode() {
Vector<Integer> leftValues = new Vector<>(values.subList(0, values.size() / 2));
Vector<Integer> rightValues = new Vector<>(values.subList(values.size() / 2 + 1, values.size()));
Vector<btreeNode> leftNodes = new Vector<>(nodes.subList(0, nodes.size() / 2));
Vector<btreeNode> rightNodes = new Vector<>(nodes.subList(nodes.size() / 2, nodes.size()));
int midVal = values.elementAt(values.size() / 2);
btreeNode leftNode = new btreeNode(this, leftValues, leftNodes);
btreeNode rightNode = new btreeNode(this, rightValues, rightNodes);
values.clear();
nodes.clear();
values.add(midVal);
nodes.add(leftNode);
nodes.add(rightNode);
}
Vector<btreeNode> getNodes() {
return nodes;
}
int getIndexOfNode(btreeNode n) {
return nodes.indexOf(n);
}
int getIndexOfValue(int n) {
return values.indexOf(n);
}
int removeValue(int index) {
return values.remove(index);
}
int removeLastValue() {
return values.remove(values.size() - 1);
}
int removeFirstValue() {
return values.remove(0);
}
btreeNode removeNode(int index) {
return nodes.remove(index);
}
void removeNode(btreeNode n) {
nodes.remove(n);
}
btreeNode removeLastNode() {
return nodes.remove(nodes.size() - 1);
}
btreeNode removeFirstNode() {
return nodes.remove(0);
}
void addAllNodes(int index, Vector<btreeNode> n) {
nodes.addAll(index, n);
}
btreeNode nodeAt(int index) {
return nodes.elementAt(index);
}
int valueAt(int index) {
return values.elementAt(index);
}
void setValueAt(int index, int n) {
values.set(index, n);
}
int valueSize() {
return values.size();
}
int nodeSize() {
return nodes.size();
}
int getLastValue() {
return values.lastElement();
}
btreeNode getParent() {
return parent;
}
boolean isNodeALeaf() {
return nodes.isEmpty();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.size(); i++)
sb.append(values.elementAt(i) + ", ");
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
btree.java
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
public class btree {
btreeNode root = new btreeNode();
void insert(int v) throws Exception {
btreeNode node = root.findNodeToInsert(v);
node.insert(v);
node.overflow();
}
boolean find(int v) {
return root.findValue(v);
}
void delete(int v) throws Exception {
btreeNode n = root.findNodeValue(v);
if(n == null)
return;
int i = n.getIndexOfValue(v);
if(n.isNodeALeaf()) {
n.removeValue(i);
n.underflow();
}
else {
btreeNode lastRight = n.nodeAt(i).traverseRight();
int lastRightVal = lastRight.getLastValue();
lastRight.removeLastValue();
n.setValueAt(i, lastRightVal);
lastRight.underflow();
}
}
void debugStr(int level, btreeNode n, HashMap<Integer, Vector<String>> h) {
Vector<String> s1 = h.get(level);
if (s1 == null) {
s1 = new Vector<>();
h.put(level, s1);
}
s1.add(n.toString() + " (" + n.getParent() + ")");
for (int i = 0; i < n.getNodes().size(); i++) {
debugStr(level + 1, n.getNodes().elementAt(i), h);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
HashMap<Integer, Vector<String>> disp1 = new HashMap<>();
debugStr(1, root, disp1);
Set<Integer> keys = disp1.keySet();
for (Integer i : keys) {
Vector<String> v = disp1.get(i);
v.forEach((String str) -> sb.append(str + " | "));
sb.append("\n");
}
return sb.toString();
}
}
SimpleAdapter in Android
ListView without ImageView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/title" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/artist" />
</LinearLayout>
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", "Poker Face");
map.put("artist", "Lady Gaga");
data.add(map);
map = new HashMap<String, String>();
map.put("title", "Yeah!");
map.put("artist", "Usher");
data.add(map);
SimpleAdapter simpleAdapter = new SimpleAdapter(
this,
data,
R.layout.listview_without_images_view,
new String[]{ "title", "artist" },
new int[]{ R.id.title, R.id.artist });
ListView noImages = (ListView)findViewById(R.id.listViewNoImages);
noImages.setAdapter(simpleAdapter);
ListView with ImageView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/title" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/artist" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView" />
</LinearLayout>
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", "Poker Face");
map.put("artist", "Lady Gaga");
map.put("pic", ((Integer)R.drawable.pic).toString());
data.add(map);
map = new HashMap<String, String>();
map.put("title", "Yeah!");
map.put("artist", "Usher");
map.put("pic", ((Integer)R.drawable.pic2).toString());
data.add(map);
SimpleAdapter simpleAdapter = new SimpleAdapter(
this,
data,
R.layout.listview_with_images_view,
new String[]{ "title", "artist", "pic" },
new int[]{ R.id.title, R.id.artist, R.id.imageView });
simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder(){
@Override
public boolean setViewValue(View view, Object o, String s) {
if(view.getClass() == ImageView.class) {
ImageView image = (ImageView)view;
image.setImageResource(Integer.parseInt(s));
return true;
}
return false;
}
});
ListView withImages = (ListView)findViewById(R.id.listViewImages);
withImages.setAdapter(simpleAdapter);
Full code
https://github.com/randcode-generator/SimpleAdapterExample
Interface and lambda in Java
public class name {
interface IName {
void fullName(String a, String b);
}
public static void main(String[] args) {
IName g = (a, b) -> System.out.println(a + " " + b);
g.fullName("John", "Smith");
}
}
Memory Mapped Files in Java
Program1.cs
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Program1 {
public static void main(String[] args) throws Exception {
File f = new File("/tmp/test.txt");
f.delete();
FileChannel fc = new RandomAccessFile(f, "rw").getChannel();
{
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1000);
String input = "Hello world!!";
for (int i = 0; i < input.length(); i++) {
mem.putChar(input.charAt(i));
}
mem.putChar('\0');
}
System.out.println("Run program 2 then press any key");
System.in.read();
{
System.out.println("\nProgram 2 said: ");
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1000);
char c;
while ((c = mem.getChar()) != '\0') {
System.out.print(c);
}
System.out.println();
}
}
}
Program2.java
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Program2 {
public static void main(String[] args) throws Exception {
File f = new File("/tmp/test.txt");
FileChannel fc = new RandomAccessFile(f, "rw").getChannel();
{
System.out.println("Program 1 said \n");
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1000);
char c;
while ((c = mem.getChar()) != '\0') {
System.out.print(c);
}
System.out.println();
}
{
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1000);
String input = "Randomly generating code";
for (int i = 0; i < input.length(); i++) {
mem.putChar(input.charAt(i));
}
mem.putChar('\0');
}
}
}
Dependency Injection Pattern in Java using Spring (part 4)
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy1</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>.\lib</outputDirectory>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
IValidator.java
package com.compare;
public interface IValidator<T> {
boolean isValid(T instance);
}
GreaterThanFourValidator.java
package com.compare;
public class GreaterThanFourValidator implements IValidator<Integer> {
@Override
public boolean isValid(Integer instance) {
return instance > 4;
}
}
IntegerOnlyValidator.java
package com.compare;
public class IntegerOnlyValidator implements IValidator<String>{
@Override
public boolean isValid(String instance) {
int i = 0;
boolean b = false;
try {
Integer.parseInt(instance);
b = true;
}
catch (Exception e)
{
}
return b;
}
}
GreaterThanFourValidatorTest.java
package com.compare;
public class GreaterThanFourValidatorTest {
IValidator<Integer> validator;
public IValidator<Integer> getValidator() {
return validator;
}
public void setValidator(IValidator<Integer> validator) {
this.validator = validator;
}
}
IntegerOnlyValidatorTest.java
package com.compare;
public class IntegerOnlyValidatorTest {
IValidator<String> validator;
public IValidator<String> getValidator() {
return validator;
}
public void setValidator(IValidator<String> validator) {
this.validator = validator;
}
}
Main.java
package com.compare;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml")) {
IntegerOnlyValidatorTest intOnly = (IntegerOnlyValidatorTest) context.getBean("IntegerOnlyTest");
System.out.println(intOnly.validator.isValid("5554"));
System.out.println(intOnly.validator.isValid("123ab"));
GreaterThanFourValidatorTest greater4Only = (GreaterThanFourValidatorTest) context.getBean("GreaterThanFourTest");
System.out.println(greater4Only.validator.isValid(10));
System.out.println(greater4Only.validator.isValid(1));
}
}
}
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="GreaterThanFour" class="com.compare.GreaterThanFourValidator" />
<bean id="IntegerOnly" class="com.compare.IntegerOnlyValidator" />
<bean id="GreaterThanFourTest" class="com.compare.GreaterThanFourValidatorTest">
<property name="validator">
<ref local="GreaterThanFour"/>
</property>
</bean>
<bean id="IntegerOnlyTest" class="com.compare.IntegerOnlyValidatorTest">
<property name="validator">
<ref local="IntegerOnly"/>
</property>
</bean>
</beans>
Dependency Injection Pattern in Java using Spring (Part 3)
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy1</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>.\lib</outputDirectory>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
IPerson.java
package conferenceRoom;
public interface IPerson {
String getName();
}
Person.java
package conferenceRoom;
public class Person implements IPerson{
String name = "default";
public Person(String name)
{
this.name = name;
}
@Override
public String getName() {
return name;
}
}
IConferenceRoom.java
package conferenceRoom;
public interface IConferenceRoom
{
IPerson[] getPeople();
}
ConferenceRoom.java
package conferenceRoom;
public class ConferenceRoom implements IConferenceRoom {
IPerson[] people;
public ConferenceRoom(IPerson[] people)
{
this.people = people;
}
@Override
public IPerson[] getPeople() {
return people;
}
}
Work.java
package conferenceRoom;
public class Work {
IConferenceRoom conferenceRoom1;
IConferenceRoom conferenceRoom2;
public IConferenceRoom getConferenceRoom1() {
return conferenceRoom1;
}
public void setConferenceRoom1(IConferenceRoom conferenceRoom1) {
this.conferenceRoom1 = conferenceRoom1;
}
public IConferenceRoom getConferenceRoom2() {
return conferenceRoom2;
}
public void setConferenceRoom2(IConferenceRoom conferenceRoom2) {
this.conferenceRoom2 = conferenceRoom2;
}
}
Main.java
package conferenceRoom;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml")) {
Work work = (Work)context.getBean("Work");
System.out.println("People at conference room 1");
for(IPerson p : work.getConferenceRoom1().getPeople())
{
System.out.println(p.getName());
}
System.out.println();
System.out.println("People at conference room 2");
for(IPerson p : work.getConferenceRoom2().getPeople())
{
System.out.println(p.getName());
}
IConferenceRoom outOfTheBlue = (IConferenceRoom)context.getBean("conferenceRoom_OutofTheBlue");
work.setConferenceRoom2(outOfTheBlue);
System.out.println();
System.out.println("People at conference room 1");
for(IPerson p : work.getConferenceRoom1().getPeople())
{
System.out.println(p.getName());
}
System.out.println();
System.out.println("People at conference room 2");
for(IPerson p : work.getConferenceRoom2().getPeople())
{
System.out.println(p.getName());
}
}
}
}
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="John" class="conferenceRoom.Person">
<constructor-arg>
<value>John</value>
</constructor-arg>
</bean>
<bean id="Catherine" class="conferenceRoom.Person">
<constructor-arg>
<value>Catherine</value>
</constructor-arg>
</bean>
<bean id="Ben" class="conferenceRoom.Person">
<constructor-arg>
<value>Ben</value>
</constructor-arg>
</bean>
<bean id="Elizabeth" class="conferenceRoom.Person">
<constructor-arg>
<value>Elizabeth</value>
</constructor-arg>
</bean>
<bean id="Jennifer" class="conferenceRoom.Person">
<constructor-arg>
<value>Jennifer</value>
</constructor-arg>
</bean>
<bean id="Michael" class="conferenceRoom.Person">
<constructor-arg>
<value>Michael</value>
</constructor-arg>
</bean>
<bean id="conference1" class="conferenceRoom.ConferenceRoom">
<constructor-arg>
<array value-type="conferenceRoom.IPerson">
<ref local="John"/>
<ref local="Catherine" />
</array>
</constructor-arg>
</bean>
<bean id="conference2" class="conferenceRoom.ConferenceRoom">
<constructor-arg>
<array value-type="conferenceRoom.IPerson">
<ref local="Ben"/>
<ref local="Elizabeth" />
</array>
</constructor-arg>
</bean>
<bean id="conferenceRoom_OutofTheBlue" class="conferenceRoom.ConferenceRoom">
<constructor-arg>
<array value-type="conferenceRoom.IPerson">
<ref local="Jennifer"/>
<ref local="Michael" />
</array>
</constructor-arg>
</bean>
<bean id="Work" class="conferenceRoom.Work">
<property name="conferenceRoom1">
<ref local="conference1" />
</property>
<property name="conferenceRoom2">
<ref local="conference2" />
</property>
</bean>
</beans>
Dependency Injection Pattern in Java using Spring (Part 2)
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy1</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>.\lib</outputDirectory>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
IPerson.java
package work;
public interface IPerson {
String getName();
}
Person.java
package work;
public class Person implements IPerson{
String name = "default";
public Person(String name)
{
this.name = name;
}
@Override
public String getName() {
return name;
}
}
Work.java
package work;
public class Work {
IPerson office1;
IPerson office2;
public IPerson getOffice1() {
return office1;
}
public void setOffice1(IPerson office1) {
this.office1 = office1;
}
public IPerson getOffice2() {
return office2;
}
public void setOffice2(IPerson office2) {
this.office2 = office2;
}
}
Main.java
package work;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml")) {
Work work = (Work)context.getBean("Work");
System.out.println(work.getOffice1().getName() + " is at office 1");
System.out.println(work.getOffice2().getName() + " is at office 2");
}
}
}
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="John" class="work.Person">
<constructor-arg>
<value>John</value>
</constructor-arg>
</bean>
<bean id="Catherine" class="work.Person">
<constructor-arg>
<value>Catherine</value>
</constructor-arg>
</bean>
<bean id="Work" class="work.Work">
<property name="office1">
<ref local="John"/>
</property>
<property name="office2">
<ref local="Catherine"/>
</property>
</bean>
</beans>
Palindrome in Java
Solution to Project Euler problem 4
package projectEuler;
public class Problem4 {
static boolean isPalindrome(String x)
{
int i = 0;
int j = x.length() - 1;
while (i <= j)
{
if (x.charAt(i) != x.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void main(String[] args) {
int max = 0;
for (int i = 100; i < 1000; i++)
{
for (int j = 100; j < 1000; j++)
{
Integer prod = i * j;
String prodStr = prod.toString();
if(isPalindrome(prodStr))
max = Math.max(max, prod);
}
}
System.out.println(max);
}
}
Simple multithreaded server/client in Java
Server.java
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
public void Start()
{
try {
ServerSocket serverSocket = new ServerSocket(5000);
ExecutorService service = Executors.newFixedThreadPool(20);
while(true)
{
final Socket socket = serverSocket.accept();
service.submit(new Runnable() {
@Override
public void run() {
try {
StringBuilder sb = new StringBuilder();
InputStreamReader br = new InputStreamReader(socket.getInputStream());
int c;
while((c = br.read()) != 0)
{
sb.append((char)c);
}
System.out.println("rec: " + sb.toString());
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
Date date = new Date();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
String outStr = dateFormat.format(date) + '\0';
os.write(outStr.getBytes());
socket.close();
System.out.println("sent: " + sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server s = new Server();
s.Start();
}
}
Client.java
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Client {
public void Start()
{
final int NUMBER_OF_THREADS = 2000;
ExecutorService service = Executors.newFixedThreadPool(20);
for(int i = 0; i < NUMBER_OF_THREADS; i++)
{
service.submit(new Runnable() {
@Override
public void run() {
try {
StringBuilder sb = new StringBuilder();
Socket s = new Socket("127.0.0.1", 5000);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outStr = dateFormat.format(date) + '\0';
os.write(outStr.getBytes());
System.out.println("sent: " + outStr);
InputStreamReader br = new InputStreamReader(s.getInputStream());
int c;
while((c = br.read()) != 0)
{
sb.append((char)c);
}
System.out.println("rec: " + sb.toString());
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
public static void main(String[] args) {
Client c = new Client();
c.Start();
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}