Skip to content

Commit

Permalink
Merge pull request #28 from evasiba-ericsson/master
Browse files Browse the repository at this point in the history
 	made publish handle any json and not only json arrays
  • Loading branch information
vasile-baluta authored Oct 5, 2016
2 parents 1e28a96 + a40ab61 commit fae7993
Show file tree
Hide file tree
Showing 12 changed files with 426 additions and 203 deletions.
7 changes: 4 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
classpath 'org.github.ngbinh.scalastyle:gradle-scalastyle-plugin_2.11:0.8.2'
}
}
Expand All @@ -21,7 +21,7 @@ plugins {

war {
baseName = 'remrem-publish'
version = '0.1.5'
version = '0.1.6'
}

apply plugin: 'spring-boot'
Expand Down Expand Up @@ -70,7 +70,7 @@ repositories {
}

ext {
sprintBootVersion = "1.3.5.RELEASE"
sprintBootVersion = "1.4.1.RELEASE"
}

task wrapper(type: Wrapper) {
Expand Down Expand Up @@ -99,6 +99,7 @@ dependencies {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
compile "org.springframework.boot:spring-boot-starter-actuator:$sprintBootVersion"
compile "org.springframework.boot:spring-boot:$sprintBootVersion"
compile 'com.rabbitmq:amqp-client:3.5.7'
compile 'com.google.code.gson:gson:2.6.2'
compile 'org.projectlombok:lombok:1.16.8'
Expand Down
70 changes: 37 additions & 33 deletions src/main/java/com/ericsson/eiffel/remrem/publish/App.java
Original file line number Diff line number Diff line change
@@ -1,41 +1,45 @@
package com.ericsson.eiffel.remrem.publish;

import lombok.extern.slf4j.Slf4j;
import java.util.List;

import org.springframework.boot.Banner;
import org.springframework.boot.DefaultApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;

import com.ericsson.eiffel.remrem.publish.cli.CLI;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.util.Arrays;
import com.ericsson.eiffel.remrem.publish.cli.CliOptions;
import com.ericsson.eiffel.remrem.publish.config.SpringLoggingInitializer;

@SpringBootApplication
@Slf4j
@SpringBootApplication
@ComponentScan("com.ericsson.eiffel.remrem")
public class App extends SpringBootServletInitializer {
public static void main(String[] args) {

// CLI class checks if arguments are passed to application
// and if so we do not start the service but act based on
// passed arguments. If no arguments are passed the server
// will be started
CLI cli = new CLI();
boolean needsStartService = cli.parse(args);

if (needsStartService) {
startService(args);
}
}

private static void startService(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args);

log.info("Let's inspect the beans provided by Spring Boot:");

String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
log.info(beanName);
}
}
public static void main(String[] args) {
startService(args);
}

private static void startService(String[] args) {
handleArgs(args);
SpringApplication application = new SpringApplication(App.class);
application.addInitializers(new SpringLoggingInitializer());
application.setBannerMode(Banner.Mode.OFF);
application.setLogStartupInfo(false);
// We do not start web service if any CLI arguments are passed
if (CliOptions.hasParsedOptions())
application.setWebEnvironment(false);
ApplicationContext ctx = application.run(args);
}

private static void handleArgs(String[] args) {
//We sort out Spring specific arguments and send the others to CLI parser
DefaultApplicationArguments springARgs = new DefaultApplicationArguments(args);
List<String> nonOptions = springARgs.getNonOptionArgs();
String[] nonSpringArgs = nonOptions.toArray(new String[0]);
// We need to parse the cLI options before Spring starts since we need the available when
// Spring instantiate autowired components needing argument values
if (nonSpringArgs.length > 0)
CliOptions.parse(nonSpringArgs);
}
}
184 changes: 64 additions & 120 deletions src/main/java/com/ericsson/eiffel/remrem/publish/cli/CLI.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
package com.ericsson.eiffel.remrem.publish.cli;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import com.ericsson.eiffel.remrem.publish.config.PropertiesConfig;
import com.ericsson.eiffel.remrem.publish.helper.RMQHelper;
import com.ericsson.eiffel.remrem.publish.service.MessageService;
import com.ericsson.eiffel.remrem.publish.service.MessageServiceRMQImpl;
import com.ericsson.eiffel.remrem.publish.service.SendResult;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
* Class for interpreting the passed arguments from command line.
Expand All @@ -35,130 +30,62 @@
* @author evasiba
*
*/
public class CLI {
private Options options=null;

public CLI() {
options = createCLIOptions();
}

/**
* Creates the options needed by command line interface
* @return the options this CLI can handle
*/
private static Options createCLIOptions() {
Options options = new Options();
options.addOption("h", "help", false, "show help.");
options.addOption("f", "content_file", true, "event content file, mandatory");
options.addOption("mb", "message_bus", true, "host of message bus to use, default is 127.0.0.1");
options.addOption("en", "exchange_name", true, "exchange name, default is eiffel.poc");
options.addOption("rk", "routing_key", true, "routing key, mandatory");
options.addOption("np", "non_persistent", false, "remove persistence from message sending");

return options;
}

/**
* Prints the help for this application and exits.
* @param options the options to print usage help for
*/
private static void help(Options options) {
// This prints out some help
HelpFormatter formater = new HelpFormatter();
formater.printHelp("java -jar", options);
System.exit(1);
}

/**
* Parse the given arguments and act on them
* @param args command line arguments
* @return if the service should start or not
*/
public boolean parse(String[] args) {
CommandLineParser parser = new DefaultParser();
boolean startService = true;
try {
CommandLine commandLine = parser.parse(options, args);
Option[] existingOptions = commandLine.getOptions();
if (existingOptions.length > 0) {
startService = false;
handleOptions(commandLine);
}
} catch (Exception e) {
e.printStackTrace();
help(options);
}
return startService;
}
@Component
@ComponentScan(basePackages = "com.ericsson.eiffel.remrem")
public class CLI implements CommandLineRunner{

@Autowired @Qualifier("messageServiceRMQImpl") MessageService messageService;

/**
* Delegates actions depending on the passed arguments
* @param commandLine command line arguments
*/
private void handleOptions(CommandLine commandLine) {
handleMessageBusOptions(commandLine);
private void handleOptions() {
CommandLine commandLine = CliOptions.getCommandLine();
if (commandLine.hasOption("h")) {
System.out.println("You passed help flag.");
clearSystemProperties();
help(options);
} else if (commandLine.hasOption("f") && commandLine.hasOption("rk")) {
CliOptions.clearSystemProperties();
CliOptions.help();
} else if (commandLine.hasOption("f")) {
String filePath = commandLine.getOptionValue("f");
String routingKey = commandLine.getOptionValue("rk");
handleContentFile(filePath, routingKey);
handleContentFile(filePath);
} else if (commandLine.hasOption("json")) {
String content = getJsonString(commandLine);
handleContent(content);
} else {
System.out.println("Missing arguments, please review your arguments" +
" and check if any mandatory argument is missing");
clearSystemProperties();
help(options);
CliOptions.clearSystemProperties();
CliOptions.help();
}
}

/**
* Sets the system properties with values passed for
* message bus host and exchange name
* @param commandLine command line arguments
*/
private void handleMessageBusOptions(CommandLine commandLine){
if (commandLine.hasOption("mb")) {
String messageBusHost = commandLine.getOptionValue("mb");
String key = PropertiesConfig.MESSAGE_BUSS_HOST;
System.setProperty(key, messageBusHost);
}
private String getJsonString(CommandLine commandLine) {
String jsonContent = commandLine.getOptionValue("json");

if (commandLine.hasOption("en")) {
String exchangeName = commandLine.getOptionValue("en");
String key = PropertiesConfig.EXCHANGE_NAME;
System.setProperty(key, exchangeName);
if (jsonContent.equals("-")) {
try {
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bufReader = new BufferedReader(isReader);
jsonContent = bufReader.readLine();
} catch (Exception e) {
e.printStackTrace();
System.exit(-5);
}

}

String usePersistance = "true";
if (commandLine.hasOption("np")) {
usePersistance = "false";
}
String key = PropertiesConfig.USE_PERSISTENCE;
System.setProperty(key, usePersistance);
return jsonContent;
}

/**
* Handle event from file
* @param filePath the path of the file where the messages reside
*/
public void handleContentFile(String filePath, String routingKey) {
JsonParser parser = new JsonParser();
public void handleContentFile(String filePath) {
try {
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
String fileContent = new String(fileBytes);
JsonArray bodyJson = parser.parse(fileContent).getAsJsonArray();
List<String> msgs = new ArrayList<>();
for (JsonElement obj : bodyJson) {
msgs.add(obj.toString());
}
MessageService msgService = new MessageServiceRMQImpl();
List<SendResult> results = msgService.send(routingKey, msgs);
msgService.cleanUp();
clearSystemProperties();
for(SendResult result : results)
System.out.println(result.getMsg());
handleContent(fileContent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Expand All @@ -167,13 +94,30 @@ public void handleContentFile(String filePath, String routingKey) {
}

/**
* Remove the system properties add by this application
* Handle event from file
* @param filePath the path of the file where the messages reside
*/
private void clearSystemProperties() {
String key = PropertiesConfig.MESSAGE_BUSS_HOST;
System.clearProperty(key);
key = PropertiesConfig.EXCHANGE_NAME;
System.clearProperty(key);
}
public void handleContent(String content) {
try {
String routingKey = CliOptions.getCommandLine().getOptionValue("rk");
List<SendResult> results = messageService.send(content, routingKey);
for(SendResult result : results)
System.out.println(result.getMsg());
messageService.cleanUp();
CliOptions.clearSystemProperties();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
}
}

@Override
public void run(String... args) throws Exception {
if (CliOptions.hasParsedOptions())
handleOptions();
boolean cliMode = Boolean.getBoolean(PropertiesConfig.CLI_MODE);
if (cliMode)
CliOptions.help();
}
}
Loading

0 comments on commit fae7993

Please sign in to comment.