text
stringlengths
101
200k
repo_name
stringlengths
5
73
stars
stringlengths
3
6
repo_language
stringlengths
1
24
file_name
stringlengths
2
57
mime_type
stringclasses
22 values
hash
int64
-9,223,369,786,400,666,000
9,223,339,290B
<html> <head> </head> <body> <div av="av-value" av-r="av-value for name replace"> <span id="av-value">av-value for name replace</span> <span id="cv-value">cv-value for name replace</span> <span id="gv-value">gv-value for name replace</span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-629,756,118,476,902,400
<html> <head> </head> <body> <div> <div id="test"> Prometheus </div> <span id="testspace">I love this game!</span> <span id="testnbsp"><span>three space here(&nbsp;&nbsp;&nbsp;)</span></span> <span id="testgreatermark">3 &gt; 2 or 3 &lt; 2, it's a question.</span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,686,647,391,390,974,700
<html> <head> </head> <body> <div pv="pv-value at parent" av="av-value at parent"> <div av="av-value at attr"> <span id="av-value">av-value at attr</span> <span id="pv-value">pv-value at parent</span> <span id="cv-value">cv-value at context</span> <span id="gv-value">gv-value</span> </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-376,708,165,696,219,840
<html> <head> </head> <body> Tomorrow's weather is sunny. <br> Today's weather is cloudy. <br> 明日の天気は雨です。 <br> Today's weather is cloudy. <br> 明日の天気は雨です。 <br> Click &lt;a href="https://www.test.com/"&gt;here&lt;/a&gt; to contact us. <br> Click <a href="https://www.test.com/">here</a> to contact us. <br> html:Click &lt;a href="https://www.test.com/"&gt;here&lt;/a&gt; to contact us. <br> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,704,755,352,888,159,000
<html> <head> </head> <body> <div> <span id="cv-value">cv-value at context</span> <span id="gv-value">gv-value</span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,134,907,666,558,043,000
<html> <head> </head> <body> <div pv="pv-value at parent" av="av-value at parent"> <div av="av-value at attr"> <span id="av-value">av-value at context</span> <span id="pv-value">pv-value at context</span> <span id="cv-value">cv-value at global</span> <span id="gv-value">gv-value at global</span> </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,515,891,582,180,607,000
<html> <head> </head> <body> <div> <div id="test"> <strong>BBB:0</strong> </div> <div id="test"> <strong>BBB:1</strong> </div> <div id="test"> <strong>BBB:2</strong> </div> <div id="test"> <strong>BBB:3</strong> </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,425,616,306,705,891,000
<html> <head> </head> <body> <div> <div id="d1"> <span id="s1">wow!</span> </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,957,696,880,050,869,000
<html> <head> </head> <body> <div> <span id="testadd" class="a"></span> <span id="testaddexisted" class="a b"></span> <span id="testremovebynull"></span> <span id="testremovebyminus" class="a"></span> <span id="testremovebyaddnull" class="a b null"></span> <span id="testset" class="b"></span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-886,406,509,629,892,200
<html> <head> </head> <body> <div> <span>BBB:0</span> <span>BBB:1</span> <span>BBB:2</span> <span>BBB:3</span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,840,166,863,669,320,000
<html> <head> </head> <body> <div id="outer"> <div id="outerDiv"> outerValue </div> <div id="inner" afd:dataref-exist="value"> <ul id="innerList"> <li>listParam0</li> <li>listParam1</li> <li>listParam2</li> </ul> </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,133,539,622,836,973,000
<html> <head> </head> <body> <div> <span id="cv-value">cv-value at global</span> <span id="gv-value">gv-value at global</span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,889,254,291,017,159,000
<html> <head> </head> <body> <div> <div id="test-text"> a </div> <div id="test-text"> b </div> <div id="test-text"> c </div> <div id="test-long"> 1 </div> <div id="test-long"> 2 </div> <div id="test-long"> 3 </div> <div id="test-integer"> 10 </div> <div id="test-integer"> 20 </div> <div id="test-integer"> 30 </div> <div id="test-boolean"> true </div> <div id="test-boolean"> false </div> <div id="test-boolean"> false </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,579,143,874,221,830,000
<html> <head> </head> <body> <p id="pv">666</p> <div id="pv"></div> <div id="kv"> 3 </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,206,308,831,217,527,000
<html> <head> </head> <body> <p id="pv">666</p> <div id="pv"> 777 </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,178,038,199,072,834,000
<html> <head> </head> <body> <div> <span>bb123</span> <div> xx </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,549,228,145,569,898,500
<html> <head> <script> xxx ff </script> <meta mm="0"> <meta ch="vb"> <title>xxx</title> </head> <body> <div> OK </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,674,095,452,344,145,200
<html> <head> </head> <body> <div> <div id="test-text"> a </div> <div id="test-text"> b </div> <div id="test-text"> c </div> <div id="test-text"> d </div> <div id="test-text"> e </div> <div id="test-text"> f </div> <div id="test-text"> g </div> <div id="test-text"> h </div> <div id="test-text"> i </div> <div id="test-text"> j </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,026,214,155,323,740,000
<html> <head> </head> <body> Tomorrowの天気はsunnyです。 <br> 今日の天気は曇りです。 <br> 明日の天気は雨です。 <br> 今日の天気は曇りです。 <br> 明日の天気は雨です。 <br> お問い合わせは&lt;a href="https://www.test.com/"&gt;こちら&lt;/a&gt;まで。 <br> お問い合わせは <a href="https://www.test.com/">こちら</a>まで。 <br> html:お問い合わせは&lt;a href="https://www.test.com/"&gt;こちら&lt;/a&gt;まで。 <br> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,817,580,885,305,166,000
<html> <head> </head> <body> <div> <span class="value">fire-resolved</span> <span class="count">1</span> </div> <div> <span class="value">fire-resolved</span> <span class="count">1</span> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,870,595,924,354,100,000
<html> <head> </head> <body> <div> <div id="test-text"> a </div> <div id="test-text"> b </div> <div id="test-text"> c </div> </div> </body> </html>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,366,587,505,475,987,000
weatherreport=Tomorrow's weather is sunny (ja). weatherreport1=%s\u306e\u5929\u6c17\u306f%s\u3067\u3059\u3002 weatherreport2=%s\u306e\u5929\u6c17\u306f%s\u3067\u3059\u3002 weatherreport2.date=\u4eca\u65e5 weatherreport2.weather=\u66c7\u308a weatherreport3=%s\u306e\u5929\u6c17\u306f%s\u3067\u3059\u3002 weatherreport3.date=\u660e\u65e5 weatherreport3.weather=\u96e8 textUrl=\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002 htmlUrl=html:\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002 escapeUrl=text:html:\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,505,671,811,385,658,000
weatherreport1={0}\u306e\u5929\u6c17\u306f{1}\u3067\u3059\u3002 weatherreport2={0}\u306e\u5929\u6c17\u306f{1}\u3067\u3059\u3002 weatherreport2.date=\u4eca\u65e5 weatherreport2.weather=\u66c7\u308a weatherreport3={0}\u306e\u5929\u6c17\u306f{1}\u3067\u3059\u3002 weatherreport3.date=\u660e\u65e5 weatherreport3.weather=\u96e8 textUrl=\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002 htmlUrl=html:\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002 escapeUrl=text:html:\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,434,720,705,880,055,000
weatherreport=Tomorrow's weather is sunny. weatherreport1=%s's weather is %s. weatherreport2=%s's weather is %s. weatherreport2.date=Today weatherreport2.weather=cloudy weatherreport3=%s's weather is %s. weatherreport3.date=Tomorrow weatherreport3.weather=rain textUrl=Click <a href="https://www.test.com/">here</a> to contact us. htmlUrl=html:Click <a href="https://www.test.com/">here</a> to contact us. escapeUrl=text:html:Click <a href="https://www.test.com/">here</a> to contact us.
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,050,314,648,625,860,000
weatherreport1={date}\u306e\u5929\u6c17\u306f{weather}\u3067\u3059\u3002 weatherreport2={date}\u306e\u5929\u6c17\u306f{weather}\u3067\u3059\u3002 weatherreport2.date=\u4eca\u65e5 weatherreport2.weather=\u66c7\u308a weatherreport3={date}\u306e\u5929\u6c17\u306f{weather}\u3067\u3059\u3002 weatherreport3.date=\u660e\u65e5 weatherreport3.weather=\u96e8 textUrl=\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002 htmlUrl=html:\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002 escapeUrl=text:html:\u304a\u554f\u3044\u5408\u308f\u305b\u306f<a href="https://www.test.com/">\u3053\u3061\u3089</a>\u307e\u3067\u3002
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,669,672,761,129,241,000
weatherreport1={0}''s weather is {1}. weatherreport2={0}''s weather is {1}. weatherreport2.date=Today weatherreport2.weather=cloudy weatherreport3={0}''s weather is {1}. weatherreport3.date=Tomorrow weatherreport3.weather=rain textUrl=Click <a href="https://www.test.com/">here</a> to contact us. htmlUrl=html:Click <a href="https://www.test.com/">here</a> to contact us. escapeUrl=text:html:Click <a href="https://www.test.com/">here</a> to contact us.
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,153,217,144,476,422,000
weatherreport1={date}'s weather is {weather}. weatherreport2={date}'s weather is {weather}. weatherreport2.date=Today weatherreport2.weather=cloudy weatherreport3={date}'s weather is {weather}. weatherreport3.date=Tomorrow weatherreport3.weather=rain weatherreport-split#1={date}'s weather weatherreport-split#2=is {weather}. textUrl=Click <a href="https://www.test.com/">here</a> to contact us. htmlUrl=html:Click <a href="https://www.test.com/">here</a> to contact us. escapeUrl=text:html:Click <a href="https://www.test.com/">here</a> to contact us.
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,380,206,454,393,023,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static org.testng.Assert.assertEquals; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.util.i18n.I18nMessageHelper; import com.astamuse.asta4d.util.i18n.MappedParamI18nMessageHelper; import com.astamuse.asta4d.util.i18n.OrderedParamI18nMessageHelper; import com.astamuse.asta4d.util.i18n.formatter.ApacheStrSubstitutorFormatter; import com.astamuse.asta4d.util.i18n.formatter.JDKMessageFormatFormatter; import com.astamuse.asta4d.util.i18n.formatter.SymbolPlaceholderFormatter; import com.astamuse.asta4d.util.i18n.pattern.CharsetResourceBundleFactory; import com.astamuse.asta4d.util.i18n.pattern.JDKResourceBundleMessagePatternRetriever; import com.astamuse.asta4d.util.i18n.pattern.LatinEscapingResourceBundleFactory; @Test public class ResourceBundleUtilTest extends BaseTest { @BeforeClass public void setDefaultLocale() { Locale.setDefault(Locale.ROOT); } @Test public void useSymbolFormatter() throws Exception { OrderedParamI18nMessageHelper helper = new OrderedParamI18nMessageHelper(new SymbolPlaceholderFormatter()); setUp(helper, "symbol_placeholder_messages"); assertEquals(helper.getMessage("weatherreport1", "Tomorrow", "sunny"), "Tomorrow's weather is sunny."); } @Test public void useSymbolFormatterJaJp() throws Exception { OrderedParamI18nMessageHelper helper = new OrderedParamI18nMessageHelper(new SymbolPlaceholderFormatter()); setUp(helper, "symbol_placeholder_messages"); assertEquals(helper.getMessage(Locale.JAPAN, "weatherreport1", "明日", "晴れ"), "明日の天気は晴れです。"); } @Test public void useNumberFormatter() throws Exception { OrderedParamI18nMessageHelper helper = new OrderedParamI18nMessageHelper(new JDKMessageFormatFormatter()); setUp(helper, "number_placeholder_messages"); assertEquals(helper.getMessage("weatherreport1", "Tomorrow", "sunny"), "Tomorrow's weather is sunny."); } @Test public void useNumberFormatterJaJp() throws Exception { OrderedParamI18nMessageHelper helper = new OrderedParamI18nMessageHelper(new JDKMessageFormatFormatter()); setUp(helper, "number_placeholder_messages"); assertEquals(helper.getMessage(Locale.JAPAN, "weatherreport1", "明日", "晴れ"), "明日の天気は晴れです。"); } @Test public void useNamedFormatter() throws Exception { MappedParamI18nMessageHelper helper = new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter()); setUp(helper, "named_placeholder_messages"); Map<String, Object> params = new HashMap<String, Object>(); params.put("date", "Tomorrow"); params.put("weather", "sunny"); assertEquals(helper.getMessage("weatherreport1", params), "Tomorrow's weather is sunny."); } @Test public void useNamedFormatterWithSplittedMessagePattern() throws Exception { MappedParamI18nMessageHelper helper = new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter()); setUp(helper, "named_placeholder_messages"); Map<String, Object> params = new HashMap<String, Object>(); params.put("date", "Tomorrow"); params.put("weather", "sunny"); assertEquals(helper.getMessage("weatherreport-split", params), "Tomorrow's weather is sunny."); } @Test public void useNamedFormatterJaJp() throws Exception { MappedParamI18nMessageHelper helper = new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter()); setUp(helper, "named_placeholder_messages"); Map<String, Object> params = new HashMap<String, Object>(); params.put("date", "明日"); params.put("weather", "晴れ"); assertEquals(helper.getMessage(Locale.JAPAN, "weatherreport1", params), "明日の天気は晴れです。"); } @Test public void utf8MessageFileJaJp() throws Exception { MappedParamI18nMessageHelper helper = new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter()); setUp(helper, "utf_8_messages"); // reset to utf-8 ((JDKResourceBundleMessagePatternRetriever) helper.getMessagePatternRetriever()) .setResourceBundleFactory(new CharsetResourceBundleFactory("UTF-8")); Map<String, Object> params = new HashMap<String, Object>(); params.put("date", "明日"); params.put("weather", "晴れ"); assertEquals(helper.getMessage(Locale.JAPAN, "weatherreport", params), "明日の天気は晴れです。"); } private void setUp(I18nMessageHelper helper, String fileName) { Context context = Context.getCurrentThreadContext(); context.setCurrentLocale(Locale.US); JDKResourceBundleMessagePatternRetriever retriever = (JDKResourceBundleMessagePatternRetriever) helper.getMessagePatternRetriever(); retriever.setResourceNames("com.astamuse.asta4d.test.render.messages." + fileName); retriever.setResourceBundleFactory(new LatinEscapingResourceBundleFactory()); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,067,058,501,462,296,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import java.util.ResourceBundle; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.util.i18n.pattern.JDKResourceBundleMessagePatternRetriever; @Test public class JDKResourceBundleMessagePatternRetrieverTest extends BaseTest { private static final String EXISTING_FILE = "com/astamuse/asta4d/test/unit/JDKResourceBundleMessagePatternRetrieverTest"; private static final String NOT_EXISTING_FILE = "com/astamuse/asta4d/test/unit/JDKResourceBundleMessagePatternRetrieverTest_NotExisting"; private static final String KEY_NOT_EXISTING_FILE = "com/astamuse/asta4d/test/unit/JDKResourceBundleMessagePatternRetrieverTest_KeyNotExisting"; @BeforeMethod public void beforeMethod() { ResourceBundle.clearCache(); } public void testSingleResourceFileExistingKey() { JDKResourceBundleMessagePatternRetriever retriever = new JDKResourceBundleMessagePatternRetriever(); retriever.setResourceNames(EXISTING_FILE); Assert.assertEquals(retriever.retrieve(null, "test"), "testxxx"); } public void testSingleResourceFileNotExistingKey() { JDKResourceBundleMessagePatternRetriever retriever = new JDKResourceBundleMessagePatternRetriever(); retriever.setResourceNames(EXISTING_FILE); Assert.assertNull(retriever.retrieve(null, "test_not_existing")); } public void testMultiResourceFileExistingKey() { JDKResourceBundleMessagePatternRetriever retriever = new JDKResourceBundleMessagePatternRetriever(); retriever.setResourceNames(NOT_EXISTING_FILE, EXISTING_FILE); Assert.assertEquals(retriever.retrieve(null, "test"), "testxxx"); } public void testMultiResourceFileNotExistingKey() { JDKResourceBundleMessagePatternRetriever retriever = new JDKResourceBundleMessagePatternRetriever(); retriever.setResourceNames(NOT_EXISTING_FILE, EXISTING_FILE); Assert.assertNull(retriever.retrieve(null, "test_not_existing")); } public void testMultiResourceFileExistingKey2() { JDKResourceBundleMessagePatternRetriever retriever = new JDKResourceBundleMessagePatternRetriever(); retriever.setResourceNames(NOT_EXISTING_FILE, EXISTING_FILE, KEY_NOT_EXISTING_FILE); Assert.assertEquals(retriever.retrieve(null, "test"), "testxxx"); } public void testMultiResourceFileNotExistingKey2() { JDKResourceBundleMessagePatternRetriever retriever = new JDKResourceBundleMessagePatternRetriever(); retriever.setResourceNames(NOT_EXISTING_FILE, EXISTING_FILE, KEY_NOT_EXISTING_FILE); Assert.assertNull(retriever.retrieve(null, "test_not_existing")); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,465,624,101,448,198,700
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.ParallelRecursivePolicy; import com.astamuse.asta4d.util.collection.RowConvertor; import com.astamuse.asta4d.util.collection.RowConvertorBuilder; public class ParallelListConvertingTest extends BaseTest { @BeforeClass public void setDefaultLocale() { Locale.setDefault(Locale.ROOT); } @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*Recursive parallel list converting is forbidden.*") public void testForException() { tryConvert(ParallelRecursivePolicy.EXCEPTION); } @Test public void testForCurrentThread() { tryConvert(ParallelRecursivePolicy.CURRENT_THREAD); } @Test public void testForNewThread() { tryConvert(ParallelRecursivePolicy.NEW_THREAD); } private void tryConvert(final ParallelRecursivePolicy policy) { Configuration.getConfiguration().setRecursivePolicyForParallelListConverting(policy); List<Integer> list = new ArrayList<>(); list.add(1); ListConvertUtil.transform(list, new RowConvertor<Integer, List<Long>>() { public boolean isParallel() { return true; } @Override public List<Long> convert(int rowIndex, Integer obj) { List<Long> subList = new ArrayList<>(); subList.add(Thread.currentThread().getId()); return ListConvertUtil.transform(subList, RowConvertorBuilder.parallel(internalObj -> { Long cid = Thread.currentThread().getId(); if (policy == ParallelRecursivePolicy.CURRENT_THREAD) { Assert.assertEquals(cid, internalObj); } else { Assert.assertNotEquals(cid, internalObj); } return cid; })); } }); } @DataProvider(name = "data") public Object[][] getNumberLimitOfParallelTestData() { //@formatter:off return new Object[][] { {Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)}, {Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)}, {Arrays.asList(1, 2, 3, 4, 5, 6, 7)}, }; //@formatter:on } /* we have to warm up the test at first, or the measured time may over 350ms due to the overhead of thread splitting*/ @Test(dataProvider = "data", dependsOnMethods = "testNumberLimitOfParallelWarmingup") public void testNumberLimitOfParallel(List<Integer> list) { Configuration.getConfiguration().setNumberLimitOfParallelListConverting(3); long start = System.currentTimeMillis(); List<Integer> rList = ListConvertUtil.transform(list, RowConvertorBuilder.parallel((i) -> { try { Thread.sleep(100); } catch (Exception e) { throw new RuntimeException(e); } return i; })); long end = System.currentTimeMillis(); long timeUsed = end - start; if (timeUsed < 200) { throw new AssertionError("Time used is less than 200 milliseconds with only " + timeUsed + " milliseconds."); } if (timeUsed > 350) { throw new AssertionError("Time used is over than 350 milliseconds and it takes " + timeUsed + " milliseconds."); } Assert.assertEquals(rList, list); } @Test(dataProvider = "data") public void testNumberLimitOfParallelWarmingup(List<Integer> list) { Configuration.getConfiguration().setNumberLimitOfParallelListConverting(3); for (int i = 0; i < 10_0000; i++) { List<Integer> rList = ListConvertUtil.transform(list, RowConvertorBuilder.parallel((k) -> { return k; })); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,642,520,002,421,889,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.jsoup.nodes.Element; import org.testng.Assert; import org.testng.annotations.Test; import com.astamuse.asta4d.render.ChildReplacer; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.test.RendererTestException; import com.astamuse.asta4d.render.test.RendererTester; import com.astamuse.asta4d.render.test.TestableElementWrapper; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.util.ElementUtil; import com.astamuse.asta4d.util.collection.RowConvertor; public class RenderTesterTest extends BaseTest { @Test public void testGetSingle() { // prepare test target Renderer render = Renderer.create(); render.add("#someIdForInt", 12345); render.add("#someIdForLong", 12345L); render.add("#someIdForBool", true); render.add("#someIdForStr", "a str"); render.add("#someIdForNull", (Object) null); render.add("#someIdForClear", Clear); Element newChild = ElementUtil.parseAsSingle("<div></div>"); render.add("#someIdForElementSetter", new ChildReplacer(newChild)); render.add("#someIdForElement", ElementUtil.parseAsSingle("<div>eee</div>")); render.add("#someIdForRenderer", Renderer.create("#value", "value")); render.add("#someIdForRendable", () -> { return Renderer.create("#id", "xx"); }); // perform test RendererTester tester = RendererTester.forRenderer(render); Assert.assertFalse(tester.noOp()); Assert.assertEquals(tester.get("#someIdForInt"), 12345); Assert.assertEquals(tester.get("#someIdForLong"), 12345L); Assert.assertEquals(tester.get("#someIdForBool"), true); Assert.assertEquals(tester.get("#someIdForStr"), "a str"); Assert.assertEquals(tester.get("#someIdForNull"), null); Assert.assertEquals(tester.get("#someIdForClear"), Clear); Assert.assertFalse(tester.noOp("#someIdForClear")); Assert.assertTrue(tester.noOp("#notexistop")); Assert.assertEquals(tester.get("#someIdForElementSetter"), new ChildReplacer(ElementUtil.parseAsSingle("<div></div>"))); Assert.assertEquals(tester.get("#someIdForElement"), TestableElementWrapper.parse("<div>eee</div>")); RendererTester recursiveTester = RendererTester.forRenderer((Renderer) tester.get("#someIdForRenderer")); Assert.assertEquals(recursiveTester.get("#value"), "value"); recursiveTester = RendererTester.forRenderer(((Renderable) tester.get("#someIdForRendable")).render()); Assert.assertEquals(recursiveTester.get("#id"), "xx"); // noop test tester = RendererTester.forRenderer(Renderer.create()); Assert.assertTrue(tester.noOp()); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "There is no value to be rendered for selector(.*)") public void testGetSingleNotFound() { Renderer render = Renderer.create(); render.add("#someId", 12345); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.get("#someIdNotExist"), 12345); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "(.*)as a list(.*)") public void testGetSingleFoundMore() { Renderer render = Renderer.create(); render.add("#someId", Arrays.asList(123, 345)); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.get("#someId"), 123); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "(.*)as a empty list(.*)") public void testGetSingleFoundMore2() { Renderer render = Renderer.create(); render.add("#someId", Collections.emptyList()); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.get("#someId"), 123); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "(.*)multiple times(.*)") public void testGetSingleFoundMore3() { Renderer render = Renderer.create(); render.add("#someId", 123); render.add("#someId", 345); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.get("#someId"), 123); } @Test public void testGetList() { // prepare test target Renderer render = Renderer.create(); render.add("#someIdForInt", Arrays.asList(123, 456, 789)); render.add("#someIdForLong", Arrays.asList(123L, 456L, 789L)); render.add("#someIdForBool", Arrays.asList(true, true, false)); render.add("#someIdForStr", Arrays.asList("str1", "str2", "str3")); Element newChild1 = ElementUtil.parseAsSingle("<div>1</div>"); Element newChild2 = ElementUtil.parseAsSingle("<div>2</div>"); render.add("#someIdForElementSetter", Arrays.asList(new ChildReplacer(newChild1), new ChildReplacer(newChild2))); render.add("#someIdForElement", Arrays.asList(newChild1, newChild2)); // perform test RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.getAsList("#someIdForInt"), Arrays.asList(123, 456, 789)); Assert.assertEquals(tester.getAsList("#someIdForLong"), Arrays.asList(123L, 456L, 789L)); Assert.assertEquals(tester.getAsList("#someIdForBool"), Arrays.asList(true, true, false)); Assert.assertEquals(tester.getAsList("#someIdForStr"), Arrays.asList("str1", "str2", "str3")); Assert.assertEquals(tester.getAsList("#someIdForElementSetter"), Arrays.asList(new ChildReplacer(ElementUtil.parseAsSingle("<div>1</div>")), new ChildReplacer(ElementUtil.parseAsSingle("<div>2</div>")))); Assert.assertEquals(tester.getAsList("#someIdForElement"), Arrays.asList(TestableElementWrapper.parse("<div>1</div>"), TestableElementWrapper.parse("<div>2</div>"))); } @Test public void testGetListAsRenderer() { Renderer render = Renderer.create(); render.add("#someIdForRenderer", Arrays.asList(123, 456, 789), new RowConvertor<Integer, Renderer>() { @Override public Renderer convert(int rowIndex, Integer obj) { return Renderer.create("#id", "id-" + obj).add("#otherId", "otherId-" + obj); } }); render.add("#someIdForStream", Arrays.asList(123, 456, 789).stream().map((i) -> { return Renderer.create("#id", "id-" + i).add("#otherId", "otherId-" + i); })); RendererTester tester = RendererTester.forRenderer(render); for (String selector : Arrays.asList("#someIdForRenderer", "#someIdForStream")) { // to test by traditional way { List<RendererTester> testerList = tester.getAsRendererTesterList(selector); List<String> confirmIdList = Arrays.asList("id-123", "id-456", "id-789"); Assert.assertEquals(testerList.size(), 3); for (int i = 0; i < testerList.size(); i++) { RendererTester recursiveTester = testerList.get(i); Assert.assertEquals(recursiveTester.get("#id"), confirmIdList.get(i)); } } // to test by more functional way { List<String> confirmOtherIdList = Arrays.asList("otherId-123", "otherId-456", "otherId-789"); List<RendererTester> testerList = tester.getAsRendererTesterList(selector); Assert.assertEquals(testerList.stream().map((t) -> { return t.get("#otherId"); }).collect(Collectors.toList()), confirmOtherIdList); } } } @Test public void testGetAttr() { Renderer render = Renderer.create(); render.add("#id", "+class", "yyy"); render.add("#id", "-class", "zzz"); render.add("#id", "+class", "xxx"); render.add("#id", "value", new Date(123456L)); render.add("#id", "href", (Object) null); render.add("#idstr", "value", "hg"); render.add("#idint", "value", 3); render.add("#idlong", "value", 3L); render.add("#idbool", "value", true); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.getAttrAsList("#id", "+class"), Arrays.asList("yyy", "xxx")); Assert.assertEquals(tester.getAttr("#id", "-class"), "zzz"); Assert.assertEquals(tester.getAttr("#id", "value"), new Date(123456L)); Assert.assertEquals(tester.getAttr("#id", "href"), null); Assert.assertEquals(tester.getAttr("#idstr", "value"), "hg"); Assert.assertEquals(tester.getAttr("#idint", "value"), "3"); Assert.assertEquals(tester.getAttr("#idlong", "value"), "3"); Assert.assertEquals(tester.getAttr("#idbool", "value"), "true"); Assert.assertFalse(tester.noOp("#id", "+class")); Assert.assertFalse(tester.noOp("#id", "-class")); Assert.assertFalse(tester.noOp("#id", "value")); Assert.assertFalse(tester.noOp("#id", "href")); Assert.assertFalse(tester.noOp("#idstr", "value")); Assert.assertFalse(tester.noOp("#idint", "value")); Assert.assertFalse(tester.noOp("#idlong", "value")); Assert.assertFalse(tester.noOp("#idbool", "value")); Assert.assertTrue(tester.noOp("#id", "+cccc")); Assert.assertTrue(tester.noOp("#id", "-cccc")); Assert.assertTrue(tester.noOp("#id", "cccc")); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "There is no value to be rendered for attr(.*)") public void testGetAttrNotFound() { Renderer render = Renderer.create(); render.add("#id", "+class", "yyy"); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.getAttr("#id", "href"), null); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "(.*)more than one values(.*)") public void testGetAttrFindMore() { Renderer render = Renderer.create(); render.add("#id", "value", "yyy"); render.add("#id", "value", "zzz"); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.getAttr("#id", "value"), "zzz"); } @Test(expectedExceptions = RendererTestException.class, expectedExceptionsMessageRegExp = "This method is only for retrieving rendered value of \"\\+class\" and \"\\-class\" attr action") public void testGetAttrFindMore2() { Renderer render = Renderer.create(); render.add("#id", "value", "yyy"); render.add("#id", "value", "zzz"); RendererTester tester = RendererTester.forRenderer(render); Assert.assertEquals(tester.getAttrAsList("#id", "value"), Arrays.asList("yyy", "zzz")); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,152,941,114,729,005,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.testng.Assert; import org.testng.annotations.Test; import com.astamuse.asta4d.render.ElementNotFoundHandler; import com.astamuse.asta4d.render.RenderUtil; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; public class ElementNotFoundHandlerOnDocumentTest extends BaseTest { @Test public void notFoundOnDocument() throws Exception { String html = "<html><body><span>x</span></body></html>"; Document doc = Jsoup.parse(html); Renderer renderer = Renderer.create(); renderer.add(new ElementNotFoundHandler("div") { @Override public Renderer alternativeRenderer() { return Renderer.create("span", "y"); } }); RenderUtil.apply(doc, renderer); Assert.assertEquals(doc.select("span").text(), "y"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,204,964,239,828,495,400
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.test.render.infra.BaseTest; public class InjectUtilForMethodTest extends BaseTest { @Test public void stringNotFound() throws Exception { setData(null); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireString", String.class)); assertEquals(params.length, 1); assertEquals(params[0], null); } @Test public void string2string() throws Exception { setData("value"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireString", String.class)); assertEquals(params.length, 1); assertEquals(params[0], "value"); } @Test public void string2StringArray() throws Exception { setData(new String[] { "aa", "bb" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireString", String.class)); assertEquals(params.length, 1); assertEquals(params[0], "aa"); } @Test public void stringArray2String() throws Exception { setData("value"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireString", String[].class)); assertEquals(params.length, 1); assertEquals(params[0], new String[] { "value" }); } @Test public void stringArray2StringArray() throws Exception { setData(new String[] { "aa", "bb" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireString", String[].class)); assertEquals(params.length, 1); assertEquals(params[0], new String[] { "aa", "bb" }); } @Test public void boolean2boolean() throws Exception { setData(true); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean.class)); assertEquals(params.length, 1); assertTrue((Boolean) params[0]); } @Test public void boolean2booleanArray() throws Exception { setData(true); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean[].class)); assertEquals(params.length, 1); assertEquals(params[0], new boolean[] { true }); } @Test public void booleanArray2boolean() throws Exception { setData(new boolean[] { true, false }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean.class)); assertEquals(params.length, 1); assertTrue((Boolean) params[0]); } @Test public void booleanArray2booleanArray() throws Exception { setData(new boolean[] { true, false }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean[].class)); assertEquals(params.length, 1); assertEquals(params[0], new boolean[] { true, false }); } @Test public void string2boolean() throws Exception { setData("true"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean.class)); assertEquals(params.length, 1); assertTrue((Boolean) params[0]); } @Test public void string2booleanArray() throws Exception { setData("true"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean.class)); assertEquals(params.length, 1); assertTrue((Boolean) params[0]); } @Test public void stringArray2boolean() throws Exception { setData(new String[] { "true", "false" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean.class)); assertEquals(params.length, 1); assertTrue((Boolean) params[0]); } @Test public void stringArray2booleanArray() throws Exception { setData(new String[] { "true", "false" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireBoolean", boolean[].class)); assertEquals(params.length, 1); assertEquals(params[0], new boolean[] { true, false }); } @Test public void int2int() throws Exception { setData(10); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int.class)); assertEquals(params.length, 1); assertEquals(((Integer) params[0]).intValue(), 10); } @Test public void int2intArray() throws Exception { setData(15); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int[].class)); assertEquals(params.length, 1); assertEquals(params[0], new int[] { 15 }); } @Test public void intArray2int() throws Exception { setData(new int[] { 10, 20 }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int.class)); assertEquals(params.length, 1); assertEquals(((Integer) params[0]).intValue(), 10); } @Test public void intArray2intArray() throws Exception { setData(new int[] { 10, 20 }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int[].class)); assertEquals(params.length, 1); assertEquals(params[0], new int[] { 10, 20 }); } @Test public void string2int() throws Exception { setData("15"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int.class)); assertEquals(params.length, 1); assertEquals(((Integer) params[0]).intValue(), 15); } @Test public void string2intArray() throws Exception { setData("15"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int[].class)); assertEquals(params.length, 1); assertEquals(params[0], new int[] { 15 }); } @Test public void stringArray2int() throws Exception { setData(new String[] { "10", "20" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int.class)); assertEquals(params.length, 1); assertEquals(((Integer) params[0]).intValue(), 10); } @Test public void stringArray2intArray() throws Exception { setData(new String[] { "10", "20" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireInt", int[].class)); assertEquals(params.length, 1); assertEquals(params[0], new int[] { 10, 20 }); } @Test public void long2long() throws Exception { setData(15L); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long.class)); assertEquals(params.length, 1); assertEquals(((Long) params[0]).longValue(), 15L); } @Test public void long2longArray() throws Exception { setData(15L); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long[].class)); assertEquals(params.length, 1); assertEquals(params[0], new long[] { 15L }); } @Test public void longArray2long() throws Exception { setData(new long[] { 10L, 20L }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long.class)); assertEquals(params.length, 1); assertEquals(((Long) params[0]).longValue(), 10L); } @Test public void longArray2longArray() throws Exception { setData(new long[] { 10L, 20L }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long[].class)); assertEquals(params.length, 1); assertEquals(params[0], new long[] { 10L, 20L }); } @Test public void string2long() throws Exception { setData("15"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long.class)); assertEquals(params.length, 1); assertEquals(((Long) params[0]).longValue(), 15L); } @Test public void string2longArray() throws Exception { setData("15"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long[].class)); assertEquals(params.length, 1); assertEquals(params[0], new long[] { 15L }); } @Test public void stringArray2long() throws Exception { setData(new String[] { "10", "20" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long.class)); assertEquals(params.length, 1); assertEquals(((Long) params[0]).longValue(), 10L); } @Test public void stringArray2longArray() throws Exception { setData(new String[] { "10", "20" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireLong", long[].class)); assertEquals(params.length, 1); assertEquals(params[0], new long[] { 10L, 20L }); } /** * There is a bug for lambda inside method * * @throws Exception */ @Test public void lambdaInside() throws Exception { setData(null); Object[] params = InjectUtil.getMethodInjectParams(getMethod("lambdaInside", String.class)); assertEquals(params.length, 1); assertEquals(params[0], null); } @Test(enabled = false) public void requireString(String param) { } @Test(enabled = false) public void requireString(String[] param) { } @Test(enabled = false) public void requireBoolean(boolean param) { } @Test(enabled = false) public void requireBoolean(boolean[] param) { } @Test(enabled = false) public void requireInt(int param) { } @Test(enabled = false) public void requireInt(int[] param) { } @Test(enabled = false) public void requireLong(long param) { } @Test(enabled = false) public void requireLong(long[] param) { } @Test(enabled = false) public void lambdaInside(String param) { List<String> names = Arrays.asList("hoge hoge", "foo bar", "naoki", "kishida"); names.stream().forEach(s -> System.out.println(s)); } private static void setData(Object data) { Context context = Context.getCurrentThreadContext(); context.setData("param", data); } private static Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { return InjectUtilForMethodTest.class.getMethod(name, parameterTypes); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
355,912,018,755,151,700
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import org.testng.annotations.Test; import com.astamuse.asta4d.util.MultiSearchPathResourceLoader; public class MultiSearchPathResourceLoaderTest { @Test public void searchForOneName() { StringResourceLoaderForTest loader = new StringResourceLoaderForTest(new String[] { "foo", "bar", "baz" }); String resource = loader.searchResource("/", "bar"); assertEquals("bar", resource); } @Test public void searchForMultiName() { StringResourceLoaderForTest loader = new StringResourceLoaderForTest(new String[] { "foo", "bar", "baz" }); String resource = loader.searchResource("/", "qux", "baz"); assertEquals("baz", resource); } @Test public void searchForMultiName_NotFound() { StringResourceLoaderForTest loader = new StringResourceLoaderForTest(new String[] { "foo", "bar", "baz" }); String resource = loader.searchResource("/", "qux", "quux"); assertNull(resource); } @Test public void searchForMultiPath() { StringResourceLoaderForTest loader = new StringResourceLoaderForTest(new String[] { "foo", "bar", "baz", "path1/bar", "path2/qux" }); loader.setSearchPathList("path1", "path2"); String resource = loader.searchResource("/", "qux"); assertEquals("path2/qux", resource); } @Test public void searchForMultiPath_FindMultiResource() { StringResourceLoaderForTest loader = new StringResourceLoaderForTest(new String[] { "foo", "bar", "baz", "path1/bar", "path2/qux" }); loader.setSearchPathList("path1", "path2"); String resource = loader.searchResource("/", "bar"); assertEquals("bar", resource); } @Test public void searchForMultiPath_NotFound() { StringResourceLoaderForTest loader = new StringResourceLoaderForTest(new String[] { "foo", "bar", "baz", "path1/bar", "path2/qux" }); loader.setSearchPathList("path1", "path2"); String resource = loader.searchResource("/", "quux", "foobar"); assertNull(resource); } private static class StringResourceLoaderForTest extends MultiSearchPathResourceLoader<String> { private final String[] resources; public StringResourceLoaderForTest(String[] resources) { this.resources = resources; } @Override protected String loadResource(String name) { for (String resource : resources) { if (resource.equals(name)) { return resource; } } return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,900,679,122,092,488,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.testng.Assert; import org.testng.annotations.Test; import com.astamuse.asta4d.template.AbstractTemplateResolver; import com.astamuse.asta4d.template.Template; import com.astamuse.asta4d.template.TemplateException; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.test.render.infra.BaseTest; public class TemplateResolverTest extends BaseTest { @Test(expectedExceptions = TemplateNotFoundException.class) public void templateNotFoundTest() throws TemplateException, TemplateNotFoundException { AbstractTemplateResolver resolver = new AbstractTemplateResolver() { @Override protected TemplateInfo loadResource(String name) { return null; } }; Template template = resolver.findTemplate("test"); } private static InputStream createInputStream(String bodyContent) { StringBuilder sb = new StringBuilder(); sb.append("<html><body>").append(bodyContent).append("</body></html>"); ByteArrayInputStream bis = new ByteArrayInputStream(sb.toString().getBytes()); return bis; } public void templateCacheNonStatic() throws TemplateException, TemplateNotFoundException { AbstractTemplateResolver resolver1 = new AbstractTemplateResolver() { @Override protected TemplateInfo loadResource(String name) { return new TemplateInfo("p1", createInputStream("p1")); } }; AbstractTemplateResolver resolver2 = new AbstractTemplateResolver() { @Override protected TemplateInfo loadResource(String name) { return new TemplateInfo("p2", createInputStream("p2")); } }; Template template1 = resolver1.findTemplate("pp"); Template template2 = resolver2.findTemplate("pp"); Assert.assertNotSame(template1, template2); Assert.assertNotEquals(template1.getPath(), template2.getPath(), "should be different template path"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-793,296,509,734,845,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static org.testng.Assert.assertEquals; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.ContextDataHolder; import com.astamuse.asta4d.data.ContextDataSetFactory; import com.astamuse.asta4d.data.DefaultContextDataSetFactory; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.data.annotation.ContextDataSet; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.util.annotation.AnnotationConvertor; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; public class InjectUtilForConvertableAnnotationTest extends BaseTest { private final static String MyDataScope = "MyDataScope"; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @ConvertableAnnotation(MySetConvertor.class) public static @interface MySet { } public static class MySetConvertor implements AnnotationConvertor<MySet, ContextDataSet> { @Override public ContextDataSet convert(MySet originalAnnotation) { return new ContextDataSet() { @Override public Class<? extends Annotation> annotationType() { return ContextDataSet.class; } @Override public Class<? extends ContextDataSetFactory> factory() { return DefaultContextDataSetFactory.class; } @Override public boolean singletonInContext() { return false; } }; } } @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(MyDataConvertor.class) public static @interface MyData { public String name() default ""; } public static class MyDataConvertor implements AnnotationConvertor<MyData, ContextData> { @Override public ContextData convert(final MyData originalAnnotation) { return new ContextData() { @Override public Class<? extends Annotation> annotationType() { return ContextData.class; } @Override public String name() { return originalAnnotation.name(); } @Override public String scope() { return MyDataScope; } @Override public TypeUnMacthPolicy typeUnMatch() { return TypeUnMacthPolicy.DEFAULT_VALUE; } }; } } @MySet public static class TestSet { @MyData private long f1; @ContextData public ContextDataHolder<Long> f2 = new ContextDataHolder<>(Long.class); public long getF1() { return f1; } } public static class TestCls { @ContextData private TestSet myset; } @Test public void contextSetAndInjectableOnMethod() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData(MyDataScope, "f1", "6678"); ctx.setData("f2", "12345"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireHolder", TestSet.class)); TestSet set = (TestSet) params[0]; assertEquals(set.getF1(), 6678L); assertEquals(set.f2.getValue().longValue(), 12345L); } @Test public void contextSetAndInjectableOnInstance() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData(MyDataScope, "f1", "6678"); ctx.setData("f2", "12345"); TestCls tc = new TestCls(); InjectUtil.injectToInstance(tc); TestSet set = tc.myset; assertEquals(set.getF1(), 6678L); assertEquals(set.f2.getValue().longValue(), 12345L); } @Test(enabled = false) public void requireHolder(TestSet holder) { } private static Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { return InjectUtilForConvertableAnnotationTest.class.getMethod(name, parameterTypes); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,880,019,132,324,741,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.testng.Assert; import org.testng.annotations.Test; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.util.annotation.AnnotationConvertor; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.util.annotation.ConvertableAnnotationRetriever; public class ConvertableAnnotationTest extends BaseTest { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public static @interface FinalAnnotationA { public int value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @ConvertableAnnotation(ConvertAA.class) public static @interface AnnotationAA { public String value(); } public static class ConvertAA implements AnnotationConvertor<AnnotationAA, FinalAnnotationA> { @Override public FinalAnnotationA convert(final AnnotationAA originalAnnotation) { return new FinalAnnotationA() { @Override public Class<? extends Annotation> annotationType() { return FinalAnnotationA.class; } @Override public int value() { return Integer.parseInt(originalAnnotation.value()); } }; } } @AnnotationAA("45") public static class HA { } @Test public void testOneLayerConvert() { FinalAnnotationA fa = ConvertableAnnotationRetriever.retrieveAnnotation(FinalAnnotationA.class, HA.class.getAnnotations()); Assert.assertEquals(fa.value(), 45); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public static @interface FinalAnnotationB { public String value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @ConvertableAnnotation(ConvertBB.class) public static @interface AnnotationBB { public int value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @ConvertableAnnotation(ConvertBBB.class) public static @interface AnnotationBBB { public String value(); } public static class ConvertBBB implements AnnotationConvertor<AnnotationBBB, AnnotationBB> { @Override public AnnotationBB convert(final AnnotationBBB originalAnnotation) { return new AnnotationBB() { @Override public Class<? extends Annotation> annotationType() { return AnnotationBB.class; } @Override public int value() { return Integer.parseInt(originalAnnotation.value()); } }; } } public static class ConvertBB implements AnnotationConvertor<AnnotationBB, FinalAnnotationB> { @Override public FinalAnnotationB convert(final AnnotationBB originalAnnotation) { return new FinalAnnotationB() { @Override public Class<? extends Annotation> annotationType() { return FinalAnnotationB.class; } @Override public String value() { // TODO Auto-generated method stub return "v-" + originalAnnotation.value(); } }; } } @AnnotationBBB("90") public static class HB { } public void testTwoLayerConvert() { FinalAnnotationB fb = ConvertableAnnotationRetriever.retrieveAnnotation(FinalAnnotationB.class, HB.class.getAnnotations()); Assert.assertEquals(fb.value(), "v-90"); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public static @interface FinalAnnotationC { } public void testNotFound() { FinalAnnotationC fc = ConvertableAnnotationRetriever.retrieveAnnotation(FinalAnnotationC.class, HB.class.getAnnotations()); Assert.assertNull(fc); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,029,051,654,795,882,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static org.testng.Assert.assertEquals; import java.lang.reflect.Method; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.ContextDataHolder; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.data.annotation.ContextDataSet; import com.astamuse.asta4d.test.render.infra.BaseTest; public class InjectUtilForInstanceTest extends BaseTest { @ContextDataSet(singletonInContext = false) public static class TestSet { @ContextData private long f1; @ContextData public ContextDataHolder<Long> f2 = new ContextDataHolder<>(Long.class); private String f3; public long getF1() { return f1; } @ContextData public String getF3() { return f3; } public void setF3(String f3) { this.f3 = f3; } } @ContextDataSet(singletonInContext = true) public static class TestSingletonSet { @ContextData private long f1; @ContextData public ContextDataHolder<Long> f2 = new ContextDataHolder<>(Long.class); public long getF1() { return f1; } } public static class TestCls { @ContextData private TestSet myset; @ContextData private TestSingletonSet mySingletonSet; } @Test public void contextSetAndInjectableOnMethod() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", "6678"); ctx.setData("f2", "12345"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requireHolder", TestSet.class)); TestSet set = (TestSet) params[0]; assertEquals(set.getF1(), 6678L); assertEquals(set.f2.getValue().longValue(), 12345L); } @Test(enabled = false) public void requireHolder(TestSet holder) { } @Test public void contextSetAndInjectableOnInstance() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", "6678"); ctx.setData("f2", "12345"); ctx.setData("f3", "QQQ"); TestCls tc = new TestCls(); InjectUtil.injectToInstance(tc); assertEquals(tc.myset.getF1(), 6678L); assertEquals(tc.myset.f2.getValue().longValue(), 12345L); assertEquals(tc.myset.getF3(), "QQQ"); assertEquals(tc.mySingletonSet.getF1(), 6678L); assertEquals(tc.mySingletonSet.f2.getValue().longValue(), 12345L); TestCls tc2 = new TestCls(); InjectUtil.injectToInstance(tc2); assertEquals(tc.myset == tc2.myset, false);// new instance assertEquals(tc.mySingletonSet == tc2.mySingletonSet, true);// the same instance } @Test public void retriveContextSetInScopeFirst() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", "6678"); ctx.setData("f2", "12345"); // retrieve a set at first TestCls tc = new TestCls(); InjectUtil.injectToInstance(tc); TestSet set = tc.myset; // save the set into the context ctx.setData("myset", set); // retrieve again tc = new TestCls(); InjectUtil.injectToInstance(tc); // should be the same instance assertEquals(tc.myset == set, true); } private static Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { return InjectUtilForInstanceTest.class.getMethod(name, parameterTypes); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,363,624,914,096,707,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.interceptor.base.Executor; import com.astamuse.asta4d.interceptor.base.GenericInterceptor; import com.astamuse.asta4d.interceptor.base.InterceptorUtil; public class InterceptorUtilTest { @Test public void succeedAllProcess() throws Exception { TestHolder holder = new TestHolder(); List<TestIntercepter> interceptorList = new ArrayList<>(); interceptorList.add(new TestIntercepter("Intercepter1")); interceptorList.add(new TestIntercepter("Intercepter2")); interceptorList.add(new TestIntercepter("Intercepter3")); TestExecutor executor = new TestExecutor(); InterceptorUtil.executeWithInterceptors(holder, interceptorList, executor); assertEquals(holder.getExecutedBeforeProcessNames(), new String[] { "Intercepter1", "Intercepter2", "Intercepter3" }); assertEquals(holder.getExecutedAfterProcessNames(), new String[] { "Intercepter3", "Intercepter2", "Intercepter1" }); } @Test public void breakBeforeProcess() throws Exception { TestHolder holder = new TestHolder(); List<TestIntercepter> interceptorList = new ArrayList<>(); interceptorList.add(new TestIntercepter("Intercepter1")); interceptorList.add(new TestIntercepter("Intercepter2", false, false)); interceptorList.add(new TestIntercepter("Intercepter3")); TestExecutor executor = new TestExecutor(); InterceptorUtil.executeWithInterceptors(holder, interceptorList, executor); assertEquals(holder.getExecutedBeforeProcessNames(), new String[] { "Intercepter1", "Intercepter2" }); assertEquals(holder.getExecutedAfterProcessNames(), new String[] { "Intercepter1" }); } @Test public void failureMainProcess() throws Exception { TestHolder holder = new TestHolder(); List<TestIntercepter> interceptorList = new ArrayList<>(); interceptorList.add(new TestIntercepter("Intercepter1")); interceptorList.add(new TestIntercepter("Intercepter2")); interceptorList.add(new TestIntercepter("Intercepter3")); TestExecutor executor = new TestExecutor(true); try { InterceptorUtil.executeWithInterceptors(holder, interceptorList, executor); fail("No exceptions occurred."); } catch (TestException e) { assertEquals(holder.getExecutedBeforeProcessNames(), new String[] { "Intercepter1", "Intercepter2", "Intercepter3" }); assertEquals(holder.getExecutedAfterProcessNames(), new String[] { "Intercepter3", "Intercepter2", "Intercepter1" }); } } @Test public void failureBeforeProcess() throws Exception { TestHolder holder = new TestHolder(); List<TestIntercepter> interceptorList = new ArrayList<>(); interceptorList.add(new TestIntercepter("Intercepter1")); interceptorList.add(new TestIntercepter("Intercepter2", true, true)); interceptorList.add(new TestIntercepter("Intercepter3")); TestExecutor executor = new TestExecutor(); try { InterceptorUtil.executeWithInterceptors(holder, interceptorList, executor); fail("No exceptions occurred."); } catch (TestException e) { assertEquals(holder.getExecutedBeforeProcessNames(), new String[] { "Intercepter1", "Intercepter2" }); assertEquals(holder.getExecutedAfterProcessNames(), new String[] { "Intercepter1" }); } } private static class TestHolder { private final List<String> executedBeforeProcessNames = new ArrayList<>(); private final List<String> executedAfterProcessNames = new ArrayList<>(); public void addBeforeProcessName(String name) { executedBeforeProcessNames.add(name); } public void addAfterProcessName(String name) { executedAfterProcessNames.add(name); } public String[] getExecutedBeforeProcessNames() { return executedBeforeProcessNames.toArray(new String[executedBeforeProcessNames.size()]); } public String[] getExecutedAfterProcessNames() { return executedAfterProcessNames.toArray(new String[executedAfterProcessNames.size()]); } } public static class TestExecutor implements Executor<TestHolder> { private final boolean failure; public TestExecutor() { this(false); } public TestExecutor(boolean failure) { this.failure = failure; } @Override public void execute(TestHolder executionHolder) throws Exception { if (this.failure) { throw new TestException(); } } } public static class TestIntercepter implements GenericInterceptor<TestHolder> { private final String name; private final boolean beforeResult; private final boolean failureBefore; public TestIntercepter(String name) { this(name, true, false); } public TestIntercepter(String name, boolean beforeResult, boolean failBefore) { this.name = name; this.beforeResult = beforeResult; this.failureBefore = failBefore; } @Override public boolean beforeProcess(TestHolder executionHolder) throws Exception { executionHolder.addBeforeProcessName(name); if (failureBefore) { throw new TestException(); } return beforeResult; } @Override public void afterProcess(TestHolder executionHolder, ExceptionHandler exceptionHandler) { executionHolder.addAfterProcessName(name); } } @SuppressWarnings("serial") public static class TestException extends Exception { } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,133,456,808,253,197,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Date; import org.testng.Assert; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.ContextDataHolder; import com.astamuse.asta4d.data.DataOperationException; import com.astamuse.asta4d.data.InjectTrace; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.data.annotation.ContextDataSet; import com.astamuse.asta4d.test.render.infra.BaseTest; public class InjectUtilForTypeUnMatchTest extends BaseTest { @ContextDataSet public static class TestSetForException { @ContextData(typeUnMatch = TypeUnMacthPolicy.EXCEPTION) private long f1 = -1; public long getF1() { return f1; } } @Test(expectedExceptions = DataOperationException.class, expectedExceptionsMessageRegExp = ".*cannot be coverted from.*") public void exceptionWhenInjectableOnMethodSetParam() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", "xx77"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requestHolderForException", TestSetForException.class)); } @Test(expectedExceptions = DataOperationException.class, expectedExceptionsMessageRegExp = ".*cannot be coverted from.*") public void exceptionWhenInjectableOnMethodParam() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("holder", "xx77"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requestHolderForException", int.class)); } @Test(expectedExceptions = DataOperationException.class, expectedExceptionsMessageRegExp = ".*cannot be coverted from.*") public void exceptionWhenInjectableOnMethodParam2() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("holder", "xx77"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requestHolderForException2", int.class)); } @Test(expectedExceptions = DataOperationException.class, expectedExceptionsMessageRegExp = ".*cannot be coverted from.*") public void exceptionWhenInjectableOnMethodParam3() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("holder", "xx77"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requestHolderForException3", int.class)); } @Test(expectedExceptions = DataOperationException.class, expectedExceptionsMessageRegExp = ".*cannot be coverted from.*") public void exceptionWhenInjectArrayDataOnMethodSetParam() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", new String[] { "xx77" }); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requestHolderForException", TestSetForException.class)); } @Test(enabled = false) public void requestHolderForException(TestSetForException holder) { } @Test(enabled = false) public void requestHolderForException(@ContextData(typeUnMatch = TypeUnMacthPolicy.EXCEPTION) int holder) { } @Test(enabled = false) public void requestHolderForException2(@ContextData int holder) { } @Test(enabled = false) public void requestHolderForException3(int holder) { } @ContextDataSet public static class TestSetForDefaultValue { @ContextData(typeUnMatch = TypeUnMacthPolicy.DEFAULT_VALUE) private long f1 = -1; @ContextData(typeUnMatch = TypeUnMacthPolicy.DEFAULT_VALUE_AND_TRACE) private long f2 = -1; @ContextData(typeUnMatch = TypeUnMacthPolicy.DEFAULT_VALUE_AND_TRACE) private Date f3 = new Date(0); public long getF1() { return f1; } public long getF2() { return f2; } public Date getF3() { return f3; } } @Test public void defaultValueWhenInjectableOnMethodSetParam() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", "xx77"); ctx.setData("f2", "xx66"); ctx.setData("f3", "xx55"); Object[] params = InjectUtil.getMethodInjectParams(getMethod("requestHolderForDefaultValue", TestSetForDefaultValue.class)); TestSetForDefaultValue set = (TestSetForDefaultValue) params[0]; Assert.assertEquals(set.getF1(), 0); Assert.assertEquals(set.getF2(), 0); Assert.assertNull(set.getF3()); ContextDataHolder traceHolder; Field field1 = TestSetForDefaultValue.class.getDeclaredField("f1"); traceHolder = InjectTrace.getInstanceInjectionTraceInfo(set, field1); Assert.assertNull(traceHolder); Field field2 = TestSetForDefaultValue.class.getDeclaredField("f2"); traceHolder = InjectTrace.getInstanceInjectionTraceInfo(set, field2); Assert.assertEquals(traceHolder.getFoundOriginalData(), "xx66"); Field field3 = TestSetForDefaultValue.class.getDeclaredField("f3"); traceHolder = InjectTrace.getInstanceInjectionTraceInfo(set, field3); Assert.assertEquals(traceHolder.getFoundOriginalData(), "xx55"); } @Test public void defaultValueWhenInjectableOnMethodParam() throws Exception { Context ctx = Context.getCurrentThreadContext(); ctx.setData("f1", "xx77"); ctx.setData("f2", "xx66"); Method m = getMethod("requestHolderForDefaultValue", int.class, int.class); Object[] params = InjectUtil.getMethodInjectParams(m); Assert.assertEquals(params[0], 0); Assert.assertEquals(params[1], 0); ContextDataHolder traceHolder; traceHolder = InjectTrace.getMethodInjectionTraceInfo(m, 0); Assert.assertNull(traceHolder); traceHolder = InjectTrace.getMethodInjectionTraceInfo(m, 1); Assert.assertEquals(traceHolder.getFoundOriginalData(), "xx66"); } @Test(enabled = false) public void requestHolderForDefaultValue(TestSetForDefaultValue holder) { } @Test(enabled = false) public void requestHolderForDefaultValue(@ContextData(typeUnMatch = TypeUnMacthPolicy.DEFAULT_VALUE) int f1, @ContextData(typeUnMatch = TypeUnMacthPolicy.DEFAULT_VALUE_AND_TRACE) int f2) { } private static Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { return InjectUtilForTypeUnMatchTest.class.getMethod(name, parameterTypes); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,470,359,349,586,818,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit.data; import java.time.Instant; import java.time.ZoneOffset; import java.util.Date; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import org.joda.time.YearMonth; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.astamuse.asta4d.data.convertor.String2Date; import com.astamuse.asta4d.data.convertor.String2Java8Instant; import com.astamuse.asta4d.data.convertor.String2Java8LocalDateTime; import com.astamuse.asta4d.data.convertor.String2Java8LocalTime; import com.astamuse.asta4d.data.convertor.String2Java8YearMonth; import com.astamuse.asta4d.data.convertor.String2JodaDateTime; import com.astamuse.asta4d.data.convertor.String2JodaLocalDate; import com.astamuse.asta4d.data.convertor.String2JodaLocalDateTime; import com.astamuse.asta4d.data.convertor.String2JodaLocalTime; import com.astamuse.asta4d.data.convertor.String2JodaYearMonth; @Test public class DateValueConvertorTest { //@formatter:off @DataProvider(name="string2Date") Object[][] string2DateData(){ return new Object[][] { {"2014-10-23T12:00:23.000+1100", new Date(2014-1900, 10-1, 23, 12, 0, 23), DateTimeZone.forOffsetHours(11)}, {"2014-10-23T12:00:23.000", new Date(2014-1900, 10-1, 23, 12, 0, 23), null}, {"2014-10-23T12:00:23", new Date(2014-1900, 10-1, 23, 12, 0, 23), null}, {"2014-10-23", new Date(2014-1900, 10-1, 23, 0, 0, 0), null}, {"20141023T120023.000-0900", new Date(2014-1900, 10-1, 23, 12, 0, 23), DateTimeZone.forOffsetHours(-9)}, {"20141023T120023.000", new Date(2014-1900, 10-1, 23, 12, 0, 23), null}, {"20141023T120023", new Date(2014-1900, 10-1, 23, 12, 0, 23), null}, {"20141023", new Date(2014-1900, 10-1, 23, 0, 0, 0), null}, {"", null, null}, }; } //@formatter:on @Test(dataProvider = "string2Date") public void testString2Date(String s, Date d, DateTimeZone tz) throws Exception { String2Date convertor = new String2Date(); if (tz == null) { Assert.assertEquals(convertor.convert(s), d); } else { long expectedTimeGMT = d.getTime(); expectedTimeGMT += DateTimeZone.getDefault().toTimeZone().getRawOffset() - tz.toTimeZone().getRawOffset(); Date actualDate = convertor.convert(s); Assert.assertEquals(actualDate, new Date(expectedTimeGMT)); } } @Test(dataProvider = "string2Date") public void testString2JodaDateTime(String s, Date d, DateTimeZone tz) throws Exception { String2JodaDateTime convertor = new String2JodaDateTime(); if (d == null) { Assert.assertEquals(convertor.convert(s), null); } else { if (tz == null) { Assert.assertEquals(convertor.convert(s), new DateTime(d.getTime())); } else { long expectedTimeGMT = d.getTime(); expectedTimeGMT += DateTimeZone.getDefault().toTimeZone().getRawOffset() - tz.toTimeZone().getRawOffset(); DateTime actualDate = convertor.convert(s); Assert.assertEquals(actualDate, new DateTime(expectedTimeGMT)); } } } @Test(dataProvider = "string2Date") public void testString2Java8Instant(String s, Date d, DateTimeZone tz) throws Exception { String2Java8Instant convertor = new String2Java8Instant(); Instant acturalInstant = convertor.convert(s); if (d == null) { Assert.assertEquals(acturalInstant, null); } else { if (tz == null) { long expectedTimeGMT = d.getTime(); Assert.assertEquals(acturalInstant, Instant.ofEpochMilli(expectedTimeGMT)); } else { long expectedTimeGMT = d.getTime(); expectedTimeGMT += DateTimeZone.getDefault().toTimeZone().getRawOffset() - tz.toTimeZone().getRawOffset(); Assert.assertEquals(acturalInstant, Instant.ofEpochMilli(expectedTimeGMT)); } } } @Test(dataProvider = "string2Date") public void testString2JodaLocalDate(String s, Date d, DateTimeZone tz) throws Exception { String2JodaLocalDate convertor = new String2JodaLocalDate(); if (d == null) { Assert.assertEquals(convertor.convert(s), null); } else { Assert.assertEquals(convertor.convert(s), new LocalDate(d.getTime())); } } @Test(dataProvider = "string2Date") public void testString2JodaLocalDateTime(String s, Date d, DateTimeZone tz) throws Exception { String2JodaLocalDateTime convertor = new String2JodaLocalDateTime(); if (d == null) { Assert.assertEquals(convertor.convert(s), null); } else { Assert.assertEquals(convertor.convert(s), new LocalDateTime(d.getTime())); } } @Test(dataProvider = "string2Date") public void testString2Java8LocalDateTime(String s, Date d, DateTimeZone tz) throws Exception { String2Java8LocalDateTime convertor = new String2Java8LocalDateTime(); if (d == null) { Assert.assertEquals(convertor.convert(s), null); } else { long expectedTimeGMT = d.getTime(); expectedTimeGMT += DateTimeZone.getDefault().toTimeZone().getRawOffset(); Assert.assertEquals(convertor.convert(s), java.time.LocalDateTime.ofEpochSecond(expectedTimeGMT / 1000, 0, ZoneOffset.UTC)); } } //@formatter:off @DataProvider(name="string2Time") Object[][] string2TimeData(){ return new Object[][] { {"12:00:23.000+1100", LocalTime.parse("12:00:23")}, {"12:00:23.000", LocalTime.parse("12:00:23")}, {"12:00:23", LocalTime.parse("12:00:23")}, {"120023.000-0900", LocalTime.parse("12:00:23")}, {"120023.000", LocalTime.parse("12:00:23")}, {"120023", LocalTime.parse("12:00:23")}, }; } //@formatter:on @Test(dataProvider = "string2Time") public void testString2JodaLocalTime(String s, LocalTime t) throws Exception { String2JodaLocalTime convertor = new String2JodaLocalTime(); Assert.assertEquals(convertor.convert(s), t); } @Test(dataProvider = "string2Time") public void testString2Java8LocalTime(String s, LocalTime t) throws Exception { String2Java8LocalTime convertor = new String2Java8LocalTime(); java.time.LocalTime jlt = java.time.LocalTime.ofNanoOfDay(((long) t.getMillisOfDay()) * 1000 * 1000); Assert.assertEquals(convertor.convert(s), jlt); } //@formatter:off @DataProvider(name="string2ym") Object[][] string2ymData(){ return new Object[][] { {"2014-10", YearMonth.parse("2014-10")}, {"201410", YearMonth.parse("2014-10")}, }; } //@formatter:on @Test(dataProvider = "string2ym") public void testString2JodaYearMonth(String s, YearMonth ym) throws Exception { String2JodaYearMonth convertor = new String2JodaYearMonth(); Assert.assertEquals(convertor.convert(s), ym); } @Test(dataProvider = "string2ym") public void testString2Java8YearMonth(String s, YearMonth ym) throws Exception { String2Java8YearMonth convertor = new String2Java8YearMonth(); Assert.assertEquals(convertor.convert(s), java.time.YearMonth.of(ym.getYear(), ym.getMonthOfYear())); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,982,783,416,618,365,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.unit.data; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import org.joda.time.YearMonth; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.astamuse.asta4d.data.DefaultDataTypeTransformer; import com.astamuse.asta4d.data.convertor.DataValueConvertor; import com.astamuse.asta4d.data.convertor.UnsupportedValueException; import com.astamuse.asta4d.test.render.infra.BaseTest; public class DefaultDataTypeTransformerTest extends BaseTest { public static enum TestEnum { OK, NG; } public static class PA { String value; PA(String v) { this.value = v + "-PA"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PA other = (PA) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } public static class PB extends PA { String otherValue; PB(String v) { super(v); otherValue = v + "-PB"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PB other = (PB) obj; if (otherValue == null) { if (other.otherValue != null) return false; } else if (!otherValue.equals(other.otherValue)) return false; return true; } } public static class String2PB implements DataValueConvertor<String, PB> { @Override public PB convert(String obj) { PB ret = new PB(obj); return ret; } } public static class PA2String implements DataValueConvertor<PA, String> { @Override public String convert(PA obj) { return obj.value.substring(0, obj.value.indexOf("-PA")); } } public static class String2LongArray implements DataValueConvertor<String, Long[]> { @Override public Long[] convert(String obj) { String[] array = obj.split(","); Long[] ret = new Long[array.length]; for (int i = 0; i < array.length; i++) { ret[i] = Long.parseLong(array[i]); } return ret; } } public static class StringArray2Long implements DataValueConvertor<String[], Long> { @Override public Long convert(String[] obj) { if (obj.length == 1) { return Long.parseLong(obj[0]); } else { return Long.parseLong(obj[1]); } } } public static class String2LongSpecial implements DataValueConvertor<String, Long> { @Override public Long convert(String obj) { if (obj.startsWith("special:")) { Long value = Long.parseLong(obj.substring("special:".length())); return value + 100; } else { return null; } } } private DefaultDataTypeTransformer invoker; @BeforeClass public void prepareInvoker() { invoker = new DefaultDataTypeTransformer(); List<DataValueConvertor> list = new LinkedList<DataValueConvertor>(); list.add(new String2PB()); list.add(new PA2String()); list.add(new String2LongArray()); list.add(new StringArray2Long()); list.add(new String2LongSpecial()); invoker.setDataTypeConvertorList(list); } @DataProvider(name = "test-data") public Object[][] getTestData() throws Exception { //@formatter:off return new Object[][] { //for enum {String.class, TestEnum.class, "OK", TestEnum.OK}, {String[].class, TestEnum[].class, new String[]{"OK","OK", "NG"}, new TestEnum[]{TestEnum.OK,TestEnum.OK,TestEnum.NG}}, //basic cases {String.class, Integer.class, "123", 123}, {String.class, Integer[].class, "123", new Integer[]{123}}, {String[].class, Integer[].class, new String[]{"123", "456"}, new Integer[]{123, 456}}, {String[].class, Integer.class, new String[]{"123", "456"}, 123}, {String[].class, Date.class, new String[]{"2014-11-10"}, new Date(2014-1900, 11-1, 10)}, {String[].class, Instant.class, new String[]{"2014-11-10"}, ZonedDateTime.of(java.time.LocalDateTime.of(2014, 11,10,0,0), ZoneId.systemDefault()).toInstant()}, {String[].class, java.time.LocalDate.class, new String[]{"2014-11-10"}, java.time.LocalDate.of(2014, 11, 10)}, {String[].class, java.time.LocalDateTime.class, new String[]{"2014-11-10T12:00:00"}, java.time.LocalDateTime.of(2014, 11, 10, 12,0,0)}, {String[].class, java.time.LocalTime.class, new String[]{"12:00:00"}, java.time.LocalTime.of(12,0,0)}, {String[].class, java.time.YearMonth.class, new String[]{"2014-11"}, java.time.YearMonth.of( 2014,11)}, {String[].class, DateTime.class, new String[]{"2014-11-10"}, new DateTime(2014, 11, 10, 0,0)}, {String[].class, LocalDate.class, new String[]{"2014-11-10"}, new LocalDate(2014, 11, 10)}, {String[].class, LocalDateTime.class, new String[]{"2014-11-10T12:00:00"}, new LocalDateTime(2014, 11, 10, 12,0,0)}, {String[].class, LocalTime.class, new String[]{"12:00:00"}, new LocalTime( 12,0,0)}, {String[].class, YearMonth.class, new String[]{"2014-11"}, new YearMonth( 2014,11)}, //explicit array conversion {String.class, Long[].class, "123,456", new Long[]{123L, 456L}}, {String[].class, Long.class, new String[]{"123","456"}, 456L}, //recursive array conversion {String.class, Integer[][].class, "123", null},//don't support {String[].class, Integer[][].class, new String[]{"123", "456"}, null},//don't support {String.class, Long[][].class, "123,456", new Long[][]{{123L, 456L}}}, {String[][].class, Integer.class, new String[][]{{"123","456"}}, 123}, {String[][][].class, Integer.class, new String[][][]{{{"123","456"}}}, 123}, //compatible type {String.class, PA.class, "123", new PB("123")}, {PB.class, String.class, new PB("123"), "123"}, //transform by content format {String.class, Long.class, "special:398", 498L}, }; //@formatter:on } @Test(dataProvider = "test-data") public void testTransforming(Class srcType, Class targetType, Object data, Object expectedData) throws UnsupportedValueException { Object ret = invoker.transform(srcType, targetType, data); if (expectedData != null) { Assert.assertTrue(expectedData.getClass().isAssignableFrom(ret.getClass())); } Assert.assertEquals(ret, expectedData); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,107,367,889,817,154,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jsoup.nodes.Element; import org.testng.annotations.Test; import com.astamuse.asta4d.render.ElementNotFoundHandler; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.RowRenderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; import com.astamuse.asta4d.util.ElementUtil; public class AdvancedRenderingTest extends BaseTest { public static class TestRender { public Renderer continualSelectAll() { Renderer render = new GoThroughRenderer(); // replace element Element elem = ElementUtil.parseAsSingle("<div>i am a danymic element</div>"); Renderer repElem = Renderer.create("*", elem); repElem.addDebugger("after rep elem"); repElem.add("*", "replacetext"); repElem.addDebugger("after rep text"); render.addDebugger("before d1"); render.add("#d1", repElem); render.addDebugger("after d1"); Renderer attrSet = Renderer.create("div", "a", "b"); attrSet.add("#d3[a=b]", "+class", "tc"); render.addDebugger("before d2"); render.add("#d2", attrSet); render.addDebugger("after d2"); return render; } public Renderer setAnyTypeOuter(int count) { Renderer render = new GoThroughRenderer(); List<String> list = new ArrayList<>(); for (int i = 0; i < count; i++) { list.add("listParam" + i); } render.add("#outerDiv", "outerValue"); render.add("#inner", "outerList", list); render.add("#outer", "-count", (Object) null); return render; } public Renderer setAnyTypeInner(List<String> outerList) { Renderer render = new GoThroughRenderer(); render.add("#innerList > li", outerList); render.add("#inner", "-outerList", (Object) null); return render; } public Renderer pseudoRootRenderingWithNestedSnippet_outer() { Renderer renderer = Renderer.create("#inner", Arrays.asList(1, 2, 3), new RowRenderer<Integer>() { @Override public Renderer apply(Integer row) { return Renderer.create(":root", "value", row); } }); return renderer; } public Renderer pseudoRootRenderingWithNestedSnippet_inner(String value) { Renderer renderer = Renderer.create("#v", value); renderer.add(":root", new ElementSetter() { @Override public void set(Element elem) { elem.appendText("test-append"); } }); return renderer; } public Renderer pseudoRootRenderingOnFackedGroup() { // The recursive renderer will create a faked group on the target root, which causes the pseudo :root selector failed. // So we have to handle this case. Renderer renderer = Renderer.create(":root", Renderer.create("div", "t1")); renderer.add(":root", Renderer.create("div", "t2")); return renderer; } public Renderer pseudoRootRenderingWithElementNotFoundHandler() { Renderer renderer = Renderer.create(":root", Renderer.create("div", "t1")); renderer.add(new ElementNotFoundHandler("span") { @Override public Renderer alternativeRenderer() { return Renderer.create(":root", Renderer.create("div", "t2")); } }); renderer.add(":root", Renderer.create("div", "t3")); return renderer; } } public AdvancedRenderingTest() { } @Test public void testPseudoRootRenderingOnFackedGroup() throws Throwable { new SimpleCase("AdvancedRendering_pseudoRootRendering.html"); } @Test public void testContinualSelectAll() throws Throwable { new SimpleCase("AdvancedRendering_continualSelectAll.html"); } @Test public void testDataRef() throws Throwable { new SimpleCase("AdvancedRendering_dataRef.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,472,611,743,266,431,500
/* * [Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; public class InjectTest extends BaseTest { public static class TestRender { public Renderer methodDefaultSearch(String av, String pv, String cv, String gv) { Renderer render = Renderer.create("#av-value", av); render.add("#pv-value", pv); render.add("#cv-value", cv); render.add("#gv-value", gv); return render; } public Renderer methodScopeSearch(@ContextData(scope = Context.SCOPE_DEFAULT) String av, @ContextData(scope = Context.SCOPE_DEFAULT) String pv, @ContextData(scope = Context.SCOPE_GLOBAL) String cv, @ContextData(scope = Context.SCOPE_GLOBAL) String gv) { Renderer render = Renderer.create("#av-value", av); render.add("#pv-value", pv); render.add("#cv-value", cv); render.add("#gv-value", gv); return render; } public Renderer methodNameSearch(@ContextData(name = "av-r") String av, @ContextData(name = "cv-r") String cv, @ContextData(name = "gv-r") String gv) { Renderer render = Renderer.create("#av-value", av); render.add("#cv-value", cv); render.add("#gv-value", gv); return render; } public Renderer methodTypeConvertor(int intvalue, long longvalue, boolean boolvalue) { Renderer render = Renderer.create("#intvalue", intvalue); render.add("#longvalue", longvalue); render.add("#boolvalue", boolvalue); return render; } } public static class InstaneDefaultSearchRender { @ContextData private String cv; private String gv; public Renderer render() { Renderer render = new GoThroughRenderer(); render.add("#cv-value", cv); render.add("#gv-value", gv); return render; } public String getGv() { return gv; } @ContextData public void setGv(String gv) { this.gv = gv; } } public static class InstaneScopeSearchRender { @ContextData(scope = Context.SCOPE_GLOBAL) private String cv; private String gv; public Renderer render() { Renderer render = new GoThroughRenderer(); render.add("#cv-value", cv); render.add("#gv-value", gv); return render; } public String getGv() { return gv; } @ContextData(scope = Context.SCOPE_GLOBAL) public void setGv(String gv) { this.gv = gv; } } public static class InstaneNameSearchRender { @ContextData(name = "cv-r") private String cv; private String gv; public Renderer render() { Renderer render = new GoThroughRenderer(); render.add("#cv-value", cv); render.add("#gv-value", gv); return render; } public String getGv() { return gv; } @ContextData(name = "gv-r") public void setGv(String gv) { this.gv = gv; } } public static class InstanceTypeConvertorRender { @ContextData private int intvalue; @ContextData private long longvalue; @ContextData private boolean boolvalue; public Renderer render() { Renderer render = Renderer.create("#intvalue", intvalue); render.add("#longvalue", longvalue); render.add("#boolvalue", boolvalue); return render; } } public void testMethodDefaultSearch() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "pv", "pv-value at context"); context.setData(Context.SCOPE_DEFAULT, "cv", "cv-value at context"); context.setData(Context.SCOPE_GLOBAL, "cv", "cv-value at global"); context.setData(Context.SCOPE_GLOBAL, "gv", "gv-value"); new SimpleCase("Inject_testMethodDefaultSearch.html"); } public void testMethodScopeSearch() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "av", "av-value at context"); context.setData(Context.SCOPE_DEFAULT, "pv", "pv-value at context"); context.setData(Context.SCOPE_DEFAULT, "cv", "cv-value at context"); context.setData(Context.SCOPE_GLOBAL, "cv", "cv-value at global"); context.setData(Context.SCOPE_DEFAULT, "gv", "gv-value at context"); context.setData(Context.SCOPE_GLOBAL, "gv", "gv-value at global"); new SimpleCase("Inject_testMethodScopeSearch.html"); } public void testMethodNameSearch() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "cv", "cv-value"); context.setData(Context.SCOPE_DEFAULT, "cv-r", "cv-value for name replace"); context.setData(Context.SCOPE_GLOBAL, "gv-r", "gv-value for name replace"); context.setData(Context.SCOPE_GLOBAL, "gv", "gv-value"); new SimpleCase("Inject_testMethodNameSearch.html"); } public void testMethodTypeConvertor() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "intvalue", "222"); context.setData(Context.SCOPE_DEFAULT, "longvalue", "333"); context.setData(Context.SCOPE_DEFAULT, "boolvalue", "false"); new SimpleCase("Inject_testMethodTypeConvertor.html"); } public void testInstanceDefaultSearch() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "cv", "cv-value at context"); context.setData(Context.SCOPE_GLOBAL, "cv", "cv-value at global"); context.setData(Context.SCOPE_GLOBAL, "gv", "gv-value"); new SimpleCase("Inject_testInstanceDefaultSearch.html"); } public void testInstanceScopeSearch() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "cv", "cv-value at context"); context.setData(Context.SCOPE_GLOBAL, "cv", "cv-value at global"); context.setData(Context.SCOPE_DEFAULT, "gv", "gv-value at context"); context.setData(Context.SCOPE_GLOBAL, "gv", "gv-value at global"); new SimpleCase("Inject_testInstanceScopeSearch.html"); } public void testInstanceNameSearch() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "cv", "cv-value"); context.setData(Context.SCOPE_DEFAULT, "cv-r", "cv-value for name replace"); context.setData(Context.SCOPE_GLOBAL, "gv", "gv-value"); context.setData(Context.SCOPE_GLOBAL, "gv-r", "gv-value for name replace"); new SimpleCase("Inject_testInstanceNameSearch.html"); } public void testInstanceTypeConvertor() throws Throwable { Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_DEFAULT, "intvalue", "111"); context.setData(Context.SCOPE_DEFAULT, "longvalue", "555"); context.setData(Context.SCOPE_DEFAULT, "boolvalue", "true"); new SimpleCase("Inject_testInstanceTypeConvertor.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
213,549,293,968,984,420
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.snippet.InitializableSnippet; import com.astamuse.asta4d.snippet.SnippetInvokeException; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; public class SimpleSnippetRenderingTest extends BaseTest { public static class StaticEmbed { public Renderer render(String ctype) { return Renderer.create("#hellodiv", "statically loaded before snippet being executed"); } } public static class TagEmbed { public Renderer render(String ctype) { return Renderer.create("span", ctype); } } public static class SnippetTag { public Renderer render() { return Renderer.create("span", "wow"); } } public static class InitSnippet implements InitializableSnippet { @ContextData private String value; private long id; private String resolvedValue; private int count = 0; @Override public void init() throws SnippetInvokeException { resolvedValue = value + "-resolved"; count++; } @ContextData private void setId(long id) { this.id = id; } public Renderer render_1() { return Renderer.create(".value", resolvedValue).add(".count", count); } public Renderer render_2() { return Renderer.create(".value", resolvedValue).add(".count", count); } } public static class AttrConflict { public Renderer outer() { return Renderer.create("afd|snippet", "status", 5); } public Renderer inner(int status) { return Renderer.create("#x-status", status); } } public void testTagEmbed() throws Throwable { new SimpleCase("SimpleSnippet_TagEmbed.html"); } @Test(enabled = false) public void testStaticEmbed() throws Throwable { new SimpleCase("SimpleSnippet_StaticEmbed.html"); } public void testSnippetTag() throws Throwable { new SimpleCase("SimpleSnippet_SnippetTag.html"); } public void testBasePackageSnippetSearch() throws Throwable { new SimpleCase("SimpleSnippet_BasePackage.html"); } public void testSnippetInit() throws Throwable { Context.getCurrentThreadContext().setData("value", "fire"); new SimpleCase("SimpleSnippet_SnippetInit.html"); } public void testAttrConflict() throws Throwable { new SimpleCase("SimpleSnippet_AttrConflict.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,476,033,707,512,325,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import java.util.Locale; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; public class ResolveTemplateByLocaleTest extends BaseTest { @Test public void currentLocaleJaJP() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.JAPAN); new SimpleCase("ResolveTemplateByLocale.html", "ResolveTemplateByLocale_ja_JP.html"); } @Test public void currentLocaleJa() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.JAPANESE); new SimpleCase("ResolveTemplateByLocale.html", "ResolveTemplateByLocale.html"); } @Test public void currentLocaleEnUS() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.US); new SimpleCase("ResolveTemplateByLocale.html", "ResolveTemplateByLocale_en.html"); } @Test public void currentLocaleEnGB() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.UK); new SimpleCase("ResolveTemplateByLocale.html", "ResolveTemplateByLocale_en.html"); } @Test public void currentLocaleDeDE() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.GERMANY); new SimpleCase("ResolveTemplateByLocale.html", "ResolveTemplateByLocale.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-65,373,542,889,015,260
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.jsoup.nodes.Element; import org.testng.annotations.Test; import com.astamuse.asta4d.render.ChildReplacer; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; import com.astamuse.asta4d.test.render.infra.TimeCalculator; import com.astamuse.asta4d.util.ElementUtil; @Test public class LambdaRenderingTest extends BaseTest { public static class TestRender { public Renderer removeClassInListRendering() { List<Integer> list = IntStream.range(1, 10 + 1).boxed().collect(Collectors.toList()); return Renderer.create(".item", list, i -> { Renderer render = Renderer.create(".x-num", i); int idx = (i % 3) + 1; render.add(".x-idx-" + idx, "-class", "x-remove"); render.add(".x-remove", (Object) null); return render; }); } public Renderer renderableRendering() { final Map<String, String> valueMap = new HashMap<>(); valueMap.put("value", "00"); Renderer render = Renderer.create("#test", (Element e) -> { valueMap.put("value", "xx"); }); render.add("#test", () -> { return Renderer.create("*", valueMap.get("value")); }); return render; } public Renderer listTextRendering() { Renderer renderer = new GoThroughRenderer(); List<String> textList = Arrays.asList("a", "b", "c"); renderer.add("div#test-text", textList.stream()); List<Long> longList = Arrays.asList(10L, 20L, 30L); renderer.add("div#test-long", longList, (index, obj) -> { return obj / 10; }); List<Integer> integerList = Arrays.asList(100, 200, 300); renderer.add("div#test-integer", integerList.stream().map(obj -> { return obj / 10; })); List<Boolean> booleanList = Arrays.asList(true, false, false); renderer.add("div#test-boolean", booleanList, obj -> { return obj && true; }); return renderer; } public Renderer listElementRendering() { Renderer renderer = Renderer.create("div#test", IntStream.range(0, 3 + 1).mapToObj(i -> { return ElementUtil.parseAsSingle("<span>BBB:" + i + "</span>"); })); return renderer; } public Renderer listChildReplacing() { List<Integer> list = IntStream.range(0, 3 + 1).boxed().collect(Collectors.toList()); Renderer renderer = Renderer.create("div#test", list, i -> { return new ChildReplacer(ElementUtil.parseAsSingle("<strong>BBB:" + i + "</strong>")); }); return renderer; } public Renderer listRecursiveRendering() { List<String[]> list = new ArrayList<>(); for (int i = 0; i <= 3; i++) { String[] sa = { "aa-" + i, "bb-" + i }; list.add(sa); } Renderer renderer = Renderer.create("div#test", list, obj -> { Renderer r = Renderer.create("#s1", obj[0]); r.add("#s2", obj[1]); return r; }); return renderer; } public Renderer parallelStreamRenderingCorrectness() { Renderer renderer = new GoThroughRenderer(); List<String> textList = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); renderer.add("div#test-text", textList.parallelStream().map(t -> { return t; })); return renderer; } public Renderer parallelStreamRenderingTimeConsuming() { Renderer renderer = new GoThroughRenderer(); List<String> textList = Arrays.asList("a", "b", "c"); renderer.add("div#test-text", textList.parallelStream().map(t -> { try { Thread.currentThread().sleep(1000); } catch (Exception e) { throw new RuntimeException(e); } return t; })); return renderer; } } public void testRemoveClassInListRendering() throws Throwable { new SimpleCase("LambdaRendering_removeClassInListRendering.html"); } public void testRenderableRendering() throws Throwable { new SimpleCase("LambdaRendering_renderableRendering.html"); } public void testListElementRendering() throws Throwable { new SimpleCase("LambdaRendering_listElementRendering.html"); } public void testListTextRendering() throws Throwable { new SimpleCase("LambdaRendering_listTextRendering.html"); } public void testListChildReplacing() throws Throwable { new SimpleCase("LambdaRendering_listChildReplacing.html"); } public void testListRecursiveRendering() throws Throwable { new SimpleCase("LambdaRendering_listRecursiveRendering.html"); } @Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = ".*not supported.*") public void testParallelStreamRenderingException() throws Throwable { new SimpleCase("LambdaRendering_parallelStreamRenderingCorrectness.html"); } /* The following parallel stream related tests are disabled because we change our action to always throw exception for parallel stream */ @Test(enabled = false) public void testParallelStreamRenderingCorrectness() throws Throwable { // we want to confirm it 10 times for (int i = 0; i < 10; i++) { new SimpleCase("LambdaRendering_parallelStreamRenderingCorrectness.html"); } } @Test(enabled = false) public void testParallelStreamRenderingTimeConsuming() throws Throwable { // we do not know how many threads will be started for parallel stream by the jvm, so if we render a list with too many elements, we // will have no idea about what is the appropriate execution time for multi-thread rendering. Thus we limit the size of target list // to 3, which means 2 seconds is a ideal value. TimeCalculator.shouldRunInTime(() -> { try { new SimpleCase("LambdaRendering_parallelStreamRenderingTimeConsuming.html"); } catch (Throwable e) { throw new RuntimeException(e); } }, 2000); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,449,568,169,048,534,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.ChildReplacer; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; import com.astamuse.asta4d.util.ElementUtil; import com.astamuse.asta4d.util.collection.RowConvertor; public class RenderingTest extends BaseTest { public static class TestRender { public Renderer elementRendering() { Element elem = ElementUtil.parseAsSingle("<div>i am a danymic element</div>"); Renderer render = Renderer.create("*", elem); render.addDebugger("TestRender"); return render; } public Renderer textRendering() { Renderer renderer = Renderer.create("div#test", "Prometheus"); renderer.add("#testspace", "I love this game!"); renderer.add("#testnbsp", new ChildReplacer(ElementUtil.parseAsSingle("<span>three space here(&nbsp;&nbsp;&nbsp;)</span>"))); renderer.add("#testgreatermark", "3 > 2 or 3 < 2, it's a question."); return renderer; } public Renderer pseudoRootRendering() { Renderer renderer = Renderer.create(":root", "rendering at pseudo root"); return renderer; } public Renderer normalAttrSetting() { Renderer renderer = new GoThroughRenderer(); renderer.add("#testadd", "+v", "2"); renderer.add("#testaddexisted", "+v", "2"); renderer.add("#testremovebynull", "v", (Object) null); renderer.add("#testremovebyClear", "v", Clear); renderer.add("#testremovebyminus", "-v", ""); renderer.add("#testremovebyaddnull", "+v", (Object) null); renderer.add("#testremovebyaddClear", "+v", Clear); renderer.add("#testset", "v", "2"); return renderer; } public Renderer classAttrSetting() { Renderer renderer = new GoThroughRenderer(); renderer.add("#testadd", "class", "a"); renderer.add("#testaddexisted", "+class", "b"); renderer.add("#testremovebynull", "class", (Object) null); renderer.add(".xabc", "should not be rendered"); renderer.add("#testremovebyminus", "-class", "b"); renderer.add("#testremovebyaddnull", "+class", (Object) null); renderer.add("#testset", "class", "b"); return renderer; } public Renderer removeClassInListRendering() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return Renderer.create(".item", list, new RowConvertor<Integer, Renderer>() { @Override public Renderer convert(int rowIndex, Integer i) { Renderer render = Renderer.create(".x-num", i); int idx = (i % 3) + 1; render.add(".x-idx-" + idx, "-class", "x-remove"); render.add(".x-remove", (Object) null); return render; } }); } public Renderer clearNode() { Renderer render = Renderer.create("#byClearRenderer", Clear); render.add("#byNullObj", (Object) null); render.add("#byNullString", (String) null); render.add("#byClearRenderer2", 1 == 1 ? Clear : "XX"); return render; } public Renderer childReplacing() { Element elem = ElementUtil.parseAsSingle("<div>i am a danymic element</div>"); Renderer render = Renderer.create("span", new ChildReplacer(elem)); return render; } public Renderer recursiveRendering() { Renderer spanRender = Renderer.create("span#s1", "wow!"); Renderer divRender = Renderer.create("#d1", spanRender); return divRender; } public Renderer renderableRendering() { final Map<String, String> valueMap = new HashMap<>(); valueMap.put("value", "00"); Renderer render = Renderer.create("#test", new ElementSetter() { @Override public void set(Element elem) { valueMap.put("value", "xx"); // do nothing } }); render.add("#test", new Renderable() { @Override public Renderer render() { return Renderer.create("*", valueMap.get("value")); } }); return render; } public Renderer listTextRendering() { Renderer renderer = new GoThroughRenderer(); // there was a bug when a selector was not found in list rendering renderer.add("#not-exists-element", "I love this game!"); List<String> textList = Arrays.asList("a", "b", "c"); renderer.add("div#test-text", textList); List<Long> longList = Arrays.asList(1L, 2L, 3L); renderer.add("div#test-long", longList); List<Integer> integerList = Arrays.asList(10, 20, 30); renderer.add("div#test-integer", integerList); List<Boolean> booleanList = Arrays.asList(true, false, false); renderer.add("div#test-boolean", booleanList); return renderer; } public Renderer listElementRendering() { List<Element> list = new ArrayList<>(); for (int i = 0; i <= 3; i++) { Element elem = ElementUtil.parseAsSingle("<span>BBB:" + i + "</span>"); list.add(elem); } Renderer renderer = Renderer.create("div#test", list); return renderer; } public Renderer listChildReplacing() { List<Element> list = new ArrayList<>(); for (int i = 0; i <= 3; i++) { Element elem = ElementUtil.parseAsSingle("<strong>BBB:" + i + "</strong>"); list.add(elem); } Renderer renderer = Renderer.create("div#test", list, new RowConvertor<Element, ChildReplacer>() { @Override public ChildReplacer convert(int rowIdx, Element obj) { return new ChildReplacer(obj); } }); return renderer; } public Renderer listRecursiveRendering() { List<String[]> list = new ArrayList<>(); for (int i = 0; i <= 3; i++) { String[] sa = { "aa-" + i, "bb-" + i }; list.add(sa); } Renderer renderer = Renderer.create("div#test", list, new RowConvertor<String[], Renderer>() { @Override public Renderer convert(int rowIdx, String[] obj) { Renderer r = Renderer.create("#s1", obj[0]); r.add("#s2", obj[1]); return r; } }); return renderer; } public Renderer addOperation() { Renderer r1 = Renderer.create("#s1", "r-1"); Renderer r2 = Renderer.create("#s2", "r-2"); Renderer r3 = Renderer.create("#s3", "r-3"); r1.add(r2); r2.add(r3); return r2; } } public void testElementRendering() throws Throwable { new SimpleCase("Rendering_elementRendering.html"); } public void testTextRendering() throws Throwable { new SimpleCase("Rendering_textRendering.html"); } public void testPseudoRootRendering() throws Throwable { new SimpleCase("Rendering_pseudoRootRendering.html"); } public void testNormalAttrSetting() throws Throwable { new SimpleCase("Rendering_normalAttrSetting.html"); } public void testClassAttrSetting() throws Throwable { new SimpleCase("Rendering_classAttrSetting.html"); } public void testRemoveClassInListRendering() throws Throwable { // TODO to resovle this problem new SimpleCase("Rendering_removeClassInListRendering.html"); } /* we do not need to test Element setter because there are several renderers extending from it. public void testElementSetter() { new SimpleCase("Rendering_elementSetter.html"); } */ public void testClearNode() throws Throwable { new SimpleCase("Rendering_clearNode.html"); } public void testChildReplacing() throws Throwable { new SimpleCase("Rendering_childReplacing.html"); } public void testRecursiveRendering() throws Throwable { new SimpleCase("Rendering_recursiveRendering.html"); } public void testRenderableRendering() throws Throwable { new SimpleCase("Rendering_renderableRendering.html"); } public void testListElementRendering() throws Throwable { new SimpleCase("Rendering_listElementRendering.html"); } public void testListTextRendering() throws Throwable { new SimpleCase("Rendering_listTextRendering.html"); } public void testListChildReplacing() throws Throwable { new SimpleCase("Rendering_listChildReplacing.html"); } public void testListRecursiveRendering() throws Throwable { new SimpleCase("Rendering_listRecursiveRendering.html"); } public void testRendererAddOperation() throws Throwable { // it should act correctly even though we do not add renderer to // the first created render and do not return the head renderer new SimpleCase("Rendering_addOperation.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,805,235,806,057,207,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import java.util.Arrays; import java.util.List; import org.testng.annotations.Test; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; import com.astamuse.asta4d.test.render.infra.TimeCalculator; import com.astamuse.asta4d.util.ElementUtil; import com.astamuse.asta4d.util.collection.RowConvertorBuilder; @Test(singleThreaded = true) public class ParallelTest extends BaseTest { public static class TestRender { public Renderer listTextRenderingLambda() { Configuration.getConfiguration().setNumberLimitOfParallelListConverting(50); List<String> list = Arrays.asList("a", "b", "c", "d"); Renderer renderer = Renderer.create("div#test", list, RowConvertorBuilder.parallel(obj -> { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } return obj + "-sleep"; })); return renderer; } public Renderer snippetInDiv() { Renderer renderer = Renderer.create("div", "in div"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } return renderer; } public Renderer snippetReplaceDiv() { Renderer renderer = Renderer.create("div", ElementUtil.parseAsSingle("<span>replace to span</span>")); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } return renderer; } public Renderer snippetNormal() { Renderer renderer = Renderer.create("div", "+class", "normal"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } return renderer; } } @Test public void paralleListConversionLambda() { TimeCalculator.shouldRunInTime(new Runnable() { @Override public void run() { try { new SimpleCase("ParallelTest_parallelListConversionLambda.html"); } catch (Throwable t) { throw new RuntimeException(t); } } }, 2000); } @Test public void paralleSnippet() { TimeCalculator.shouldRunInTime(new Runnable() { @Override public void run() { try { new SimpleCase("ParallelTest_parallelSnippet.html"); } catch (Throwable t) { throw new RuntimeException(t); } } }, 2000); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,602,002,441,482,083,300
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import org.testng.annotations.Test; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.template.TemplateException; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; public class TemplateExtractionTest extends BaseTest { @Test public void loadTempateWithExtension() throws Throwable { new SimpleCase("TemplateWithExtension.html"); } public static class RenderException { public Renderer render() { throw new RuntimeException("this method should not be invoked"); } } @Test public void loadTempateWithClear() throws Throwable { new SimpleCase("TemplateWithClear.html"); } @Test public void loadTempateWithComment() throws Throwable { new SimpleCase("TemplateWithComment.html"); } public static class MetaRender { public Renderer render() { return Renderer.create("meta", "mm", "0"); } } @Test public void loadTempateWithSpecialHeadTags() throws Throwable { new SimpleCase("TemplateWithSpecialHeadTags.html"); } @Test public void loadTempateWithEmbed() throws Throwable { new SimpleCase("TemplateWithEmbed.html"); } @Test(expectedExceptions = TemplateException.class, expectedExceptionsMessageRegExp = ".+does not exist\\.") public void loadTempateWithEmbedNotFound() throws Throwable { new SimpleCase("TemplateWithEmbedNotFound.html"); } @Test public void loadTempateWithEmbedBaseFolder() throws Throwable { new SimpleCase("TemplateWithEmbedBaseFolder.html"); } @Test public void loadTempateWithExtensionAndEmbedMerge() throws Throwable { new SimpleCase("TemplateWithExtensionAndEmbedMerge.html"); } @Test public void loadTemplateWithThreeLevelExtension() throws Throwable { new SimpleCase("ThreeLevelExtension_Child.html"); } @Test public void loadTemplateWithoutBodyTag() throws Throwable { new SimpleCase("TemplateWithoutBodyTag.html"); } @Test public void loadTemplateWithBodyOnlyAttr() throws Throwable { new SimpleCase("TemplateWithBodyOnlyAttr.html"); } @Test public void loadTemplateWithBodyOnlyMeta() throws Throwable { new SimpleCase("TemplateWithBodyOnlyMeta.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-700,383,334,717,251,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import org.testng.annotations.Test; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.snippet.SnippetInvokeException; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; import com.astamuse.asta4d.util.ElementUtil; @Test public class AdvancedSnippetTest extends BaseTest { public static class TestSnippet { public Renderer nestedSnippet_outer() { Renderer render = Renderer.create("#pv", "666"); render.add("#inner", "value", "777"); return render; } public Renderer nestedSnippet_inner(String value) { return Renderer.create("#pv", value); } public Renderer deletedNestedSnippet_outer() { return Renderer.create("#inner", Clear); } public Renderer nestedEmbed(String value) { return Renderer.create("#kv", value); } public Renderer dynamicSnippetSub() { Renderer render = Renderer.create("*", ElementUtil.text("ff")); return render; } } public static class ParentSnippet { public Renderer render() { return Renderer.create("p", "parent"); } public Renderer rx(String x) { return Renderer.create("p", "parent"); } } public static class MiddleSnippet extends ParentSnippet { } public static class ChildSnippet extends MiddleSnippet { public Renderer render() { return Renderer.create("p", "child"); } public Renderer rx(@ContextData(name = "xxx") String x) { return Renderer.create("p", "child"); } } public static class InitializingFailedSnippet { @ContextData int value; public Renderer render() { return Renderer.create(); } } public AdvancedSnippetTest() { } public void testDeletedNestedSnippet() throws Throwable { new SimpleCase("AdvancedSnippet_deletedNestedSnippet.html"); } public void testNestedSnippet() throws Throwable { new SimpleCase("AdvancedSnippet_nestedSnippet.html"); } public void testNestedEmbed() throws Throwable { new SimpleCase("AdvancedSnippet_nestedEmbed.html"); } public void testOverrideRenderMethod() throws Throwable { new SimpleCase("AdvancedSnippet_overrideRenderMethod.html"); } @Test(expectedExceptions = SnippetInvokeException.class, expectedExceptionsMessageRegExp = ".*Found data\\(ads\\) cannot be coverted from \\[class java\\.lang\\.String\\] to \\[class java\\.lang\\.Integer\\].*") public void testInitializingFailedSnippet() throws Throwable { Context.getCurrentThreadContext().setData("value", "ads"); new SimpleCase("AdvancedSnippet_initializingFailed.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,546,250,799,888,421,400
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import com.astamuse.asta4d.Component; import com.astamuse.asta4d.Component.AttributesRequire; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; public class ComponentRenderingTest extends BaseTest { public static class Page { public Renderer render(final String ctype) throws Exception { return Renderer.create("span", new Component("/ComponentRenderingTest_component.html", new AttributesRequire() { @Override protected void prepareAttributes() { this.add("value", ctype); } })); } } public static class Comp { public Renderer render(final String value) throws Exception { return Renderer.create(".value", value); } } public void testComponent() throws Throwable { new SimpleCase("ComponentRenderingTest.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,115,710,435,675,151,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import java.util.Locale; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; import com.astamuse.asta4d.util.i18n.I18nMessageHelper; import com.astamuse.asta4d.util.i18n.I18nMessageHelperTypeAssistant; import com.astamuse.asta4d.util.i18n.MappedParamI18nMessageHelper; import com.astamuse.asta4d.util.i18n.OrderedParamI18nMessageHelper; import com.astamuse.asta4d.util.i18n.formatter.ApacheStrSubstitutorFormatter; import com.astamuse.asta4d.util.i18n.formatter.JDKMessageFormatFormatter; import com.astamuse.asta4d.util.i18n.formatter.SymbolPlaceholderFormatter; import com.astamuse.asta4d.util.i18n.pattern.JDKResourceBundleMessagePatternRetriever; public class ExternalizeMessageTest extends BaseTest { public static class TestSnippet { public Renderer setWeatherreportInfo_NumberedParamKey() { Renderer renderer = new GoThroughRenderer(); renderer.add("afd|msg", "p0", "Tomorrow"); renderer.add("afd|msg", "p1", "sunny"); return renderer; } public Renderer setWeatherreportInfo_NamedParamKey() { Renderer renderer = new GoThroughRenderer(); renderer.add("afd|msg", "date", "Tomorrow"); renderer.add("afd|msg", "weather", "sunny"); return renderer; } } @BeforeClass public void setDefaultLocale() { Locale.setDefault(Locale.ROOT); } @Test public void externalizeMessage_DefaultMsg() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.US); setUpResourceBundleManager("symbol_placeholder_messages", new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter())); new SimpleCase("ExternalizeMessage_DefaultMsg.html", "ExternalizeMessage_DefaultMsg.html"); } @Test public void externalizeMessage_SymbolPlaceholder_us() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.US); setUpResourceBundleManager("symbol_placeholder_messages", new OrderedParamI18nMessageHelper((new SymbolPlaceholderFormatter()))); new SimpleCase("ExternalizeMessage_NumberedParamKey.html", "ExternalizeMessage_SymbolPlaceholder_us.html"); } @Test public void externalizeMessage_SymbolPlaceholder_ja() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.JAPAN); setUpResourceBundleManager("symbol_placeholder_messages", new OrderedParamI18nMessageHelper((new SymbolPlaceholderFormatter()))); new SimpleCase("ExternalizeMessage_NumberedParamKey.html", "ExternalizeMessage_SymbolPlaceholder_ja.html"); } @Test public void externalizeMessage_JDKMessageFormat_us() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.US); setUpResourceBundleManager("number_placeholder_messages", new OrderedParamI18nMessageHelper(new JDKMessageFormatFormatter())); new SimpleCase("ExternalizeMessage_NumberedParamKey.html", "ExternalizeMessage_SymbolPlaceholder_us.html"); } @Test public void externalizeMessage_JDKMessageFormat_ja() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.JAPAN); setUpResourceBundleManager("number_placeholder_messages", new OrderedParamI18nMessageHelper(new JDKMessageFormatFormatter())); new SimpleCase("ExternalizeMessage_NumberedParamKey.html", "ExternalizeMessage_SymbolPlaceholder_ja.html"); } @Test public void externalizeMessage_NamedPlaceholder_us() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.US); setUpResourceBundleManager("named_placeholder_messages", new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter())); new SimpleCase("ExternalizeMessage_NamedParamKey.html", "ExternalizeMessage_SymbolPlaceholder_us.html"); } @Test public void externalizeMessage_NamedPlaceholder_ja() throws Throwable { Context.getCurrentThreadContext().setCurrentLocale(Locale.JAPAN); setUpResourceBundleManager("named_placeholder_messages", new MappedParamI18nMessageHelper(new ApacheStrSubstitutorFormatter())); new SimpleCase("ExternalizeMessage_NamedParamKey.html", "ExternalizeMessage_SymbolPlaceholder_ja.html"); } private static void setUpResourceBundleManager(String fileName, I18nMessageHelper helper) { Configuration configuration = Configuration.getConfiguration(); configuration.setI18nMessageHelper(helper); JDKResourceBundleMessagePatternRetriever retriever = (JDKResourceBundleMessagePatternRetriever) configuration .getI18nMessageHelper().getMessagePatternRetriever(); retriever.setResourceNames("com.astamuse.asta4d.test.render.messages." + fileName); // re initialize the I18nMessageTypeAssistant System.setProperty("I18nMessageHelperTypeAssistant.Test", "xxx"); I18nMessageHelperTypeAssistant.reCreateInternalInstance(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
625,272,608,748,705,800
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render; import java.util.concurrent.atomic.AtomicInteger; import org.testng.annotations.Test; import com.astamuse.asta4d.data.ContextBindData; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.test.render.infra.BaseTest; import com.astamuse.asta4d.test.render.infra.SimpleCase; @Test(singleThreaded = true) public class ContextBindDataTest extends BaseTest { private final static AtomicInteger NonParallelRenderCounter = new AtomicInteger(); public static class NonParallelRender { private AtomicInteger coutner = NonParallelRenderCounter; private ContextBindData<Integer> data = new ContextBindData<Integer>() { @Override protected Integer buildData() { // should return 1 return coutner.incrementAndGet(); } }; public Renderer render() { return Renderer.create("*", data.get()); } } private final static AtomicInteger ParallelRenderCounter = new AtomicInteger(); public static class ParallelRender { private AtomicInteger counter = ParallelRenderCounter; private ContextBindData<Integer> data = new ContextBindData<Integer>(true) { @Override protected Integer buildData() { // should return 1 return counter.incrementAndGet(); } }; public Renderer render() { return Renderer.create("*", data.get()); } } public ContextBindDataTest() { // TODO Auto-generated constructor stub } public void testNonParallel() throws Throwable { new SimpleCase("ContextBindData_nonParallel.html"); } public void testParallel() throws Throwable { for (int i = 0; i < 20; i++) { new SimpleCase("ContextBindData_parallel.html"); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,571,356,447,355,413,500
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render.infra; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.snippet.resolve.DefaultSnippetResolver; import com.astamuse.asta4d.template.ClasspathTemplateResolver; @Test public class BaseTest { private final static Configuration configuration = new Configuration() { { ClasspathTemplateResolver templateResolver = new ClasspathTemplateResolver(); templateResolver.setSearchPathList("/com/astamuse/asta4d/test/render/templates"); this.setTemplateResolver(templateResolver); DefaultSnippetResolver snippetResolver = new DefaultSnippetResolver(); snippetResolver.setSearchPathList("com.astamuse.asta4d.test.render"); this.setSnippetResolver(snippetResolver); this.setOutputAsPrettyPrint(true); this.setSaveCallstackInfoOnRendererCreation(true); } }; static { Configuration.setConfiguration(configuration); } @BeforeMethod public void initContext() { Context context = Context.getCurrentThreadContext(); if (context == null) { context = new Context(); Context.setCurrentThreadContext(context); } context.init(); } @AfterMethod public void clearContext() { Context.getCurrentThreadContext().clear(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,496,498,594,823,830,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render.infra; public class TimeCalculator { public final static void shouldRunInTime(Runnable run, long time) { long begin = System.currentTimeMillis(); run.run(); long end = System.currentTimeMillis(); long period = end - begin; assert period < time : "Execution is expected less than " + time + "ms but it takes " + period + "ms"; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,264,675,692,279,456,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.test.render.infra; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.testng.Assert; import com.astamuse.asta4d.Page; public class SimpleCase { public SimpleCase(String templateFileName) throws Throwable { this(templateFileName, templateFileName); } public SimpleCase(String templateFileName, String confirmFileName) throws Throwable { String ostr = null; String cstr = null; try { Page originPage = Page.buildFromPath(retrieveTempateFielParentPath() + templateFileName); ostr = revert2comparableString(originPage); cstr = revert2comparableString(retrieveConfirmFielParentPath() + confirmFileName); Assert.assertEquals(ostr, cstr); } catch (Throwable t) { output(templateFileName + ":rendering result", ostr); output(confirmFileName + ":expected result", cstr); throw t; } } protected String retrieveTempateFielParentPath() { return "/com/astamuse/asta4d/test/render/templates/"; } protected String retrieveConfirmFielParentPath() { return "/com/astamuse/asta4d/test/render/confirms/"; } private String revert2comparableString(Page page) { return page.output(); } private String revert2comparableString(String path) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(SimpleCase.class.getResourceAsStream(path), "UTF-8"))) { StringBuilder sb = new StringBuilder(); char[] b = new char[1024]; int line; while (0 <= (line = reader.read(b))) { sb.append(b, 0, line); } return sb.toString(); } } private void output(String title, String page) { System.out.println(String.format("===============%s===================", title)); if (page == null) { System.out.println("##null##"); } else { System.out.println(page); } System.out.println("==============================================================="); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,298,299,440,426,709,500
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0"> <wb-module deploy-name="asta4d-core"> <wb-resource deploy-path="/" source-path="/src/main/java"/> <wb-resource deploy-path="/" source-path="/src/main/jsoup"/> </wb-module> </project-modules>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,389,848,258,305,720,000
eclipse.preferences.version=1 encoding//src/main/java=UTF-8 encoding//src/test/java=UTF-8 encoding//src/test/resources=UTF-8 encoding//src/test/resources/com/astamuse/asta4d/test/render/confirms/ExternalizeMessage_SymbolPlaceholder_us.html=UTF-8 encoding/<project>=UTF-8
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,551,411,531,858,013,000
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.astamuse</groupId> <artifactId>asta4d</artifactId> <version>1.2.1-SNAPSHOT</version> </parent> <groupId>com.astamuse</groupId> <artifactId>asta4d-web</artifactId> <packaging>jar</packaging> <name>com.astamuse.asta4d-web</name> <description>web functionalities of asta4d framework, including view first and url matching</description> <dependencies> <dependency> <groupId>com.astamuse</groupId> <artifactId>asta4d-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.astamuse</groupId> <artifactId>asta4d-core</artifactId> <version>${project.version}</version> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.11.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.7.8</version> </dependency> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.apache.commons.io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.2.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.3</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> <configuration> <instrumentation> <excludes> <exclude>com\astamuse\asta4d\web\copyleft\*</exclude> </excludes> </instrumentation> </configuration> <executions> <execution> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.18.1</version> <executions> <execution> <phase>test</phase> <goals> <goal>report-only</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.18.1</version> <reportSets> <reportSet> <reports> <report>report-only</report> </reports> </reportSet> </reportSets> </plugin> </plugins> </reporting> </project>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,078,554,976,444,508,000
<div id="global-msg-container" style="width:90%;"> <ul id="info-msg"> <li style="background-color:#C1FFC1" afd:message-duplicator>info-msg-stub </ul> <ul id="warn-msg"> <li style="background-color:#FFF68F" afd:message-duplicator>warn-msg-stub </ul> <ul id="err-msg"> <li style="background-color:#FFC1C1" afd:message-duplicator>err-msg-stub </ul> </div>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,902,035,190,910,768,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web; import javax.servlet.ServletContext; import com.astamuse.asta4d.template.AbstractTemplateResolver; public class WebApplicationTemplateResolver extends AbstractTemplateResolver { private ServletContext servletContext; public WebApplicationTemplateResolver() { super(); } public WebApplicationTemplateResolver(ServletContext servletContext) { super(); this.servletContext = servletContext; } public ServletContext getServletContext() { return servletContext; } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override protected TemplateInfo loadResource(String path) { if (servletContext == null) { ServletContext sc = WebApplicationContext.getCurrentThreadWebApplicationContext().getServletContext(); return createTemplateInfo(path, sc.getResourceAsStream(path)); } else { return createTemplateInfo(path, servletContext.getResourceAsStream(path)); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,027,845,834,123,384,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.ContextMap; import com.astamuse.asta4d.util.DelegatedContextMap; import com.astamuse.asta4d.util.UnmodifiableContextMap; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.util.context.SessionMap; public class WebApplicationContext extends Context { public final static String SCOPE_REQUEST = "request"; public final static String SCOPE_PATHVAR = "pathvar"; public final static String SCOPE_QUERYPARAM = "query"; public final static String SCOPE_QUERYPARAM_ALIAS = "param"; public final static String SCOPE_SESSION = "session"; public final static String SCOPE_HEADER = "header"; public final static String SCOPE_COOKIE = "cookie"; public final static String SCOPE_FLASH = "flash"; private final static String SAVEKEY_REQUEST = WebApplicationContext.class.getName() + "##SAVEKEY-REQUEST"; private final static String SAVEKEY_RESPONSE = WebApplicationContext.class.getName() + "##SAVEKEY-RESPONSE"; private final static String SAVEKEY_SERVLET_CONTEXT = WebApplicationContext.class.getName() + "##SAVEKEY-SERVLET-CONTEXT"; private final static String SAVEKEY_ACCESS_URI = WebApplicationContext.class.getName() + "##SAVEKEY-ACCESS-URI"; public final static String SAVEKEY_CURRENT_RULE = WebApplicationContext.class.getName() + "##SAVEKEY_CURRENT_RULE"; public final static WebApplicationContext getCurrentThreadWebApplicationContext() { return Context.getCurrentThreadContext(); } public HttpServletRequest getRequest() { return this.getData(SAVEKEY_REQUEST); } public void setRequest(HttpServletRequest request) { this.setData(SAVEKEY_REQUEST, request); } public HttpServletResponse getResponse() { return this.getData(SAVEKEY_RESPONSE); } public void setResponse(HttpServletResponse response) { this.setData(SAVEKEY_RESPONSE, response); } public ServletContext getServletContext() { return this.getData(SAVEKEY_SERVLET_CONTEXT); } public void setServletContext(ServletContext servletContext) { this.setData(SAVEKEY_SERVLET_CONTEXT, servletContext); } public void setAccessURI(String uri) { this.setData(SAVEKEY_ACCESS_URI, uri); } public String getAccessURI() { return this.getData(SAVEKEY_ACCESS_URI); } public void setCurrentRule(UrlMappingRule rule) { this.setData(SAVEKEY_CURRENT_RULE, rule); } public UrlMappingRule getCurrentRule() { return this.getData(SAVEKEY_CURRENT_RULE); } @SuppressWarnings("unchecked") @Override protected ContextMap createMapForScope(String scope) { ContextMap map = null; switch (scope) { case SCOPE_SESSION: { HttpServletRequest request = getRequest(); map = new SessionMap(request); } break; case SCOPE_HEADER: { HttpServletRequest request = getRequest(); map = DelegatedContextMap.createByNonThreadSafeHashMap(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String[] values = getHeaderValues(request.getHeaders(name)); map.put(name, values); } map = new UnmodifiableContextMap(map); } break; case SCOPE_COOKIE: { HttpServletRequest request = getRequest(); map = DelegatedContextMap.createByNonThreadSafeHashMap(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String name = cookie.getName(); String[] values = mergeCookieValues(cookie, (String[]) map.get(name)); map.put(name, values); } } map = new UnmodifiableContextMap(map); } break; case SCOPE_REQUEST: map = super.acquireMapForScope(SCOPE_DEFAULT); break; case SCOPE_QUERYPARAM_ALIAS: case SCOPE_QUERYPARAM: { HttpServletRequest request = getRequest(); map = DelegatedContextMap.createByNonThreadSafeHashMap(); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = paramNames.nextElement(); String[] values = request.getParameterValues(name); map.put(name, values); } map = new UnmodifiableContextMap(map); } break; case SCOPE_PATHVAR: map = DelegatedContextMap.createByNonThreadSafeHashMap(); break; default: map = super.createMapForScope(scope); } return map; } public Context clone() { Context newCtx = new WebApplicationContext(); copyScopesTo(newCtx); return newCtx; } private static String[] getHeaderValues(Enumeration<String> headers) { List<String> values = new ArrayList<>(); while (headers.hasMoreElements()) { values.add(headers.nextElement()); } return values.toArray(new String[values.size()]); } private static String[] mergeCookieValues(Cookie cookie, String[] cookies) { if (cookies == null) { return new String[] { cookie.getValue() }; } String[] cookieValues = new String[cookies.length + 1]; System.arraycopy(cookies, 0, cookieValues, 0, cookies.length); cookieValues[cookieValues.length - 1] = cookie.getValue(); return cookieValues; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,656,467,762,485,608,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.ContextDataHolder; import com.astamuse.asta4d.data.DataOperationException; import com.astamuse.asta4d.data.DefaultContextDataFinder; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public class WebApplicationContextDataFinder extends DefaultContextDataFinder { private final static String ByTypeScope = WebApplicationContextDataFinder.class.getName() + "#ByType"; public WebApplicationContextDataFinder() { List<String> dataScopeOrder = new ArrayList<>(); dataScopeOrder.add(WebApplicationContext.SCOPE_ATTR); dataScopeOrder.add(WebApplicationContext.SCOPE_PATHVAR); dataScopeOrder.add(WebApplicationContext.SCOPE_QUERYPARAM); dataScopeOrder.add(WebApplicationContext.SCOPE_FLASH); dataScopeOrder.add(WebApplicationContext.SCOPE_COOKIE); dataScopeOrder.add(WebApplicationContext.SCOPE_HEADER); dataScopeOrder.add(WebApplicationContext.SCOPE_REQUEST); dataScopeOrder.add(WebApplicationContext.SCOPE_SESSION); dataScopeOrder.add(WebApplicationContext.SCOPE_GLOBAL); this.setDataSearchScopeOrder(dataScopeOrder); } @SuppressWarnings("rawtypes") @Override public ContextDataHolder findDataInContext(Context context, String scope, String name, Class<?> type) throws DataOperationException { // TODO class equals is not reliable if (type.equals(HttpServletRequest.class)) { return new ContextDataHolder<>(HttpServletRequest.class.getName(), ByTypeScope, ((WebApplicationContext) context).getRequest()); } else if (type.equals(HttpServletResponse.class)) { return new ContextDataHolder<>(HttpServletResponse.class.getName(), ByTypeScope, ((WebApplicationContext) context).getResponse()); } else if (type.equals(ServletContext.class)) { return new ContextDataHolder<>(ServletContext.class.getName(), ByTypeScope, ((WebApplicationContext) context).getServletContext()); } else if (type.equals(UrlMappingRule.class)) { return new ContextDataHolder<>(UrlMappingRule.class.getName(), ByTypeScope, ((WebApplicationContext) context).getCurrentRule()); } else { return super.findDataInContext(context, scope, name, type); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,844,161,918,339,386,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.interceptor.PageInterceptor; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.web.dispatch.AntPathRuleMatcher; import com.astamuse.asta4d.web.dispatch.DefaultRequestHandlerInvokerFactory; import com.astamuse.asta4d.web.dispatch.DispatcherRuleMatcher; import com.astamuse.asta4d.web.dispatch.RequestHandlerInvokerFactory; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleInitializer; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSet; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleSet; import com.astamuse.asta4d.web.util.bean.DeclareInstanceResolver; import com.astamuse.asta4d.web.util.message.DefaultMessageRenderingHelper; import com.astamuse.asta4d.web.util.message.MessageRenderingHelper; import com.astamuse.asta4d.web.util.timeout.DefaultSessionAwareExpirableDataManager; import com.astamuse.asta4d.web.util.timeout.ExpirableDataManager; public class WebApplicationConfiguration extends Configuration { private String flashScopeForwardParameterName = "flash_scope_id"; private ExpirableDataManager expirableDataManager = new DefaultSessionAwareExpirableDataManager(); private MessageRenderingHelper messageRenderingHelper = new DefaultMessageRenderingHelper(); private RequestHandlerInvokerFactory requestHandlerInvokerFactory; private List<DeclareInstanceResolver> instanceResolverList = new ArrayList<>(); private DispatcherRuleMatcher ruleMatcher = new AntPathRuleMatcher(); @SuppressWarnings("rawtypes") private UrlMappingRuleInitializer urlMappingRuleInitializer = null; @SuppressWarnings("rawtypes") private Class<? extends UrlMappingRuleSet> urlMappingRuleSetCls = HandyRuleSet.class; public WebApplicationConfiguration() { this.setTemplateResolver(new WebApplicationTemplateResolver()); this.setContextDataFinder(new WebApplicationContextDataFinder()); this.setRequestHandlerInvokerFactory(new DefaultRequestHandlerInvokerFactory()); this.setPageInterceptorList(new LinkedList<PageInterceptor>()); } protected List<PageInterceptor> createDefaultPageInterceptorList() { // afford a convenience for global rendering by default List<PageInterceptor> pageInterceptorList = new LinkedList<>(); // configurable message rendering interceptor pageInterceptorList.add(new PageInterceptor() { @Override public void prePageRendering(Renderer renderer) { // do nothing } @Override public void postPageRendering(Renderer renderer) { MessageRenderingHelper helper = WebApplicationConfiguration.getWebApplicationConfiguration().getMessageRenderingHelper(); if (helper != null) { renderer.add(helper.createMessageRenderer()); } } }); return pageInterceptorList; } @Override public void setPageInterceptorList(List<PageInterceptor> pageInterceptorList) { List<PageInterceptor> list = createDefaultPageInterceptorList(); list.addAll(pageInterceptorList); super.setPageInterceptorList(list); } public final static WebApplicationConfiguration getWebApplicationConfiguration() { return (WebApplicationConfiguration) getConfiguration(); } public String getFlashScopeForwardParameterName() { return flashScopeForwardParameterName; } public void setFlashScopeForwardParameterName(String flashScopeForwardParameterName) { this.flashScopeForwardParameterName = flashScopeForwardParameterName; } public ExpirableDataManager getExpirableDataManager() { return expirableDataManager; } public void setExpirableDataManager(ExpirableDataManager expirableDataManager) { this.expirableDataManager = expirableDataManager; } public MessageRenderingHelper getMessageRenderingHelper() { return messageRenderingHelper; } public void setMessageRenderingHelper(MessageRenderingHelper messageRenderingHelper) { this.messageRenderingHelper = messageRenderingHelper; } public RequestHandlerInvokerFactory getRequestHandlerInvokerFactory() { return requestHandlerInvokerFactory; } public void setRequestHandlerInvokerFactory(RequestHandlerInvokerFactory requestHandlerInvokerFactory) { this.requestHandlerInvokerFactory = requestHandlerInvokerFactory; } public List<DeclareInstanceResolver> getInstanceResolverList() { return instanceResolverList; } public void setInstanceResolverList(List<DeclareInstanceResolver> instanceResolverList) { this.instanceResolverList = instanceResolverList; } public DispatcherRuleMatcher getRuleMatcher() { return ruleMatcher; } public void setRuleMatcher(DispatcherRuleMatcher ruleMatcher) { this.ruleMatcher = ruleMatcher; } @SuppressWarnings("rawtypes") public UrlMappingRuleInitializer getUrlMappingRuleInitializer() { return urlMappingRuleInitializer; } @SuppressWarnings("rawtypes") public void setUrlMappingRuleInitializer(UrlMappingRuleInitializer urlMappingRuleInitializer) { this.urlMappingRuleInitializer = urlMappingRuleInitializer; } @SuppressWarnings("rawtypes") public Class<? extends UrlMappingRuleSet> getUrlMappingRuleSetCls() { return urlMappingRuleSetCls; } @SuppressWarnings("rawtypes") public void setUrlMappingRuleSetCls(Class<? extends UrlMappingRuleSet> urlMappingRuleSetCls) { this.urlMappingRuleSetCls = urlMappingRuleSetCls; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
175,544,131,744,693,120
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.servlet.ServletConfig; import org.apache.commons.io.FilenameUtils; import com.astamuse.asta4d.web.initialization.Initializer; import com.astamuse.asta4d.web.initialization.SimplePropertyFileInitializer; import com.astamuse.asta4d.web.util.SystemPropertyUtil; import com.astamuse.asta4d.web.util.SystemPropertyUtil.PropertyScope; public class WebApplicatoinConfigurationInitializer { public void initConfigurationFromFile(ServletConfig sc, WebApplicationConfiguration conf) throws Exception { String[] fileNames = retrievePossibleConfigurationFileNames(); InputStream input = null; String fileType = null; // find file from classpath ClassLoader clsLoder = WebApplicatoinConfigurationInitializer.class.getClassLoader(); for (String name : fileNames) { input = clsLoder.getResourceAsStream(name); if (input != null) { fileType = FilenameUtils.getExtension(name); break; } } // find from file system // I can do goto by while loop :) while (input == null) { // find key String fileKey = retrieveConfigurationFileNameKey(); if (fileKey == null) { break; } // get path String filePath = retrieveConfigurationFileName(sc, fileKey); if (filePath == null) { break; } // load file File f = new File(filePath); input = new FileInputStream(f); fileType = FilenameUtils.getExtension(filePath); break; } if (input != null) { try { Initializer initializer = retrieveInitializer(fileType); initializer.initliaze(input, conf); } finally { input.close(); } } } protected Initializer retrieveInitializer(String fileType) { // at present, we only support properties file, but we will try to support .js or .groovy as well in future. switch (fileType) { case "properties": return new SimplePropertyFileInitializer(); default: throw new UnsupportedOperationException("File type of " + fileType + " does not be supported for initialize asta4d Configuration."); } } protected String[] retrievePossibleConfigurationFileNames() { // return new String[] { // "asta4d.conf.properties, ast4d.conf.js, asta4d.conf.groovy" }; return new String[] { "asta4d.conf.properties" }; } protected String retrieveConfigurationFileNameKey() { return "asta4d.conf"; } protected String retrieveConfigurationFileName(ServletConfig sc, String key) { return SystemPropertyUtil.retrievePropertyValue(sc, key, PropertyScope.ServletConfig, PropertyScope.JNDI, PropertyScope.SystemProperty); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,432,815,770,313,720,300
/* * Copyright 2002-2010 the original author or authors. * * Licensed 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 com.astamuse.asta4d.web.copyleft; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.Validate; /** * PathMatcher implementation for Ant-style path patterns. Examples are provided * below. * * <p> * Part of this mapping code has been kindly borrowed from <a * href="http://ant.apache.org">Apache Ant</a>. * * <p> * The mapping matches URLs using the following rules:<br> * <ul> * <li>? matches one character</li> * <li>* matches zero or more characters</li> * <li>** matches zero or more 'directories' in a path</li> * </ul> * * <p> * Some examples:<br> * <ul> * <li><code>com/t?st.jsp</code> - matches <code>com/test.jsp</code> but also * <code>com/tast.jsp</code> or <code>com/txst.jsp</code></li> * <li><code>com/*.jsp</code> - matches all <code>.jsp</code> files in the * <code>com</code> directory</li> * <li><code>com/&#42;&#42;/test.jsp</code> - matches all <code>test.jsp</code> * files underneath the <code>com</code> path</li> * <li><code>org/springframework/&#42;&#42;/*.jsp</code> - matches all * <code>.jsp</code> files underneath the <code>org/springframework</code> path</li> * <li><code>org/&#42;&#42;/servlet/bla.jsp</code> - matches * <code>org/springframework/servlet/bla.jsp</code> but also * <code>org/springframework/testing/servlet/bla.jsp</code> and * <code>org/servlet/bla.jsp</code></li> * </ul> * * @author Alef Arendsen * @author Juergen Hoeller * @author Rob Harrop * @author Arjen Poutsma * @since 16.07.2003 */ public class SpringAntPathMatcher { private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}"); /** Default path separator: "/" */ public static final String DEFAULT_PATH_SEPARATOR = "/"; private String pathSeparator = DEFAULT_PATH_SEPARATOR; /** * Set the path separator to use for pattern parsing. Default is "/", as in * Ant. */ public void setPathSeparator(String pathSeparator) { this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR); } public boolean isPattern(String path) { return (path.indexOf('*') != -1 || path.indexOf('?') != -1); } public boolean match(String pattern, String path) { return doMatch(pattern, path, true, null); } public boolean matchStart(String pattern, String path) { return doMatch(pattern, path, false, null); } /** * Actually match the given <code>path</code> against the given * <code>pattern</code>. * * @param pattern * the pattern to match against * @param path * the path String to test * @param fullMatch * whether a full pattern match is required (else a pattern match * as far as the given base path goes is sufficient) * @return <code>true</code> if the supplied <code>path</code> matched, * <code>false</code> if it didn't */ protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<String, String> uriTemplateVariables) { if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) { return false; } String[] pattDirs = SpringStringUtils.tokenizeToStringArray(pattern, this.pathSeparator); String[] pathDirs = SpringStringUtils.tokenizeToStringArray(path, this.pathSeparator); int pattIdxStart = 0; int pattIdxEnd = pattDirs.length - 1; int pathIdxStart = 0; int pathIdxEnd = pathDirs.length - 1; // Match all elements up to the first ** while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { String patDir = pattDirs[pattIdxStart]; if ("**".equals(patDir)) { break; } if (!matchStrings(patDir, pathDirs[pathIdxStart], uriTemplateVariables)) { return false; } pattIdxStart++; pathIdxStart++; } if (pathIdxStart > pathIdxEnd) { // Path is exhausted, only match if rest of pattern is * or **'s if (pattIdxStart > pattIdxEnd) { return (pattern.endsWith(this.pathSeparator) ? path.endsWith(this.pathSeparator) : !path.endsWith(this.pathSeparator)); } if (!fullMatch) { return true; } if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) { return true; } for (int i = pattIdxStart; i <= pattIdxEnd; i++) { if (!pattDirs[i].equals("**")) { return false; } } return true; } else if (pattIdxStart > pattIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { // Path start definitely matches due to "**" part in pattern. return true; } // up to last '**' while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { String patDir = pattDirs[pattIdxEnd]; if (patDir.equals("**")) { break; } if (!matchStrings(patDir, pathDirs[pathIdxEnd], uriTemplateVariables)) { return false; } pattIdxEnd--; pathIdxEnd--; } if (pathIdxStart > pathIdxEnd) { // String is exhausted for (int i = pattIdxStart; i <= pattIdxEnd; i++) { if (!pattDirs[i].equals("**")) { return false; } } return true; } while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) { int patIdxTmp = -1; for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) { if (pattDirs[i].equals("**")) { patIdxTmp = i; break; } } if (patIdxTmp == pattIdxStart + 1) { // '**/**' situation, so skip one pattIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd int patLength = (patIdxTmp - pattIdxStart - 1); int strLength = (pathIdxEnd - pathIdxStart + 1); int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { String subPat = pattDirs[pattIdxStart + j + 1]; String subStr = pathDirs[pathIdxStart + i + j]; if (!matchStrings(subPat, subStr, uriTemplateVariables)) { continue strLoop; } } foundIdx = pathIdxStart + i; break; } if (foundIdx == -1) { return false; } pattIdxStart = patIdxTmp; pathIdxStart = foundIdx + patLength; } for (int i = pattIdxStart; i <= pattIdxEnd; i++) { if (!pattDirs[i].equals("**")) { return false; } } return true; } /** * Tests whether or not a string matches against a pattern. The pattern may * contain two special characters:<br> * '*' means zero or more characters<br> * '?' means one and only one character * * @param pattern * pattern to match against. Must not be <code>null</code>. * @param str * string which must be matched against the pattern. Must not be * <code>null</code>. * @return <code>true</code> if the string matches against the pattern, or * <code>false</code> otherwise. */ private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) { SpringAntPathStringMatcher matcher = new SpringAntPathStringMatcher(pattern, str, uriTemplateVariables); return matcher.matchStrings(); } /** * Given a pattern and a full path, determine the pattern-mapped part. * <p> * For example: * <ul> * <li>'<code>/docs/cvs/commit.html</code>' and ' * <code>/docs/cvs/commit.html</code> -> ''</li> * <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> ' * <code>cvs/commit</code>'</li> * <li>'<code>/docs/cvs/*.html</code>' and ' * <code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li> * <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> ' * <code>cvs/commit</code>'</li> * <li>'<code>/docs/**\/*.html</code>' and ' * <code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li> * <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> ' * <code>docs/cvs/commit.html</code>'</li> * <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> ' * <code>/docs/cvs/commit.html</code>'</li> * <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> ' * <code>/docs/cvs/commit.html</code>'</li> * </ul> * <p> * Assumes that {@link #match} returns <code>true</code> for ' * <code>pattern</code>' and '<code>path</code>', but does * <strong>not</strong> enforce this. */ public String extractPathWithinPattern(String pattern, String path) { String[] patternParts = SpringStringUtils.tokenizeToStringArray(pattern, this.pathSeparator); String[] pathParts = SpringStringUtils.tokenizeToStringArray(path, this.pathSeparator); StringBuilder builder = new StringBuilder(); // Add any path parts that have a wildcarded pattern part. int puts = 0; for (int i = 0; i < patternParts.length; i++) { String patternPart = patternParts[i]; if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) { if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) { builder.append(this.pathSeparator); } builder.append(pathParts[i]); puts++; } } // Append any trailing path parts. for (int i = patternParts.length; i < pathParts.length; i++) { if (puts > 0 || i > 0) { builder.append(this.pathSeparator); } builder.append(pathParts[i]); } return builder.toString(); } public Map<String, String> extractUriTemplateVariables(String pattern, String path) { Map<String, String> variables = new LinkedHashMap<String, String>(); boolean result = doMatch(pattern, path, true, variables); Validate.isTrue(result, "Pattern \"" + pattern + "\" is not a match for \"" + path + "\""); return variables; } /** * Combines two patterns into a new pattern that is returned. * <p> * This implementation simply concatenates the two patterns, unless the * first pattern contains a file extension match (such as {@code *.html}. In * that case, the second pattern should be included in the first, or an * {@code IllegalArgumentException} is thrown. * <p> * For example: * <table> * <tr> * <th>Pattern 1</th> * <th>Pattern 2</th> * <th>Result</th> * </tr> * <tr> * <td>/hotels</td> * <td>{@code null}</td> * <td>/hotels</td> * </tr> * <tr> * <td>{@code null}</td> * <td>/hotels</td> * <td>/hotels</td> * </tr> * <tr> * <td>/hotels</td> * <td>/bookings</td> * <td>/hotels/bookings</td> * </tr> * <tr> * <td>/hotels</td> * <td>bookings</td> * <td>/hotels/bookings</td> * </tr> * <tr> * <td>/hotels/*</td> * <td>/bookings</td> * <td>/hotels/bookings</td> * </tr> * <tr> * <td>/hotels/&#42;&#42;</td> * <td>/bookings</td> * <td>/hotels/&#42;&#42;/bookings</td> * </tr> * <tr> * <td>/hotels</td> * <td>{hotel}</td> * <td>/hotels/{hotel}</td> * </tr> * <tr> * <td>/hotels/*</td> * <td>{hotel}</td> * <td>/hotels/{hotel}</td> * </tr> * <tr> * <td>/hotels/&#42;&#42;</td> * <td>{hotel}</td> * <td>/hotels/&#42;&#42;/{hotel}</td> * </tr> * <tr> * <td>/*.html</td> * <td>/hotels.html</td> * <td>/hotels.html</td> * </tr> * <tr> * <td>/*.html</td> * <td>/hotels</td> * <td>/hotels.html</td> * </tr> * <tr> * <td>/*.html</td> * <td>/*.txt</td> * <td>IllegalArgumentException</td> * </tr> * </table> * * @param pattern1 * the first pattern * @param pattern2 * the second pattern * @return the combination of the two patterns * @throws IllegalArgumentException * when the two patterns cannot be combined */ public String combine(String pattern1, String pattern2) { if (!SpringStringUtils.hasText(pattern1) && !SpringStringUtils.hasText(pattern2)) { return ""; } else if (!SpringStringUtils.hasText(pattern1)) { return pattern2; } else if (!SpringStringUtils.hasText(pattern2)) { return pattern1; } else if (!pattern1.contains("{") && match(pattern1, pattern2)) { return pattern2; } else if (pattern1.endsWith("/*")) { if (pattern2.startsWith("/")) { // /hotels/* + /booking -> /hotels/booking return pattern1.substring(0, pattern1.length() - 1) + pattern2.substring(1); } else { // /hotels/* + booking -> /hotels/booking return pattern1.substring(0, pattern1.length() - 1) + pattern2; } } else if (pattern1.endsWith("/**")) { if (pattern2.startsWith("/")) { // /hotels/** + /booking -> /hotels/**/booking return pattern1 + pattern2; } else { // /hotels/** + booking -> /hotels/**/booking return pattern1 + "/" + pattern2; } } else { int dotPos1 = pattern1.indexOf('.'); if (dotPos1 == -1) { // simply concatenate the two patterns if (pattern1.endsWith("/") || pattern2.startsWith("/")) { return pattern1 + pattern2; } else { return pattern1 + "/" + pattern2; } } String fileName1 = pattern1.substring(0, dotPos1); String extension1 = pattern1.substring(dotPos1); String fileName2; String extension2; int dotPos2 = pattern2.indexOf('.'); if (dotPos2 != -1) { fileName2 = pattern2.substring(0, dotPos2); extension2 = pattern2.substring(dotPos2); } else { fileName2 = pattern2; extension2 = ""; } String fileName = fileName1.endsWith("*") ? fileName2 : fileName1; String extension = extension1.startsWith("*") ? extension2 : extension1; return fileName + extension; } } /** * Given a full path, returns a {@link Comparator} suitable for sorting * patterns in order of explicitness. * <p> * The returned <code>Comparator</code> will * {@linkplain java.util.Collections#sort(java.util.List, java.util.Comparator) * sort} a list so that more specific patterns (without uri templates or * wild cards) come before generic patterns. So given a list with the * following patterns: * <ol> * <li><code>/hotels/new</code></li> * <li><code>/hotels/{hotel}</code></li> * <li><code>/hotels/*</code></li> * </ol> * the returned comparator will sort this list so that the order will be as * indicated. * <p> * The full path given as parameter is used to test for exact matches. So * when the given path is {@code /hotels/2}, the pattern {@code /hotels/2} * will be sorted before {@code /hotels/1}. * * @param path * the full path to use for comparison * @return a comparator capable of sorting patterns in order of explicitness */ public Comparator<String> getPatternComparator(String path) { return new AntPatternComparator(path); } private static class AntPatternComparator implements Comparator<String> { private final String path; private AntPatternComparator(String path) { this.path = path; } public int compare(String pattern1, String pattern2) { if (pattern1 == null && pattern2 == null) { return 0; } else if (pattern1 == null) { return 1; } else if (pattern2 == null) { return -1; } boolean pattern1EqualsPath = pattern1.equals(path); boolean pattern2EqualsPath = pattern2.equals(path); if (pattern1EqualsPath && pattern2EqualsPath) { return 0; } else if (pattern1EqualsPath) { return -1; } else if (pattern2EqualsPath) { return 1; } int wildCardCount1 = getWildCardCount(pattern1); int wildCardCount2 = getWildCardCount(pattern2); int bracketCount1 = SpringStringUtils.countOccurrencesOf(pattern1, "{"); int bracketCount2 = SpringStringUtils.countOccurrencesOf(pattern2, "{"); int totalCount1 = wildCardCount1 + bracketCount1; int totalCount2 = wildCardCount2 + bracketCount2; if (totalCount1 != totalCount2) { return totalCount1 - totalCount2; } int pattern1Length = getPatternLength(pattern1); int pattern2Length = getPatternLength(pattern2); if (pattern1Length != pattern2Length) { return pattern2Length - pattern1Length; } if (wildCardCount1 < wildCardCount2) { return -1; } else if (wildCardCount2 < wildCardCount1) { return 1; } if (bracketCount1 < bracketCount2) { return -1; } else if (bracketCount2 < bracketCount1) { return 1; } return 0; } private int getWildCardCount(String pattern) { if (pattern.endsWith(".*")) { pattern = pattern.substring(0, pattern.length() - 2); } return SpringStringUtils.countOccurrencesOf(pattern, "*"); } /** * Returns the length of the given pattern, where template variables are * considered to be 1 long. */ private int getPatternLength(String pattern) { Matcher m = VARIABLE_PATTERN.matcher(pattern); return m.replaceAll("#").length(); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,667,395,981,754,798,000
This package contains some copies from spring framework for using its ant path parser. It originated with Apache License, Version 2.0. Following is the original License declaration: Copyright 2002-2009 the original author or authors. Licensed 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.
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,817,974,605,903,820,000
package com.astamuse.asta4d.web.copyleft; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; public class SpringStringUtils { public SpringStringUtils() { // TODO Auto-generated constructor stub } /** * Tokenize the given String into a String array via a StringTokenizer. * Trims tokens and omits empty tokens. * <p> * The given delimiters string is supposed to consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using <code>delimitedListToStringArray</code> * * @param str * the String to tokenize * @param delimiters * the delimiter characters, assembled as String (each of those * characters is individually considered as delimiter). * @return an array of the tokens * @see java.util.StringTokenizer * @see java.lang.String#trim() * @see #delimitedListToStringArray */ public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } /** * Tokenize the given String into a String array via a StringTokenizer. * <p> * The given delimiters string is supposed to consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using <code>delimitedListToStringArray</code> * * @param str * the String to tokenize * @param delimiters * the delimiter characters, assembled as String (each of those * characters is individually considered as delimiter) * @param trimTokens * trim the tokens via String's <code>trim</code> * @param ignoreEmptyTokens * omit empty tokens from the result array (only applies to * tokens that are empty after trimming; StringTokenizer will not * consider subsequent delimiters as token in the first place). * @return an array of the tokens (<code>null</code> if the input String was * <code>null</code>) * @see java.util.StringTokenizer * @see java.lang.String#trim() * @see #delimitedListToStringArray */ public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList<String>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return toStringArray(tokens); } /** * Copy the given Collection into a String array. The Collection must * contain String elements only. * * @param collection * the Collection to copy * @return the String array (<code>null</code> if the passed-in Collection * was <code>null</code>) */ public static String[] toStringArray(Collection<String> collection) { if (collection == null) { return null; } return collection.toArray(new String[collection.size()]); } /** * Copy the given Enumeration into a String array. The Enumeration must * contain String elements only. * * @param enumeration * the Enumeration to copy * @return the String array (<code>null</code> if the passed-in Enumeration * was <code>null</code>) */ public static String[] toStringArray(Enumeration<String> enumeration) { if (enumeration == null) { return null; } List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); } /** * Check that the given CharSequence is neither <code>null</code> nor of * length 0. Note: Will return <code>true</code> for a CharSequence that * purely consists of whitespace. * <p> * * <pre> * StringUtils.hasLength(null) = false * StringUtils.hasLength("") = false * StringUtils.hasLength(" ") = true * StringUtils.hasLength("Hello") = true * </pre> * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not null and has length * @see #hasText(String) */ public static boolean hasLength(CharSequence str) { return (str != null && str.length() > 0); } /** * Check that the given String is neither <code>null</code> nor of length 0. * Note: Will return <code>true</code> for a String that purely consists of * whitespace. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not null and has length * @see #hasLength(CharSequence) */ public static boolean hasLength(String str) { return hasLength((CharSequence) str); } /** * Check whether the given CharSequence has actual text. More specifically, * returns <code>true</code> if the string not <code>null</code>, its length * is greater than 0, and it contains at least one non-whitespace character. * <p> * * <pre> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not <code>null</code>, * its length is greater than 0, and it does not contain whitespace * only * @see java.lang.Character#isWhitespace */ public static boolean hasText(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String has actual text. More specifically, * returns <code>true</code> if the string not <code>null</code>, its length * is greater than 0, and it contains at least one non-whitespace character. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not <code>null</code>, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return hasText((CharSequence) str); } /** * Count the occurrences of the substring in string s. * * @param str * string to search in. Return 0 if this is null. * @param sub * string to search for. Return 0 if this is null. */ public static int countOccurrencesOf(String str, String sub) { if (str == null || sub == null || str.length() == 0 || sub.length() == 0) { return 0; } int count = 0; int pos = 0; int idx; while ((idx = str.indexOf(sub, pos)) != -1) { ++count; pos = idx + sub.length(); } return count; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,491,459,063,620,659,000
/* * Copyright 2002-2009 the original author or authors. * * Licensed 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 com.astamuse.asta4d.web.copyleft; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.Validate; /** * Package-protected helper class for {@link SpringAntPathMatcher}. Tests whether or * not a string matches against a pattern via a {@link Pattern}. * * <p> * The pattern may contain special characters: '*' means zero or more * characters; '?' means one and only one character; '{' and '}' indicate a URI * template pattern. For example <tt>/users/{user}</tt>. * * @author Arjen Poutsma * @author Rossen Stoyanchev * @since 3.0 */ class SpringAntPathStringMatcher { private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; private final Pattern pattern; private String str; private final List<String> variableNames = new LinkedList<String>(); private final Map<String, String> uriTemplateVariables; /** Construct a new instance of the <code>AntPatchStringMatcher</code>. */ SpringAntPathStringMatcher(String pattern, String str, Map<String, String> uriTemplateVariables) { this.str = str; this.uriTemplateVariables = uriTemplateVariables; this.pattern = createPattern(pattern); } private Pattern createPattern(String pattern) { StringBuilder patternBuilder = new StringBuilder(); Matcher m = GLOB_PATTERN.matcher(pattern); int end = 0; while (m.find()) { patternBuilder.append(quote(pattern, end, m.start())); String match = m.group(); if ("?".equals(match)) { patternBuilder.append('.'); } else if ("*".equals(match)) { patternBuilder.append(".*"); } else if (match.startsWith("{") && match.endsWith("}")) { int colonIdx = match.indexOf(':'); if (colonIdx == -1) { patternBuilder.append(DEFAULT_VARIABLE_PATTERN); variableNames.add(m.group(1)); } else { String variablePattern = match.substring(colonIdx + 1, match.length() - 1); patternBuilder.append('('); patternBuilder.append(variablePattern); patternBuilder.append(')'); String variableName = match.substring(1, colonIdx); variableNames.add(variableName); } } end = m.end(); } patternBuilder.append(quote(pattern, end, pattern.length())); return Pattern.compile(patternBuilder.toString()); } private String quote(String s, int start, int end) { if (start == end) { return ""; } return Pattern.quote(s.substring(start, end)); } /** * Main entry point. * * @return <code>true</code> if the string matches against the pattern, or * <code>false</code> otherwise. */ public boolean matchStrings() { Matcher matcher = pattern.matcher(str); if (matcher.matches()) { if (uriTemplateVariables != null) { // SPR-8455 Validate.isTrue(variableNames.size() == matcher.groupCount(), "The number of capturing groups in the pattern segment " + pattern + " does not match the number of URI template variables it defines, which can occur if " + " capturing groups are used in a URI template regex. Use non-capturing groups instead."); for (int i = 1; i <= matcher.groupCount(); i++) { String name = this.variableNames.get(i - 1); String value = matcher.group(i); uriTemplateVariables.put(name, value); } } return true; } else { return false; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,913,180,370,975,680,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface RequestContextData { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,107,653,199,382,769,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface HeaderData { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,760,777,582,921,674,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface QueryParam { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,254,894,532,903,114,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface SessionData { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,886,052,660,274,947,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface PathVar { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,578,312,403,373,549,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface CookieData { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,846,094,155,296,035,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.annotation.convertor.WebSpecialScopeConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(WebSpecialScopeConvertor.class) public @interface FlashData { String name() default ""; TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,900,527,922,459,334,700
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.annotation.convertor; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.util.annotation.AnnotationConvertor; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.annotation.CookieData; import com.astamuse.asta4d.web.annotation.FlashData; import com.astamuse.asta4d.web.annotation.HeaderData; import com.astamuse.asta4d.web.annotation.PathVar; import com.astamuse.asta4d.web.annotation.QueryParam; import com.astamuse.asta4d.web.annotation.RequestContextData; import com.astamuse.asta4d.web.annotation.SessionData; public class WebSpecialScopeConvertor implements AnnotationConvertor<Annotation, ContextData> { @Override public ContextData convert(Annotation originalAnnotation) { String scope = ""; if (originalAnnotation instanceof CookieData) { scope = WebApplicationContext.SCOPE_COOKIE; } else if (originalAnnotation instanceof FlashData) { scope = WebApplicationContext.SCOPE_FLASH; } else if (originalAnnotation instanceof HeaderData) { scope = WebApplicationContext.SCOPE_HEADER; } else if (originalAnnotation instanceof PathVar) { scope = WebApplicationContext.SCOPE_PATHVAR; } else if (originalAnnotation instanceof QueryParam) { scope = WebApplicationContext.SCOPE_QUERYPARAM; } else if (originalAnnotation instanceof RequestContextData) { scope = WebApplicationContext.SCOPE_REQUEST; } else if (originalAnnotation instanceof SessionData) { scope = WebApplicationContext.SCOPE_SESSION; } try { Method nameMethod = originalAnnotation.annotationType().getMethod("name"); String name = (String) nameMethod.invoke(originalAnnotation); Method typeUnMatchMethod = originalAnnotation.annotationType().getMethod("typeUnMatch"); TypeUnMacthPolicy typeUnMatch = (TypeUnMacthPolicy) typeUnMatchMethod.invoke(originalAnnotation); return gen(scope, name, typeUnMatch); } catch (Exception e) { throw new RuntimeException(e); } } private ContextData gen(final String scope, final String name, final TypeUnMacthPolicy typeUnMatch) { return new ContextData() { @Override public Class<? extends Annotation> annotationType() { return ContextData.class; } @Override public String scope() { return scope; } @Override public String name() { return name; } @Override public TypeUnMacthPolicy typeUnMatch() { return typeUnMatch; } }; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,068,936,344,447,450,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.messaging; @SuppressWarnings("serial") public class DataMessage implements Asta4dMessage { public enum DataType { JSON("json"); private final String text; private DataType(String text) { this.text = text; } String getText() { return text; } } private final String data; private final DataType dataType; public DataMessage(String data, DataType dataType) { this.data = data; this.dataType = dataType; } public String getData() { return data; } public String getDataType() { return dataType.getText(); } public String toJsonString() { // TODO use Json Library StringBuilder sb = new StringBuilder(); sb.append('{'); sb.append("\"data\":" + getData()); sb.append(','); sb.append("\"dataType\":\"" + getDataType() + "\""); sb.append('}'); return sb.toString(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,653,318,420,056,425,500
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.messaging; @SuppressWarnings("serial") public class UnregisterMessage implements Asta4dMessage { private final String uuid; public UnregisterMessage(String uuid) { this.uuid = uuid; } public String getUuid() { return uuid; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,694,722,344,044,047,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.messaging; import java.io.Serializable; public interface Asta4dMessage extends Serializable { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,519,570,794,664,526,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.messaging; public class MessageManager { /* private final static MessageManager MANAGER = new MessageManager(); private BrokerService broker; private TopicConnection connection; private TopicSession session; public String register(String messageid, Asta4dMessageListener listener) throws JMSException { return register(messageid, IdGenerator.createId(), listener); } public String register(String messageid, String uuid, Asta4dMessageListener listener) throws JMSException { if (isEmpty(messageid) || isEmpty(uuid) || listener == null) { throw new IllegalArgumentException(); } MessageConsumer consumer = session.createSubscriber(session.createTopic(messageid)); consumer.setMessageListener(new ActiveMQMessageListener(consumer, uuid, listener)); return uuid; } public void unregister(String messageid, String uuid) throws JMSException { if (isEmpty(messageid) || isEmpty(uuid)) { throw new IllegalArgumentException(); } Message message = session.createObjectMessage(new UnregisterMessage(uuid)); TopicPublisher publisher = null; try { publisher = session.createPublisher(session.createTopic(messageid)); publisher.publish(message); } catch (Exception e) { if (publisher != null) { publisher.close(); } } } public void sendMessage(String messageid, Asta4dMessage afdMessage) throws JMSException { if (isEmpty(messageid) || afdMessage == null) { throw new IllegalArgumentException(); } Message message = session.createObjectMessage(afdMessage); TopicPublisher publisher = null; try { publisher = session.createPublisher(session.createTopic(messageid)); publisher.publish(message); } catch (Exception e) { if (publisher != null) { publisher.close(); } } } private MessageManager() { try { TransportConnector connector = new TransportConnector(); connector.setUri(new URI("tcp://localhost:61616")); broker = new BrokerService(); broker.setPersistent(false); broker.setUseJmx(true); broker.addConnector(connector); broker.start(); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connection = connectionFactory.createTopicConnection(); connection.setClientID(MessageManager.class.getName()); connection.start(); session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); } catch (Exception e) { // TODO } } @Override protected void finalize() throws Throwable { try { if (session != null) { session.close(); } } finally { try { if (connection != null) { connection.stop(); connection.close(); } } finally { if (broker != null && broker.isStarted()) { broker.stop(); } } } } public static MessageManager getInstance() { return MANAGER; } private static class ActiveMQMessageListener implements MessageListener { private final MessageConsumer consumer; private final String uuid; private final Asta4dMessageListener orgListener; private ActiveMQMessageListener(MessageConsumer consumer, String uuid, Asta4dMessageListener orgListener) { this.consumer = consumer; this.uuid = uuid; this.orgListener = orgListener; } @Override public void onMessage(Message message) { if (!(message instanceof ActiveMQObjectMessage)) { return; } try { ActiveMQObjectMessage mqMsg = (ActiveMQObjectMessage) message; String messageid = ((Topic) mqMsg.getDestination()).getTopicName(); Asta4dMessage afdMsg = (Asta4dMessage) mqMsg.getObject(); if (afdMsg instanceof UnregisterMessage) { UnregisterMessage unregisterMessage = (UnregisterMessage) afdMsg; if (!uuid.equals(unregisterMessage.getUuid())) { return; } if (orgListener.unregister(messageid, unregisterMessage)) { consumer.close(); } } else { if (orgListener.onMessage(messageid, afdMsg)) { consumer.close(); } } } catch (JMSException e) { // TODO } } } */ }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,883,648,395,862,253,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.messaging; public interface Asta4dMessageListener { boolean onMessage(String messageid, Asta4dMessage message); boolean unregister(String messageid, UnregisterMessage message); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,983,937,674,566,159
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.builtin; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; public class GenericPathTemplateHandler extends AbstractGenericPathHandler { public GenericPathTemplateHandler() { } public GenericPathTemplateHandler(String basePath) { super(basePath); } @RequestHandler public Object handle(UrlMappingRule currentRule) { String path = super.convertPath(currentRule); if (path == null) { WebApplicationContext context = WebApplicationContext.getCurrentThreadWebApplicationContext(); String url = context.getAccessURI(); return new TemplateNotFoundException("Generically convert from path:" + url); } else { return path; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
824,067,894,307,542,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.builtin; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.io.FilenameUtils; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public abstract class AbstractGenericPathHandler { public final static String VAR_BASEPATH = "basePath"; private final static ConcurrentHashMap<String, String> genericMapResult = new ConcurrentHashMap<>(); private final static String NullHolder = AbstractGenericPathHandler.class.getName() + "#NULL"; private String _basePath = null; public AbstractGenericPathHandler() { } public AbstractGenericPathHandler(String basePath) { this._basePath = basePath; } public String convertPath(UrlMappingRule currentRule) { WebApplicationContext context = Context.getCurrentThreadContext(); String uri = context.getAccessURI(); String targetPath = genericMapResult.get(uri); if (targetPath != null) { if (targetPath.equals(NullHolder)) { return null; } else { return targetPath; } } else { String basePath = context.getData(WebApplicationContext.SCOPE_PATHVAR, VAR_BASEPATH); if (basePath == null) { basePath = _basePath; } if (basePath == null) {// default from web context root targetPath = uri; } else { basePath = FilenameUtils.normalize(basePath, true); String src = currentRule.getSourcePath(); // convert for /**/* String mask = "/**/*"; int idx = src.indexOf(mask); if (idx >= 0) { String parentPath = src.substring(0, idx); String childPath = uri.substring(parentPath.length()); if (basePath.endsWith("/")) { basePath = basePath.substring(0, basePath.length() - 1); } if (!childPath.startsWith("/")) { childPath = "/" + childPath; } targetPath = basePath + childPath; } else {// be a one 2 one mapping targetPath = basePath; } } if (fileNameSecurityCheck(targetPath)) { genericMapResult.put(uri, targetPath); return targetPath; } else { genericMapResult.put(uri, NullHolder); return null; } } } private boolean fileNameSecurityCheck(String path) { // we do not allow any unnormalized path for security reason String normalizedPath = FilenameUtils.normalize(path, true); return path.equals(normalizedPath); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,785,562,353,400,165,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.builtin; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.URLConnection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.tuple.Pair; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.util.MemorySafeResourceCache; import com.astamuse.asta4d.util.MemorySafeResourceCache.ResouceHolder; import com.astamuse.asta4d.util.MultiSearchPathResourceLoader; import com.astamuse.asta4d.util.i18n.LocalizeUtil; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; import com.astamuse.asta4d.web.dispatch.response.provider.BinaryDataProvider; import com.astamuse.asta4d.web.dispatch.response.provider.HeaderInfoProvider; import com.astamuse.asta4d.web.util.data.BinaryDataUtil; /** * A static resouce handler for service static resources such as js, css or static html files. * * The following path vars can be configured for specializing response headers: * * <ul> * <li>{@link #VAR_CONTENT_TYPE} * <li>{@link #VAR_CONTENT_CACHE_SIZE_LIMIT_K} * <li>{@link #VAR_CACHE_TIME} * <li>{@link #VAR_LAST_MODIFIED} * </ul> * * Or the following methods can be override for more complex calculations: * * <ul> * <li>{@link #judgContentType(String)} * <li>{@link #getContentCacheSizeLimit(String)} * <li>{@link #decideCacheTime(String)} * <li>{@link #getLastModifiedTime(String)} * </ul> * * @author e-ryu * */ public class StaticResourceHandler extends AbstractGenericPathHandler { /** * see {@link #judgContentType(String)} */ public final static String VAR_CONTENT_TYPE = StaticResourceHandler.class.getName() + "#content_type"; /** * see {@link #getContentCacheSizeLimit(String)} */ public final static String VAR_CONTENT_CACHE_SIZE_LIMIT_K = StaticResourceHandler.class.getName() + "#content_cache_size_limit_k"; /** * see {@link #decideCacheTime(String)} */ public final static String VAR_CACHE_TIME = StaticResourceHandler.class.getName() + "#cache_time"; /** * see {@link #getLastModifiedTime(String)} */ public final static String VAR_LAST_MODIFIED = StaticResourceHandler.class.getName() + "#last_modified"; private final static Logger logger = LoggerFactory.getLogger(StaticResourceHandler.class); private final static long DefaultLastModified = DateTime.now().getMillis(); // one hour private final static long DefaultCacheTime = 1000 * 60 * 60; protected final static class StaticFileInfo { String contentType; String actualPath; long lastModified; int cacheLimit; SoftReference<byte[]> content; InputStream firstTimeInput; } private final static MemorySafeResourceCache<String, StaticFileInfo> StaticFileInfoMap = new MemorySafeResourceCache<>(); public StaticResourceHandler() { super(); } public StaticResourceHandler(String basePath) { super(basePath); } private HeaderInfoProvider createSimpleHeaderResponse(int status) { HeaderInfoProvider provider = new HeaderInfoProvider(status); provider.setContinuable(false); return provider; } @RequestHandler public Object handler(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, UrlMappingRule currentRule) throws FileNotFoundException, IOException { String path = convertPath(currentRule); if (path == null) { return createSimpleHeaderResponse(404); } StaticFileInfo info = retrieveStaticFileInfo(servletContext, path); return response(request, response, servletContext, info, path); } protected StaticFileInfo retrieveStaticFileInfo(ServletContext servletContext, String path) throws FileNotFoundException, IOException { Locale locale = LocalizeUtil.defaultWhenNull(null); String staticFileInfoKey = LocalizeUtil.createLocalizedKey(path, locale); ResouceHolder<StaticFileInfo> cachedResource = Configuration.getConfiguration().isCacheEnable() ? StaticFileInfoMap.get(staticFileInfoKey) : null; StaticFileInfo info = null; if (cachedResource == null) { info = createInfo(servletContext, locale, path); StaticFileInfoMap.put(staticFileInfoKey, info); } else { if (cachedResource.exists()) { info = cachedResource.get(); } else { info = null; } } return info; } protected Object response(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, StaticFileInfo info, String requiredPath) throws FileNotFoundException, IOException { if (info == null) { return createSimpleHeaderResponse(404); } if (Configuration.getConfiguration().isCacheEnable()) { long clientTime = retrieveClientCachedTime(request); if (clientTime >= info.lastModified) { return createSimpleHeaderResponse(304); } } // our header provider is not convenient for date header... hope we can // improve it in future long cacheTime = decideCacheTime(requiredPath, info.actualPath); response.setStatus(200); response.setHeader("Content-Type", info.contentType); response.setDateHeader("Expires", DateTime.now().getMillis() + cacheTime); response.setDateHeader("Last-Modified", info.lastModified); response.setHeader("Cache-control", "max-age=" + (cacheTime / 1000)); // here we do not synchronize threads because we do not matter if (info.content == null && info.firstTimeInput != null) { // no cache, and we have opened it at first time InputStream input = info.firstTimeInput; info.firstTimeInput = null; return new BinaryDataProvider(input); } else if (info.content == null && info.firstTimeInput == null) { // no cache return new BinaryDataProvider(servletContext, this.getClass().getClassLoader(), info.actualPath); } else { // should cache byte[] data = null; data = info.content.get(); if (data == null) { InputStream input = BinaryDataUtil.retrieveInputStreamByPath(servletContext, this.getClass().getClassLoader(), info.actualPath); // if we went to here, which means we are not overing the cache size limit, so we do not need to check null. data = retrieveBytesFromInputStream(input, info.cacheLimit); info.content = new SoftReference<byte[]>(data); } return new BinaryDataProvider(data); } } private long retrieveClientCachedTime(HttpServletRequest request) { try { long time = request.getDateHeader("If-Modified-Since"); return DateTimeZone.getDefault().convertLocalToUTC(time, false); } catch (Exception e) { logger.debug("retrieve If-Modified-Since failed", e); return -1; } } private StaticFileInfo createInfo(final ServletContext servletContext, Locale locale, String path) throws FileNotFoundException, IOException { MultiSearchPathResourceLoader<Pair<String, InputStream>> loader = new MultiSearchPathResourceLoader<Pair<String, InputStream>>() { @Override protected Pair<String, InputStream> loadResource(String name) { InputStream is = BinaryDataUtil.retrieveInputStreamByPath(servletContext, this.getClass().getClassLoader(), name); if (is != null) { return Pair.of(name, is); } else { return null; } } }; Pair<String, InputStream> foundResource = loader.searchResource("/", LocalizeUtil.getCandidatePaths(path, locale)); if (foundResource == null) { return null; } StaticFileInfo info = new StaticFileInfo(); info.contentType = judgContentType(path); info.actualPath = foundResource.getLeft(); info.lastModified = getLastModifiedTime(path); // cut the milliseconds info.lastModified = info.lastModified / 1000 * 1000; info.cacheLimit = getContentCacheSizeLimit(path); if (info.cacheLimit == 0) {// don't cache info.content = null; // we will use the retrieved input stream at the first time for performance reason info.firstTimeInput = foundResource.getRight(); } else { byte[] contentData = retrieveBytesFromInputStream(foundResource.getRight(), info.cacheLimit); if (contentData == null) {// we cannot cache it due to over limited size // fallback to no cache case info.content = null; info.firstTimeInput = null; } else { try { info.content = new SoftReference<byte[]>(contentData); } finally { foundResource.getRight().close(); } info.firstTimeInput = null; } } return info; } private byte[] retrieveBytesFromInputStream(InputStream input, int cacheSize) throws IOException { byte[] b = new byte[cacheSize]; int len = input.read(b); if (input.read() >= 0) {// over the limit of cache size return null; } else { if (len < cacheSize) { byte[] nb = new byte[len]; System.arraycopy(b, 0, nb, 0, len); return nb; } else {// going to buy lottery return b; } } } private final static Map<String, String> MimeTypeMap = new HashMap<>(); static { MimeTypeMap.put("js", "application/javascript"); MimeTypeMap.put("css", "text/css"); MimeTypeMap.put("ico", "image/x-icon"); } /** * The header value of Content-Type * * @param path * @return a guess of the content type by file name extension, "application/octet-stream" when not matched */ protected String judgContentType(String path) { Context context = Context.getCurrentThreadContext(); String forceContentType = context.getData(WebApplicationContext.SCOPE_PATHVAR, VAR_CONTENT_TYPE); if (forceContentType != null) { return forceContentType; } String fileName = FilenameUtils.getName(path); // guess the type by file name extension String type = URLConnection.guessContentTypeFromName(fileName); if (type == null) { type = MimeTypeMap.get(FilenameUtils.getExtension(fileName)); } if (type == null) { type = "application/octet-stream"; } return type; } /** * The header value of Cache-control and Expires. * * override this method to supply the specialized cache time. * * @param path * @return cache time in millisecond unit */ protected long decideCacheTime(String requiredPath, String actualTargetFilePath) { Long varCacheTime = Context.getCurrentThreadContext().getData(WebApplicationContext.SCOPE_PATHVAR, VAR_CACHE_TIME); if (varCacheTime != null) { return varCacheTime; } else { return DefaultCacheTime; } } /** * * The header value of Last-Modified. * * override this method to supply the specialized last modified time * * @param path * @return the time of last modified time in millisecond unit(In http protocol, the time unit should be second, but we will cope with * this matter) */ protected long getLastModifiedTime(String path) { WebApplicationContext context = Context.getCurrentThreadContext(); Long varLastModified = context.getData(WebApplicationContext.SCOPE_PATHVAR, VAR_LAST_MODIFIED); if (varLastModified != null) { return varLastModified; } else { long retrieveTime = BinaryDataUtil.retrieveLastModifiedByPath(context.getServletContext(), this.getClass().getClassLoader(), path); if (retrieveTime == 0L) { return DefaultLastModified; } else { return retrieveTime; } } } /** * Retrieve the max cachable size limit for a certain path in byte unit.Be care of that the path var is set by kilobyte unit for * convenience but this method will return in byte unit. <br> * This is a default implementation which does not see the path and will return 0 for not caching when path var is not set. * <p> * Note: we do not cache it by default because the resources in war should have been cached by the servlet container. * * * @param path * @return the max cachable size limit for a certain path in byte unit. */ protected int getContentCacheSizeLimit(String path) { Integer varCacheSize = Context.getCurrentThreadContext().getData(WebApplicationContext.SCOPE_PATHVAR, VAR_CONTENT_CACHE_SIZE_LIMIT_K); if (varCacheSize != null) { return varCacheSize * 1000; } else { return 0; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,076,281,365,095,714,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.initialization; import java.io.InputStream; import com.astamuse.asta4d.web.WebApplicationConfiguration; public interface Initializer { public void initliaze(InputStream input, WebApplicationConfiguration configuration) throws Exception; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,723,128,463,803,944,200
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.initialization; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.configuration.PropertiesConfiguration; import com.astamuse.asta4d.web.WebApplicationConfiguration; public class SimplePropertyFileInitializer implements Initializer { @Override public void initliaze(InputStream input, WebApplicationConfiguration configuration) throws Exception { PropertiesConfiguration pc = new PropertiesConfiguration(); pc.load(input); BeanUtilsBean bu = retrieveBeanUtilsBean(); Iterator<String> keys = pc.getKeys(); while (keys.hasNext()) { String key = keys.next(); String value = pc.getString(key); fillConfiguration(configuration, bu, key, value); } } protected BeanUtilsBean retrieveBeanUtilsBean() { BeanUtilsBean bu = new BeanUtilsBean(new ConvertUtilsBean() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object convert(String value, Class clazz) { if (clazz.isEnum()) { return Enum.valueOf(clazz, value); } else if (clazz.equals(Class.class)) { try { return Class.forName(value); } catch (Exception e) { throw new RuntimeException(e); } } else if (expectInstance(clazz)) { try { return Class.forName(value).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } else { return super.convert(value, clazz); } } }); return bu; } @SuppressWarnings("rawtypes") protected boolean expectInstance(Class clz) { Package pkg = clz.getPackage(); if (pkg == null) { return false; } else { return pkg.getName().startsWith("com.astamuse.asta4d."); } } @SuppressWarnings("rawtypes") protected void fillConfiguration(WebApplicationConfiguration conf, BeanUtilsBean beanUtil, String key, String value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Class cls = PropertyUtils.getPropertyType(conf, key); if (cls.isArray()) { String[] values = value.split(","); beanUtil.setProperty(conf, key, values); } else { beanUtil.setProperty(conf, key, value); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,865,741,855,961,328,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.web.WebApplicationConfiguration; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.WebApplicatoinConfigurationInitializer; import com.astamuse.asta4d.web.dispatch.RequestDispatcher; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSet; /** * Here we are going to implement a view first mechanism of view resolving. We need a url mapping algorithm too. * */ public class Asta4dServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private final static Logger logger = LoggerFactory.getLogger(Asta4dServlet.class); protected RequestDispatcher dispatcher = new RequestDispatcher(); private List<UrlMappingRule> ruleList; @Override public void init(ServletConfig config) throws ServletException { super.init(config); try { WebApplicationConfiguration asta4dConf = createConfiguration(); createConfigurationInitializer().initConfigurationFromFile(config, asta4dConf); Configuration.setConfiguration(asta4dConf); asta4dConf.getExpirableDataManager().start(); asta4dConf.addShutdownHookers(() -> { asta4dConf.getExpirableDataManager().stop(); }); ruleList = createRuleList(); } catch (Exception e) { throw new ServletException(e); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private List<UrlMappingRule> createRuleList() throws InstantiationException, IllegalAccessException { WebApplicationConfiguration conf = WebApplicationConfiguration.getWebApplicationConfiguration(); UrlMappingRuleSet ruleSet = conf.getUrlMappingRuleSetCls().newInstance(); conf.getUrlMappingRuleInitializer().initUrlMappingRules(ruleSet); logger.info("url mapping rules are initialized."); return ruleSet.getArrangedRuleList(); } @Override protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { logger.debug("access for:{}", req.getRequestURI()); WebApplicationContext context = null; try { context = Context.getCurrentThreadContext(); if (context == null) { context = createAsta4dContext(); Context.setCurrentThreadContext(context); } context.init(); context.setRequest(req); context.setResponse(res); context.setServletContext(getServletContext()); service(); } catch (Exception e) { throw new ServletException(e); } finally { if (context != null) { context.clear(); } } } /** * Subclass can override this method to do something before or after real service process. * * eg. {@link WebApplicationContext#setAccessURI(String)} can be called before this method to rewrite access uri. * * @throws Exception */ protected void service() throws Exception { if (Configuration.getConfiguration().isCacheEnable()) { dispatcher.dispatchAndProcess(ruleList); } else { dispatcher.dispatchAndProcess(createRuleList()); } } protected WebApplicationContext createAsta4dContext() { WebApplicationContext context = new WebApplicationContext(); return context; } protected WebApplicationConfiguration createConfiguration() { return new WebApplicationConfiguration(); } protected WebApplicatoinConfigurationInitializer createConfigurationInitializer() { return new WebApplicatoinConfigurationInitializer(); } @Override public void destroy() { for (Runnable runnable : WebApplicationConfiguration.getConfiguration().getShutdownHookers()) { try { runnable.run(); } catch (Exception ex) { logger.error("error occured to invoke shutdown hookers", ex); } } WebApplicationConfiguration.setConfiguration(null);// for gc System.gc();// if possible super.destroy(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,511,510,689,347,884,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; public enum HttpMethod { GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, CONNECT, PATCH, UNKNOWN; public static HttpMethod getMethod(String m) { try { return HttpMethod.valueOf(m.toUpperCase()); } catch (IllegalArgumentException e) { return HttpMethod.UNKNOWN; } } public static class ExtendHttpMethod { private String method; public ExtendHttpMethod(String method) { this.method = method.toUpperCase(); } public static ExtendHttpMethod of(String method) { return new ExtendHttpMethod(method); } public String getMethod() { return this.method; } @Override public int hashCode() { return method.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ExtendHttpMethod other = (ExtendHttpMethod) obj; if (method == null) { if (other.method != null) return false; } else if (!method.equals(other.method)) return false; return true; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,366,875,327,024,871,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.interceptor.base.Executor; import com.astamuse.asta4d.interceptor.base.GenericInterceptor; import com.astamuse.asta4d.interceptor.base.InterceptorUtil; import com.astamuse.asta4d.web.dispatch.interceptor.RequestHandlerInterceptor; import com.astamuse.asta4d.web.dispatch.interceptor.RequestHandlerResultHolder; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.request.ResultTransformerUtil; import com.astamuse.asta4d.web.dispatch.response.provider.ContentProvider; import com.astamuse.asta4d.web.util.bean.AnnotationMethodHelper; import com.astamuse.asta4d.web.util.bean.DeclareInstanceUtil; public class DefaultRequestHandlerInvoker implements RequestHandlerInvoker { public static final String TRACE_VAR_CURRENT_HANDLER = "TRACE_VAR_CURRENT_HANDLER#" + DefaultRequestHandlerInvoker.class; /* (non-Javadoc) * @see com.astamuse.asta4d.web.dispatch.RequestHandlerInvoker#invoke(com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule) */ @Override public List<ContentProvider> invoke(UrlMappingRule rule) throws Exception { RequestHandlerInvokeExecutor executor = new RequestHandlerInvokeExecutor(rule.getHandlerList(), rule.getResultTransformerList()); RequestHandlerResultHolder holder = new RequestHandlerResultHolder(); InterceptorUtil.executeWithInterceptors(holder, buildInterceptorList(rule), executor); return holder.getContentProviderList(); } /* private static WebPageView getForwardPageView(Map<Class<? extends ForwardDescriptor>, String> forwardDescriptors, ForwardDescriptor forwardDescriptor) { String path = forwardDescriptors.get(forwardDescriptor.getClass()); if (StringUtils.isEmpty(path)) { return null; } return new WebPageView(path); } */ private List<RequestHandlerInterceptorWrapper> buildInterceptorList(UrlMappingRule rule) { List<RequestHandlerInterceptorWrapper> list = new ArrayList<>(); for (RequestHandlerInterceptor interceptor : rule.getInterceptorList()) { list.add(new RequestHandlerInterceptorWrapper(rule, interceptor)); } return list; } private static class RequestHandlerInterceptorWrapper implements GenericInterceptor<RequestHandlerResultHolder> { private final UrlMappingRule rule; private final RequestHandlerInterceptor interceptor; public RequestHandlerInterceptorWrapper(UrlMappingRule rule, RequestHandlerInterceptor interceptor) { this.rule = rule; this.interceptor = interceptor; } @Override public boolean beforeProcess(RequestHandlerResultHolder holder) throws Exception { interceptor.preHandle(rule, holder); return holder.getContentProviderList() == null; } @Override public void afterProcess(RequestHandlerResultHolder holder, ExceptionHandler exceptionHandler) { interceptor.postHandle(rule, holder, exceptionHandler); } } private static class RequestHandlerInvokeExecutor implements Executor<RequestHandlerResultHolder> { private final List<Object> requestHandlerList; private final List<ResultTransformer> resultTransformerList; private final Logger logger = LoggerFactory.getLogger(this.getClass()); public RequestHandlerInvokeExecutor(List<Object> requestHandlerList, List<ResultTransformer> resultTransformerList) { this.requestHandlerList = requestHandlerList; this.resultTransformerList = resultTransformerList; } @Override public void execute(RequestHandlerResultHolder holder) throws Exception { List<ContentProvider> cpList = new ArrayList<>(); Object result; ContentProvider cp; Context context = Context.getCurrentThreadContext(); for (Object handler : requestHandlerList) { try { context.setData(TRACE_VAR_CURRENT_HANDLER, handler); result = invokeMethodForAnnotation(handler, RequestHandler.class); } catch (Throwable t) { logger.error(t.getMessage(), t); result = t; } finally { context.setData(TRACE_VAR_CURRENT_HANDLER, null); } if (result != null) { cp = ResultTransformerUtil.transform(result, resultTransformerList); cpList.add(cp); if (!cp.isContinuable()) { break; } }// result != null }// for if (cpList.isEmpty()) { cpList.add(ResultTransformerUtil.transform(null, resultTransformerList)); } holder.setContentProviderList(cpList); } private Object invokeMethodForAnnotation(Object obj, Class<? extends Annotation> annotation) throws Exception { Object targetObj = DeclareInstanceUtil.retrieveInovkeTargetObject(obj); Method m = AnnotationMethodHelper.findMethod(targetObj, annotation); if (m == null) { // TODO maybe we can return a null? String msg = String.format("Method not found for annotation %s at class %s:", annotation.toString(), targetObj.getClass() .getName()); throw new InvocationTargetException(new RuntimeException(msg)); } try { return DeclareInstanceUtil.invokeMethod(targetObj, m); } catch (Exception e) { String msg = "Error occured when invoke method for annotiona %s on %s"; msg = String.format(msg, annotation.getName(), targetObj.getClass().getName()); logger.error(msg, e); throw e; } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,326,993,293,962,551,300
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; public class DefaultRequestHandlerInvokerFactory implements RequestHandlerInvokerFactory { private RequestHandlerInvoker invoker = new DefaultRequestHandlerInvoker(); /* (non-Javadoc) * @see com.astamuse.asta4d.web.dispatch.RequestHandlerInvokerFactory#getInvoker() */ @Override public RequestHandlerInvoker getInvoker() { return invoker; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,347,366,395,399,734,300
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; import java.util.List; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.response.provider.ContentProvider; public interface RequestHandlerInvoker { public List<ContentProvider> invoke(UrlMappingRule rule) throws Exception; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,578,344,988,655,821,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; public interface RequestHandlerInvokerFactory { public RequestHandlerInvoker getInvoker(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,459,605,121,217,171,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.web.WebApplicationConfiguration; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.util.SecureIdGenerator; public class RedirectUtil { // for performance reason private static final String KEY_FLASH_SCOPE_ID = WebApplicationConfiguration.getWebApplicationConfiguration() .getFlashScopeForwardParameterName(); private static final long DATA_EXPIRE_TIME_MILLI_SECONDS = 30_000; private static final String FlashScopeDataListKey = RedirectUtil.class.getName() + "##FlashScopeDataListKey"; private static final String RedirectInterceptorMapKey = RedirectUtil.class.getName() + "##RedirectInterceptorMapKey"; /** * <p> * register a redirect interceptor to current context with duplicated id check, if there has been an interceptor registered by same id, * the later interceptor will be rejected. * * <p> * <b>NOTE:</b>There is no guaranty about the execution order of registered interceptors. * * @param id * duplication check will be skipped when null specified * @param interceptor * @return true: the given interceptor is registered<br> * false: the given interceptor is no regiestered because the id has been registered */ public static final boolean registerRedirectInterceptor(String id, RedirectInterceptor interceptor) { Context context = Context.getCurrentThreadContext(); Map<String, RedirectInterceptor> map = context.getData(RedirectInterceptorMapKey); if (map == null) { map = new HashMap<>(); context.setData(RedirectInterceptorMapKey, map); } // we don't do duplicated check for null id if (id == null) { map.put(id, interceptor); return true; } else { // we don't do thread lock because we believe all the operations about redirection should be done at the handler side, which // means there is no concurrent issue. if (map.get(id) == null) { map.put(id, interceptor); return true; } else { return false; } } } public static void addFlashScopeData(Map<String, Object> flashScopeData) { if (flashScopeData == null || flashScopeData.isEmpty()) { return; } WebApplicationContext context = Context.getCurrentThreadContext(); List<Map<String, Object>> dataList = context.getData(FlashScopeDataListKey); if (dataList == null) { dataList = new LinkedList<>(); context.setData(FlashScopeDataListKey, dataList); } dataList.add(flashScopeData); } public static void addFlashScopeData(String name, Object data) { Map<String, Object> map = new HashMap<String, Object>(); map.put(name, data); addFlashScopeData(map); } public static void redirectToUrlWithSavedFlashScopeData(HttpServletResponse response, int status, String url) { // regulate status if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) { // } else { status = HttpURLConnection.HTTP_MOVED_TEMP; } // check illegal url if (url.indexOf('\n') >= 0 || url.indexOf('\r') >= 0) { throw new RuntimeException("illegal redirct url:" + url); } // before redirect task Map<String, RedirectInterceptor> interceptorMap = Context.getCurrentThreadContext().getData(RedirectInterceptorMapKey); if (interceptorMap != null) { for (RedirectInterceptor interceptor : interceptorMap.values()) { interceptor.beforeRedirect(); } addFlashScopeData(RedirectInterceptorMapKey, interceptorMap); } // create flash data map Map<String, Object> dataMap = new HashMap<String, Object>(); WebApplicationContext context = Context.getCurrentThreadContext(); List<Map<String, Object>> dataList = context.getData(FlashScopeDataListKey); if (dataList != null) { for (Map<String, Object> map : dataList) { dataMap.putAll(map); } } // save flash data map if (!dataMap.isEmpty()) { String flashScopeId = SecureIdGenerator.createEncryptedURLSafeId(); WebApplicationConfiguration.getWebApplicationConfiguration().getExpirableDataManager() .put(flashScopeId, dataMap, DATA_EXPIRE_TIME_MILLI_SECONDS); // create target url if (url.contains("?")) { url = url + '&' + KEY_FLASH_SCOPE_ID + '=' + flashScopeId; } else { url = url + '?' + KEY_FLASH_SCOPE_ID + '=' + flashScopeId; } } // do redirection response.setStatus(status); response.addHeader("Location", url); } public static void restoreFlashScopeData(HttpServletRequest request) { String flashScopeId = request.getParameter(RedirectUtil.KEY_FLASH_SCOPE_ID); if (StringUtils.isEmpty(flashScopeId)) { return; } else { Map<String, Object> savedMap = WebApplicationConfiguration.getWebApplicationConfiguration().getExpirableDataManager() .get(flashScopeId, true); if (savedMap == null) { return; } else { WebApplicationContext context = WebApplicationContext.getCurrentThreadWebApplicationContext(); for (Entry<String, Object> entry : savedMap.entrySet()) { context.setData(WebApplicationContext.SCOPE_FLASH, entry.getKey(), entry.getValue()); } Map<String, RedirectInterceptor> interceptorMap = context.getData(WebApplicationContext.SCOPE_FLASH, RedirectInterceptorMapKey); if (interceptorMap != null) { for (RedirectInterceptor interceptor : interceptorMap.values()) { interceptor.afterRedirectDataRestore(); } } } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,018,225,940,397,530,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; import com.astamuse.asta4d.web.dispatch.HttpMethod.ExtendHttpMethod; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingResult; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; /** * * @author e-ryu * */ public interface DispatcherRuleMatcher { /** * * @param request * @param rule * @return */ public UrlMappingResult match(UrlMappingRule rule, HttpMethod method, ExtendHttpMethod extendMethod, String uri, String queryString); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-516,262,935,450,293,100
/* * Copyright 2014 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; public interface RedirectInterceptor { public void beforeRedirect(); public void afterRedirectDataRestore(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,187,158,011,633,033,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; import java.util.HashMap; import java.util.Map; import com.astamuse.asta4d.web.copyleft.SpringAntPathMatcher; import com.astamuse.asta4d.web.dispatch.HttpMethod.ExtendHttpMethod; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingResult; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; /** * Use the spring mvc ant path matching rule to find matched rule. <br> * * @author e-ryu * */ public class AntPathRuleMatcher implements DispatcherRuleMatcher { private SpringAntPathMatcher pathMatcher = new SpringAntPathMatcher(); @Override public UrlMappingResult match(UrlMappingRule rule, HttpMethod method, ExtendHttpMethod extendMethod, String uri, String queryString) { UrlMappingResult mappingResult = null; if (matchMethod(rule, method, extendMethod)) { if (matchPath(rule, uri)) { mappingResult = new UrlMappingResult(); mappingResult.setPathVarMap(variables(rule, uri)); mappingResult.setRule(rule); } } return mappingResult; } protected boolean matchMethod(UrlMappingRule rule, HttpMethod method, ExtendHttpMethod extendMethod) { HttpMethod ruleMethod = rule.getMethod(); if (ruleMethod == null) { return true;// match all } if (ruleMethod != method) { return false; } if (method == HttpMethod.UNKNOWN) { ExtendHttpMethod ruleExtendMethod = rule.getExtendMethod(); if (ruleExtendMethod == null) { return true; // match all extend method } else { return ruleExtendMethod.equals(extendMethod); } } else { return true;// method macthed } } protected boolean matchPath(UrlMappingRule rule, String uri) { return pathMatcher.match(rule.getSourcePath(), uri); } protected Map<String, Object> variables(UrlMappingRule rule, String uri) { Map<String, Object> pathVarMap = new HashMap<>(); pathVarMap.putAll(pathMatcher.extractUriTemplateVariables(rule.getSourcePath(), uri)); return pathVarMap; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,940,268,302,439,604,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch; import java.net.URLDecoder; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.web.WebApplicationConfiguration; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.dispatch.HttpMethod.ExtendHttpMethod; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingResult; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.response.provider.ContentProvider; public class RequestDispatcher { public final static String KEY_REQUEST_HANDLER_RESULT = "RequestDispatcher##KEY_REQUEST_HANDLER_RESULT"; private final static Logger logger = LoggerFactory.getLogger(RequestDispatcher.class); public RequestDispatcher() { } public void dispatchAndProcess(List<UrlMappingRule> ruleList) throws Exception { WebApplicationContext context = (WebApplicationContext) Context.getCurrentThreadContext(); HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); HttpMethod method; ExtendHttpMethod extendMethod; method = HttpMethod.getMethod(request.getMethod()); extendMethod = method == HttpMethod.UNKNOWN ? ExtendHttpMethod.of(request.getMethod()) : null; String uri = context.getAccessURI(); if (uri == null) { uri = URLDecoder.decode(request.getRequestURI(), "UTF-8"); String contextPath = request.getContextPath(); uri = uri.substring(contextPath.length()); context.setAccessURI(uri); } String queryString = request.getQueryString(); UrlMappingResult result = null; for (UrlMappingRule rule : ruleList) { result = rule.getRuleMatcher().match(rule, method, extendMethod, uri, queryString); if (result != null) { break; } } // if not found result, we do not need return 404, instead of user // defining all match rule if (result == null) { logger.warn( "There is no matched rule found, we will simply return a 404. You should define your own matching all rule for this case."); response.setStatus(404); return; } if (logger.isDebugEnabled()) { logger.debug("apply rule at :" + result.getRule()); } writePathVarToContext(context, result.getPathVarMap()); UrlMappingRule rule = result.getRule(); context.setCurrentRule(rule); writePathVarToContext(context, rule.getExtraVarMap()); RedirectUtil.restoreFlashScopeData(request); List<ContentProvider> requestResult = handleRequest(rule); for (ContentProvider cp : requestResult) { cp.produce(rule, response); } } /** * * @param request * @return ContentProvider * @throws Exception */ private List<ContentProvider> handleRequest(UrlMappingRule currentRule) throws Exception { Context context = Context.getCurrentThreadContext(); RequestHandlerInvokerFactory factory = WebApplicationConfiguration.getWebApplicationConfiguration() .getRequestHandlerInvokerFactory(); RequestHandlerInvoker invoker = factory.getInvoker(); List<ContentProvider> cpList = invoker.invoke(currentRule); context.setData(KEY_REQUEST_HANDLER_RESULT, cpList); return cpList; } private void writePathVarToContext(WebApplicationContext context, Map<String, Object> pathVarMap) { Iterator<Entry<String, Object>> it = pathVarMap.entrySet().iterator(); Entry<String, Object> entry; while (it.hasNext()) { entry = it.next(); context.setData(WebApplicationContext.SCOPE_PATHVAR, entry.getKey(), entry.getValue()); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
675,368,538,771,170,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed 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 com.astamuse.asta4d.web.dispatch.mapping; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.util.IdGenerator; import com.astamuse.asta4d.web.WebApplicationConfiguration; import com.astamuse.asta4d.web.dispatch.DispatcherRuleMatcher; import com.astamuse.asta4d.web.dispatch.HttpMethod; import com.astamuse.asta4d.web.dispatch.HttpMethod.ExtendHttpMethod; import com.astamuse.asta4d.web.dispatch.interceptor.RequestHandlerInterceptor; import com.astamuse.asta4d.web.dispatch.interceptor.RequestHandlerResultHolder; import com.astamuse.asta4d.web.util.bean.DeclareInstanceAdapter; import com.astamuse.asta4d.web.util.bean.DeclareInstanceUtil; /** * * @author e-ryu * * @param <H> * rule with handler configurable * @param <T> * rule with target decided */ public abstract class UrlMappingRuleSet<H, T> { public final static String ID_VAR_NAME = UrlMappingRuleSet.class.getName() + "-rule-id"; public final static String REMAP_ID_VAR_NAME = UrlMappingRuleSet.class.getName() + "-remap-rule-id"; public final static int DEFAULT_PRIORITY = 0; protected final static AtomicInteger Sequencer = new AtomicInteger(); protected final static class InterceptorHolder { String attribute; RequestHandlerInterceptor interceptor; public InterceptorHolder(String attribute, RequestHandlerInterceptor interceptor) { super(); this.attribute = attribute; this.interceptor = interceptor; } } protected final static class RequestHandlerHolder { String attribute; Object handler; public RequestHandlerHolder(String attribute, Object handler) { super(); this.attribute = attribute; this.handler = handler; } } protected static class InterceptorWrapper implements RequestHandlerInterceptor { final static String InterceptorInstanceCacheKey = InterceptorWrapper.class.getName() + "#InterceptorInstanceCacheKey"; DeclareInstanceAdapter adapter; String id; InterceptorWrapper(DeclareInstanceAdapter adapter) { this.adapter = adapter; this.id = InterceptorInstanceCacheKey + "##" + IdGenerator.createId(); } @Override public void preHandle(UrlMappingRule rule, RequestHandlerResultHolder holder) { RequestHandlerInterceptor interceptor = (RequestHandlerInterceptor) adapter.asTargetInstance(); Context.getCurrentThreadContext().setData(id, interceptor); interceptor.preHandle(rule, holder); } @Override public void postHandle(UrlMappingRule rule, RequestHandlerResultHolder holder, ExceptionHandler exceptionHandler) { // retrieve the instance that actually was executed RequestHandlerInterceptor interceptor = Context.getCurrentThreadContext().getData(id); interceptor.postHandle(rule, holder, exceptionHandler); } } protected HttpMethod defaultMethod = HttpMethod.GET; protected List<InterceptorHolder> interceptorHolderList = new ArrayList<>(); protected List<RequestHandlerHolder> defaultHandlerList = new ArrayList<>(); protected List<UrlMappingRule> ruleList = new ArrayList<>(); protected List<UrlMappingRuleRewriter> userCustomizedRuleRewriterList = new ArrayList<>(); protected DispatcherRuleMatcher defaultRuleMatcher = WebApplicationConfiguration.getWebApplicationConfiguration().getRuleMatcher(); public void setDefaultMethod(HttpMethod defaultMethod) { this.defaultMethod = defaultMethod; } public void addRequestHandlerInterceptor(String attribute, Object... interceptorList) { RequestHandlerInterceptor interceptor; Object instance; for (Object obj : interceptorList) { instance = DeclareInstanceUtil.createInstance(obj); if (instance instanceof RequestHandlerInterceptor) { interceptor = (RequestHandlerInterceptor) instance; interceptorHolderList.add(new InterceptorHolder(attribute, interceptor)); } else if (instance instanceof DeclareInstanceAdapter) { interceptor = new InterceptorWrapper((DeclareInstanceAdapter) instance); interceptorHolderList.add(new InterceptorHolder(attribute, interceptor)); } } } public void addRequestHandlerInterceptor(Object... interceptorList) { addRequestHandlerInterceptor(null, interceptorList); } public void addDefaultRequestHandler(String attribute, Object... handlerList) { for (Object handler : handlerList) { defaultHandlerList.add(new RequestHandlerHolder(attribute, handler)); } } public void addDefaultRequestHandler(Object... handlerList) { addDefaultRequestHandler(null, handlerList); } public void addRuleRewriter(UrlMappingRuleRewriter ruleRewriter) { userCustomizedRuleRewriterList.add(ruleRewriter); } protected UrlMappingRule searchRuleById(List<UrlMappingRule> list, String id) { UrlMappingRule result = null; Object ruleId; for (UrlMappingRule rule : list) { ruleId = rule.extraVar(ID_VAR_NAME); if (ruleId == null) { continue; } else if (ruleId.equals(id)) { result = rule; break; } } if (result == null) { throw new IllegalArgumentException("Can not find a rule is identified by given id:" + id); } else { return result; } } public List<UrlMappingRule> getArrangedRuleList() { List<UrlMappingRule> arrangedRuleList = new ArrayList<>(ruleList); // user customized rewriting at first for (UrlMappingRule rule : arrangedRuleList) { for (UrlMappingRuleRewriter rewriter : userCustomizedRuleRewriterList) { rewriter.rewrite(rule); } } // config remapped rule Object reMapId; UrlMappingRule copyFromRule; for (UrlMappingRule rule : arrangedRuleList) { reMapId = rule.extraVar(REMAP_ID_VAR_NAME); if (reMapId == null) { continue; } copyFromRule = searchRuleById(arrangedRuleList, reMapId.toString()); List<String> originalAttrList = rule.getAttributeList(); Map<String, Object> originalVarMap = rule.getExtraVarMap(); int originalPriority = rule.getPriority(); rule.setAttributeList(new ArrayList<>(copyFromRule.getAttributeList())); rule.setExtraVarMap(new HashMap<>(copyFromRule.getExtraVarMap())); rule.setPriority(copyFromRule.getPriority()); rule.setHandlerList(new ArrayList<>(copyFromRule.getHandlerList())); rule.setInterceptorList(new ArrayList<>(copyFromRule.getInterceptorList())); rule.setResultTransformerList(new ArrayList<>(copyFromRule.getResultTransformerList())); // add original configurations back if (originalAttrList != null) { rule.getAttributeList().addAll(originalAttrList); } if (originalVarMap != null) { rule.getExtraVarMap().putAll(originalVarMap); } if (originalPriority != DEFAULT_PRIORITY) { rule.setPriority(originalPriority); } } // set interceptor List<RequestHandlerInterceptor> interceptorList; for (UrlMappingRule rule : arrangedRuleList) { interceptorList = new ArrayList<>(); for (InterceptorHolder iHolder : interceptorHolderList) { if (iHolder.attribute == null) { interceptorList.add(iHolder.interceptor); } else if (rule.hasAttribute(iHolder.attribute)) { interceptorList.add(iHolder.interceptor); } } rule.setInterceptorList(interceptorList); } // set default request handler List<Object> requestHandlerList; for (UrlMappingRule rule : arrangedRuleList) { requestHandlerList = new ArrayList<>(); for (RequestHandlerHolder handlerHolder : defaultHandlerList) { Object handler = DeclareInstanceUtil.createInstance(handlerHolder.handler); if (handlerHolder.attribute == null) { requestHandlerList.add(handler); } else if (rule.hasAttribute(handlerHolder.attribute)) { requestHandlerList.add(handler); } } requestHandlerList.addAll(rule.getHandlerList()); rule.setHandlerList(requestHandlerList); } for (UrlMappingRule rule : arrangedRuleList) { List<UrlMappingRuleRewriter> list = UrlMappingRuleSetHelper.getBeforeSortRuleRewritter(rule); if (list != null) { for (UrlMappingRuleRewriter rewriter : list) { rewriter.rewrite(rule); } } } // sort by priority Collections.sort(arrangedRuleList, new Comparator<UrlMappingRule>() { @Override public int compare(UrlMappingRule r1, UrlMappingRule r2) { int pc = r1.getPriority() - r2.getPriority(); if (pc != 0) { return pc; } else { return r1.getSeq() - r2.getSeq(); } } }); return arrangedRuleList; } public abstract H add(String sourcePath); public abstract T add(String sourcePath, String targetPath); public abstract H add(HttpMethod method, String sourcePath); public abstract T add(HttpMethod method, String sourcePath, String targetPath); public abstract H add(ExtendHttpMethod extendMethod, String sourcePath); public abstract T add(ExtendHttpMethod extendMethod, String sourcePath, String targetPath); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,355,550,986,140,634,000