Skip to content

Writing and Deploying a Simple Echo Application

antonbobukh edited this page Oct 26, 2014 · 2 revisions

To demonstrate how to write cocaine applications using cocaine-framework-java let's write simple echo-application that would send back any message.

Writing an application

To create a new project, you need to call mvn archetype:generate goal, like the following:

mvn archetype:generate -DarchetypeCatalog=https://raw.githubusercontent.com/cocaine/cocaine-framework-java/master/archetype-catalog.xml \
    -DarchetypeGroupId=ru.yandex.cocaine \
    -DarchetypeArtifactId=cocaine-worker-archetype \
    -DarchetypeVersion=0.11.1.0 \
    -DgroupId=my.group.id \
    -DartifactId=my-artifact-id \
    -Dversion=version

At this point our worker looks like this:

package my.group.id;

import java.util.Arrays;

import cocaine.Handler;
import cocaine.Runner;
import org.apache.log4j.Logger;
import rx.Observable;
import rx.Observer;

public class Application {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Handler("echo")
    public void echo(Observable<byte[]> request, final Observer<byte[]> response) {
        request.subscribe(new Observer<byte[]>() {
            @Override
            public void onCompleted() {
                logger.info("onCompleted");
                response.onCompleted();
            }

            @Override
            public void onError(Throwable e) {
                logger.info("onError: " + e); 
                response.onError(e);
            }

            @Override
            public void onNext(byte[] bytes) {
                logger.info("onNext: " + Arrays.toString(bytes));
                response.onNext(bytes);
            }
        });
    }   

    public static void main(String[] args) {
        Runner.run(new Application(), args);
    }   

}

Our worker is ready to process requests.

Deploying

There are only few steps left. First, you need to build an application and upload it to the cocaine runtime. There is a file required to run the application - Manifest (manifest.json):

{
    "slave" : "run.sh"
}

There is only one property - slave - location of our run.sh file.

To start the application you must provide a profile (profile.json):

{
    "pool-limit" : 4
}

At last only few steps left:

  • pack an application: mvn package;
  • start cocaine-runtime daemon;
  • upload the application through cocaine-tools: cocaine-tool app upload --name echo --manifest=manifest.json --package=target/my-artifact-id-version-bundle.tar.gz
  • upload a new profile: cocaine-tool profile upload --name echoProfile --profile=profile.json
  • start out the application: cocaine-tool app start --name echo --profile=echoProfile