Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Double.MIN_Value is greater than zero

i got confused today thinking double.Min_Value is 0 but its slightly greater :)

   A constant holding the smallest positive nonzero value of type (oracle java)
0x0.0000000000001P-1022; // 4.9e-324

Template Method


"Defines the skeleton of the algorithm , and defers some implementation to the sub classes."

the above example makeDrink() calls

  1. addWater
  2. addFruit
  3. addIce
the addFruit implementation is left to the sub classes orange and apple juice makers

the method makeDrink is made final so that the steps of making the juice is not changed

State Design Pattern


"It allows to change the behavior of the object when the state of an object changes"


Memento

Memento

Mediator

mediator

Iterator

  • single responsibility, 
  • simplifies aggregator
  • does not expose implementation of aggregator

Strategy Pattern





  1. Defines a set of algorithms
  2. Makes them interchangeable
  3. clients have the option to select 
in the example below the client can tell the type of indexer to use in the dictionary
the behavior of indexer which changes is moved to another class there by separating
the class which changes and the one which does not change 
the dictionary delegates calls to search and sort to the indexer 

Chain Of Responsibility

CHAIN OF RESPONSIBILITY

Proxy

proxy

Composite

Composite

This Pattern is useful

  1. when there is a need for hierarchical structure
  2. when the leaf and non leaf are to be treated alike 
Example GUI: a text field is the simplest component
a form can be a complex component which can have a field.

Facade

Facade

Adaptor

Adaptor

Builder Pattern


"To create a complex object 
controlled by another class director
Build an object step by step"

Abstract Factory


Provides an interface for creating family of objects
Without knowing concrete classes 

Maven Notes

Makes Build easy and uniform
helps maintain project quality
some useful commands
    skip tests
    -Dmaven.test.skip=true or -DskipTests=true
    run a single unit test
    nmvn test -Dtest=TestName
    Debug output
    Mvn -X parameter or -e parameter
    MOJO ?
    Maven plain Old Java Object
    dependencies on public Maven repositories?
    https://repository.apache.org/
    Multiple Threads to resolve Artifacts?
    mvn -Dmave.artifact.threads=10 clean install  (default is 5)
    Create a Maven Project
    nmvn archetype:generate -DgroupId=com.bytes.my -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
     
     
    Phases in Maven
    validate: validate the project is correct and all necessary information is available
    compile: compile the source code of the project
    test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
    package: take the compiled code and package it in its distributable format, such as a JAR.
    integration-test: process and deploy the package if necessary into an environment where integration tests can be run
    verify: run any checks to verify the package is valid and meets quality criteria
    install: install the package into the local repository, for use as a dependency in other projects locally
    deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.
    clean: cleans up artifacts created by prior builds
    site: generates site documentation for this project

























Oracle SOA – JMS

two types of messaging models

  1. Queues : the message is used only once
  2. Topics : its perfect for notification, the same message is used by many clients.

Annotations @ Runtime

for an annotation to be accessible at runtime it has to be annotated as follows
@Retention(RUNTIME)
How to access annotations
Method[] methods = cls.getMethods();
for(int i=0;i<methods.length';i++){
Annotation[] annos = methods[i].getAnnotations();
// the annos[] can be type casted to the annotation and then used.
}

ORA-01691: DEV_SOAINFRA.SYS_LOB

Internal Exception: java.sql.BatchUpdateException: ORA-01691: unable to extend lob segment DEV_SOAINFRA.SYS_LOB0000073615C00017$$ by 1024 in tablespace DEV_SOAINFRA

Error Code: 1691
    at oracle.integration.platform.instance.store.DOStore.put(DOStore.java:177)
    at oracle.integration.platform.instance.error.DOObjectExceptionHandler.recover(DOObjectExceptionHandler.java:41)
    at oracle.integration.platform.instance.error.FileBackedExceptionHandler.recover(FileBackedExceptionHandler.java:301)
    at oracle.integration.platform.instance.error.FileBackedExceptionHandler.run(FileBackedExceptionHandler.java:355)
    at oracle.integration.platform.blocks.executor.WorkManagerExecutor$1.run(WorkManagerExecutor.java:106)
    at weblogic.work.j2ee.J2EEWorkManager$WorkWithListener.run(J2EEWorkManager.java:183)
    at weblogic.work.DaemonWorkThread.run(DaemonWorkThread.java:30)
Caused by: Exception [TOPLINK-4002] (Oracle TopLink - 11g Release 1 (11.1.1.3.0) (Build 100323)): oracle.toplink.exceptions.DatabaseException

 

Solution

Increase the table space of DEV_SOAINFRA

  1. log in to oracle em web gui https://<hostname/ip>:1158/em
  2. click on server tab
  3. under storage –> select Tablespaces
  4. click on edit, then there is another edit click on it too
  5. and then you will get file size increase it appropriately.

image

linux script to replace

replaces a list of properties in a directory /root/source

for y in `ls /source`;
do sed -f replace.sed /root/source/$y > ./tmp/$y;
done


replace.sed
---------------
s/__CLUSTERNAME__/grapesClus/g
s/__Place2__/Value2/g 



Understanding the delivery of email to Google Apps


Any email sent to email addresses hosted on Google Apps can be filtered with Postini (feature from GoogleApps Business Edition).  Postini is the first line of defense from spam and viruses. An e-mail may be quarantined by this system if it contains a virus, is clearly identified as spam or violates system policy rules. If an e-mail is flagged by the Postini system it will be added to the Quarantine area and user will be alerted in a daily Quarantine Summary. The Quarantine Summary has a Deliver option for each message, so if a message has been placed in Quarantine inadvertently a user can request its delivery using this function. If an expected e-mail is missing or a user just wants to check to be proactive, Quarantine can be checked in real time by logging into Postini. From this location, the Quarantine box can be viewed and messages can be delivered if the user so chooses.

Adding users to the Postini

Generally, Postini automatically create user accounts (along with any associated alias addresses) by synchronizing account information with Google Apps account. The first synchronization occurs when service with Google Apps is registered, as part of the activation process. After that, the service synchronizes accounts approximately every 15 to 30 minutes, so the new users quickly receive all the benefits of Postini (Message Security or Message Discovery)

Directory Sync (DS)

Postini service stores a list of users, to allow each user to have custom quarantine and mail filter settings. With Directory Sync, the email protection service can contact the Active Directory(AD) to collect the user list information. Directory Sync will add, delete or move users so that the registered users in the email protection service match the registered users on AD. Directory Sync connects to AD securely, using standard XML technology. Some setup is required to enable Directory Sync to connect to AD


SOA composite

SOA Composite Application: is an assembly of services, components, wires deployed together as a single application
Binding Components Connectivity between soa composite and external world.

Service Binding : incoming
Reference Binding: out going
Service Infrastructure Internal message transport
Service Engines Host the business logic or processing rules of the service components
UDDI and MDS services are stored in MDS and published in UDDI
SOA Archive its a deployment unit.
Wires connect all the above components

Oracle SOA suite components

  • Soa Service Infrastructure : provides routing mechanism and facilitates data flow.
  • Oracle Mediator : used to configure routing services and define rules for them, routes,validates,filters and transforms.
  • Oracle Adapters: is a way to integrate transport protocols like BAM,FTP,JMS,AQ,Files,MQ
  • Business Events and Events Delivery Network:  used to raise events when needed, the definition of events are stored in MDS
  • Oracle Metadata Repository: stores things like the routing rules,xslt,xsd,wsdl etc in the db.
  • Oracle Business Rules : enables routing messages, routing assignments these are stored in  MDS
  • Oracle WSM Policy Manager: provides message level security policies, signing, encryption,                                         
             authentication and role based access , it also collects stats about quality uptime etc.
  • Oracle BPEL Process Manager: Assembles discrete processes( sync and a-sync services ) into and end to end process flow.
  • Human Workflow : used to configure human involvement in the work flow like approval, exception handling and performing activities.
  • Oracle Business Activity Monitoring: Monitors business process/services in real time,analyze events, trends etc
  • Oracle User Messaging Service: enables sending messages from the user to application and application to user.
  • Oracle B2B: exchange of messages between and enterprise and its partners.
  • Oracle JDeveloper: enables developers to model, create, discover, assemble, orchestrate, test, deploy, and maintain
             composite applications based on services.
  • Oracle Enterprise Manager: is used to configure, monitor and manage a SOA composite application.
summary from http://download.oracle.com/docs/cd/E12839_01/integration.1111/e10223/index.htm

Eclipse and tomcat out of memory

Open launch configuration and add the following to the VM arguments.

image

-Xms768m -Xmx1024m -XX:MaxPermSize=512m

Web Services

o
Web Service: a software system designed to support interoperable machine-to-machine interaction over a network.
the interface (contract) of communication is called WSDL.

Web Services Architecture
clip_image001[10]

Service Registry:An registry which maintains the list of service providers.
Service Provider:The one which provides the service.
Service Requestor: The one which requests the service which is the client.
the service requestor or the client sends a SOAP request in an HTTP/SNMP/UDP packet and at the service provider
side the SOAP request is extracted from the packet and interpreted.
Top – Down / Bottom Up Approaches
In top-down approach wsdl is written first and then the java code is generated and implemented.
in bottom-up approach java code is written first and then the wsdl is generated for the same.
Web services with eclipse
eclipse plugin to install:  http://axis.apache.org/axis2/java/core/tools/index.html axis2-eclipse-codegen-plugin
downlaod and extract to plugins folder of eclipse.
WSDL- web services description Language.
Parts of a WSDL
  1. Service : is a collection of network endpoints, or ports.
  2. Binding : the communication protocol used along with the data format specification.
  3. Port Type :collection of abstract operations.
  4. Messages : the data being exchanged.
  5. Types       : has the data types used by the web service.
  6. Operation : description of the operation supported by the service.
  7. Port : endpoint which is a combination of a binding port and a network address
wsdl structure looks like this.
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions>
<wsdl:types>
</wsdl:types>
<wsdl:message name="messageName">
</wsdl:message>
<wsdl:portType name="portName">
</wsdl:portType>
<wsdl:binding name="soapBinding" type="impl:portTypeName">
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/protocol"/>
</wsdl:binding>
<wsdl:service name="serviceName">    
<wsdl:port binding="soapBinding" name="HelloWorld">
</wsdl:port>
</wsdl:service>
</wsdl:definitions>



WSDL supports four types of operations { one-way , request-response , solicit-response , notification }
<soap:binding transport indicates the protocol used for sending the soap request
http,snmp,smtp,ftp etc.
Hello world web services using Eclipse and axis2 plug in.
  1. create a new project with name HelloWebService
  2. write a simple Java Class
    public class HelloImpl {
    // says hello
    public String sayHello() {
    return "Hello world";
    }
    // adds two numbers
    public int addNumbers(int a, int b) {
    return a + b;
    }
    }
     



  3.  Right click on the above class file, select –> Web Services –> Create Web Service
  4. and select test Service from the panel, which will create the webservice as well as test the service.
  5. the server runtime can be used to select the application/web server and click next.
image
6. Select the methods of the java class to be exposed as webservice operations in this case , sayHello and addNumbers operations
image
7. Start the server clicking the start button in the next window and then click next.
8. click next and Finish, which will open the Web services Explorer
image

Take JVM Heap Dump


JVM will generate the heap dump when there is OutOfMemory Error when the following option is used.

-XX:+HeapDumpOnOutOfMemoryError

the dump file will be generated at user home dir.

Approximate Search or Spell Check using Trie in Java

the sample code in java which uses  TRIE ds can be found <<Click here>>

the main program which has to be run is MainRunner.Java

modify the searchString variable in the main program.

books.txt : this file has the list of books which are indexed for the approximate search.

commonwords.txt this file has the words which will be ignored.

Features:

can detect 4 types of errors

the exact word say is programming
1) Transposition : prorgamming
2) Insertion: programNming
3) Deletion: programing {m is deleted}
4) Substitution: projramming

would all list the results of books which have programming text.







Service Mix Drools

Adding A Service mix drools  

mvn archetype:create  -DarchetypeGroupId=org.apache.servicemix.tooling  -DarchetypeArtifactId=servicemix-drools-service-unit  -DarchetypeVersion=2010.01  -DgroupId=com.bytes.tutorial  -DartifactId=drools-su -Dversion=1.01

groupId, Value: com.bytes.tutorial
packageName, Value: com.bytes.tutorial
package, Value: com.bytes.tutorial
version, Value: 1.01
artifactId, Value: com.bytes.drools




here is the example 

i have xml files in a folder C:\SOURCE and the content of them is some thing like this below, based on the content

the drools will be configured in such a way that their destination is decided by the drools.
File1
<?xml version="1.0" encoding="UTF-8"?>
<test id="1">
this file matches rule 1
</test>

File2
<?xml version="1.0" encoding="UTF-8"?>
<test id="2">
this file matches rule 2
</test>

File3
<?xml version="1.0" encoding="UTF-8"?>
<test id="3">
this file matches rule 3
</test>

Then the D-rools are configured like this.
the above rules check the id attribute present in the xml based on that 
they send the messages to one of file_sender1,file_sender2,file_sender3.
package org.apache.servicemix.drools

import org.apache.servicemix.drools.model.Exchange;

global org.apache.servicemix.drools.model.JbiHelper jbi;

rule "Route to target1"
when
me : Exchange( status == Exchange.ACTIVE, $in : in != null )
eval( $in.xpath("/test/@id = 1") )
then
jbi.route( "service:http://servicemix.apache.org/bytes/file_sender1" );
end

rule "Route to target2"
when
me : Exchange( status == Exchange.ACTIVE, $in : in != null )
eval( $in.xpath("/test/@id = 2") )
then
jbi.route( "service:http://servicemix.apache.org/bytes/file_sender2" );
end

rule "Route to target3"
when
me : Exchange( status == Exchange.ACTIVE, $in : in != null )
eval( $in.xpath("/test/@id = 3") )
then
jbi.route( "service:http://servicemix.apache.org/bytes/file_sender3" );
end


File Poller 
<file:poller service="bytes:file_poller" endpoint="file-poller"
targetService="bytes:serviceNameDR"
targetEndpoint="drools" 
file="file:C:/SOURCE">

File Sender
<file:sender service="bytes:file_sender1"
endpoint="file-sender"
directory="file:C:/DESTINATION1" />
<file:sender service="bytes:file_sender2"
endpoint="file-sender"
directory="file:C:/DESTINATION2" />
<file:sender service="bytes:file_sender3"
endpoint="file-sender"
directory="file:C:/DESTINATION3" />

the sample code can be found here download



Caused by: org.drools.CheckedDroolsException : Service Mix Drools

The default template generated by the maven for service mix drools su has some errors like

Caused by: org.drools.CheckedDroolsException: There were errors in the rule source:

Rule Compilation error : [Rule name=Unspecified id, agendaGroup=MAIN, salience=0, no-loop=false]
org/apache/servicemix/drools/Rule_Unspecified_id_0.java (8:292) : in cannot be resolved

it says in Cannot be resolved, the way the default router.drl was generated needs to be corrected,

to access the in Message it has to be prefixed with “$” so it should be $in

rule "Route to target1"
when
me : Exchange( status == Exchange.ACTIVE, $in : in != null )
eval( $in.xpath("/bar:test/@id = 1") )
then
jbi.route( "bytes::file_sender1" );
end





MORPHIC

Morphic is the name given to Pharo’s graphical interface.it does not have separate modes for “composing” and “running” the interface: all the graphical elements can be assembled and disassembled by the user, at any time.
You can create a morph to represent any object, although how good a representation you get depends
on the object!
To create a morph to represent a string object, execute the following code in aworkspace.

                              'Morph' asMorph openInWorld

This creates a Morph to represent the string 'Morph', and then opens it (that is, displays it) in the “world”, which is the name that Pharo gives to the screen. You should obtain a graphical element—a Morph—which you can manipulate by meta-clicking.




MANIPULATING MORPHS:
Morphs are objects, so we can manipulate them like any other object in
Smalltalk: by sending messages, we can change their properties, create new
subclasses of Morph
  • Every morph, even if it is not currently open on the screen, has a position
    and a size.
  • All morphs are considered to occupy a rectangular region of the screen; if they are irregularly shaped, their position and size are those of the smallest rectangular “box” that surrounds them, which is
    known as the morph’s bounding box, or just its “bounds”.
  • The position method returns a Point that describes the location of the morph’s upper left corner (or the upper left corner of its bounding box).
  • The origin of the coordinate system is the screen’s upper left corner, with y coordinates increasing down the screen and x coordinates increasing to the right.
  • The extent method also returns a point, but this point specifies the width and height of the morph
    rather than a location.
    "Type the following code into a workspace and do it :"
                  joe := Morph new color: Color blue.
                  joe openInWorld.
                  bill := Morph new color: Color red .
                  bill openInWorld.
    Then type joe position and print it . To move joe, execute joe position: (joe position +(10@3)) repeatedly.

Design Patterns in the JDK

Design Patterns in the JDK - Java Code Geeks

javax.jbi.messaging.MessagingException: Out not supported

Scenario: FilePoller = > EIP Pipeline => {transformer is the bean below} => File Sender { target }
the exception was at the bean. Complete Exception is below
javax.jbi.messaging.MessagingException: Out not supported
at org.apache.servicemix.jbi.messaging.MessageExchangeImpl.setMessag(MessageExchangeImpl.java:357)
at com.bytes.tutorial.MyBean.onMessageExchange(MyBean.java:46)
at org.apache.servicemix.bean.BeanEndpoint.onProviderExchange(BeanEndpoint.java:230)
at org.apache.servicemix.bean.BeanEndpoint.process(BeanEndpoint.java:217)
at org.apache.servicemix.common.AsyncBaseLifeCycle.doProcess(AsyncBaseLifeCycle.java:627)
at org.apache.servicemix.common.AsyncBaseLifeCycle.processExchange(AsyncBaseLifeCycle.java:581)
at org.apache.servicemix.common.AsyncBaseLifeCycle.onMessageExchange(AsyncBaseLifeCycle.java:535)
at org.apache.servicemix.common.SyncLifeCycleWrapper.onMessageExchangeSyncLifeCycleWrapper.java:60)
at org.apache.servicemix.jbi.messaging.DeliveryChannelImpl.processInBound(DeliveryChannelImpl.java:632)
at org.apache.servicemix.jbi.nmr.flow.AbstractFlow.doRouting(AbstractFlow.java:185)
at org.apache.servicemix.jbi.nmr.flow.seda.SedaFlow.doRouting(SedaFlow.java:168)
at org.apache.servicemix.jbi.nmr.flow.seda.SedaQueue$1.run(SedaQueue.java:134)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)


  public void onMessageExchange(MessageExchange exchange)
throws MessagingException {
System.out.println("Received exchange: " + exchange);
System.out.println("getPattern exchange: " + exchange.getPattern());
System.out.println("getStatus exchange: " + exchange.getStatus());
System.out.println("Role exchange: " + exchange.getRole().toString());
NormalizedMessage in = exchange.getMessage("in");
exchange.setMessage(in, "out");
channel.send(exchange);
}

is changed to have a check

        if (exchange.getStatus() == ExchangeStatus.DONE)
return;
or
  if (exchange.getStatus() == ExchangeStatus.ACTIVE){
System.out.println("Received exchange: " + exchange);
System.out.println("getPattern exchange: " + exchange.getPattern());
System.out.println("getStatus exchange: " + exchange.getStatus());
System.out.println("Role exchange: " + exchange.getRole().toString());
NormalizedMessage in = exchange.getMessage("in");
exchange.setMessage(in, "out");
channel.send(exchange);
}



Failed to read artifact descriptor for bouncycastle:bcprov-jdk13:jar

Failed to read artifact descriptor for bouncycastle:bcprov-jdk13:jar:132: Could not transfer artifact bouncycastle:bcprov-jdk13:pom:132 from java.net (http://download.java.net/maven/1): No connector available to access repository java.net (http://download.java.net/maven/1) of type legacy using the available factories WagonRepositoryConnectorFactory -> [Help 1]


WorkAround

install maven 2.2.1 it solved my problem , i was using 3.0.3 before

ServiceMix EIP Pipeline

MVN command to create a eip
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-eip-service-unit -DarchetypeVersion=2010.01 -DgroupId=com.bytes.tutorial -DartifactId=eip-su -Dversion=1.01
[INFO] Using property: groupId = com.bytes.tutorial
[INFO] Using property: artifactId = eip-su
[INFO] Using property: version = 1.01
[INFO] Using property: package = com.bytes.tutorial
Confirm properties configuration:
groupId: com.bytes.tutorial
artifactId: eip-su
version: 1.01
package: com.bytes.tutorial
Y: y
the eip su is then created ,add this as dependency to the SA
<dependency>

<groupId>com.bytes.tutorial</groupId>

<artifactId>eip-su</artifactId>

<version>1.01</version>

</dependency>
the XBEAN.XML generated will have all examples of the patterns that can be used.
we can use pipe pattern
Source DIR => File-Poller => bytes:pipeline=> myBeanService=> File-Sender => Destination DIR
<eip:pipeline service="bytes:eipPipeBean" endpoint="endpoint">
<eip:transformer>
<eip:exchange-target service="bytes:myBeanService" />
</eip:transformer>
<eip:target>
<eip:exchange-target service="bytes:file_sender" />
</eip:target>
</eip:pipeline>



As show above this EIP pipeline is configured in such a way that


the bean “bytes:myBeanService” processes the data and gives it to the bytes:file_sender .


that should take care of writing the files to that directory.


find the sample code here => Example

Exception Could not find route for exchange: Service Mix

WARN  - FileComponent                  - Target service (fileTObean) and endpoi
t (endpoint) specified, but no matching endpoint found.  Only the service will
e used for routing.
WARN  - DefaultBroker                  - ServiceName (fileTObean) specified for
routing, but can't find it registered
WARN  - DefaultBroker                  - ServiceName (fileTObean) specified for
routing, but can't find it registered
ERROR - FileComponent                  - Failed to process file: D:\boyapati\De
ktop\ALARM\books.xml. Reason: javax.jbi.messaging.MessagingE
ception: Could not find route for exchange: InOnly[
  id: ID:10.142.216.169-12e80f2505a-14:137

this can be because of Name space

check xbean.xml
there is a text generated "xmlns:replaceMe="http://servicemix.apache.org/replaceMe" "
this name space has to be same for a service to find another service. :)

Adding a service Mix Bean

MVN Command used to create bean SU
mvn archetype:generate -DarchetypeGroupId=org.apache.servicemix.tooling
-DarchetypeArtifactId=servicemix-bean-service-unit -DarchetypeVersion=2010.01
-DgroupId=com.bytes.tutorial -DartifactId=bean-su -Dversion=1.01
1K downloaded  (servicemix-bean-service-unit-3.2.3.pom)
[INFO] Using property: groupId = com.bytes.tutorial
[INFO] Using property: artifactId = bean-su
[INFO] Using property: version = 1.01
[INFO] Using property: package = com.bytes.tutorial
Confirm properties configuration:
groupId: com.bytes.tutorial
artifactId: bean-su
version: 1.01
package: com.bytes.tutorial
Y: y
and the bean su is added to the parent folder, for it to be part of an assembly an entry has to be added into the assembly
like this under dependencies tag of sa’s pom.xml
<dependency>
<groupId>org.apache.servicemix</groupId>
<artifactId>servicemix-core</artifactId>
<version>${servicemix-version}</version>
<scope>provided</scope>
</dependency>

A bean class MyBean is created automatically along with the entry in the xbean.xml
package com.bytes.tutorial;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.InOnly;
import javax.jbi.messaging.InOut;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessageExchangeFactory;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.namespace.QName;

import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.jbi.messaging.NormalizedMessageImpl;
import org.apache.servicemix.jbi.util.MessageUtil;

public class MyBean implements MessageExchangeListener {

@Resource
private DeliveryChannel channel;

public void onMessageExchange(MessageExchange exchange)
throws MessagingException {

if (exchange.getStatus() == ExchangeStatus.ACTIVE)
{
System.out.println("Received exchange: " + exchange);
System.out.println("getPattern exchange: " + exchange.getPattern());
System.out.println("getStatus exchange: " + exchange.getStatus());
System.out.println("Role exchange: " + exchange.getRole().toString());
NormalizedMessage in = exchange.getMessage("in");
exchange.setMessage(in, "out");
channel.send(exchange);
       }
}
}






the above bean just consumes a message exchange and prints the message and sends it back to the channel.
<bean:endpoint service="bytes:myBeanService" endpoint="endpoint" bean="#myBean"/>

<bean id="myBean" class="com.bytes.tutorial.MyBean"/>
Configure the bean as the above service so that it can be called from the EIP Pipeline.



we will see in the next post how to integrate the file poller the sender and this bean which will process the data in between.


http://www.snippets.24bytes.com/2011/03/servicemix-eip.html

Hello World File SU (service Mix)

Create a Maven Project
create a empty folder and create a pom.xml with the following content
<?xml version="1.0" encoding="UTF-8"?>
<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.bytes.tutorial</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>bytes</name>
<url>http://servicemix.org</url>
<modules>
<module>bytes-sa</module>
</modules>
</project>

Create a Service Assembly

mvn archetype:generate -DarchetypeArtifactId=servicemix-service-assembly
-DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=bytes-sa

(Note: this will also add an entry into the above pom.xml dependency list)
you will get a prompt asking for
Define value for property 'groupId': : com.bytes.tutorial
[INFO] Using property: artifactId = bytes-sa
Define value for property 'version': 1.0-SNAPSHOT:
Define value for property 'package': com.bytes.tutorial:
Confirm properties configuration:
groupId: com.bytes.tutorial
artifactId: bytes-sa
version: 1.0-SNAPSHOT
package: com.bytes.tutorial
Y: y

Create a Service Unit(File SU)

Command to create a SU

mvn archetype:generate -DarchetypeGroupId=org.ap
ache.servicemix.tooling -DarchetypeArtifactId=servicemix-file-service-unit -Darc
hetypeVersion=2010.01 -DgroupId=com.bytes.tutorial -DartifactId=file-su


[INFO] Using property: groupId = com.bytes.tutorial
[INFO] Using property: artifactId = file-su
[INFO] Using property: version = 1.0
[INFO] Using property: package = com.bytes.tutorial
Confirm properties configuration:
groupId: com.bytes.tutorial
artifactId: file-su
version: 1.0
package: com.bytes.tutorial
Y: y

RUN mvn install

---------------------------------------------------------------
Reactor Summary:
---------------------------------------------------------------
bytes ............................................... SUCCESS
bytes SA ............................................ SUCCESS
Apache ServiceMix :: File Service Unit ................ SUCCESS

---------------------------------------------------------------
---------------------------------------------------------------
BUILD SUCCESSFUL

which means the project is configured successfully.

FILE-SU CONFIGURATION

we will configure the FILE-SU in such a way that the poller polls a director for valid XML files and gives them to file-sender ,

the file sender copies them into another folder

POLLER < =   D:\SOURCE
||
V
SENDER =>  D:\DESTINATION
open the XBEAN.XML under FILE-SU  you would find a poller tag like the one below
POLLER CONFIG
  <file:poller service="bytes:file_poller" endpoint="file-poller"
targetService="bytes:file_sender"
targetEndpoint="file-sender"
file="file:C:/SOURCE">





  1. Give the name of the poller service and its end point.
  2. The target service, end point to which the file polled is sent.
  3. File: the directory which has to be polled regularly for XML files.
SENDER CONFIG

<file:sender service="bytes:file_sender"
endpoint="file-sender"
directory="file:/D:/DESTINATION">






  1. name of the sender service should match the targetService of the poller 

  2. configure the directory where the files should be sent “directory”
do an mvn install and then go to the service assembly folder
and pick the jar file from the target and deploy in the hotdeploy 
folder of service mix and see the MAGIC.
download the sample here

Search 24 Bytes