http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-core/src/main/java/org/apache/activemq/openwire/utils/CronParser.java ---------------------------------------------------------------------- diff --git a/openwire-core/src/main/java/org/apache/activemq/openwire/utils/CronParser.java b/openwire-core/src/main/java/org/apache/activemq/openwire/utils/CronParser.java deleted file mode 100644 index 491f26d..0000000 --- a/openwire-core/src/main/java/org/apache/activemq/openwire/utils/CronParser.java +++ /dev/null @@ -1,357 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.openwire.utils; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.List; -import java.util.StringTokenizer; - -import javax.jms.MessageFormatException; - -public class CronParser { - - private static final int NUMBER_TOKENS = 5; - private static final int MINUTES = 0; - private static final int HOURS = 1; - private static final int DAY_OF_MONTH = 2; - private static final int MONTH = 3; - private static final int DAY_OF_WEEK = 4; - - public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException { - - long result = 0; - - if (cronEntry == null || cronEntry.length() == 0) { - return result; - } - - // Handle the once per minute case "* * * * *" - // starting the next event at the top of the minute. - if (cronEntry.equals("* * * * *")) { - result = currentTime + 60 * 1000; - result = result / 60000 * 60000; - return result; - } - - List<String> list = tokenize(cronEntry); - List<CronEntry> entries = buildCronEntries(list); - Calendar working = Calendar.getInstance(); - working.setTimeInMillis(currentTime); - working.set(Calendar.SECOND, 0); - - CronEntry minutes = entries.get(MINUTES); - CronEntry hours = entries.get(HOURS); - CronEntry dayOfMonth = entries.get(DAY_OF_MONTH); - CronEntry month = entries.get(MONTH); - CronEntry dayOfWeek = entries.get(DAY_OF_WEEK); - - // Start at the top of the next minute, cron is only guaranteed to be - // run on the minute. - int timeToNextMinute = 60 - working.get(Calendar.SECOND); - working.add(Calendar.SECOND, timeToNextMinute); - - // If its already to late in the day this will roll us over to tomorrow - // so we'll need to check again when done updating month and day. - int currentMinutes = working.get(Calendar.MINUTE); - if (!isCurrent(minutes, currentMinutes)) { - int nextMinutes = getNext(minutes, currentMinutes); - working.add(Calendar.MINUTE, nextMinutes); - } - - int currentHours = working.get(Calendar.HOUR_OF_DAY); - if (!isCurrent(hours, currentHours)) { - int nextHour = getNext(hours, currentHours); - working.add(Calendar.HOUR_OF_DAY, nextHour); - } - - // We can roll into the next month here which might violate the cron setting - // rules so we check once then recheck again after applying the month settings. - doUpdateCurrentDay(working, dayOfMonth, dayOfWeek); - - // Start by checking if we are in the right month, if not then calculations - // need to start from the beginning of the month to ensure that we don't end - // up on the wrong day. (Can happen when DAY_OF_WEEK is set and current time - // is ahead of the day of the week to execute on). - doUpdateCurrentMonth(working, month); - - // Now Check day of week and day of month together since they can be specified - // together in one entry, if both "day of month" and "day of week" are restricted - // (not "*"), then either the "day of month" field (3) or the "day of week" field - // (5) must match the current day or the Calenday must be advanced. - doUpdateCurrentDay(working, dayOfMonth, dayOfWeek); - - // Now we can chose the correct hour and minute of the day in question. - - currentHours = working.get(Calendar.HOUR_OF_DAY); - if (!isCurrent(hours, currentHours)) { - int nextHour = getNext(hours, currentHours); - working.add(Calendar.HOUR_OF_DAY, nextHour); - } - - currentMinutes = working.get(Calendar.MINUTE); - if (!isCurrent(minutes, currentMinutes)) { - int nextMinutes = getNext(minutes, currentMinutes); - working.add(Calendar.MINUTE, nextMinutes); - } - - result = working.getTimeInMillis(); - - if (result <= currentTime) { - throw new ArithmeticException("Unable to compute next scheduled exection time."); - } - - return result; - } - - protected static long doUpdateCurrentMonth(Calendar working, CronEntry month) throws MessageFormatException { - int currentMonth = working.get(Calendar.MONTH) + 1; - if (!isCurrent(month, currentMonth)) { - int nextMonth = getNext(month, currentMonth); - working.add(Calendar.MONTH, nextMonth); - - // Reset to start of month. - resetToStartOfDay(working, 1); - - return working.getTimeInMillis(); - } - - return 0L; - } - - protected static long doUpdateCurrentDay(Calendar working, CronEntry dayOfMonth, CronEntry dayOfWeek) throws MessageFormatException { - - int currentDayOfWeek = working.get(Calendar.DAY_OF_WEEK) - 1; - int currentDayOfMonth = working.get(Calendar.DAY_OF_MONTH); - - // Simplest case, both are unrestricted or both match today otherwise - // result must be the closer of the two if both are set, or the next - // match to the one that is. - if (!isCurrent(dayOfWeek, currentDayOfWeek) || !isCurrent(dayOfMonth, currentDayOfMonth)) { - - int nextWeekDay = Integer.MAX_VALUE; - int nextCalendarDay = Integer.MAX_VALUE; - - if (!isCurrent(dayOfWeek, currentDayOfWeek)) { - nextWeekDay = getNext(dayOfWeek, currentDayOfWeek); - } - - if (!isCurrent(dayOfMonth, currentDayOfMonth)) { - nextCalendarDay = getNext(dayOfMonth, currentDayOfMonth); - } - - if (nextWeekDay < nextCalendarDay) { - working.add(Calendar.DAY_OF_WEEK, nextWeekDay); - } else { - working.add(Calendar.DAY_OF_MONTH, nextCalendarDay); - } - - // Since the day changed, we restart the clock at the start of the day - // so that the next time will either be at 12am + value of hours and - // minutes pattern. - resetToStartOfDay(working, working.get(Calendar.DAY_OF_MONTH)); - - return working.getTimeInMillis(); - } - - return 0L; - } - - public static void validate(final String cronEntry) throws MessageFormatException { - List<String> list = tokenize(cronEntry); - List<CronEntry> entries = buildCronEntries(list); - for (CronEntry e : entries) { - validate(e); - } - } - - static void validate(final CronEntry entry) throws MessageFormatException { - List<Integer> list = entry.currentWhen; - if (list.isEmpty() || list.get(0).intValue() < entry.start || list.get(list.size() - 1).intValue() > entry.end) { - throw new MessageFormatException("Invalid token: " + entry); - } - } - - static int getNext(final CronEntry entry, final int current) throws MessageFormatException { - int result = 0; - - if (entry.currentWhen == null) { - entry.currentWhen = calculateValues(entry); - } - - List<Integer> list = entry.currentWhen; - int next = -1; - for (Integer i : list) { - if (i.intValue() > current) { - next = i.intValue(); - break; - } - } - if (next != -1) { - result = next - current; - } else { - int first = list.get(0).intValue(); - result = entry.end + first - entry.start - current; - - // Account for difference of one vs zero based indices. - if (entry.name.equals("DayOfWeek") || entry.name.equals("Month")) { - result++; - } - } - - return result; - } - - static boolean isCurrent(final CronEntry entry, final int current) throws MessageFormatException { - boolean result = entry.currentWhen.contains(new Integer(current)); - return result; - } - - protected static void resetToStartOfDay(Calendar target, int day) { - target.set(Calendar.DAY_OF_MONTH, day); - target.set(Calendar.HOUR_OF_DAY, 0); - target.set(Calendar.MINUTE, 0); - target.set(Calendar.SECOND, 0); - } - - static List<String> tokenize(String cron) throws IllegalArgumentException { - StringTokenizer tokenize = new StringTokenizer(cron); - List<String> result = new ArrayList<String>(); - while (tokenize.hasMoreTokens()) { - result.add(tokenize.nextToken()); - } - if (result.size() != NUMBER_TOKENS) { - throw new IllegalArgumentException("Not a valid cron entry - wrong number of tokens(" + result.size() + "): " + cron); - } - return result; - } - - protected static List<Integer> calculateValues(final CronEntry entry) { - List<Integer> result = new ArrayList<Integer>(); - if (isAll(entry.token)) { - for (int i = entry.start; i <= entry.end; i++) { - result.add(i); - } - } else if (isAStep(entry.token)) { - int denominator = getDenominator(entry.token); - String numerator = getNumerator(entry.token); - CronEntry ce = new CronEntry(entry.name, numerator, entry.start, entry.end); - List<Integer> list = calculateValues(ce); - for (Integer i : list) { - if (i.intValue() % denominator == 0) { - result.add(i); - } - } - } else if (isAList(entry.token)) { - StringTokenizer tokenizer = new StringTokenizer(entry.token, ","); - while (tokenizer.hasMoreTokens()) { - String str = tokenizer.nextToken(); - CronEntry ce = new CronEntry(entry.name, str, entry.start, entry.end); - List<Integer> list = calculateValues(ce); - result.addAll(list); - } - } else if (isARange(entry.token)) { - int index = entry.token.indexOf('-'); - int first = Integer.parseInt(entry.token.substring(0, index)); - int last = Integer.parseInt(entry.token.substring(index + 1)); - for (int i = first; i <= last; i++) { - result.add(i); - } - } else { - int value = Integer.parseInt(entry.token); - result.add(value); - } - Collections.sort(result); - return result; - } - - protected static boolean isARange(String token) { - return token != null && token.indexOf('-') >= 0; - } - - protected static boolean isAStep(String token) { - return token != null && token.indexOf('/') >= 0; - } - - protected static boolean isAList(String token) { - return token != null && token.indexOf(',') >= 0; - } - - protected static boolean isAll(String token) { - return token != null && token.length() == 1 && (token.charAt(0) == '*' || token.charAt(0) == '?'); - } - - protected static int getDenominator(final String token) { - int result = 0; - int index = token.indexOf('/'); - String str = token.substring(index + 1); - result = Integer.parseInt(str); - return result; - } - - protected static String getNumerator(final String token) { - int index = token.indexOf('/'); - String str = token.substring(0, index); - return str; - } - - static List<CronEntry> buildCronEntries(List<String> tokens) { - - List<CronEntry> result = new ArrayList<CronEntry>(); - - CronEntry minutes = new CronEntry("Minutes", tokens.get(MINUTES), 0, 60); - minutes.currentWhen = calculateValues(minutes); - result.add(minutes); - CronEntry hours = new CronEntry("Hours", tokens.get(HOURS), 0, 24); - hours.currentWhen = calculateValues(hours); - result.add(hours); - CronEntry dayOfMonth = new CronEntry("DayOfMonth", tokens.get(DAY_OF_MONTH), 1, 31); - dayOfMonth.currentWhen = calculateValues(dayOfMonth); - result.add(dayOfMonth); - CronEntry month = new CronEntry("Month", tokens.get(MONTH), 1, 12); - month.currentWhen = calculateValues(month); - result.add(month); - CronEntry dayOfWeek = new CronEntry("DayOfWeek", tokens.get(DAY_OF_WEEK), 0, 6); - dayOfWeek.currentWhen = calculateValues(dayOfWeek); - result.add(dayOfWeek); - - return result; - } - - static class CronEntry { - - final String name; - final String token; - final int start; - final int end; - - List<Integer> currentWhen; - - CronEntry(String name, String token, int start, int end) { - this.name = name; - this.token = token; - this.start = start; - this.end = end; - } - - @Override - public String toString() { - return this.name + ":" + token; - } - } -}
http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-core/src/test/java/org/apache/activemq/openwire/commands/OpenWireTextMessageTest.java ---------------------------------------------------------------------- diff --git a/openwire-core/src/test/java/org/apache/activemq/openwire/commands/OpenWireTextMessageTest.java b/openwire-core/src/test/java/org/apache/activemq/openwire/commands/OpenWireTextMessageTest.java index c92f92c..d4a3811 100644 --- a/openwire-core/src/test/java/org/apache/activemq/openwire/commands/OpenWireTextMessageTest.java +++ b/openwire-core/src/test/java/org/apache/activemq/openwire/commands/OpenWireTextMessageTest.java @@ -28,10 +28,7 @@ import javax.jms.JMSException; import javax.jms.MessageNotReadableException; import javax.jms.MessageNotWriteableException; -import org.apache.activemq.openwire.commands.CommandTypes; -import org.apache.activemq.openwire.commands.Message; -import org.apache.activemq.openwire.commands.OpenWireTextMessage; -import org.apache.activemq.util.MarshallingSupport; +import org.apache.activemq.openwire.utils.MarshallingSupport; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.ByteArrayOutputStream; import org.junit.Test; http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-core/src/test/java/org/apache/activemq/openwire/ide/OpenWireCodecGenerator.java ---------------------------------------------------------------------- diff --git a/openwire-core/src/test/java/org/apache/activemq/openwire/ide/OpenWireCodecGenerator.java b/openwire-core/src/test/java/org/apache/activemq/openwire/ide/OpenWireCodecGenerator.java deleted file mode 100644 index e066fe7..0000000 --- a/openwire-core/src/test/java/org/apache/activemq/openwire/ide/OpenWireCodecGenerator.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.openwire.ide; - -import java.io.File; -import java.io.IOException; - -import org.apache.activemq.openwire.generator.GeneratorTask; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class for running the OpenWire source generator from within an - * IDE or as part of a test. - */ -public class OpenWireCodecGenerator { - - private static final Logger LOG = LoggerFactory.getLogger(OpenWireCodecGenerator.class); - - private final GeneratorTask generator = new GeneratorTask(); - - private int baseVersion = 10; - private int maxVersion = 10; - - private File sourceDir; - private File targetDir; - - /** - * @param args - * @throws IOException - */ - public static void main(String[] args) throws IOException { - - OpenWireCodecGenerator runner = new OpenWireCodecGenerator(); - - runner.setBaseVersion(10); - runner.setMaxVersion(10); - - File sourceDir = new File("./src/main/java/io/neutronjms/openwire/commands").getCanonicalFile(); - File targetDir = new File("./target/generated-sources/openwire").getCanonicalFile(); - - if (!sourceDir.exists()) { - throw new IOException("Source dir does not exist. " + sourceDir); - } - - if (!targetDir.exists()) { - targetDir.createNewFile(); - if (!targetDir.exists()) { - throw new IOException("Source dir does not exist. " + targetDir); - } - } - - runner.setSourceDir(sourceDir); - runner.setTargetDir(targetDir); - - runner.generate(); - } - - /** - * Runs the OpenWire generator using the configured generation values. - */ - public void generate() { - generator.setFromVersion(getBaseVersion()); - generator.setToVersion(getMaxVersion()); - generator.setSourceDir(getSourceDir()); - generator.setTargetDir(getTargetDir()); - - try { - generator.execute(); - } catch (RuntimeException e) { - LOG.warn("Caught exception while executing generator: ", e); - throw e; - } - } - - public int getBaseVersion() { - return baseVersion; - } - - public void setBaseVersion(int version) { - this.baseVersion = version; - } - - public int getMaxVersion() { - return maxVersion; - } - - public void setMaxVersion(int version) { - this.maxVersion = version; - } - - public File getSourceDir() { - return sourceDir; - } - - public void setSourceDir(File sourceDir) { - this.sourceDir = sourceDir; - } - - public File getTargetDir() { - return targetDir; - } - - public void setTargetDir(File targetDir) { - this.targetDir = targetDir; - } -} http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-core/src/test/java/org/apache/activemq/openwire/utils/CronParserTest.java ---------------------------------------------------------------------- diff --git a/openwire-core/src/test/java/org/apache/activemq/openwire/utils/CronParserTest.java b/openwire-core/src/test/java/org/apache/activemq/openwire/utils/CronParserTest.java deleted file mode 100644 index 907b524..0000000 --- a/openwire-core/src/test/java/org/apache/activemq/openwire/utils/CronParserTest.java +++ /dev/null @@ -1,363 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.openwire.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Calendar; -import java.util.List; - -import javax.jms.MessageFormatException; - -import org.apache.activemq.openwire.utils.CronParser; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CronParserTest { - - private static final Logger LOG = LoggerFactory.getLogger(CronParserTest.class); - - @Test - public void testgetNextTimeDayOfWeek() throws MessageFormatException { - - // using an absolute date so that result will be absolute - Monday 15 Nov 2010 - Calendar current = Calendar.getInstance(); - current.set(2010, Calendar.NOVEMBER, 15, 9, 15, 30); - LOG.debug("start:" + current.getTime()); - - String test = "* * * * 5"; - long next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - Calendar result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(0,result.get(Calendar.MINUTE)); - assertEquals(0,result.get(Calendar.HOUR)); - // expecting Friday 19th - assertEquals(19,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.NOVEMBER,result.get(Calendar.MONTH)); - assertEquals(2010,result.get(Calendar.YEAR)); - } - - @Test - public void testgetNextTimeDayOfWeekVariant() throws MessageFormatException { - - // using an absolute date so that result will be absolute - Monday 7 March 2011 - Calendar current = Calendar.getInstance(); - current.set(2011, Calendar.MARCH, 7, 9, 15, 30); - LOG.debug("start:" + current.getTime()); - - String test = "50 20 * * 5"; - long next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - Calendar result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(50,result.get(Calendar.MINUTE)); - assertEquals(20,result.get(Calendar.HOUR_OF_DAY)); - // expecting Friday 11th - assertEquals(11,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.FRIDAY,result.get(Calendar.DAY_OF_WEEK)); - assertEquals(Calendar.MARCH,result.get(Calendar.MONTH)); - assertEquals(2011,result.get(Calendar.YEAR)); - - // Match to the day of week, but to late to run, should just a week forward. - current = Calendar.getInstance(); - current.set(2011, Calendar.MARCH, 11, 22, 0, 30); - LOG.debug("update:" + current.getTime()); - - next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - //assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(50,result.get(Calendar.MINUTE)); - assertEquals(20,result.get(Calendar.HOUR_OF_DAY)); - // expecting Friday 18th - assertEquals(18,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.FRIDAY,result.get(Calendar.DAY_OF_WEEK)); - assertEquals(Calendar.MARCH,result.get(Calendar.MONTH)); - assertEquals(2011,result.get(Calendar.YEAR)); - } - - @Test - public void testgetNextTimeMonthVariant() throws MessageFormatException { - - // using an absolute date so that result will be absolute - Monday 7 March 2011 - Calendar current = Calendar.getInstance(); - current.set(2011, Calendar.MARCH, 7, 9, 15, 30); - LOG.debug("start:" + current.getTime()); - - String test = "0 20 * 4,5 0"; - long next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - Calendar result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(0,result.get(Calendar.MINUTE)); - assertEquals(20,result.get(Calendar.HOUR_OF_DAY)); - // expecting Sunday 3rd of April - assertEquals(Calendar.APRIL,result.get(Calendar.MONTH)); - assertEquals(3,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.SUNDAY,result.get(Calendar.DAY_OF_WEEK)); - assertEquals(2011,result.get(Calendar.YEAR)); - - current = Calendar.getInstance(); - current.set(2011, Calendar.APRIL, 30, 22, 0, 30); - LOG.debug("update:" + current.getTime()); - - next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(0,result.get(Calendar.MINUTE)); - assertEquals(20,result.get(Calendar.HOUR_OF_DAY)); - // expecting Sunday 1st of May - assertEquals(1,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.SUNDAY,result.get(Calendar.DAY_OF_WEEK)); - assertEquals(Calendar.MAY,result.get(Calendar.MONTH)); - assertEquals(2011,result.get(Calendar.YEAR)); - - // Move past last time and see if reschedule to next year works. - current = Calendar.getInstance(); - current.set(2011, Calendar.MAY, 30, 22, 0, 30); - LOG.debug("update:" + current.getTime()); - - next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(0,result.get(Calendar.MINUTE)); - assertEquals(20,result.get(Calendar.HOUR_OF_DAY)); - // expecting Sunday 1st of April - 2012 - assertEquals(1,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.SUNDAY,result.get(Calendar.DAY_OF_WEEK)); - assertEquals(Calendar.APRIL,result.get(Calendar.MONTH)); - assertEquals(2012,result.get(Calendar.YEAR)); - } - - @Test - public void testgetNextTimeMonth() throws MessageFormatException { - - // using an absolute date so that result will be absolute - Monday 15 Nov 2010 - Calendar current = Calendar.getInstance(); - current.set(2010, Calendar.NOVEMBER, 15, 9, 15, 30); - LOG.debug("start:" + current.getTime()); - - String test = "* * * 12 *"; - long next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - Calendar result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(0,result.get(Calendar.MINUTE)); - assertEquals(0,result.get(Calendar.HOUR_OF_DAY)); - assertEquals(1,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.DECEMBER,result.get(Calendar.MONTH)); - assertEquals(2010,result.get(Calendar.YEAR)); - } - - @Test - public void testgetNextTimeDays() throws MessageFormatException { - - // using an absolute date so that result will be absolute - Monday 15 Nov 2010 - Calendar current = Calendar.getInstance(); - current.set(2010, Calendar.NOVEMBER, 15, 9, 15, 30); - LOG.debug("start:" + current.getTime()); - - String test = "* * 16 * *"; - long next = CronParser.getNextScheduledTime(test, current.getTimeInMillis()); - - Calendar result = Calendar.getInstance(); - result.setTimeInMillis(next); - LOG.debug("next:" + result.getTime()); - - assertEquals(0,result.get(Calendar.SECOND)); - assertEquals(0,result.get(Calendar.MINUTE)); - assertEquals(0,result.get(Calendar.HOUR)); - assertEquals(16,result.get(Calendar.DAY_OF_MONTH)); - assertEquals(Calendar.NOVEMBER,result.get(Calendar.MONTH)); - assertEquals(2010,result.get(Calendar.YEAR)); - } - - @Test - public void testgetNextTimeMinutes() throws MessageFormatException { - String test = "30 * * * *"; - long current = 20*60*1000; - Calendar calender = Calendar.getInstance(); - calender.setTimeInMillis(current); - LOG.debug("start:" + calender.getTime()); - long next = CronParser.getNextScheduledTime(test, current); - - calender.setTimeInMillis(next); - LOG.debug("next:" + calender.getTime()); - long result = next - current; - assertEquals(60*10*1000,result); - } - - @Test - public void testgetNextTimeHours() throws MessageFormatException { - String test = "* 1 * * *"; - - Calendar calender = Calendar.getInstance(); - calender.set(1972, 2, 2, 17, 10, 0); - long current = calender.getTimeInMillis(); - long next = CronParser.getNextScheduledTime(test, current); - - calender.setTimeInMillis(next); - long result = next - current; - long expected = 60*1000*60*8 + 60 * 1000; - assertEquals(expected,result); - } - - @Test - public void testgetNextTimeHoursZeroMin() throws MessageFormatException { - String test = "0 1 * * *"; - - Calendar calender = Calendar.getInstance(); - calender.set(1972, 2, 2, 17, 10, 0); - long current = calender.getTimeInMillis(); - long next = CronParser.getNextScheduledTime(test, current); - - calender.setTimeInMillis(next); - long result = next - current; - long expected = 60*1000*60*7 + 60*1000*50; - assertEquals(expected,result); - } - - @Test - public void testValidate() { - try { - CronParser.validate("30 08 10 06 ? "); - CronParser.validate("30 08 ? 06 5 "); - CronParser.validate("30 08 ? 06 * "); - CronParser.validate("* * * * * "); - CronParser.validate("* * * * 1-6 "); - CronParser.validate("* * * * 1,2,5 "); - CronParser.validate("*/10 0-4,8-12 * * 1-2,3-6/2 "); - - } catch (Exception e) { - fail("Should be valid "); - } - - try { - CronParser.validate("61 08 10 06 * "); - fail("Should not be valid "); - } catch (Exception e) { - } - try { - CronParser.validate("61 08 06 * "); - fail("Should not be valid "); - } catch (Exception e) { - } - } - - @Test - public void testGetNextCommaSeparated() throws MessageFormatException { - String token = "3,5,7"; - // test minimum values - int next = CronParser.getNext(createEntry(token, 1, 10), 3); - assertEquals(2, next); - next = CronParser.getNext(createEntry(token, 1, 10), 8); - assertEquals(4, next); - next = CronParser.getNext(createEntry(token, 1, 10), 1); - assertEquals(2, next); - } - - @Test - public void testGetNextRange() throws MessageFormatException { - String token = "3-5"; - // test minimum values - int next = CronParser.getNext(createEntry(token, 1, 10), 3); - assertEquals(1, next); - next = CronParser.getNext(createEntry(token, 1, 10), 5); - assertEquals(7, next); - next = CronParser.getNext(createEntry(token, 1, 10), 6); - assertEquals(6, next); - next = CronParser.getNext(createEntry(token, 1, 10), 1); - assertEquals(2, next); - } - - @Test - public void testGetNextExact() throws MessageFormatException { - String token = "3"; - int next = CronParser.getNext(createEntry(token, 0, 10), 2); - assertEquals(1, next); - next = CronParser.getNext(createEntry(token, 0, 10), 3); - assertEquals(10, next); - next = CronParser.getNext(createEntry(token, 0, 10), 1); - assertEquals(2, next); - } - - @Test - public void testTokenize() { - String test = "*/5 * * * *"; - List<String> list = CronParser.tokenize(test); - assertEquals(list.size(), 5); - - test = "*/5 * * * * *"; - try { - list = CronParser.tokenize(test); - fail("Should have throw an exception"); - } catch (Throwable e) { - } - - test = "*/5 * * * *"; - try { - list = CronParser.tokenize(test); - fail("Should have throw an exception"); - } catch (Throwable e) { - } - - test = "0 1 2 3 4"; - list = CronParser.tokenize(test); - assertEquals(list.size(), 5); - - assertEquals(list.get(0), "0"); - assertEquals(list.get(1), "1"); - assertEquals(list.get(2), "2"); - assertEquals(list.get(3), "3"); - assertEquals(list.get(4), "4"); - } - - public void testGetNextScheduledTime() { - fail("Not yet implemented"); - } - - CronParser.CronEntry createEntry(String str, int start, int end) { - return new CronParser.CronEntry("test", str, start, end); - } - -} http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-core/src/test/java/org/apache/activemq/openwire/utils/MarshallingSupport.java ---------------------------------------------------------------------- diff --git a/openwire-core/src/test/java/org/apache/activemq/openwire/utils/MarshallingSupport.java b/openwire-core/src/test/java/org/apache/activemq/openwire/utils/MarshallingSupport.java new file mode 100644 index 0000000..0bd38ce --- /dev/null +++ b/openwire-core/src/test/java/org/apache/activemq/openwire/utils/MarshallingSupport.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.openwire.utils; + +import java.io.DataOutput; +import java.io.IOException; + +/** + * Support functions for dealing with data in OpenWire. + */ +public class MarshallingSupport { + + public static void writeUTF8(DataOutput dataOut, String text) throws IOException { + + if (text != null) { + int strlen = text.length(); + int utflen = 0; + char[] charr = new char[strlen]; + int c = 0; + int count = 0; + + text.getChars(0, strlen, charr, 0); + + for (int i = 0; i < strlen; i++) { + c = charr[i]; + if ((c >= 0x0001) && (c <= 0x007F)) { + utflen++; + } else if (c > 0x07FF) { + utflen += 3; + } else { + utflen += 2; + } + } + // TODO diff: Sun code - removed + byte[] bytearr = new byte[utflen + 4]; // TODO diff: Sun code + bytearr[count++] = (byte) ((utflen >>> 24) & 0xFF); // TODO diff: + // Sun code + bytearr[count++] = (byte) ((utflen >>> 16) & 0xFF); // TODO diff: + // Sun code + bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF); + bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF); + for (int i = 0; i < strlen; i++) { + c = charr[i]; + if ((c >= 0x0001) && (c <= 0x007F)) { + bytearr[count++] = (byte) c; + } else if (c > 0x07FF) { + bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); + bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F)); + bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); + } else { + bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); + bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); + } + } + dataOut.write(bytearr); + + } else { + dataOut.writeInt(-1); + } + } + +} http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-generator/pom.xml ---------------------------------------------------------------------- diff --git a/openwire-generator/pom.xml b/openwire-generator/pom.xml index 1cde472..6a84089 100644 --- a/openwire-generator/pom.xml +++ b/openwire-generator/pom.xml @@ -33,55 +33,32 @@ <dependencies> <!-- =================================== --> - <!-- Required Dependencies --> + <!-- Required Dependencies --> <!-- =================================== --> <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> + <groupId>org.apache.activemq</groupId> + <artifactId>openwire-annotations</artifactId> </dependency> <dependency> - <groupId>groovy</groupId> - <artifactId>gram</artifactId> - <version>1.1</version> + <groupId>org.reflections</groupId> + <artifactId>reflections</artifactId> </dependency> <dependency> - <groupId>groovy</groupId> - <artifactId>groovy-all</artifactId> - <version>1.0-jsr-04</version> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> </dependency> <dependency> - <groupId>annogen</groupId> - <artifactId>annogen</artifactId> - <version>0.1.0</version> + <groupId>org.apache.ant</groupId> + <artifactId>ant</artifactId> </dependency> + <dependency> - <groupId>ant</groupId> - <artifactId>ant</artifactId> - <version>1.6.2</version> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + <scope>test</scope> </dependency> </dependencies> - <profiles> - <profile> - <id>default-tools.jar</id> - <activation> - <property> - <name>java.vendor</name> - <value>Sun Microsystems Inc.</value> - </property> - </activation> - <dependencies> - <dependency> - <groupId>com.sun</groupId> - <artifactId>tools</artifactId> - <version>1.6.0</version> - <scope>system</scope> - <systemPath>${java.home}/../lib/tools.jar</systemPath> - </dependency> - </dependencies> - </profile> - </profiles> - <build> <plugins> <plugin> @@ -92,4 +69,5 @@ </plugin> </plugins> </build> + </project> http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/AbstractGenerator.java ---------------------------------------------------------------------- diff --git a/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/AbstractGenerator.java b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/AbstractGenerator.java new file mode 100644 index 0000000..f9594b6 --- /dev/null +++ b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/AbstractGenerator.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.openwire.generator; + +import java.io.PrintWriter; + +/** + * Base class that provides useful default implementations if Generator + * related tasks. + */ +public abstract class AbstractGenerator implements Generator { + + private String baseDir; + + /** + * @return the baseDir where the generator should operate. + */ + @Override + public String getBaseDir() { + return baseDir; + } + + /** + * @param baseDir + * the base directory to use as the root of the generation process. + */ + @Override + public void setBaseDir(String baseDir) { + this.baseDir = baseDir; + } + + /** + * Writes the common Apache 2.0 license used in all generated source content. + * + * @param out + * A PrintWriter instance to write the license to. + */ + public static void writeApacheLicense(PrintWriter out) { + out.println("/*"); + out.println(" * Licensed to the Apache Software Foundation (ASF) under one or more"); + out.println(" * contributor license agreements. See the NOTICE file distributed with"); + out.println(" * this work for additional information regarding copyright ownership."); + out.println(" * The ASF licenses this file to You under the Apache License, Version 2.0"); + out.println(" * (the \"License\"); you may not use this file except in compliance with"); + out.println(" * the License. You may obtain a copy of the License at"); + out.println(" *"); + out.println(" * http://www.apache.org/licenses/LICENSE-2.0"); + out.println(" *"); + out.println(" * Unless required by applicable law or agreed to in writing, software"); + out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS,"); + out.println(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."); + out.println(" * See the License for the specific language governing permissions and"); + out.println(" * limitations under the License."); + out.println(" */"); + } +} http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generator.java ---------------------------------------------------------------------- diff --git a/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generator.java b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generator.java new file mode 100644 index 0000000..787cd07 --- /dev/null +++ b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generator.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.openwire.generator; + +import java.util.List; + +/** + * Interface used for all Generator types. + */ +public interface Generator { + + public void run(List<OpenWireTypeDescriptor> typeDescriptors) throws Exception; + + public void setBaseDir(String baseDir); + + public String getBaseDir(); + +} http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorTask.java ---------------------------------------------------------------------- diff --git a/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorTask.java b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorTask.java index 24573d1..cf0a8bd 100644 --- a/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorTask.java +++ b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorTask.java @@ -16,191 +16,98 @@ */ package org.apache.activemq.openwire.generator; -import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; -import org.codehaus.jam.JamService; -import org.codehaus.jam.JamServiceFactory; -import org.codehaus.jam.JamServiceParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The main task that controls the OpenWire code generation routines. */ public class GeneratorTask extends Task { - protected int fromVersion = 1; - protected int toVersion = 1; - protected boolean rangedGenerate = true; - protected File sourceDir = new File("./src/main/java"); - protected File targetDir = new File("./src/main/java"); - protected boolean generateMarshalers = true; - protected boolean generateTests = false; - protected String commandsPackage; - protected String codecPackageRoot; + private static final Logger LOG = LoggerFactory.getLogger(GeneratorTask.class); + + private String baseDir = "./src/main/java"; public static void main(String[] args) { Project project = new Project(); project.init(); + GeneratorTask generator = new GeneratorTask(); generator.setProject(project); - if (args.length > 0) { - generator.fromVersion = Integer.parseInt(args[0]); - } - - if (args.length > 0) { - generator.toVersion = Integer.parseInt(args[0]); - } - - if (args.length > 1) { - generator.sourceDir = new File(args[1]); - } - - if (args.length > 2) { - generator.targetDir = new File(args[1]); - } - - if (args.length > 3) { - generator.commandsPackage = args[2]; - } - - if (args.length > 4) { - generator.codecPackageRoot = args[3]; - } - - generator.execute(); - } - - @Override - public void execute() throws BuildException { try { - System.out.println("======================================================"); - System.out.println("OpenWire Generator: Command source files in: "); - System.out.println("" + sourceDir); - System.out.println("======================================================"); - - JamServiceFactory jamServiceFactory = JamServiceFactory.getInstance(); - JamServiceParams params = jamServiceFactory.createServiceParams(); - File[] dirs = new File[] { sourceDir }; - params.includeSourcePattern(dirs, "**/*.java"); - JamService jam = jamServiceFactory.createService(params); - - if (generateMarshalers) { - if (!isRangedGenerate()) { - runMarshalerGenerateScript(jam, fromVersion); - if (toVersion != fromVersion) { - runMarshalerGenerateScript(jam, toVersion); - } - } else { - for (int i = fromVersion; i <= toVersion; ++i) { - runMarshalerGenerateScript(jam, i); - } - } - } - - if (generateTests) { - if (!isRangedGenerate()) { - runTestGenerateScript(jam, fromVersion); - if (toVersion != fromVersion) { - runTestGenerateScript(jam, toVersion); - } - } else { - for (int i = fromVersion; i <= toVersion; ++i) { - runTestGenerateScript(jam, i); - } - } + if (args.length >= 1) { + generator.setBaseDir(args[1]); } + generator.execute(); } catch (Exception e) { - throw new BuildException(e); + System.out.println("Error generating source:"); + e.printStackTrace(); } } - protected void runMarshalerGenerateScript(JamService jam, int version) throws Exception { - System.out.println("======================================================"); - System.out.println(" Generating Marshallers for OpenWire version: " + version); - System.out.println("======================================================"); - MarshallingGenerator script = new MarshallingGenerator(); - runScript(script, jam, version); - } - - protected void runTestGenerateScript(JamService jam, int version) throws Exception { - System.out.println("======================================================"); - System.out.println(" Generating Test Cases for OpenWire version: " + version); - System.out.println("======================================================"); - TestsGenerator script = new TestsGenerator(); - runScript(script, jam, version); - } + //----- Perform the generation by finding generators ---------------------// - protected void runScript(MultiSourceGenerator script, JamService jam, int version) throws Exception { - script.setJam(jam); - script.setTargetDir(targetDir.getCanonicalPath()); - script.setOpenwireVersion(version); - if (commandsPackage != null) { - script.setCommandsPackage(commandsPackage); - } - if (codecPackageRoot != null) { - script.setCodecPackageRoot(codecPackageRoot); - } - script.run(); - } - - public int getFromVersion() { - return fromVersion; - } - - public void setFromVersion(int version) { - this.fromVersion = version; - } - - public int getToVersion() { - return toVersion; - } - - public void setToVersion(int version) { - this.toVersion = version; - } - - public File getSourceDir() { - return sourceDir; - } + @Override + public void execute() throws BuildException { - public void setSourceDir(File sourceDir) { - this.sourceDir = sourceDir; - } + LOG.info("==========================================================="); + LOG.info("Running OpenWire Generator"); + LOG.info("==========================================================="); + LOG.info("Base Diractory = {}", getBaseDir()); - public File getTargetDir() { - return targetDir; - } + try { + List<OpenWireTypeDescriptor> descriptors = new ArrayList<OpenWireTypeDescriptor>(); - public void setTargetDir(File targetDir) { - this.targetDir = targetDir; - } + Set<Class<?>> openWireTypes = GeneratorUtils.findOpenWireTypes(); + for (Class<?> openWireType : openWireTypes) { + LOG.info("Found OpenWire Type: {}", openWireType.getSimpleName()); + descriptors.add(new OpenWireTypeDescriptor(openWireType)); + } - public boolean isGenerateMarshalers() { - return generateMarshalers; - } + List<Generator> generators = getOpenWireGenerators(); - public void setGenerateMarshalers(boolean generateMarshalers) { - this.generateMarshalers = generateMarshalers; - } + for (Generator generator : generators) { + generator.setBaseDir(getBaseDir()); - public boolean isGenerateTests() { - return generateTests; + generator.run(descriptors); + } + } catch (Exception ex) { + throw new BuildException(ex); + } finally { + LOG.info("==========================================================="); + } } - public void setGenerateTests(boolean generateTests) { - this.generateTests = generateTests; + /** + * Returns the active generators to run with. Can be overridden by an extension. + * + * @return list of generators to use. + */ + protected List<Generator> getOpenWireGenerators() { + return Generators.BUILTIN; } - public boolean isRangedGenerate() { - return this.rangedGenerate; + /** + * @return the baseDir + */ + public String getBaseDir() { + return baseDir; } - public void setRangedGenerate(boolean rangedGenerate) { - this.rangedGenerate = rangedGenerate; + /** + * @param baseDir the baseDir to set + */ + public void setBaseDir(String baseDir) { + this.baseDir = baseDir; } } http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorUtils.java ---------------------------------------------------------------------- diff --git a/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorUtils.java b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorUtils.java new file mode 100644 index 0000000..0c27511 --- /dev/null +++ b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/GeneratorUtils.java @@ -0,0 +1,211 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.openwire.generator; + +import static org.reflections.ReflectionUtils.getAllMethods; +import static org.reflections.ReflectionUtils.withModifier; +import static org.reflections.ReflectionUtils.withParametersCount; +import static org.reflections.ReflectionUtils.withPrefix; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Set; + +import org.apache.activemq.openwire.annotations.OpenWireProperty; +import org.apache.activemq.openwire.annotations.OpenWireType; +import org.reflections.ReflectionUtils; +import org.reflections.Reflections; + +import com.google.common.base.Predicates; + +/** + * Collection of useful methods when generating OpenWire types. + */ +public class GeneratorUtils { + + public static final String OPENWIRE_TYPES_PACKAGE = "org.apache.activemq.openwire.commands"; + public static final Reflections REFLECTIONS = new Reflections(OPENWIRE_TYPES_PACKAGE); + + /** + * Returns the set of OpenWire types annotated with the OpenWireType marker. + * + * @return a set of class objects representing all the annotated OpenWire types. + * + * @throws Exception if an error occurs reading the types. + */ + public static Set<Class<?>> findOpenWireTypes() throws Exception { + final Reflections reflections = new Reflections(OPENWIRE_TYPES_PACKAGE); + + final Set<Class<?>> protocolTypes = + reflections.getTypesAnnotatedWith(OpenWireType.class); + + return protocolTypes; + } + + /** + * Given an OpenWire protocol object, find and return all the fields in the object + * that are annotated with the OpenWireProperty marker. + * + * @param openWireType + * the OpenWire protocol object to query for property values. + * + * @return a {@code Set<Field>} containing the annotated properties from the given object. + * + * @throws Exception if an error occurs while scanning for properties. + */ + public static Set<Field> finalOpenWireProperties(Class<?> openWireType) throws Exception { + @SuppressWarnings("unchecked") + final Set<Field> properties = + ReflectionUtils.getAllFields(openWireType, ReflectionUtils.withAnnotation(OpenWireProperty.class)); + + return properties; + } + + /** + * Attempt to locate the get method for the given property contained in the target OpenWire + * type. + * + * @param openWireType + * The OpenWire type to search. + * @param property + * The property whose get method must be located. + * + * @return the name of the get method for the given property. + * + * @throws Exception if an error occurs finding the get method. + */ + @SuppressWarnings("unchecked") + public static Method findGetMethodForProperty(Class<?> openWireType, OpenWirePropertyDescriptor property) throws Exception { + + if (property.getType().equals(boolean.class)) { + Set<Method> getters = getAllMethods(openWireType, + Predicates.and( + withModifier(Modifier.PUBLIC), + withPrefix("is"), + withParametersCount(0))); + + // Found an isX method, use that. + if (!getters.isEmpty()) { + for (Method method : getters) { + if (method.getName().equalsIgnoreCase("is" + property.getPropertyName())) { + return method; + } + } + } + } + + Set<Method> getters = getAllMethods(openWireType, + Predicates.and( + withModifier(Modifier.PUBLIC), + withPrefix("get"), + withParametersCount(0))); + + // Found an getX method, use that. + if (!getters.isEmpty()) { + for (Method method : getters) { + if (method.getName().equalsIgnoreCase("get" + property.getPropertyName())) { + return method; + } + } + } + + throw new IllegalArgumentException("Property class has invalid bean method names."); + } + + /** + * Attempt to locate the set method for the given property contained in the target OpenWire + * type. + * + * @param openWireType + * The OpenWire type to search. + * @param property + * The property whose set method must be located. + * + * @return the name of the set method for the given property. + * + * @throws Exception if an error occurs finding the set method. + */ + @SuppressWarnings("unchecked") + public static Method findSetMethodForProperty(Class<?> openWireType, OpenWirePropertyDescriptor property) throws Exception { + + Set<Method> setters = getAllMethods(openWireType, + Predicates.and( + withModifier(Modifier.PUBLIC), + withPrefix("set"), + withParametersCount(1))); + + // Found an getX method, use that. + if (!setters.isEmpty()) { + for (Method method : setters) { + if (method.getName().equalsIgnoreCase("set" + property.getPropertyName())) { + return method; + } + } + } + + throw new IllegalArgumentException("Property class has invalid bean method names."); + } + + /** + * Construct a File instance that points to the targeted output folder + * + * @param base + * The base directory to start from. + * @param targetPackage + * The name of the java package where the generated code will go. + * + * @return a new File object that points to the output folder. + * + * @throws Exception if an error occurs. + */ + public static File createDestination(String base, String targetPackage) throws Exception { + targetPackage = targetPackage.replace(".", File.separator); + + final File outputFolder = new File(base, targetPackage); + if (!outputFolder.exists()) { + outputFolder.mkdirs(); + } + + return outputFolder; + } + + /** + * Returns the capitalize version of the given string. If the string is empty, does + * not start with a letter, or is the first letter is already upper case then the + * original String is returned. + * + * @param value + * The String value to capitalize. + * + * @return the given value with the first letter capitalized. + */ + public static String capitalize(final String value) { + if (value == null || value.isEmpty()) { + return value; + } + + char entry = value.charAt(0); + + if (!Character.isLetter(entry) || Character.isUpperCase(entry)) { + return value; + } + + return Character.toUpperCase(entry) + value.substring(1); + } +} http://git-wip-us.apache.org/repos/asf/activemq-openwire/blob/0c90d2e3/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generators.java ---------------------------------------------------------------------- diff --git a/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generators.java b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generators.java new file mode 100644 index 0000000..83ef59a --- /dev/null +++ b/openwire-generator/src/main/java/org/apache/activemq/openwire/generator/Generators.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.openwire.generator; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.activemq.openwire.generator.builtin.UniversalMarshallerFactoryGenerator; +import org.apache.activemq.openwire.generator.builtin.UniversalMarshallerGenerator; + +/** + * Directory of all generators in this library. + */ +public class Generators { + + public static List<Generator> BUILTIN = new ArrayList<Generator>(); + + static { + BUILTIN.add(new UniversalMarshallerGenerator()); + BUILTIN.add(new UniversalMarshallerFactoryGenerator()); + } +}
