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
/* * 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.util.i18n; import com.astamuse.asta4d.Configuration; /** * This class is used for retrieving and using configured helper more smoothly. If there is a customized helper implementation, a new * assistant class can be created too just like this one. * * @author e-ryu * */ public class I18nMessageHelperTypeAssistant { public static enum Type { Mapped, Ordered } /** * we do not declare it as final because we will recreate the instance for test purpose */ private static I18nMessageHelperTypeAssistant _instance = new I18nMessageHelperTypeAssistant(); /** * DO NOT USE IT!!! IT IS FOR TEST PURPOSE!!! */ @Deprecated public static void reCreateInternalInstance() { if (System.getProperty("I18nMessageHelperTypeAssistant.Test") != null) { _instance = new I18nMessageHelperTypeAssistant(); } else { throw new UnsupportedOperationException("reCreateInternalInstance() is used for test purpose. DO NOT USE IT!!!"); } } private final Type configuredHelperType; private final MappedParamI18nMessageHelper mappedTypeHelper; private final OrderedParamI18nMessageHelper orderedTypeHelper; private I18nMessageHelperTypeAssistant() { I18nMessageHelper helper = Configuration.getConfiguration().getI18nMessageHelper(); if (helper instanceof MappedParamI18nMessageHelper) { configuredHelperType = Type.Mapped; mappedTypeHelper = (MappedParamI18nMessageHelper) helper; orderedTypeHelper = null; } else if (helper instanceof OrderedParamI18nMessageHelper) { configuredHelperType = Type.Ordered; mappedTypeHelper = null; orderedTypeHelper = (OrderedParamI18nMessageHelper) helper; } else { configuredHelperType = null; mappedTypeHelper = null; orderedTypeHelper = null; } } public static final Type configuredHelperType() { return _instance.configuredHelperType; } public static final MappedParamI18nMessageHelper getConfiguredMappedHelper() { return _instance.mappedTypeHelper; } public static final OrderedParamI18nMessageHelper getConfiguredOrderedHelper() { return _instance.orderedTypeHelper; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,161,635,286,398,682,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.util.i18n; import java.util.Locale; import com.astamuse.asta4d.util.i18n.pattern.JDKResourceBundleMessagePatternRetriever; import com.astamuse.asta4d.util.i18n.pattern.MessagePatternRetriever; /** * The sub class of this class should not return null in all the getMessage methods. Returns empty string or key instead. * * * @author e-ryu * */ public abstract class I18nMessageHelper { private MessagePatternRetriever messagePatternRetriever; public I18nMessageHelper() { this(new JDKResourceBundleMessagePatternRetriever()); } public I18nMessageHelper(MessagePatternRetriever messagePatternRetriever) { this.messagePatternRetriever = messagePatternRetriever; } public MessagePatternRetriever getMessagePatternRetriever() { return messagePatternRetriever; } public void setMessagePatternRetriever(MessagePatternRetriever messagePatternRetriever) { this.messagePatternRetriever = messagePatternRetriever; } /** * retrieve message by given key * * @param key * @return retrieved message, empty string or the given key if message not found(cannot be null) */ public abstract String getMessage(String key); /** * retrieve message by given locale and key * * @param locale * @param key * @return retrieved message, empty string or the given key if message not found(cannot be null) */ public abstract String getMessage(Locale locale, String key); /** * retrieve message by given key * * @param key * @param defaultPattern * @return retrieved message, return defaultPattern#toString() if message not found */ public abstract String getMessageWithDefault(String key, Object defaultPattern); /** * retrieve message by given locale and key * * @param locale * @param key * @param defaultPattern * @return retrieved message, return defaultPattern#toString() if message not found */ public abstract String getMessageWithDefault(Locale locale, String key, Object defaultPattern); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,357,103,275,720,530,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.util.i18n; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.Context; public class LocalizeUtil { public static String[] getCandidatePaths(String path, Locale locale) { int dotIndex = path.lastIndexOf("."); String name = dotIndex > 0 ? path.substring(0, dotIndex) : path; String extension = dotIndex > 0 ? path.substring(dotIndex) : StringUtils.EMPTY; List<String> candidatePathList = new ArrayList<>(); if (!StringUtils.isEmpty(locale.getVariant())) { candidatePathList.add(name + '_' + locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant() + extension); } if (!StringUtils.isEmpty(locale.getCountry())) { candidatePathList.add(name + '_' + locale.getLanguage() + "_" + locale.getCountry() + extension); } if (!StringUtils.isEmpty(locale.getLanguage())) { candidatePathList.add(name + '_' + locale.getLanguage() + extension); } candidatePathList.add(path); return candidatePathList.toArray(new String[candidatePathList.size()]); } public static String createLocalizedKey(String str, Locale locale) { if (StringUtils.isEmpty(locale.toLanguageTag())) { return str; } return str + "::" + locale.toLanguageTag(); } public static Locale getLocale(String localeStr) { if (StringUtils.isEmpty(localeStr)) { return null; } try { return LocaleUtils.toLocale(localeStr); } catch (IllegalArgumentException e) { return null; } } public static final Locale defaultWhenNull(Locale locale) { if (locale == null) { locale = Context.getCurrentThreadContext().getCurrentLocale(); if (locale == null) { locale = Locale.getDefault(); if (locale == null) { locale = Locale.ROOT; } } } return locale; } private LocalizeUtil() { } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,606,982,137,441,608,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.util.i18n; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import com.astamuse.asta4d.util.i18n.formatter.ApacheStrSubstitutorFormatter; import com.astamuse.asta4d.util.i18n.formatter.MappedValueFormatter; /** * Allow format message by a given parameter map, A {@link MappedValueFormatter} is required to supply concrete formatting style and the * default is {@link ApacheStrSubstitutorFormatter} which uses StrSubstitutor from Apache Common lang3. * <p> * * If message is not found for given key(and locale), the key will be treated as default message if the default message is not specified. * * @author e-ryu * @see ApacheStrSubstitutorFormatter */ public class MappedParamI18nMessageHelper extends I18nMessageHelper { private MappedValueFormatter formatter; public MappedParamI18nMessageHelper() { this(new ApacheStrSubstitutorFormatter()); } public MappedParamI18nMessageHelper(MappedValueFormatter formatter) { this.formatter = formatter; } public MappedValueFormatter getFormatter() { return formatter; } @Override public String getMessage(String key) { return getMessageInternal(null, key, null, null); } @Override public String getMessage(Locale locale, String key) { return getMessageInternal(locale, key, null, null); } /** * Retrieve message by given key and format it by given parameter map. * * @param key * @param paramMap * @return */ public String getMessage(String key, Map<String, Object> paramMap) { return getMessageInternal(null, key, null, paramMap); } /** * Retrieve message by given key and format it by given parameter pairs. * * @param key * @param params * @return */ @SuppressWarnings("rawtypes") public String getMessage(String key, Pair... params) { return getMessageInternal(null, key, null, pairToMap(params)); } /** * Retrieve message by given locale and key and format it by given parameter map. * * @param locale * @param key * @param paramMap * @return */ public String getMessage(Locale locale, String key, Map<String, Object> paramMap) { return getMessageInternal(locale, key, null, paramMap); } /** * Retrieve message by given locale and key and format it by given parameter pairs. * * @param locale * @param key * @param params * @return */ @SuppressWarnings("rawtypes") public String getMessage(Locale locale, String key, Pair... params) { return getMessageInternal(locale, key, null, pairToMap(params)); } @Override public String getMessageWithDefault(String key, Object defaultPattern) { return getMessageInternal(null, key, defaultPattern, null); } @Override public String getMessageWithDefault(Locale locale, String key, Object defaultPattern) { return getMessageInternal(locale, key, defaultPattern, null); } /** * Retrieve message by given key and format it by given parameter map. If message is not found, defaultPattern#toString will be used to * generate a default message pattern to be formatted. * * @param key * @param defaultPattern * @param paramMap * @return */ public String getMessageWithDefault(String key, Object defaultPattern, Map<String, Object> paramMap) { return getMessageInternal(null, key, defaultPattern, paramMap); } /** * Retrieve message by given key and format it by given parameter pairs. If message is not found, defaultPattern#toString will be used * to generate a default message pattern to be formatted. * * @param key * @param defaultPattern * @param params * @return */ @SuppressWarnings("rawtypes") public String getMessageWithDefault(String key, Object defaultPattern, Pair... params) { return getMessageInternal(null, key, defaultPattern, pairToMap(params)); } /** * Retrieve message by given locale and key and format it by given parameter map. If message is not found, defaultPattern#toString will * be used to generate a default message pattern to be formatted. * * @param locale * @param key * @param defaultPattern * @param paramMap * @return */ public String getMessageWithDefault(Locale locale, String key, Object defaultPattern, Map<String, Object> paramMap) { return getMessageInternal(locale, key, defaultPattern, paramMap); } /** * Retrieve message by given locale and key and format it by given parameter pairs. If message is not found, defaultPattern#toString * will be used to generate a default message pattern to be formatted. * * @param locale * @param key * @param defaultPattern * @param params * @return */ @SuppressWarnings("rawtypes") public String getMessageWithDefault(Locale locale, String key, Object defaultPattern, Pair... params) { return getMessageInternal(locale, key, defaultPattern, pairToMap(params)); } protected String getMessageInternal(Locale locale, String key, Object defaultPattern, Map<String, Object> paramMap) { String pattern = getMessagePatternRetriever().retrieve(locale, key); if (pattern == null) { pattern = defaultPattern == null ? key : defaultPattern.toString(); } if (StringUtils.isEmpty(pattern)) { return ""; } else { return formatter.format(pattern, paramMap); } } @SuppressWarnings("rawtypes") private Map<String, Object> pairToMap(Pair[] params) { Map<String, Object> map = new HashMap<>(); for (Pair pair : params) { map.put(pair.getKey().toString(), pair.getValue()); } return map; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,792,325,012,561,581,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.util.i18n; import java.text.MessageFormat; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.util.i18n.formatter.JDKMessageFormatFormatter; import com.astamuse.asta4d.util.i18n.formatter.OrderedValueFormatter; /** * Allow format message by a given parameter array. A {@link OrderedValueFormatter} is required to supply concrete formatting style and the * default is {@link JDKMessageFormatFormatter} which uses JDK's {@link MessageFormat} to format message string. * <p> * If message is not found for given key(and locale), the key will be treated as default message if the default message is not specified. * * @author e-ryu * */ public class OrderedParamI18nMessageHelper extends I18nMessageHelper { private OrderedValueFormatter formatter; public OrderedParamI18nMessageHelper() { this(new JDKMessageFormatFormatter()); } public OrderedParamI18nMessageHelper(OrderedValueFormatter formatter) { this.formatter = formatter; } public OrderedValueFormatter getFormatter() { return formatter; } @Override public String getMessage(String key) { return getMessageInternal(null, key, null, null); } @Override public String getMessage(Locale locale, String key) { return getMessageInternal(locale, key, null, null); } /** * Retrieve message by given key and format it by given parameter array. * * @param key * @param params * @return */ public String getMessage(String key, Object... params) { return getMessageInternal(null, key, null, params); } /** * Retrieve message by given locale and key and format it by given parameter array. * * @param locale * @param key * @param params * @return */ public String getMessage(Locale locale, String key, Object... params) { return getMessageInternal(locale, key, null, params); } @Override public String getMessageWithDefault(String key, Object defaultPattern) { return getMessageInternal(null, key, defaultPattern, null); } @Override public String getMessageWithDefault(Locale locale, String key, Object defaultPattern) { return getMessageInternal(locale, key, defaultPattern, null); } /** * Retrieve message by given key and format it by given parameter array.If message is not found, defaultPattern#toString will be used to * generate a default message pattern to be formatted. * * @param key * @param defaultPattern * @param params * @return */ public String getMessageWithDefault(String key, Object defaultPattern, Object... params) { return getMessageInternal(null, key, defaultPattern, params); } /** * Retrieve message by given locale and key and format it by given parameter array.If message is not found, defaultPattern#toString will * be used to generate a default message pattern to be formatted. * * @param locale * @param key * @param defaultPattern * @param params * @return */ public String getMessageWithDefault(Locale locale, String key, Object defaultPattern, Object... params) { return getMessageInternal(locale, key, defaultPattern, params); } protected String getMessageInternal(Locale locale, String key, Object defaultPattern, Object[] params) { String pattern = getMessagePatternRetriever().retrieve(locale, key); if (pattern == null) { pattern = defaultPattern == null ? key : defaultPattern.toString(); } if (StringUtils.isEmpty(pattern)) { return ""; } else { return formatter.format(pattern, params); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,330,366,770,684,036,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.util.i18n.formatter; import java.util.Map; public interface MappedValueFormatter { public String format(String pattern, Map<String, Object> paramMap); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,208,820,716,544,528,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.util.i18n.formatter; public interface OrderedValueFormatter { public String format(String pattern, Object... params); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,033,018,348,127,629,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.util.i18n.formatter; import java.util.Map; import org.apache.commons.lang3.text.StrSubstitutor; /** * A message formatter using Apache common lang3's StrSubstitutor. The variable * name should be wrapped with a pair of braces. * <p> * <i> The quick brown {fox} jumps over the lazy {dog} </i> * <p> * In above statement, the fox and dog will be treated as variable names. The * default escape character is '\'. * * @author e-ryu * */ public class ApacheStrSubstitutorFormatter implements MappedValueFormatter { private String prefix = "{"; private String suffix = "}"; private char escape = '\\'; public void setPrefix(String prefix) { this.prefix = prefix; } public void setSuffix(String suffix) { this.suffix = suffix; } public void setEscape(char escape) { this.escape = escape; } @Override public String format(String pattern, Map<String, Object> paramMap) { StrSubstitutor sub = new StrSubstitutor(paramMap, prefix, suffix, escape); return sub.replace(pattern); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-131,317,237,356,940,770
/* * 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.util.i18n.formatter; import java.text.MessageFormat; /** * Use {@link MessageFormat#format(String, Object...)} to format message * * @author e-ryu * */ public class JDKMessageFormatFormatter implements OrderedValueFormatter { @Override public String format(String pattern, Object... params) { try { return MessageFormat.format(pattern, params); } catch (IllegalArgumentException e) { return pattern; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,132,435,802,283,988,200
/* * 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.util.i18n.formatter; import java.util.MissingFormatArgumentException; /** * Use {@link String#format(String, Object...)} to format message. * * @author e-ryu * */ public class SymbolPlaceholderFormatter implements OrderedValueFormatter { @Override public String format(String pattern, Object... params) { try { return String.format(pattern, params); } catch (MissingFormatArgumentException e) { return pattern; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,918,842,247,022,134,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.util.i18n.pattern; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; public class CharsetResourceBundleFactory implements ResourceBundleFactory { private Charset charset; public CharsetResourceBundleFactory() { this("UTF-8"); } public CharsetResourceBundleFactory(String charset) { this(Charset.forName(charset)); } public CharsetResourceBundleFactory(Charset charset) { this.charset = charset; } public Charset getCharset() { return charset; } public void setCharset(Charset charset) { this.charset = charset; } public void setCharset(String charset) { this.charset = Charset.forName(charset); } protected ResourceBundle.Control createControl() { return new ResourceBundle.Control() { // this method is copied from the parent class @SuppressWarnings("unchecked") @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String bundleName = toBundleName(baseName, locale); ResourceBundle bundle = null; if (format.equals("java.class")) { try { Class<? extends ResourceBundle> bundleClass = (Class<? extends ResourceBundle>) loader.loadClass(bundleName); // If the class isn't a ResourceBundle subclass, throw a // ClassCastException. if (ResourceBundle.class.isAssignableFrom(bundleClass)) { bundle = bundleClass.newInstance(); } else { throw new ClassCastException(bundleClass.getName() + " cannot be cast to ResourceBundle"); } } catch (ClassNotFoundException e) { } } else if (format.equals("java.properties")) { final String resourceName = toResourceName(bundleName, "properties"); final ClassLoader classLoader = loader; final boolean reloadFlag = reload; InputStream stream = null; try { stream = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>() { public InputStream run() throws IOException { InputStream is = null; if (reloadFlag) { URL url = classLoader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { // Disable caches to get fresh data for // reloading. connection.setUseCaches(false); is = connection.getInputStream(); } } } else { is = classLoader.getResourceAsStream(resourceName); } return is; } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } if (stream != null) { try { // Only this line is changed to make it to read properties files as specified charset. bundle = new PropertyResourceBundle(new InputStreamReader(stream, charset)); } finally { stream.close(); } } } else { throw new IllegalArgumentException("unknown format: " + format); } return bundle; } }; } @Override public ResourceBundle retrieveResourceBundle(String baseName, Locale locale) { return ResourceBundle.getBundle(baseName, locale == null ? Locale.getDefault() : locale, createControl()); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,503,764,671,618,157,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.util.i18n.pattern; import java.util.Locale; import java.util.ResourceBundle; public class LatinEscapingResourceBundleFactory implements ResourceBundleFactory { @Override public ResourceBundle retrieveResourceBundle(String baseName, Locale locale) { return ResourceBundle.getBundle(baseName, locale == null ? Locale.getDefault() : locale); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,449,902,200,531,920,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.util.i18n.pattern; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.util.i18n.LocalizeUtil; /** * We allow row splitted messages. For a given key, if there is no corresponding message, we will try to search keys as "key#1", "key#2"... * then combine them as a single message. * * @author e-ryu * */ public class JDKResourceBundleMessagePatternRetriever implements MessagePatternRetriever { private ResourceBundleFactory resourceBundleFactory = new CharsetResourceBundleFactory(); protected String[] resourceNames = new String[0]; public ResourceBundleFactory getResourceBundleFactory() { return resourceBundleFactory; } public void setResourceBundleFactory(ResourceBundleFactory resourceBundleFactory) { this.resourceBundleFactory = resourceBundleFactory; } public void setResourceNames(String... resourceNames) { this.resourceNames = resourceNames.clone(); } @Override public String retrieve(Locale locale, String key) { String pattern = null; for (String resourceName : resourceNames) { try { ResourceBundle resourceBundle = getResourceBundle(resourceName, locale); pattern = retrieveResourceFromBundle(resourceBundle, key); // if the pattern is not found, MissingResourceException will be // thrown and the break will be skipped break; } catch (MissingResourceException e) { // } } return pattern; } protected ResourceBundle getResourceBundle(String resourceName, Locale locale) { Configuration config = Configuration.getConfiguration(); if (!config.isCacheEnable()) { ResourceBundle.clearCache(); } return resourceBundleFactory.retrieveResourceBundle(resourceName, LocalizeUtil.defaultWhenNull(locale)); } /** * In this method, we allow row splitted message. For a given key, if there is no corresponding message, we will try to search keys as * "key#1", "key#2"... then combine them as a single message. * * @param bundle * @param key * @throws MissingResourceException * if no object for the given key can be found * @return */ protected String retrieveResourceFromBundle(ResourceBundle bundle, String key) throws MissingResourceException { String res = null; try { return bundle.getString(key); } catch (MissingResourceException e) { // check if there is a splitted message try { res = bundle.getString(key + "#1"); } catch (MissingResourceException ex) { // we throw the original exception throw e; } StringBuilder sb = new StringBuilder(res.length() * 3); sb.append(res); try { for (int row = 2;/* loop for ever */; row++) { sb.append(bundle.getString(key + "#" + row)); } } catch (MissingResourceException ex) { return sb.toString(); } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,231,966,628,302,001,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.util.i18n.pattern; import java.util.Locale; import java.util.ResourceBundle; public interface ResourceBundleFactory { public ResourceBundle retrieveResourceBundle(String baseName, Locale locale); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,803,271,442,205,826,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.util.i18n.pattern; import java.util.Locale; import com.astamuse.asta4d.util.i18n.I18nMessageHelper; /** * A retriever used by {@link I18nMessageHelper} to retrieve message * * @author e-ryu * */ public interface MessagePatternRetriever { /** * * @param locale * @param key * @return null if no message pattern for the given key can be found */ public String retrieve(Locale locale, String key); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,146,071,038,356,902,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.util.collection; @FunctionalInterface public interface RowConvertor<S, T> { public T convert(int rowIndex, S obj); default public boolean isParallel() { return false; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,748,611,810,042,062,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.util.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; public class ListConvertUtil { // private final static Logger logger = LoggerFactory.getLogger(ListConvertUtil.class); private final static String ParallelListConversionMark = "ParallelListConversionMark##" + ListConvertUtil.class.getName(); private final static ExecutorService ListExecutorService; private final static ExecutorService ParallelFallbackExecutor; static { Configuration conf = Configuration.getConfiguration(); ListExecutorService = conf.getParallelListConvertingExecutorFactory().createExecutorService(); ParallelFallbackExecutor = Executors.newCachedThreadPool(); } private final static <S, T> List<T> _transform(Iterable<S> sourceList, RowConvertor<S, T> convertor) { List<T> newList = new LinkedList<>(); Iterator<S> it = sourceList.iterator(); int idx = 0; while (it.hasNext()) { newList.add(convertor.convert(idx, it.next())); idx++; } return new ArrayList<>(newList); } public final static <S, T> List<T> transform(Iterable<S> sourceList, RowConvertor<S, T> convertor) { if (convertor.isParallel()) { List<Future<T>> futureList = transformToFuture(sourceList, convertor); List<T> newList = new ArrayList<>(futureList.size()); Iterator<Future<T>> it = futureList.iterator(); try { while (it.hasNext()) { newList.add(it.next().get()); } } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } return newList; } else { return _transform(sourceList, convertor); } } public final static <S, T> List<Future<T>> transformToFuture(final Iterable<S> sourceList, final RowConvertor<S, T> convertor) { final Context context = Context.getCurrentThreadContext(); final Configuration conf = Configuration.getConfiguration(); Boolean isInParallelConverting = context.getData(ParallelListConversionMark); // for non-parallel converting, we will force to current thread converting. boolean doParallel = convertor.isParallel(); ParallelRecursivePolicy policy = doParallel ? conf.getRecursivePolicyForParallelConverting() : ParallelRecursivePolicy.CURRENT_THREAD; if (isInParallelConverting != null || !doParallel) {// recursive converting or non-parallel switch (policy) { case EXCEPTION: throw new RuntimeException( "Recursive parallel list converting is forbidden (by default) to avoid deadlock. You can change this policy by Configuration.setRecursivePolicyForParallelListConverting()."); case CURRENT_THREAD: List<T> list = _transform(sourceList, convertor); return transform(list, new RowConvertor<T, Future<T>>() { @Override public Future<T> convert(int rowIndex, final T obj) { return new Future<T>() { @Override public final boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public final boolean isCancelled() { return false; } @Override public final boolean isDone() { return true; } @Override public final T get() throws InterruptedException, ExecutionException { return obj; } @Override public final T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return obj; } }; } }); case NEW_THREAD: return invokeByExecutor(ParallelFallbackExecutor, sourceList, convertor, 2); default: return Collections.emptyList(); } } else {// in non recursive converting Context newContext = context.clone(); newContext.setData(ParallelListConversionMark, Boolean.TRUE); try { return Context.with(newContext, () -> { return invokeByExecutor(ListExecutorService, sourceList, convertor, conf.getNumberLimitOfParallelListConverting()); }); } catch (Exception e) { throw new RuntimeException(e); } } // end else in non recursive } private static <S, T> List<Future<T>> invokeByExecutor(ExecutorService taskService, Iterable<S> sourceList, RowConvertor<S, T> convertor, int maxParallelNumber) { /* * At first, we extract and dispatch the source list elements to slots as following order: * slot 0, slot 1, slot 2, ..., slot n * 0, 1, 2, ..., n-1 * n, n+1, n+2, ..., 2n-1 * . * . * . * xn, xn+1, xn+2, xn+3(last) * * Then we dispatch each slot to executor service to perform the transforming, after that, we build a future list * which contains delegated future which delegate all the future methods to the future of corresponding slot and * then retrieve the corresponding element by calculated index. */ @SuppressWarnings("unchecked") List<S>[] groupedListArray = new List[maxParallelNumber]; for (int i = 0; i < maxParallelNumber; i++) { groupedListArray[i] = new LinkedList<>(); } Iterator<S> srcIt = sourceList.iterator(); int count = 0; while (srcIt.hasNext()) { groupedListArray[count % maxParallelNumber].add(srcIt.next()); count++; } @SuppressWarnings("unchecked") Future<T>[] futureArray = new Future[count]; final Context context = Context.getCurrentThreadContext(); for (int i = 0; i < maxParallelNumber; i++) { List<S> groupedList = groupedListArray[i]; if (groupedList.isEmpty()) { continue; } final Future<List<T>> f = taskService.submit(() -> { return Context.with(context, () -> { // NOTE: this newList must be ArrayList for later retrieving performance List<T> newList = new ArrayList<>(groupedList.size()); Iterator<S> it = groupedList.iterator(); int idx = 0; while (it.hasNext()) { newList.add(convertor.convert(idx, it.next())); idx++; } return newList; }); }); for (int k = 0; k < groupedList.size(); k++) { final int fk = k; futureArray[k * maxParallelNumber + i] = new Future<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return f.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return f.isCancelled(); } @Override public boolean isDone() { return f.isDone(); } @Override public T get() throws InterruptedException, ExecutionException { List<T> list = f.get(); // the list is promised to be ArrayList so that there is no performance issue on get invoking return list.get(fk); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { List<T> list = f.get(timeout, unit); // the list is promised to be ArrayList so that there is no performance issue on get invoking return list.get(fk); } }; } } return Arrays.asList(futureArray); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-108,831,973,577,825,900
package com.astamuse.asta4d.util.collection; import java.util.function.Function; public interface RowConvertorBuilder { public static <S, T> RowConvertor<S, T> map(Function<S, T> mapper) { return new RowConvertor<S, T>() { @Override public T convert(int rowIndex, S obj) { return mapper.apply(obj); } }; } public static <S, T> RowConvertor<S, T> parallel(RowConvertor<S, T> convertor) { return new RowConvertor<S, T>() { @Override public T convert(int rowIndex, S obj) { return convertor.convert(rowIndex, obj); } public boolean isParallel() { return true; } }; } public static <S, T> RowConvertor<S, T> parallel(Function<S, T> mapper) { return new RowConvertor<S, T>() { @Override public T convert(int rowIndex, S obj) { return mapper.apply(obj); } public boolean isParallel() { return true; } }; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,295,622,695,025,626,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.util.collection; public enum ParallelRecursivePolicy { EXCEPTION, CURRENT_THREAD, NEW_THREAD }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,020,212,328,945,522,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.interceptor; import com.astamuse.asta4d.render.Renderer; public interface PageInterceptor { public void prePageRendering(Renderer renderer); public void postPageRendering(Renderer renderer); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-9,089,348,908,734,794,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.interceptor.base; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.util.GroupedException; public class InterceptorUtil { private final static Logger logger = LoggerFactory.getLogger(InterceptorUtil.class); private final static class ExecutorWrapping<H> implements GenericInterceptor<H> { private Executor<H> executor; public ExecutorWrapping(Executor<H> executor) { this.executor = executor; } @Override public boolean beforeProcess(H executionHolder) throws Exception { executor.execute(executionHolder); return true; } @Override public void afterProcess(H exectionHolder, ExceptionHandler ex) { } } public final static <H> void executeWithConvertableInterceptors(H executionHolder, List<GenericInterceptorConvertable<H>> interceptorList, Executor<H> executor) throws Exception { List<GenericInterceptor<H>> runList = new ArrayList<>(); if (interceptorList != null) { for (GenericInterceptorConvertable<H> interceptor : interceptorList) { runList.add(interceptor.asGenericInterceptor()); } } } public final static <H> void executeWithInterceptors(H executionHolder, List<? extends GenericInterceptor<H>> interceptorList, Executor<H> executor) throws Exception { List<GenericInterceptor<H>> runList = new ArrayList<>(); if (interceptorList != null) { runList.addAll(interceptorList); } runList.add(new ExecutorWrapping<>(executor)); ExceptionHandler eh = new ExceptionHandler(); GenericInterceptor<H> lastInterceptor = beforeProcess(executionHolder, runList, eh); afterProcess(lastInterceptor, executionHolder, runList, eh); // if the passed exception has not been cleared, we will throw it // anyway. if (eh.getException() != null) { throw eh.getException(); } } private final static <H> GenericInterceptor<H> beforeProcess(H execution, List<GenericInterceptor<H>> interceptorList, ExceptionHandler eh) throws Exception { GenericInterceptor<H> lastInterceptor = null; for (GenericInterceptor<H> interceptor : interceptorList) { try { if (!interceptor.beforeProcess(execution)) { break; } lastInterceptor = interceptor; } catch (Exception ex) { eh.setException(ex); return lastInterceptor; } } return lastInterceptor; } private final static <H> void afterProcess(GenericInterceptor<H> lastInterceptor, H execution, List<GenericInterceptor<H>> interceptorList, ExceptionHandler eh) { GenericInterceptor<H> interceptor = null; boolean foundStoppedPoint = false; List<Exception> exList = new LinkedList<>(); for (int i = interceptorList.size() - 1; i >= 0; i--) { interceptor = interceptorList.get(i); if (!foundStoppedPoint) { foundStoppedPoint = interceptor == lastInterceptor; } if (foundStoppedPoint) { try { interceptor.afterProcess(execution, eh); } catch (Exception afterEx) { logger.warn("There is an exception occured in after process of interceptors.", afterEx); exList.add(afterEx); } } } // if there are exceptions in after process, we should throw them. if (!exList.isEmpty()) { GroupedException ge = new GroupedException(); ge.setExceptionList(exList); logger.error("There are exception(s) orrcured on after interceptor process", ge); throw ge; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,569,553,727,980,772,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.interceptor.base; public interface GenericInterceptor<H> { public boolean beforeProcess(H executionHolder) throws Exception; public void afterProcess(H executionHolder, ExceptionHandler exceptionHandler); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,017,870,710,854,421,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.interceptor.base; public class ExceptionHandler { private Exception exception; public ExceptionHandler() { } public ExceptionHandler(Exception exception) { super(); this.exception = exception; } public Exception getException() { return exception; } public void setException(Exception exception) { this.exception = exception; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,786,739,290,655,305,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.interceptor.base; public interface Executor<H> { public void execute(H executionHolder) throws Exception; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,906,780,739,219,929,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.interceptor.base; public interface GenericInterceptorConvertable<H> { public GenericInterceptor<H> asGenericInterceptor(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,839,084,219,365,301,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.snippet; public interface InitializableSnippet { public void init() throws SnippetInvokeException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,152,203,256,276,108,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.snippet; import com.astamuse.asta4d.render.Renderer; public interface SnippetInvoker { public Renderer invoke(String renderDeclaration) throws SnippetNotResovlableException, SnippetInvokeException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,712,376,645,860,930,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.snippet; import java.lang.reflect.Method; public class SnippetExcecutionInfo { protected SnippetDeclarationInfo declarationInfo; protected Object instance = null; protected Method method = null; public SnippetExcecutionInfo(SnippetDeclarationInfo declarationInfo, Object instance, Method method) { super(); this.declarationInfo = declarationInfo; this.instance = instance; this.method = method; } public SnippetDeclarationInfo getDeclarationInfo() { return declarationInfo; } public void setDeclarationInfo(SnippetDeclarationInfo declarationInfo) { this.declarationInfo = declarationInfo; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,174,860,892,641,235,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.snippet; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.interceptor.base.Executor; import com.astamuse.asta4d.interceptor.base.InterceptorUtil; import com.astamuse.asta4d.render.RenderUtil; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.snippet.extract.SnippetExtractor; import com.astamuse.asta4d.snippet.interceptor.ContextDataAutowireInterceptor; import com.astamuse.asta4d.snippet.interceptor.SnippetInitializeInterceptor; import com.astamuse.asta4d.snippet.interceptor.SnippetInterceptor; import com.astamuse.asta4d.snippet.resolve.SnippetResolver; public class DefaultSnippetInvoker implements SnippetInvoker { private List<SnippetInterceptor> snippetInterceptorList = getDefaultSnippetInterceptorList(); protected static class InterceptorResult { Renderer renderer = null; SnippetInterceptor finalInterceptor = null; } @Override public Renderer invoke(String renderDeclaration) throws SnippetNotResovlableException, SnippetInvokeException { Configuration conf = Configuration.getConfiguration(); SnippetExtractor extractor = conf.getSnippetExtractor(); SnippetDeclarationInfo declaration = extractor.extract(renderDeclaration); SnippetResolver resolver = conf.getSnippetResolver(); SnippetExcecutionInfo exeInfo = resolver.resloveSnippet(declaration); SnippetExecutionHolder execution = new SnippetExecutionHolder(declaration, exeInfo.getInstance(), exeInfo.getMethod(), null, null); Executor<SnippetExecutionHolder> executor = new Executor<SnippetExecutionHolder>() { @Override public void execute(SnippetExecutionHolder executionHolder) throws Exception { Object instance = executionHolder.getInstance(); Method method = executionHolder.getMethod(); Object[] params = executionHolder.getParams(); if (params == null) { executionHolder.setExecuteResult((Renderer) method.invoke(instance)); } else { executionHolder.setExecuteResult((Renderer) method.invoke(instance, params)); } } }; Context context = Context.getCurrentThreadContext(); try { context.setData(RenderUtil.TRACE_VAR_SNIPPET, execution.getInstance()); InterceptorUtil.executeWithInterceptors(execution, snippetInterceptorList, executor); return execution.getExecuteResult(); } catch (SnippetInvokeException ex) { throw ex; } catch (Exception ex) { String rawMsg = ex instanceof InvocationTargetException ? ((InvocationTargetException) ex).getTargetException().getMessage() : ex.getMessage(); Object[] params = execution.getParams(); String msg = "execute with params:" + (params == null ? null : Arrays.asList(params)) + "."; msg += " The raw exception message is:" + rawMsg; throw new SnippetInvokeException(declaration, msg, ex); } finally { context.setData(RenderUtil.TRACE_VAR_SNIPPET, null); } } protected List<SnippetInterceptor> getDefaultSnippetInterceptorList() { List<SnippetInterceptor> list = new ArrayList<>(); list.add(new ContextDataAutowireInterceptor()); list.add(new SnippetInitializeInterceptor()); return list; } public List<SnippetInterceptor> getSnippetInterceptorList() { return snippetInterceptorList; } public void setSnippetInterceptorList(List<SnippetInterceptor> snippetInterceptorList) { this.snippetInterceptorList.clear(); this.snippetInterceptorList.addAll(getDefaultSnippetInterceptorList()); if (snippetInterceptorList != null) { this.snippetInterceptorList.addAll(snippetInterceptorList); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,139,552,218,558,608,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.snippet; public class SnippetNotResovlableException extends Exception { /** * */ private static final long serialVersionUID = 1639030204768997259L; public SnippetNotResovlableException() { super(); } public SnippetNotResovlableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public SnippetNotResovlableException(String message, Throwable cause) { super(message, cause); } public SnippetNotResovlableException(String message) { super(message); } public SnippetNotResovlableException(Throwable cause) { super(cause); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,963,273,310,316,836,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.snippet; public class SnippetInvokeException extends Exception { /** * */ private static final long serialVersionUID = 115458825987835218L; public SnippetInvokeException(String msg, Throwable cause) { super(msg, cause); } public SnippetInvokeException(SnippetDeclarationInfo declaration, String msg) { super(createMsg(declaration, msg)); } public SnippetInvokeException(SnippetDeclarationInfo declaration) { super(createMsg(declaration, null)); } public SnippetInvokeException(SnippetDeclarationInfo declaration, Throwable cause) { super(createMsg(declaration, null), cause); } public SnippetInvokeException(SnippetDeclarationInfo declaration, String msg, Throwable cause) { super(createMsg(declaration, msg), cause); } private static String createMsg(SnippetDeclarationInfo declaration, String msg) { return "error occured when execute snippet " + declaration.toString() + (msg == null ? "" : " detail:" + msg); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,670,861,394,367,286,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.snippet; import java.lang.reflect.Method; import com.astamuse.asta4d.render.Renderer; public class SnippetExecutionHolder extends SnippetExcecutionInfo { private Object[] params = null; private Renderer executeResult = null; public SnippetExecutionHolder(SnippetDeclarationInfo declarationInfo, Object instance, Method method, Object[] params, Renderer executeResult) { super(declarationInfo, instance, method); this.params = params; this.executeResult = executeResult; } public Object[] getParams() { return params; } public void setParams(Object[] params) { this.params = params; } public Renderer getExecuteResult() { return executeResult; } public void setExecuteResult(Renderer executeResult) { this.executeResult = executeResult; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,688,691,924,521,669,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.snippet; public class SnippetDeclarationInfo { private String snippetName; private String snippetHandler; private int _hashcode; public SnippetDeclarationInfo(String snippetName, String snippetHandler) { super(); this.snippetName = snippetName; this.snippetHandler = snippetHandler; _hashcode = 0; _hashcode += snippetHandler == null ? 0 : snippetHandler.hashCode(); _hashcode += snippetName == null ? 0 : snippetName.hashCode(); } public String getSnippetName() { return snippetName; } public String getSnippetHandler() { return snippetHandler; } @Override public int hashCode() { return _hashcode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SnippetDeclarationInfo other = (SnippetDeclarationInfo) obj; if (snippetHandler == null) { if (other.snippetHandler != null) return false; } else if (!snippetHandler.equals(other.snippetHandler)) return false; if (snippetName == null) { if (other.snippetName != null) return false; } else if (!snippetName.equals(other.snippetName)) return false; return true; } @Override public String toString() { return String.format("[%s:%s]", snippetName, snippetHandler); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,288,235,045,058,416,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.snippet.extract; import java.util.concurrent.ConcurrentHashMap; import com.astamuse.asta4d.snippet.SnippetDeclarationInfo; /** * Extract snippet declaration as the format of "xxx.yyy:zzz", if "zzz" is not specified, "render" will be used. "xxx.yyy" which is before * colon will be treated as snippet name (usually as class name or a id of a certain class) and the part after colon will be treated as * method name. * * Additionally, "::" can be used as separator of method from version 1.1 to keep homogeneous grammar with Java 8's method reference. * * @author e-ryu * */ public class DefaultSnippetExtractor implements SnippetExtractor { private final static ConcurrentHashMap<String, SnippetDeclarationInfo> infoCache = new ConcurrentHashMap<>(); @Override public SnippetDeclarationInfo extract(String renderDeclaration) { SnippetDeclarationInfo info = infoCache.get(renderDeclaration); if (info == null) { info = _extract(renderDeclaration); infoCache.put(renderDeclaration, info); } return info; } private SnippetDeclarationInfo _extract(String renderDeclaration) { String snippetClass, snippetMethod; String[] sa = renderDeclaration.split("::|:"); if (sa.length < 2) { snippetClass = sa[0]; snippetMethod = "render"; } else { snippetClass = sa[0]; snippetMethod = sa[1]; } return new SnippetDeclarationInfo(snippetClass, snippetMethod); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,752,315,400,632,939,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.snippet.extract; import com.astamuse.asta4d.snippet.SnippetDeclarationInfo; public interface SnippetExtractor { public SnippetDeclarationInfo extract(String renderDeclaration); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,958,039,087,205,188,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.snippet.resolve; import com.astamuse.asta4d.snippet.SnippetDeclarationInfo; import com.astamuse.asta4d.snippet.SnippetExcecutionInfo; import com.astamuse.asta4d.snippet.SnippetNotResovlableException; public interface SnippetResolver { public SnippetExcecutionInfo resloveSnippet(SnippetDeclarationInfo declaration) throws SnippetNotResovlableException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,038,814,797,996,693,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.snippet.resolve; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.snippet.SnippetDeclarationInfo; import com.astamuse.asta4d.snippet.SnippetExcecutionInfo; import com.astamuse.asta4d.snippet.SnippetNotResovlableException; import com.astamuse.asta4d.util.MultiSearchPathResourceLoader; public class DefaultSnippetResolver extends MultiSearchPathResourceLoader<Object> implements SnippetResolver { private final static String InstanceMapCacheKey = DefaultSnippetResolver.class.getName() + "##InstanceMapCacheKey"; private final static ConcurrentHashMap<SnippetDeclarationInfo, Method> MethodCache = new ConcurrentHashMap<>(); @Override public SnippetExcecutionInfo resloveSnippet(SnippetDeclarationInfo declaration) throws SnippetNotResovlableException { Object instance = retrieveInstance(declaration); Method method = retrieveMethod(declaration); return new SnippetExcecutionInfo(declaration, instance, method); } protected Object retrieveInstance(SnippetDeclarationInfo declaration) throws SnippetNotResovlableException { String snippetName = declaration.getSnippetName(); Map<String, Object> instanceMap = getCacheMap(InstanceMapCacheKey); Object instance = instanceMap.get(snippetName); if (instance == null) { instance = createInstance(snippetName); instanceMap.put(snippetName, instance); } return instance; } protected Object createInstance(String snippetName) throws SnippetNotResovlableException { try { Object instance = super.searchResource(".", snippetName); if (instance == null) { throw new ClassNotFoundException("Can not found class for snippet name:" + snippetName); } return instance; } catch (Exception ex) { throw new SnippetNotResovlableException(String.format("Snippet [%s] resolve failed.", snippetName), ex); } } @Override protected Object loadResource(String name) { Class<?> clz = null; try { clz = Class.forName(name); } catch (ClassNotFoundException e) { return null; } try { return clz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } protected Method retrieveMethod(SnippetDeclarationInfo declaration) throws SnippetNotResovlableException { Method m = Configuration.getConfiguration().isCacheEnable() ? MethodCache.get(declaration) : null; if (m == null) { Object instance = retrieveInstance(declaration); m = findSnippetMethod(instance, declaration.getSnippetHandler()); if (m == null) { throw new SnippetNotResovlableException("Snippet handler cannot be resolved for " + declaration); } // we do not mind that the exited method instance would be // overrode in multi-threads environment MethodCache.put(declaration, m); } return m; } protected Method findSnippetMethod(Object snippetInstance, String methodName) { Method[] methodList = snippetInstance.getClass().getMethods(); Class<?> rendererCls = Renderer.class; List<Method> namedMtdList = new ArrayList<>(); List<Method> priorMtdList = new ArrayList<>(); for (Method method : methodList) { if (method.getName().equals(methodName) && rendererCls.isAssignableFrom(method.getReturnType())) { namedMtdList.add(method); if (method.getAnnotation(PriorRenderMethod.class) != null) { priorMtdList.add(method); } } } if (priorMtdList.isEmpty()) { if (namedMtdList.isEmpty()) { return null; } else { return namedMtdList.get(namedMtdList.size() - 1); } } else { return priorMtdList.get(priorMtdList.size() - 1); } } private Map<String, Object> getCacheMap(String key) { Context context = Context.getCurrentThreadContext(); Map<String, Object> map = context.getData(key); if (map == null) { map = new HashMap<>(); context.setData(key, map); } return map; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,557,263,556,527,134,700
package com.astamuse.asta4d.snippet.resolve; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PriorRenderMethod { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,483,556,316,122,941,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.snippet.interceptor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.snippet.InitializableSnippet; import com.astamuse.asta4d.snippet.SnippetExecutionHolder; public class SnippetInitializeInterceptor implements SnippetInterceptor { private static class InitializedListHolder { ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); List<Object> snippetList = new ArrayList<>(); } private final static String InstanceListCacheKey = SnippetInitializeInterceptor.class + "##InstanceListCacheKey##"; public static final void initContext(Context context) { context.setData(InstanceListCacheKey, new InitializedListHolder()); } @Override public boolean beforeProcess(SnippetExecutionHolder execution) throws Exception { Context context = Context.getCurrentThreadContext(); // the list would not be null InitializedListHolder listHolder = context.getData(InstanceListCacheKey); Object target = execution.getInstance(); boolean inialized = false; listHolder.lock.readLock().lock(); try { for (Object initializedSnippet : listHolder.snippetList) { if (initializedSnippet == target) { inialized = true; break; } } } finally { listHolder.lock.readLock().unlock(); } if (!inialized) { // retrieve write lock listHolder.lock.writeLock().lock(); try { // check again for (Object initializedSnippet : listHolder.snippetList) { if (initializedSnippet == target) { inialized = true; break; } } // do the initialization if (!inialized) { InjectUtil.injectToInstance(target); if (target instanceof InitializableSnippet) { ((InitializableSnippet) target).init(); } listHolder.snippetList.add(target); } } finally { listHolder.lock.writeLock().unlock(); } } return true; } @Override public void afterProcess(SnippetExecutionHolder execution, ExceptionHandler exceptionHandler) { } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,710,204,151,522,373,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.snippet.interceptor; import com.astamuse.asta4d.data.DataOperationException; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.snippet.SnippetExecutionHolder; import com.astamuse.asta4d.snippet.SnippetInvokeException; public class ContextDataAutowireInterceptor implements SnippetInterceptor { @Override public boolean beforeProcess(SnippetExecutionHolder execution) throws Exception { try { Object[] params = InjectUtil.getMethodInjectParams(execution.getMethod()); execution.setParams(params); return true; } catch (DataOperationException e) { throw new SnippetInvokeException(execution.getDeclarationInfo(), e); } } @Override public void afterProcess(SnippetExecutionHolder execution, ExceptionHandler exceptionHandler) { } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,871,601,104,498,554,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.snippet.interceptor; import com.astamuse.asta4d.interceptor.base.GenericInterceptor; import com.astamuse.asta4d.snippet.SnippetExecutionHolder; public interface SnippetInterceptor extends GenericInterceptor<SnippetExecutionHolder> { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,831,569,436,741,937,000
package com.astamuse.asta4d.template; public interface TemplateResolver { /** * * @param path * @return * @throws TemplateException * error occurs when parsing template file * @throws TemplateNotFoundException * template file does not exist */ public Template findTemplate(String path) throws TemplateException, TemplateNotFoundException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,224,944,538,486,740,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.template; public class TemplateNotFoundException extends Exception { /** * */ private static final long serialVersionUID = 1L; public TemplateNotFoundException(String path) { super("Template [" + path + "] does not exist."); } public TemplateNotFoundException(String path, String extraMsg) { super("Template [" + path + "] does not exist." + extraMsg); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,486,818,216,101,870,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.template; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.extnode.ExtNode; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.util.IdGenerator; import com.astamuse.asta4d.util.SelectorUtil; public class TemplateUtil { private static class SnippetNode extends ExtNode { /** * * @param renderer * a plain text renderer declaration */ public SnippetNode(String renderer) { super(ExtNodeConstants.SNIPPET_NODE_TAG); this.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_READY); this.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_RENDER, renderer); } } private final static Logger logger = LoggerFactory.getLogger(TemplateUtil.class); public final static void regulateElement(String path, Document doc) throws TemplateException, TemplateNotFoundException { // disabled. see {@link #loadStaticEmebed} // load static embed at first // loadStaticEmebed(doc); regulateSnippets(path, doc); regulateMsgs(path, doc); regulateEmbed(doc); } private final static String createSnippetRef() { return "sn-" + IdGenerator.createId(); } private final static void regulateMsgs(String path, Document doc) { List<Element> msgElems = doc.select(ExtNodeConstants.MSG_NODE_TAG_SELECTOR); for (Element element : msgElems) { // record template path if (!element.hasAttr(ExtNodeConstants.ATTR_TEMPLATE_PATH)) { element.attr(ExtNodeConstants.ATTR_TEMPLATE_PATH, path); } } } private final static void regulateSnippets(String path, Document doc) { // find nodes emebed with snippet attribute String snippetSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_RENDER_WITH_NS); snippetSelector = SelectorUtil.not(snippetSelector, ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR); List<Element> embedSnippets = new ArrayList<>(doc.select(snippetSelector)); // Element // Node parent; SnippetNode fakedSnippetNode; String render; for (Element element : embedSnippets) { render = element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_RENDER_WITH_NS); fakedSnippetNode = new SnippetNode(render); fakedSnippetNode.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE, ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE); // move the original node under the faked node element.after(fakedSnippetNode); element.remove(); fakedSnippetNode.appendChild(element); element.removeAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_RENDER_WITH_NS); // set parallel type if (element.hasAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_PARALLEL_WITH_NS)) { fakedSnippetNode.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_PARALLEL, ""); element.removeAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_PARALLEL_WITH_NS); } } /* * set all the nodes without status attribute or with an illegal status * value to ready */ // first, we regulate the snippets to legal form List<Element> snippetNodes = doc.select(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR); String status; for (Element sn : snippetNodes) { // record template path if (!sn.hasAttr(ExtNodeConstants.ATTR_TEMPLATE_PATH)) { sn.attr(ExtNodeConstants.ATTR_TEMPLATE_PATH, path); } // regulate status if (sn.hasAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS)) { status = sn.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS); switch (status) { case ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_READY: case ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_WAITING: case ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED: // do nothing; break; default: sn.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_READY); } } else { sn.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_READY); } // regulate id if (!sn.hasAttr(ExtNodeConstants.ATTR_SNIPPET_REF)) { sn.attr(ExtNodeConstants.ATTR_SNIPPET_REF, createSnippetRef()); } // regulate type if (!sn.hasAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE)) { sn.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE, ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_USERDEFINE); } switch (sn.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE)) { case ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE: case ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_USERDEFINE: // do nothing; break; default: // we do not allow snippet node has user customized type // attribute sn.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE, ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_USERDEFINE); } } // then let us check the nested relation for nodes without block attr snippetSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_BLOCK); snippetSelector = SelectorUtil.not(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, snippetSelector); snippetNodes = doc.select(snippetSelector); setBlockingParentSnippetId(snippetNodes); } private final static void regulateEmbed(Document doc) throws TemplateException, TemplateNotFoundException { // check nodes without block attr for blocking parent snippets String selector = SelectorUtil.attr(ExtNodeConstants.EMBED_NODE_ATTR_BLOCK); selector = SelectorUtil.not(ExtNodeConstants.EMBED_NODE_TAG_SELECTOR, selector); List<Element> embedElemes = doc.select(selector); setBlockingParentSnippetId(embedElemes); } /** * Disabled static embed at 2014.09.26. * * Developers would like to use different snippets to render a same static embed file as following: * * <pre> * &lt;afd:snippet render="SomeSnippet"&gt; * &lt;afd:embed target="/someEmbed.html" static/&gt; * &lt;/afd:snippet&gt; * </pre> * * Which confuses rendering logic and makes bad source smell, thus we decide to disable this feature. * * @param doc * @throws TemplateException * @throws TemplateNotFoundException */ @SuppressWarnings("unused") @Deprecated private final static void loadStaticEmebed(Document doc) throws TemplateException, TemplateNotFoundException { String selector = SelectorUtil.attr(SelectorUtil.tag(ExtNodeConstants.EMBED_NODE_TAG_SELECTOR), ExtNodeConstants.EMBED_NODE_ATTR_STATIC, null); int embedNodeListCount; do { List<Element> embedNodeList = doc.select(selector); embedNodeListCount = embedNodeList.size(); Iterator<Element> embedNodeIterator = embedNodeList.iterator(); Element embed; Element embedContent; while (embedNodeIterator.hasNext()) { embed = embedNodeIterator.next(); embedContent = getEmbedNodeContent(embed); mergeBlock(doc, embedContent); embed.before(embedContent); embed.remove(); } } while (embedNodeListCount > 0); } private final static void setBlockingParentSnippetId(List<Element> elems) { Element searchElem; String blockingParentId; for (Element elem : elems) { searchElem = elem.parent(); blockingParentId = ""; while (searchElem != null) { if (searchElem.tagName().equals(ExtNodeConstants.SNIPPET_NODE_TAG)) { blockingParentId = searchElem.attr(ExtNodeConstants.ATTR_SNIPPET_REF); break; } else { searchElem = searchElem.parent(); } } elem.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_BLOCK, blockingParentId); // TODO should we replace the blocked element to a dummy place // holder element to avoid being rendered by parent snippets } } public final static void resetSnippetRefs(Element elem) { String snippetRefSelector = SelectorUtil.attr(ExtNodeConstants.ATTR_SNIPPET_REF); List<Element> snippets = new ArrayList<>(elem.select(snippetRefSelector)); String oldRef, newRef; String blockedSnippetSelector; List<Element> blockedSnippets; for (Element element : snippets) { oldRef = element.attr(ExtNodeConstants.ATTR_SNIPPET_REF); newRef = createSnippetRef(); // find blocked snippet blockedSnippetSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, ExtNodeConstants.SNIPPET_NODE_ATTR_BLOCK, oldRef); blockedSnippets = new ArrayList<>(elem.select(blockedSnippetSelector)); // find blocked embed blockedSnippetSelector = SelectorUtil.attr(ExtNodeConstants.EMBED_NODE_TAG_SELECTOR, ExtNodeConstants.SNIPPET_NODE_ATTR_BLOCK, oldRef); blockedSnippets.addAll(elem.select(blockedSnippetSelector)); for (Element be : blockedSnippets) { be.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_BLOCK, newRef); } element.attr(ExtNodeConstants.ATTR_SNIPPET_REF, newRef); } } public final static Element getEmbedNodeContent(Element elem) throws TemplateException { String target; Configuration conf = Configuration.getConfiguration(); TemplateResolver templateResolver = conf.getTemplateResolver(); target = elem.attr(ExtNodeConstants.EMBED_NODE_ATTR_TARGET); if (target == null || target.isEmpty()) { String message = "Target not defined[" + elem.toString() + "]"; throw new TemplateException(message); } Template embedTarget; try { embedTarget = templateResolver.findTemplate(target); } catch (TemplateNotFoundException e) { throw new TemplateException(e); } // TODO all of the following process should be merged into template // analyze process and be cached. Document embedDoc = embedTarget.getDocumentClone(); /* Elements children = embedDoc.body().children(); Element wrappingNode = ElementUtil.wrapElementsToSingleNode(children); */ Element wrappingNode = new GroupNode(ExtNodeConstants.GROUP_NODE_ATTR_TYPE_EMBED_WRAPPER); // retrieve all the blocks that misincluded into head Element head = embedDoc.head(); Elements headChildren = head.children(); for (Element child : headChildren) { if (StringUtil.in(child.tagName(), "script", "link", ExtNodeConstants.BLOCK_NODE_TAG)) { child.remove(); wrappingNode.appendChild(child); } } Element body = embedDoc.body(); Elements bodyChildren = body.children(); wrappingNode.insertChildren(-1, bodyChildren); // copy all the attrs to the wrapping group node Iterator<Attribute> attrs = elem.attributes().iterator(); Attribute attr; while (attrs.hasNext()) { attr = attrs.next(); wrappingNode.attr(attr.getKey(), attr.getValue()); } // a embed template file may by included many times in same parent // template, so we have to avoid duplicated snippet refs resetSnippetRefs(wrappingNode); return wrappingNode; } public final static void mergeBlock(Document doc, Element content) { Iterator<Element> blockIterator = content.select(ExtNodeConstants.BLOCK_NODE_TAG_SELECTOR).iterator(); Element block, targetBlock; String blockTarget, blockType; List<Node> childNodes; while (blockIterator.hasNext()) { block = blockIterator.next(); if (block.hasAttr(ExtNodeConstants.BLOCK_NODE_ATTR_OVERRIDE)) { blockType = ExtNodeConstants.BLOCK_NODE_ATTR_OVERRIDE; } else if (block.hasAttr(ExtNodeConstants.BLOCK_NODE_ATTR_APPEND)) { blockType = ExtNodeConstants.BLOCK_NODE_ATTR_APPEND; } else if (block.hasAttr(ExtNodeConstants.BLOCK_NODE_ATTR_INSERT)) { blockType = ExtNodeConstants.BLOCK_NODE_ATTR_INSERT; } else if (!block.hasAttr("id")) { // TODO I want a approach to logging out template file path here logger.warn("The block does not declare its action or id correctlly.[{}]", block.toString()); continue; } else { continue; } blockTarget = block.attr(blockType); if (blockTarget == null || blockTarget.isEmpty()) { // TODO I want a approach to logging out template file path here logger.warn("The block does not declare its target action correctlly.[{}]", block.toString()); continue; } targetBlock = doc.select(SelectorUtil.id(ExtNodeConstants.BLOCK_NODE_TAG_SELECTOR, blockTarget)).first(); if (targetBlock == null) { // TODO I want a approach to logging out template file path here logger.warn("The block declares a not existed target block.[{}]", block.toString()); continue; } childNodes = new ArrayList<>(block.childNodes()); switch (blockType) { case ExtNodeConstants.BLOCK_NODE_ATTR_OVERRIDE: targetBlock.empty(); targetBlock.insertChildren(-1, childNodes); break; case ExtNodeConstants.BLOCK_NODE_ATTR_APPEND: targetBlock.insertChildren(-1, childNodes); break; case ExtNodeConstants.BLOCK_NODE_ATTR_INSERT: targetBlock.insertChildren(0, childNodes); break; } block.remove(); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
929,886,801,481,647,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.template; import java.io.IOException; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.util.ElementUtil; import com.astamuse.asta4d.util.IdGenerator; import com.astamuse.asta4d.util.SelectorUtil; public class Template { private String path; private Document doc = null; /** * * @param path * the actual template path * * @param input * @throws IOException */ public Template(String path, Document doc) throws TemplateException, TemplateNotFoundException { this.path = path; this.doc = doc; initDocument(); } private void initDocument() throws TemplateException, TemplateNotFoundException { clearCommentNode(); processExtension(); TemplateUtil.regulateElement(path, doc); } private void clearCommentNode() throws TemplateException { String commentSelector = SelectorUtil.tag(ExtNodeConstants.COMMENT_NODE_TAG); ElementUtil.removeNodesBySelector(doc, commentSelector, false); } private void processExtension() throws TemplateException, TemplateNotFoundException { Element extension = doc.select(ExtNodeConstants.EXTENSION_NODE_TAG_SELECTOR).first(); if (extension != null) { String parentPath = extension.attr(ExtNodeConstants.EXTENSION_NODE_ATTR_PARENT); if (parentPath == null || parentPath.isEmpty()) { throw new TemplateException(String.format("You must specify the parent of an extension (%s).", this.path)); } Configuration conf = Configuration.getConfiguration(); Template parent = conf.getTemplateResolver().findTemplate(parentPath); Document parentDoc = parent.getDocumentClone(); TemplateUtil.mergeBlock(parentDoc, extension); doc = parentDoc; } } public String getPath() { return path; } public Document getDocumentClone() { Document newDoc = doc.clone(); newDoc.attr(ExtNodeConstants.ATTR_DOC_REF, "doc-" + IdGenerator.createId()); return newDoc; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,078,663,537,744,907,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.template; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.parser.Asta4DTagSupportHtmlTreeBuilder; import org.jsoup.parser.Parser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.template.AbstractTemplateResolver.TemplateInfo; 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; public abstract class AbstractTemplateResolver extends MultiSearchPathResourceLoader<TemplateInfo>implements TemplateResolver { private final MemorySafeResourceCache<String, Template> defaultTemplateCache = new MemorySafeResourceCache<String, Template>(); private Logger logger = LoggerFactory.getLogger(this.getClass()); private MemorySafeResourceCache<String, Template> retrieveTemplateCache() { Context context = Context.getCurrentThreadContext(); Configuration conf = Configuration.getConfiguration(); if (conf.isCacheEnable()) { return defaultTemplateCache; } else { // for debug, if we do not cache it in context, some templates will // be probably initialized for hundreds times // thus there will be hundreds logs of template initializing in info // level. String key = this.getClass().getName() + "##template-cache-map"; MemorySafeResourceCache<String, Template> contextCachedMap = context.getData(key); if (contextCachedMap == null) { contextCachedMap = new MemorySafeResourceCache<>(); context.setData(key, contextCachedMap); } return contextCachedMap; } } /** * * @param path * @return * @throws TemplateException * error occurs when parsing template file * @throws TemplateNotFoundException * template file does not exist */ public Template findTemplate(String path) throws TemplateException, TemplateNotFoundException { try { MemorySafeResourceCache<String, Template> templateCache = retrieveTemplateCache(); Locale locale = LocalizeUtil.defaultWhenNull(null); String cacheKey = LocalizeUtil.createLocalizedKey(path, locale); ResouceHolder<Template> resource = templateCache.get(cacheKey); if (resource != null) { if (resource.exists()) { return resource.get(); } else { throw new TemplateNotFoundException(path); } } logger.info("Initializing template " + path); TemplateInfo info = searchResource("/", LocalizeUtil.getCandidatePaths(path, locale)); if (info == null) { templateCache.put(cacheKey, null); throw new TemplateNotFoundException(path); } InputStream input = info.getInput(); if (input == null) { templateCache.put(cacheKey, null); throw new TemplateNotFoundException(path); } try { Template t = createTemplate(info); templateCache.put(cacheKey, t); return t; } finally { // we have to close the input stream to avoid file lock try { input.close(); } catch (Exception ex) { logger.error("Error occured when close input stream of " + info.getActualPath(), ex); } } } catch (TemplateNotFoundException e) { throw e; } catch (Exception e) { throw new TemplateException(path + " resolve error", e); } } protected Template createTemplate(TemplateInfo templateInfo) throws TemplateException, TemplateNotFoundException { try { Document doc = parse(templateInfo.getInput()); return new Template(templateInfo.getActualPath(), doc); } catch (IOException e) { String msg = String.format("Template %s parsing failed.", templateInfo.getActualPath()); throw new TemplateException(msg, e); } } protected Document parse(InputStream input) throws IOException { return Jsoup.parse(input, "UTF-8", "", new Parser(new Asta4DTagSupportHtmlTreeBuilder())); } protected TemplateInfo createTemplateInfo(String path, InputStream input) { if (input == null) { return null; } return new TemplateInfo(path, input); } public static class TemplateInfo { private final String actualPath; private final InputStream input; public TemplateInfo(String path, InputStream input) { this.actualPath = path; this.input = input; } public String getActualPath() { return actualPath; } public InputStream getInput() { return input; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,337,936,756,410,014,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.template; /** * This template resolver is mostly used by test. However if you'd like to put your template files in your source folder, you can use this * resolver as well. * * @author e-ryu * */ public class ClasspathTemplateResolver extends AbstractTemplateResolver { @Override public TemplateInfo loadResource(String path) { return createTemplateInfo(path, this.getClass().getResourceAsStream(path)); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,202,041,900,951,846,100
/* * 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.template; import java.io.FileInputStream; import java.io.FileNotFoundException; public class FileTemplateResolver extends AbstractTemplateResolver { @Override protected TemplateInfo loadResource(String path) { try { return createTemplateInfo(path, new FileInputStream(path)); } catch (FileNotFoundException e) { return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,742,082,123,914,628,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.template; public class TemplateException extends Exception { /** * */ private static final long serialVersionUID = 365824897144710952L; public TemplateException() { } public TemplateException(String message) { super(message); } public TemplateException(Throwable cause) { super(cause); } public TemplateException(String message, Throwable cause) { super(message, cause); } public TemplateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,139,834,305,777,376,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.render; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.transformer.ElementSetterTransformer; public abstract class ElementNotFoundHandler extends Renderer { private final static ElementSetterTransformer DoNothingTransformer = new ElementSetterTransformer(new ElementSetter() { @Override public void set(Element elem) { // do nothing } }); public ElementNotFoundHandler(String selector) { super(selector, DoNothingTransformer); } @Override RendererType getRendererType() { return RendererType.ELEMENT_NOT_FOUND_HANDLER; } @Override public String toString() { return "ElementNotFoundHandler"; } public abstract Renderer alternativeRenderer(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,664,863,882,731,237,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.render; /** * A callback interface that allows delay the rendering logic until the real rendering is required * * @author e-ryu * */ @FunctionalInterface public interface Renderable { public Renderer render(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,228,838,127,704,260,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.render; public class RendererTestHelper { public static RendererType getRendererType(Renderer renderer) { return renderer.getRendererType(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,100,119,463,619,156,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.render; import org.jsoup.nodes.Element; /** * An ElementSetter is to be used to reset an element, including attribute setting and any child nodes operations. * * @author e-ryu * */ @FunctionalInterface public interface ElementSetter { /** * reset the passed element * * @param elem * target element */ public void set(Element elem); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,913,292,599,661,994,800
/* * 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.render; import java.util.function.Function; /** * * @author e-ryu * */ @FunctionalInterface public interface RowRenderer<S> extends Function<S, Renderer> { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,093,543,774,814,153,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.render; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jsoup.nodes.Element; import org.slf4j.Logger; import com.astamuse.asta4d.Component; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.render.transformer.ElementSetterTransformer; import com.astamuse.asta4d.render.transformer.ElementTransformer; import com.astamuse.asta4d.render.transformer.RenderableTransformer; import com.astamuse.asta4d.render.transformer.RendererTransformer; import com.astamuse.asta4d.render.transformer.Transformer; import com.astamuse.asta4d.render.transformer.TransformerFactory; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; import com.astamuse.asta4d.util.collection.RowConvertorBuilder; /** * A renderer is for describing rendering actions. * <p> * Developers usually do not need to create a Renderer by constructors directly, alternatively a renderer can be created by calling the * static {@code create} methods or the {@code add} methods. * * * @author e-ryu * */ public class Renderer { private final static boolean saveCallstackInfo; static { saveCallstackInfo = Configuration.getConfiguration().isSaveCallstackInfoOnRendererCreation(); } private String selector; private List<Transformer<?>> transformerList; private List<Renderer> chain; private String creationSiteInfo = null; /** * Create a Renderer by given css selector and {@link Transformer} * * @param selector * a selector that describes the rendering target element * @param transformer * the action that describes how to render the target element */ public Renderer(String selector, Transformer<?> transformer) { List<Transformer<?>> list = new ArrayList<>(); list.add(transformer); init(selector, list); } /** * Create a Renderer by given css selector and List of {@link Transformer}. By given a list, the target element will be duplicated to * the same count of Transformer list size. * * @param selector * a selector that describes the rendering target element * @param transformerList * the action list that describes how to render the target element */ public Renderer(String selector, List<Transformer<?>> transformerList) { init(selector, transformerList); } private void init(String selector, List<Transformer<?>> transformerList) { if (selector == null) { throw new NullPointerException("selector cannot be null"); } this.selector = selector; this.transformerList = transformerList; chain = new ArrayList<>(); chain.add(this); if (saveCallstackInfo) { StackTraceElement[] Stacks = Thread.currentThread().getStackTrace(); StackTraceElement callSite = null; boolean myClsStarted = false; for (StackTraceElement stackTraceElement : Stacks) { Class cls; try { cls = Class.forName(stackTraceElement.getClassName()); if (cls.getPackage().getName().startsWith("com.astamuse.asta4d.render")) { myClsStarted = true; continue; } else if (myClsStarted) { callSite = stackTraceElement; break; } } catch (ClassNotFoundException e) { continue; } } if (callSite != null) { creationSiteInfo = callSite.toString(); } } } public String getSelector() { return selector; } public List<Transformer<?>> getTransformerList() { return transformerList; } @Override public String toString() { return "\n\"" + selector + "\"#>\n{" + this.transformerList + "}\n\n"; } RendererType getRendererType() { return RendererType.COMMON; } String getCreationSiteInfo() { return creationSiteInfo; } /** * Get list of all the renderers hold by the current renderer * * @return an unmodifiable list of renderers */ public List<Renderer> asUnmodifiableList() { return Collections.unmodifiableList(new ArrayList<>(this.chain)); } /** * add a renderer to the current renderer as a list * * @param renderer * a renderer * @return the parameter renderer for chain calling */ public Renderer add(Renderer renderer) { this.chain.addAll(renderer.chain); for (Renderer r : renderer.chain) { r.chain = this.chain; } return renderer; } /** * See {@link #add(String, String)}. * * @param selector * a css selector * @param value * a long value that will be treated as a String * @return the created renderer for chain calling */ public Renderer add(String selector, Long value) { return add(create(selector, value)); } /** * See {@link #add(String, String)}. * * @param selector * a css selector * @param value * an int value that will be treated as a String * @return the created renderer for chain calling */ public Renderer add(String selector, Integer value) { return add(create(selector, value)); } /** * See {@link #add(String, String)}. * * @param selector * a css selector * @param value * a boolean value that will be treated as a String * @return the created renderer for chain calling */ public Renderer add(String selector, Boolean value) { return add(create(selector, value)); } /** * Create a renderer for text rendering by given parameter and add it to the current renderer. See {@link #create(String, String)}. * * @param selector * a css selector * @param value * a String value that will be rendered * @return the created renderer for chain calling */ public Renderer add(String selector, String value) { return add(create(selector, value)); } /** * Create a renderer for given value and add it to the current renderer. See {@link #create(String, Object)}. * * @param selector * a css selector * @param value * a Object value that will be rendered * @return the created renderer for chain calling */ public Renderer add(String selector, Object value) { return add(create(selector, value)); } /** * Create a renderer for predefined {@link SpecialRenderer}s. * * @param selector * a css selector * @param specialRenderer * a predefined special renderer * @return the created renderer for chain calling */ public Renderer add(String selector, SpecialRenderer specialRenderer) { return add(create(selector, specialRenderer)); } /** * See {@link #add(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a long value that will be treated as a String value * @return the created renderer for chain calling */ public Renderer add(String selector, String attr, Long value) { return add(create(selector, attr, value)); } /** * See {@link #add(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * an int value that will be treated as a String value * @return the created renderer for chain calling */ public Renderer add(String selector, String attr, Integer value) { return add(create(selector, attr, value)); } /** * See {@link #add(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a boolean value that will be treated as a String value * @return the created renderer for chain calling */ public Renderer add(String selector, String attr, Boolean value) { return add(create(selector, attr, value)); } /** * Create a renderer for attribute setting by given parameter and add it to the current renderer. See * {@link #create(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a String value that will be treated as the attribute value * @return the created renderer for chain calling */ public Renderer add(String selector, String attr, String value) { return add(create(selector, attr, value)); } /** * Create a renderer for attribute setting by given parameter and add it to the current renderer. See * {@link #create(String, String, Object)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a Object value that will be treated as the attribute value * @return the created renderer for chain calling */ public Renderer add(String selector, String attr, Object value) { return add(create(selector, attr, value)); } /** * Create a renderer for element rendering by given parameter and add it to the current renderer. See {@link #create(String, Element)}. * * @param selector * a css selector * @param elem * a element that to be rendered * @return the created renderer for chain calling */ public Renderer add(String selector, Element elem) { return add(create(selector, elem)); } /** * Create a renderer for {@link Component} rendering by given parameter and add it to the current renderer. See * {@link #create(String, Component)}. * * @param selector * a css selector * @param component * a component that to be rendered * @return the created renderer for chain calling */ public Renderer add(String selector, Component component) { return add(create(selector, component)); } /** * Create a renderer for element setting by given parameter and add it to the current renderer. See * {@link #create(String, ElementSetter)}. * * @param selector * a css selector * @param setter * an ElementSetter * @return the created renderer for chain calling */ public Renderer add(String selector, ElementSetter setter) { return add(create(selector, setter)); } /** * Create a renderer for delayed rendering callback. See {@link #create(String, Renderable)}. * * @param selector * a css selector * @param Renderable * a callback instance of * * @return the created renderer */ public Renderer add(String selector, Renderable renderable) { return add(create(selector, renderable)); } /** * Create a renderer for recursive renderer rendering by given parameter and add it to the current renderer. See * {@link #create(String, Renderer)}. * * @param selector * a css selector * @param renderer * a renderer * @return the created renderer for chain calling */ public Renderer add(String selector, Renderer renderer) { return add(create(selector, renderer)); } /** * Create a renderer for list rendering by given {@link Stream} and add it to the current renderer. See {@link #create(String, Stream)}. * * <p> * * <b>Note:Parallel stream is not supported due to the potential thread dead lock(https://bugs.openjdk.java.net/browse/JDK-8042758) * which is commented as not a bug by Oracle. For parallel rendering ,use {@link RowConvertorBuilder#parallel(Function)}/ * {@link RowConvertorBuilder#parallel(RowConvertor)} instead. </b> * * @param selector * a css selector * @param stream * a non-parallel stream with arbitrary type data * @return the created renderer for chain calling * */ public Renderer add(String selector, Stream<?> stream) { return add(create(selector, stream)); } /** * Create a renderer for list rendering by given parameter and add it to the current renderer. See {@link #create(String, Iterable)}. * * @param selector * a css selector * @param list * a list that can contain all the types that supported by the non-list add methods of Renderer. * @return the created renderer for chain calling */ public Renderer add(String selector, Iterable<?> list) { return add(create(selector, list)); } /** * Create a renderer for list rendering by given parameter with given {@link RowConvertor} and add it to the current renderer. See * {@link #create(String, Iterable, RowConvertor)}. * * @param selector * @param list * @param convertor * @return the created renderer for chain calling */ public <S, T> Renderer add(String selector, Iterable<S> list, RowConvertor<S, T> convertor) { return add(create(selector, list, convertor)); } /** * Create a renderer for list rendering by given parameter with given {@link RowConvertor} and add it to the current renderer. See * {@link #create(String, Iterable, Function )}. * * @param selector * @param list * @param mapper * @return */ public <S, T> Renderer add(String selector, Iterable<S> list, Function<S, T> mapper) { return add(create(selector, list, mapper)); } /** * add a {@link DebugRenderer} to the current Renderer and when this renderer is applied, the target element specified by the given * selector will be output by given logger. * * @param logger * the logger used to output target element * @param logMessage * a mark message will be output before the target element * @param selector * a css selector to specify the log target * * @return the created renderer or the current renderer for chain calling */ public Renderer addDebugger(Logger logger, String logMessage, String selector) { return logger.isDebugEnabled() ? add(create(selector, new DebugRenderer(logger, logMessage))) : this; } /** * add a {@link DebugRenderer} to the current Renderer and when this renderer is applied, the current rendering element (commonly the * entry element of the current rendering method, see {@link Context#setCurrentRenderingElement(Element)}) will be output by given * logger. * * * @param logger the logger used to output target element * * @param logMessage * a mark message will be output before the target element * * @return the created renderer or the current renderer for chain calling */ public Renderer addDebugger(Logger logger, String logMessage) { return logger.isDebugEnabled() ? add(new DebugRenderer(logger, logMessage)) : this; } /** * add a {@link DebugRenderer} to the current Renderer and when this renderer is applied, the target element specified by the given * selector will be output by default inner logger. * * @param logMessage * a mark message will be output before the target element * @param selector * a css selector to specify the log target * * @return the created renderer or the current renderer for chain calling * @see #addDebugger(Logger, String, String) */ public Renderer addDebugger(String logMessage, String selector) { return addDebugger(DebugRenderer.DefaultLogger, logMessage, selector); } /** * add a {@link DebugRenderer} to the current Renderer and when this renderer is applied, the current rendering element (commonly the * entry element of the current rendering method, see {@link Context#setCurrentRenderingElement(Element)}) will be output by default * inner logger. * * @param logMessage * a mark message will be output before the target element * * @return the created renderer or the current renderer for chain calling * @see #addDebugger(Logger, String) */ public Renderer addDebugger(String logMessage) { return addDebugger(DebugRenderer.DefaultLogger, logMessage); } /** * See {@link #create(String, String)}. * * @param selector * a css selector * @param value * a long value that will be treated as a String * @return the created renderer */ public final static Renderer create(String selector, Long value) { if (value == null) { return new Renderer(selector, new ElementRemover()); } else { return create(selector, new TextSetter(value)); } } /** * See {@link #create(String, String)}. * * @param selector * a css selector * @param value * an int value that will be treated as a String * @return the created renderer */ public final static Renderer create(String selector, Integer value) { if (value == null) { return new Renderer(selector, new ElementRemover()); } else { return create(selector, new TextSetter(value)); } } /** * See {@link #create(String, String)}. * * @param selector * a css selector * @param value * a boolean value that will be treated as a String * @return the created renderer */ public final static Renderer create(String selector, Boolean value) { if (value == null) { return new Renderer(selector, new ElementRemover()); } else { return create(selector, new TextSetter(value)); } } /** * Create a renderer for text by given parameter. * <p> * All child nodes of the target element specified by selector will be emptied and the given String value will be rendered as a single * text node of the target element. * * @param selector * a css selector * @param value * a String value that will be rendered * @return the created renderer */ public final static Renderer create(String selector, String value) { if (value == null) { return new Renderer(selector, new ElementRemover()); } else { return create(selector, new TextSetter(value)); } } /** * Create a renderer for given parameter. * <p> * A special typed renderer will be created by the type of the given value. If there is no coordinate renderer for the type of given * value, the value#toString() will be used to retrieve a text for rendering. * * @param selector * a css selector * @param value * a Object that will be rendered. * @return the created renderer */ public final static Renderer create(String selector, Object value) { if (value == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, TransformerFactory.generateTransformer(value)); } } /** * Create a renderer for predefined {@link SpecialRenderer}s. * * @param selector * a css selector * @param specialRenderer * a predefined special renderer * @return the created renderer */ public final static Renderer create(String selector, SpecialRenderer specialRenderer) { if (specialRenderer == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, specialRenderer.getTransformer()); } } /** * See {@link #create(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a long value that will be treated as a String value * @return the created renderer */ public final static Renderer create(String selector, String attr, Long value) { if (value == null) { return create(selector, attr, (String) null); } else { return create(selector, attr, String.valueOf(value)); } } /** * See {@link #create(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * an int value that will be treated as a String value * @return the created renderer */ public final static Renderer create(String selector, String attr, Integer value) { if (value == null) { return create(selector, attr, (String) null); } else { return create(selector, attr, String.valueOf(value)); } } /** * See {@link #create(String, String, String)}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a boolean value that will be treated as a String value * @return the created renderer */ public final static Renderer create(String selector, String attr, Boolean value) { if (value == null) { return create(selector, attr, (String) null); } else { return create(selector, attr, String.valueOf(value)); } } /** * Create a renderer for attribute setting by given parameter. * <p> * An additional character of "+" or "-" can be used as a prefix of attribute name. See detail at {@link AttributeSetter}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a String value that will be treated as the attribute value * @return the created renderer */ public final static Renderer create(String selector, String attr, String value) { return create(selector, new AttributeSetter(attr, value)); } /** * Create a renderer for attribute setting by given parameter. * <p> * An additional character of "+" or "-" can be used as a prefix of attribute name. There is also a special logic for an instance with * arbitrary type. See detail at {@link AttributeSetter}. * * @param selector * a css selector * @param attr * the attribute name to set * @param value * a Object value that will be treated as the attribute value * @return the created renderer */ public final static Renderer create(String selector, String attr, Object value) { return create(selector, new AttributeSetter(attr, value)); } /** * Create a renderer for element rendering by given parameter. * <p> * The target element specified by the selector will be completely replaced by the given element. * * @param selector * a css selector * @param elem * a element that to be rendered * @return the created renderer */ public final static Renderer create(String selector, Element elem) { if (elem == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, new ElementTransformer(elem)); } } /** * Create a renderer for {@link Component} rendering by given parameter. * <p> * The target element specified by the selector will be completely replaced by the result of given {@link Component#toElement()}. * * @param selector * a css selector * @param component * a component that to be rendered * @return the created renderer */ public final static Renderer create(String selector, Component component) { if (component == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, new ElementTransformer(component.toElement())); } } /** * Create a renderer for element setting by given parameter. * <p> * The target element specified by the given selector will not be replaced and will be passed to the given {@link ElementSetter} as a * parameter. * * @param selector * a css selector * @param setter * an ElementSetter * @return the created renderer */ public final static Renderer create(String selector, ElementSetter setter) { if (setter == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, new ElementSetterTransformer(setter)); } } /** * Create a renderer for delayed rendering callback * <p> * The target element specified by the given selector will be renderer by the returned value of {@link Renderable#render()} which will * not be invoked until the target element is actually requiring the rendering action. * * @param selector * a css selector * @param Renderable * a callback instance of Renderable * @return the created renderer */ public final static Renderer create(String selector, Renderable renderable) { if (renderable == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, new RenderableTransformer(renderable)); } } /** * Create a renderer for recursive renderer rendering by given parameter. * <p> * The given renderer will be applied to element specified by the given selector. * * @param selector * a css selector * @param renderer * a renderer * @return the created renderer for chain calling */ public final static Renderer create(String selector, Renderer renderer) { if (renderer == null) { return new Renderer(selector, new ElementRemover()); } else { return new Renderer(selector, new RendererTransformer(renderer)); } } /** * This method is a convenience to creating an instance of {@link GoThroughRenderer} * * @return a {@link GoThroughRenderer} instance */ public final static Renderer create() { return new GoThroughRenderer(); } /** * Create a renderer for list rendering by given parameter with given {@link Stream}. See {@link #create(String, List)}. * * <p> * * <b>Note:Parallel stream is not supported due to the potential thread dead lock(https://bugs.openjdk.java.net/browse/JDK-8042758) * which is commented as not a bug by Oracle. For parallel rendering ,use {@link RowConvertorBuilder#parallel(Function)}/ * {@link RowConvertorBuilder#parallel(RowConvertor)} instead. </b> * * @param selector * a css selector * @param stream * a non-parallel stream with arbitrary type data * @return the created renderer */ public final static Renderer create(String selector, Stream<?> stream) { if (stream == null) { return new Renderer(selector, new ElementRemover()); } else { if (stream.isParallel()) { String msg = "Parallel stream is not supported due to the potential thread dead lock" + "(https://bugs.openjdk.java.net/browse/JDK-8042758) which is commented as not a bug by Oracle. For parallel " + "rendering ,use RowConvertorBuilder#parallel(Function)/RowConvertorBuilder#parallel(RowConvertor) instead."; throw new IllegalArgumentException(msg); } else { List<Transformer<?>> list = stream.map(obj -> { return TransformerFactory.generateTransformer(obj); }).collect(Collectors.toList()); return new Renderer(selector, list); } } } /** * Create a renderer for list rendering by given parameter. * <p> * The target Element specified by the given selector will be duplicated times as the count of the given list and the contents of the * list will be applied to the target Element too. * * @param selector * a css selector * @param list * a list that can contain all the types supported by the non-list add methods of Renderer * @return the created renderer */ public final static Renderer create(String selector, Iterable<?> list) { if (list == null) { return new Renderer(selector, new ElementRemover()); } else { List<Transformer<?>> transformerList = new LinkedList<>(); for (Object obj : list) { transformerList.add(TransformerFactory.generateTransformer(obj)); } return new Renderer(selector, transformerList); } } /** * Create a renderer for list rendering by given parameter with given {@link RowConvertor}. See {@link #create(String, List)}. * * @param selector * a css selector * @param list * a list with arbitrary type data * @param convertor * a convertor that can convert the arbitrary types of the list data to the types supported by the non-list create methods of * Renderer * @return the created renderer */ public final static <S, T> Renderer create(String selector, Iterable<S> list, RowConvertor<S, T> convertor) { if (list == null) { return new Renderer(selector, new ElementRemover()); } else { if (convertor.isParallel() && !Configuration.getConfiguration().isBlockParallelListRendering()) { return create(selector, ListConvertUtil.transformToFuture(list, convertor)); } else { return create(selector, ListConvertUtil.transform(list, convertor)); } } } /** * Create a renderer for list rendering by given parameter with given mapper. See {@link #create(String, List)}. * * @param selector * a css selector * @param list * a list with arbitrary type data * @param Function * a mapper that can convert the arbitrary types of the list data to the types supported by the non-list create methods of * Renderer * @return the created renderer */ public final static <S, T> Renderer create(String selector, Iterable<S> list, Function<S, T> mapper) { if (list == null) { return new Renderer(selector, new ElementRemover()); } else { return create(selector, list, RowConvertorBuilder.map(mapper)); } } // Render action control /** * * @return a renderer reference for chain calling * * @see {@link RenderActionStyle#DISABLE_MISSING_SELECTOR_WARNING} * */ public Renderer disableMissingSelectorWarning() { return this.add(new RenderActionRenderer(RenderActionStyle.DISABLE_MISSING_SELECTOR_WARNING)); } /** * * @return a renderer reference for chain calling * * @see {@link RenderActionStyle#ENABLE_MISSING_SELECTOR_WARNING} * */ public Renderer enableMissingSelectorWarning() { return this.add(new RenderActionRenderer(RenderActionStyle.ENABLE_MISSING_SELECTOR_WARNING)); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,276,735,252,088,427,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.render; /** * for performance reason, we use enum to identify the special renderers. * * @author e-ryu * */ public enum RendererType { /** * common renderer */ COMMON, /** * a debug renderer will output the target element to log */ // DEBUG, /** * a do nothing renderer */ GO_THROUGH, /** * a renderer which will change the action style of rendering process */ RENDER_ACTION, /** * a renderer which will handle the case that the specified selector is not found */ ELEMENT_NOT_FOUND_HANDLER }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-210,965,490,237,991,230
/* * 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.render; import com.astamuse.asta4d.render.transformer.Transformer; public enum SpecialRenderer { /** * Remove the target node.There is no warranty about when a cleared node will be removed but it was warranted that a cleared node will * be eventually removed at the last of rendering process. <br> * * Further, a formal html element with attribute "afd:clear" will be treated as a cleared node too. * */ Clear { @Override Transformer<?> getTransformer() { return new ElementRemover(Clear); } }; abstract Transformer<?> getTransformer(); /** * we don't want to make the {@link #getTransformer()} visible to user, but in framework, we need a way to access this method across * packages. * * @param sr * @return */ public static Transformer<?> retrieveTransformer(SpecialRenderer sr) { return sr.getTransformer(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,436,912,262,062,192,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.render; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.transformer.ElementTransformer; public class ElementRemover extends ElementTransformer { public ElementRemover(Object originalData) { super(new GroupNode(), originalData); } public ElementRemover() { super(new GroupNode(), null); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,940,169,280,649,427,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.render; class RenderAction { private int disableMissingSelectorWarningCounter = 0; public boolean isOutputMissingSelectorWarning() { return disableMissingSelectorWarningCounter == 0; } public void setOutputMissingSelectorWarning(boolean outputMissingSelectorWarning) { if (outputMissingSelectorWarning) { disableMissingSelectorWarningCounter--; } else { disableMissingSelectorWarningCounter++; } if (disableMissingSelectorWarningCounter < 0) { disableMissingSelectorWarningCounter = 0; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,192,173,580,433,660,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.render; import org.jsoup.nodes.Element; /** * A ChildReplacer will empty the target Element first, then add the new child * node to the target element. * * @author e-ryu * */ public class ChildReplacer implements ElementSetter { private Element newChild; /** * Constructor * * @param newChild * the new child node */ public ChildReplacer(Element newChild) { this.newChild = newChild; } @Override public void set(Element elem) { elem.empty(); elem.appendChild(newChild); } @Override public String toString() { String s = "replace the children to:{\n" + newChild.toString() + "\n}"; return s; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((newChild == null) ? 0 : newChild.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChildReplacer other = (ChildReplacer) obj; if (newChild == null) { if (other.newChild != null) return false; } else if (!newChild.outerHtml().equals(other.newChild.outerHtml())) return false; return true; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,513,496,277,984,644,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.render; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import org.apache.commons.lang3.tuple.Pair; import org.jsoup.nodes.Element; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.render.test.TestableRendering; import com.astamuse.asta4d.util.IdGenerator; /** * An AttributeSetter is used to set attribute value of an element. The specified attribute name can be a plain text representing the target * attribute, and it can also be prefixed by an additional character: + or -. * <p> * There are several cases about how AttributeSetter perform its action by different attribute name and value.<br> * * <li>new AttriuteSetter("+class", value): call addClass(value) on target Element, null value will be treated as "null". * * <li>new AttriuteSetter("-class", value): call removeClass(value) on target Element, null value will be treated as "null". * * <li>new AttriuteSetter("class", value): call attr("class", value) on target Element if value is not null, for a null value, * removeAttr("class") will be called. * * <li>new AttriuteSetter("anyattr", value): call attr("anyattr", value) on target Element if value is not null, for a null value, * removeAttr("anyattr") will be called. * * <li>new AttriuteSetter("anyattr", {@link SpecialRenderer#Clear}): call removeAttr("anyattr") on target Element. * * <li>new AttriuteSetter("+anyattr", value): call attr("anyattr", value) on target Element if value is not null, for a null value, * removeAttr("anyattr") will be called. * * <li>new AttriuteSetter("+anyattr", {@link SpecialRenderer#Clear}): call removeAttr("anyattr") on target Element. * * <li>new AttriuteSetter("-anyattr", value): call removeAttr("anyattr") on target Element. * * * * @author e-ryu * */ public class AttributeSetter implements ElementSetter, TestableRendering { private static enum ActionType { SET { @Override protected void configure(Element elem, String attrName, Object attrValue) { if (attrValue instanceof String) { elem.removeAttr(ExtNodeConstants.ATTR_DATAREF_PREFIX_WITH_NS + attrName); elem.attr(attrName, attrValue.toString()); } else if (attrValue instanceof Number) { elem.removeAttr(ExtNodeConstants.ATTR_DATAREF_PREFIX_WITH_NS + attrName); elem.attr(attrName, attrValue.toString()); } else if (attrValue instanceof Boolean) { elem.removeAttr(ExtNodeConstants.ATTR_DATAREF_PREFIX_WITH_NS + attrName); elem.attr(attrName, attrValue.toString()); } else { String dataRefId = attrName + "_" + IdGenerator.createId(); Context context = Context.getCurrentThreadContext(); context.setData(Context.SCOPE_EXT_ATTR, dataRefId, attrValue); elem.removeAttr(attrName); elem.attr(ExtNodeConstants.ATTR_DATAREF_PREFIX_WITH_NS + attrName, dataRefId); } } }, REMOVE { @Override protected void configure(Element elem, String attrName, Object attrValue) { elem.removeAttr(ExtNodeConstants.ATTR_DATAREF_PREFIX_WITH_NS + attrName); elem.removeAttr(attrName); // for remove all class definition, we have to clear the // classNames too. if (attrName.equals("class")) { elem.classNames().clear(); } } }, ADDCLASS { @Override protected void configure(Element elem, String attrName, Object attrValue) { elem.addClass(attrValue.toString()); } }, REMOVECLASS { @Override protected void configure(Element elem, String attrName, Object attrValue) { elem.removeClass(attrValue.toString()); } }; protected abstract void configure(Element elem, String attrName, Object attrValue); } /** * this value is for test purpose */ private String originalAttrName; /** * this value is for test purpose */ private Object originalValue; private String attrName; private Object attrValue; private ActionType actionType; /** * Constructor * * @param attr * attribute name * @param value * attribute value */ public AttributeSetter(String attr, Object value) { super(); this.originalAttrName = attr; this.originalValue = value; if (attr.equalsIgnoreCase("+class")) { this.actionType = ActionType.ADDCLASS; this.attrName = "class"; } else if (attr.equalsIgnoreCase("-class")) { this.actionType = ActionType.REMOVECLASS; this.attrName = "class"; } else if (attr.equalsIgnoreCase("class")) { if (value == null) { this.actionType = ActionType.REMOVE; this.attrName = "class"; } else { this.actionType = ActionType.SET; this.attrName = "class"; } } else { if (attr.startsWith("-")) { this.actionType = ActionType.REMOVE; this.attrName = attr.substring(1); } else { if (attr.startsWith("+")) { this.attrName = attr.substring(1); } else { this.attrName = attr; } if (value == null) { this.actionType = ActionType.REMOVE; } else if (value == Clear) { this.actionType = ActionType.REMOVE; } else { this.actionType = ActionType.SET; } } } this.attrValue = value == null ? "null" : value; if (actionType == ActionType.ADDCLASS || actionType == ActionType.REMOVECLASS) { if (!(attrValue instanceof String)) { throw new IllegalArgumentException("Only String type is allowed in class setting but found unexpected value type : " + attrValue.getClass().getName()); } } } @Override public void set(Element elem) { actionType.configure(elem, attrName, attrValue); } @Override public String toString() { return actionType + " attribute " + attrName + " for value [" + attrValue + "]"; } @Override public Object retrieveTestableData() { return Pair.of(originalAttrName, originalValue); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,128,389,366,146,426,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. * */ /* * 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.render; /** * This Renderer will not do any actual rendering but change the rendering style * in rendering process flow. * * @author e-ryu * */ class RenderActionRenderer extends GoThroughRenderer { private RenderActionStyle style; public RenderActionRenderer(RenderActionStyle style) { super(); this.style = style; } public RenderActionStyle getStyle() { return style; } @Override public String toString() { return "RenderActionRender"; } @Override RendererType getRendererType() { return RendererType.RENDER_ACTION; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,318,199,125,569,641,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.render; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.render.transformer.Transformer; /** * When this renderer is applied, the current rendering element (see {@link Context#setCurrentRenderingElement(Element)}) will be output by * logger in debug level. * * @author e-ryu * */ public class DebugRenderer extends Renderer { private static final class DebugTransformer extends Transformer<Object> { Logger logger = null; String logMessage = null; String creationSiteInfo = null; public DebugTransformer() { super(null); } @Override protected Element transform(Element elem, Object content) { String logStr = logMessage + "( " + creationSiteInfo + " ):\n" + elem.toString(); logger.debug(logStr); // we have to clone a new element, which is how transformer works. Element newElem = elem.clone(); return newElem; } } final static Logger DefaultLogger = LoggerFactory.getLogger(DebugRenderer.class); public DebugRenderer(Logger logger, String logMessage) { super(":root", new DebugTransformer()); DebugTransformer dts = (DebugTransformer) getTransformerList().get(0); dts.logMessage = logMessage; dts.creationSiteInfo = getCreationSiteInfo(); dts.logger = logger; } /* @Override RendererType getRendererType() { return RendererType.DEBUG; } */ }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,423,528,878,006,874,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.render; enum RenderActionStyle { /** * output a warning message when there is no element found for a certain * selector */ ENABLE_MISSING_SELECTOR_WARNING { @Override public void apply(RenderAction action) { action.setOutputMissingSelectorWarning(true); } }, /** * not output a warning message when there is no element found for a certain * selector */ DISABLE_MISSING_SELECTOR_WARNING { @Override public void apply(RenderAction action) { action.setOutputMissingSelectorWarning(false); } }; public abstract void apply(RenderAction action); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,441,934,383,169,208,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.render; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.render.test.TestableRendering; import com.astamuse.asta4d.util.Asta4DWarningException; /** * A TextSetter will empty the target element at first, then add a new text node to the target element * * @author e-ryu * */ public class TextSetter implements ElementSetter, TestableRendering { private final static Logger logger = LoggerFactory.getLogger(TextSetter.class); private Object originContent; private String renderText; /** * Constructor * * @param content * the content wanted to be rendered */ public TextSetter(Object content) { this.originContent = content; this.renderText = content2Str(content); } private final static String content2Str(Object content) { if (content == null) { String msg = "Trying to render a null String"; // we want to get a information of where the null is passed, so we // create a exception to get the calling stacks Exception ex = new Asta4DWarningException(msg); logger.warn(msg, ex); } return content == null ? "" : content.toString(); } @Override public void set(Element elem) { elem.empty(); elem.appendText(renderText); } @Override public String toString() { return renderText; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((originContent == null) ? 0 : originContent.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TextSetter other = (TextSetter) obj; if (originContent == null) { if (other.originContent != null) return false; } else if (!originContent.equals(other.originContent)) return false; return true; } @Override public Object retrieveTestableData() { return originContent; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,510,104,224,352,156,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.render; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.transformer.ElementSetterTransformer; /** * This Renderer will do nothing, the Rendering process will jump over a render * if it is a GoThroughRenderer. * * @author e-ryu * */ public class GoThroughRenderer extends Renderer { private final static ElementSetterTransformer DoNothingTransformer = new ElementSetterTransformer(new ElementSetter() { @Override public void set(Element elem) { // do nothing } }); public GoThroughRenderer() { super("", DoNothingTransformer); } @Override public String toString() { return "GoThroughRenderer"; } @Override RendererType getRendererType() { return RendererType.GO_THROUGH; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,032,683,805,703,065,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.render; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import org.apache.commons.lang3.StringUtils; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.render.concurrent.ConcurrentRenderHelper; import com.astamuse.asta4d.render.concurrent.FutureRendererHolder; import com.astamuse.asta4d.render.transformer.RendererTransformer; import com.astamuse.asta4d.render.transformer.Transformer; import com.astamuse.asta4d.snippet.SnippetInvokeException; import com.astamuse.asta4d.snippet.SnippetInvoker; import com.astamuse.asta4d.snippet.SnippetNotResovlableException; import com.astamuse.asta4d.template.TemplateException; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.template.TemplateUtil; import com.astamuse.asta4d.util.ElementUtil; import com.astamuse.asta4d.util.SelectorUtil; import com.astamuse.asta4d.util.i18n.I18nMessageHelperTypeAssistant; import com.astamuse.asta4d.util.i18n.LocalizeUtil; /** * * This class is a functions holder which supply the ability of applying rendereres to certain Element. * * @author e-ryu * */ public class RenderUtil { public static final String PSEUDO_ROOT_SELECTOR = ":root"; public static final String TRACE_VAR_TEMPLATE_PATH = "TRACE_VAR_TEMPLATE_PATH#" + RenderUtil.class; public static final String TRACE_VAR_SNIPPET = "TRACE_VAR_SNIPPET#" + RenderUtil.class; private final static Logger logger = LoggerFactory.getLogger(RenderUtil.class); private final static List<String> EXCLUDE_ATTR_NAME_LIST = new ArrayList<>(); static { EXCLUDE_ATTR_NAME_LIST.add(ExtNodeConstants.MSG_NODE_ATTR_KEY); EXCLUDE_ATTR_NAME_LIST.add(ExtNodeConstants.MSG_NODE_ATTR_LOCALE); EXCLUDE_ATTR_NAME_LIST.add(ExtNodeConstants.ATTR_TEMPLATE_PATH); } /** * Find out all the snippet in the passed Document and execute them. The Containing embed tag of the passed Document will be exactly * mixed in here too. <br> * Recursively contained snippets will be executed from outside to inside, thus the inner snippets will not be executed until all of * their outer snippets are finished. Also, the dynamically created snippets and embed tags will comply with this rule too. * * @param doc * the Document to apply snippets * @throws SnippetNotResovlableException * @throws SnippetInvokeException * @throws TemplateException */ public final static void applySnippets(Document doc) throws SnippetNotResovlableException, SnippetInvokeException, TemplateException, TemplateNotFoundException { if (doc == null) { return; } applyClearAction(doc, false); // retrieve ready snippets String selector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_READY); List<Element> snippetList = new ArrayList<>(doc.select(selector)); int readySnippetCount = snippetList.size(); int blockedSnippetCount = 0; for (int i = readySnippetCount - 1; i >= 0; i--) { // if parent snippet has not been executed, the current snippet will // not be executed too. if (isBlockedByParentSnippet(doc, snippetList.get(i))) { snippetList.remove(i); blockedSnippetCount++; } } readySnippetCount = readySnippetCount - blockedSnippetCount; String renderDeclaration; Renderer renderer; Context context = Context.getCurrentThreadContext(); Configuration conf = Configuration.getConfiguration(); final SnippetInvoker invoker = conf.getSnippetInvoker(); String refId; String currentTemplatePath; Element renderTarget; for (Element element : snippetList) { if (!conf.isSkipSnippetExecution()) { // for a faked snippet node which is created by template // analyzing process, the render target element should be its // child. if (element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE).equals(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE)) { renderTarget = element.children().first(); // the hosting element of this faked snippet has been removed by outer a snippet if (renderTarget == null) { element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED); continue; } } else { renderTarget = element; } // we have to reset the ref of current snippet at every time to make sure the ref is always unique(duplicated snippet ref // could be created by list rendering) TemplateUtil.resetSnippetRefs(element); context.setCurrentRenderingElement(renderTarget); renderDeclaration = element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_RENDER); refId = element.attr(ExtNodeConstants.ATTR_SNIPPET_REF); currentTemplatePath = element.attr(ExtNodeConstants.ATTR_TEMPLATE_PATH); context.setCurrentRenderingElement(renderTarget); context.setData(TRACE_VAR_TEMPLATE_PATH, currentTemplatePath); try { if (element.hasAttr(ExtNodeConstants.SNIPPET_NODE_ATTR_PARALLEL)) { ConcurrentRenderHelper crHelper = ConcurrentRenderHelper.getInstance(context, doc); final Context newContext = context.clone(); final String declaration = renderDeclaration; crHelper.submitWithContext(newContext, declaration, refId, new Callable<Renderer>() { @Override public Renderer call() throws Exception { return invoker.invoke(declaration); } }); element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_WAITING); } else { renderer = invoker.invoke(renderDeclaration); applySnippetResultToElement(doc, refId, element, renderTarget, renderer); } } catch (SnippetNotResovlableException | SnippetInvokeException e) { throw e; } catch (Exception e) { SnippetInvokeException se = new SnippetInvokeException("Error occured when executing rendering on [" + renderDeclaration + "]:" + e.getMessage(), e); throw se; } context.setData(TRACE_VAR_TEMPLATE_PATH, null); context.setCurrentRenderingElement(null); } else {// if skip snippet element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED); } } // load embed nodes which blocking parents has finished List<Element> embedNodeList = doc.select(ExtNodeConstants.EMBED_NODE_TAG_SELECTOR); int embedNodeListCount = embedNodeList.size(); Iterator<Element> embedNodeIterator = embedNodeList.iterator(); Element embed; Element embedContent; while (embedNodeIterator.hasNext()) { embed = embedNodeIterator.next(); if (isBlockedByParentSnippet(doc, embed)) { embedNodeListCount--; continue; } embedContent = TemplateUtil.getEmbedNodeContent(embed); TemplateUtil.mergeBlock(doc, embedContent); embed.before(embedContent); embed.remove(); } if ((readySnippetCount + embedNodeListCount) > 0) { TemplateUtil.regulateElement(null, doc); applySnippets(doc); } else { ConcurrentRenderHelper crHelper = ConcurrentRenderHelper.getInstance(context, doc); String delcaration = null; if (crHelper.hasUnCompletedTask()) { delcaration = null; try { FutureRendererHolder holder = crHelper.take(); delcaration = holder.getRenderDeclaration(); String ref = holder.getSnippetRefId(); String reSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, ExtNodeConstants.ATTR_SNIPPET_REF, ref); Element element = doc.select(reSelector).get(0);// must have Element target; if (element.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE).equals(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE)) { target = element.children().first(); } else { target = element; } applySnippetResultToElement(doc, ref, element, target, holder.getRenderer()); applySnippets(doc); } catch (InterruptedException | ExecutionException e) { throw new SnippetInvokeException("Concurrent snippet invocation failed" + (delcaration == null ? "" : " on [" + delcaration + "]"), e); } } } } private final static void applySnippetResultToElement(Document doc, String snippetRefId, Element snippetElement, Element renderTarget, Renderer renderer) { apply(renderTarget, renderer); if (snippetElement.ownerDocument() == null) { // it means this snippet element is replaced by a // element completely String reSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, ExtNodeConstants.ATTR_SNIPPET_REF, snippetRefId); Elements elems = doc.select(reSelector); if (elems.size() > 0) { snippetElement = elems.get(0); } else { snippetElement = null; } } if (snippetElement != null) { snippetElement.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED); } } private final static boolean isBlockedByParentSnippet(Document doc, Element elem) { boolean isBlocked; String blockingId = elem.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_BLOCK); if (blockingId.isEmpty()) { // empty block id means there is no parent snippet that need to be // aware. if the original block is from a embed template, it means // that all of the parent snippets have been finished or this // element would not be imported now. isBlocked = false; } else { String parentSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, ExtNodeConstants.ATTR_SNIPPET_REF, blockingId); Elements parentSnippetSearch = elem.parents().select(parentSelector); if (parentSnippetSearch.isEmpty()) { isBlocked = false; } else { Element parentSnippet = parentSnippetSearch.first(); if (parentSnippet.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS) .equals(ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED)) { isBlocked = false; } else { isBlocked = true; } } } return isBlocked; } /** * Apply given renderer to the given element. * * @param target * applying target element * @param renderer * a renderer for applying */ public final static void apply(Element target, Renderer renderer) { List<Renderer> rendererList = renderer.asUnmodifiableList(); int count = rendererList.size(); if (count == 0) { return; } applyClearAction(target, false); RenderAction renderAction = new RenderAction(); apply(target, rendererList, renderAction, 0, count); } // TODO since this method is called recursively, we need do a test to find // out the threshold of render list size that will cause a // StackOverflowError. private final static void apply(Element target, List<Renderer> rendererList, RenderAction renderAction, int startIndex, int count) { // The renderer list have to be applied recursively because the // transformer will always return a new Element clone. if (startIndex >= count) { return; } final Renderer currentRenderer = rendererList.get(startIndex); RendererType rendererType = currentRenderer.getRendererType(); switch (rendererType) { case GO_THROUGH: apply(target, rendererList, renderAction, startIndex + 1, count); return; /* case DEBUG: currentRenderer.getTransformerList().get(0).invoke(target); apply(target, rendererList, renderAction, startIndex + 1, count); return; */ case RENDER_ACTION: ((RenderActionRenderer) currentRenderer).getStyle().apply(renderAction); apply(target, rendererList, renderAction, startIndex + 1, count); return; default: // do nothing break; } String selector = currentRenderer.getSelector(); List<Transformer<?>> transformerList = currentRenderer.getTransformerList(); List<Element> elemList; if (PSEUDO_ROOT_SELECTOR.equals(selector)) { elemList = new LinkedList<Element>(); elemList.add(target); } else { elemList = new ArrayList<>(target.select(selector)); } if (elemList.isEmpty()) { if (rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER) { elemList.add(target); transformerList.clear(); transformerList.add(new RendererTransformer(((ElementNotFoundHandler) currentRenderer).alternativeRenderer())); } else if (renderAction.isOutputMissingSelectorWarning()) { String creationInfo = currentRenderer.getCreationSiteInfo(); if (creationInfo == null) { creationInfo = ""; } else { creationInfo = " at [ " + creationInfo + " ]"; } logger.warn( "There is no element found for selector [{}]{}, if it is deserved, try Renderer#disableMissingSelectorWarning() " + "to disable this message and Renderer#enableMissingSelectorWarning could enable this warning again in " + "your renderer chain", selector, creationInfo); apply(target, rendererList, renderAction, startIndex + 1, count); return; } } else { if (rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER) { apply(target, rendererList, renderAction, startIndex + 1, count); return; } } Element delayedElement = null; Element resultNode; // TODO we suppose that the element is listed as the order from parent // to children, so we reverse it. Perhaps we need a real order process // to ensure the wanted order. Collections.reverse(elemList); boolean renderForRoot; for (Element elem : elemList) { renderForRoot = PSEUDO_ROOT_SELECTOR.equals(selector) || rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER; if (!renderForRoot) { // faked group node will be not applied by renderers(only when the current selector is not the pseudo :root) if (elem.tagName().equals(ExtNodeConstants.GROUP_NODE_TAG) && ExtNodeConstants.GROUP_NODE_ATTR_TYPE_FAKE.equals(elem.attr(ExtNodeConstants.GROUP_NODE_ATTR_TYPE))) { continue; } } if (elem == target) { delayedElement = elem; continue; } for (Transformer<?> transformer : transformerList) { resultNode = transformer.invoke(elem); elem.before(resultNode); }// for transformer elem.remove(); }// for element // if the root element is one of the process targets, we can not apply // the left renderers to original element because it will be replaced by // a new element even it is not necessary (that is how Transformer // works). if (delayedElement == null) { apply(target, rendererList, renderAction, startIndex + 1, count); } else { if (rendererType == RendererType.ELEMENT_NOT_FOUND_HANDLER && delayedElement instanceof Document) { delayedElement = delayedElement.child(0); } for (Transformer<?> transformer : transformerList) { resultNode = transformer.invoke(delayedElement); delayedElement.before(resultNode); apply(resultNode, rendererList, renderAction, startIndex + 1, count); }// for transformer delayedElement.remove(); } } /** * Clear the redundant elements which are usually created by snippet/renderer applying.If the forFinalClean is true, all the finished * snippet tags will be removed too. * * @param target * @param forFinalClean */ public final static void applyClearAction(Element target, boolean forFinalClean) { String fakeGroup = SelectorUtil.attr(ExtNodeConstants.GROUP_NODE_TAG_SELECTOR, ExtNodeConstants.GROUP_NODE_ATTR_TYPE, ExtNodeConstants.GROUP_NODE_ATTR_TYPE_FAKE); ElementUtil.removeNodesBySelector(target, fakeGroup, true); String clearGroup = SelectorUtil.attr(ExtNodeConstants.GROUP_NODE_TAG_SELECTOR, ExtNodeConstants.ATTR_CLEAR, null); ElementUtil.removeNodesBySelector(target, clearGroup, false); ElementUtil.removeNodesBySelector(target, SelectorUtil.attr(ExtNodeConstants.ATTR_CLEAR_WITH_NS), false); if (forFinalClean) { String removeSnippetSelector = SelectorUtil.attr(ExtNodeConstants.SNIPPET_NODE_TAG_SELECTOR, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS, ExtNodeConstants.SNIPPET_NODE_ATTR_STATUS_FINISHED); // TODO check if there are unfinished snippet left. ElementUtil.removeNodesBySelector(target, removeSnippetSelector, true); ElementUtil.removeNodesBySelector(target, ExtNodeConstants.BLOCK_NODE_TAG_SELECTOR, true); ElementUtil.removeNodesBySelector(target, ExtNodeConstants.GROUP_NODE_TAG_SELECTOR, true); } } // public final static void public final static void applyMessages(Element target) { Context context = Context.getCurrentThreadContext(); List<Element> msgElems = target.select(ExtNodeConstants.MSG_NODE_TAG_SELECTOR); for (final Element msgElem : msgElems) { Attributes attributes = msgElem.attributes(); String key = attributes.get(ExtNodeConstants.MSG_NODE_ATTR_KEY); // List<String> externalizeParamKeys = getExternalizeParamKeys(attributes); Object defaultMsg = new Object() { @Override public String toString() { return ExtNodeConstants.MSG_NODE_ATTRVALUE_HTML_PREFIX + msgElem.html(); } }; Locale locale = LocalizeUtil.getLocale(attributes.get(ExtNodeConstants.MSG_NODE_ATTR_LOCALE)); String currentTemplatePath = attributes.get(ExtNodeConstants.ATTR_TEMPLATE_PATH); if (StringUtils.isEmpty(currentTemplatePath)) { logger.warn("There is a msg tag which does not hold corresponding template file path:{}", msgElem.outerHtml()); } else { context.setData(TRACE_VAR_TEMPLATE_PATH, currentTemplatePath); } final Map<String, Object> paramMap = getMessageParams(attributes, locale, key); String text; switch (I18nMessageHelperTypeAssistant.configuredHelperType()) { case Mapped: text = I18nMessageHelperTypeAssistant.getConfiguredMappedHelper().getMessageWithDefault(locale, key, defaultMsg, paramMap); break; case Ordered: default: // convert map to array List<Object> numberedParamNameList = new ArrayList<>(); for (int index = 0; paramMap.containsKey(ExtNodeConstants.MSG_NODE_ATTR_PARAM_PREFIX + index); index++) { numberedParamNameList.add(paramMap.get(ExtNodeConstants.MSG_NODE_ATTR_PARAM_PREFIX + index)); } text = I18nMessageHelperTypeAssistant.getConfiguredOrderedHelper().getMessageWithDefault(locale, key, defaultMsg, numberedParamNameList.toArray()); } Node node; if (text.startsWith(ExtNodeConstants.MSG_NODE_ATTRVALUE_TEXT_PREFIX)) { node = ElementUtil.text(text.substring(ExtNodeConstants.MSG_NODE_ATTRVALUE_TEXT_PREFIX.length())); } else if (text.startsWith(ExtNodeConstants.MSG_NODE_ATTRVALUE_HTML_PREFIX)) { node = ElementUtil.parseAsSingle(text.substring(ExtNodeConstants.MSG_NODE_ATTRVALUE_HTML_PREFIX.length())); } else { node = ElementUtil.text(text); } msgElem.replaceWith(node); context.setData(TRACE_VAR_TEMPLATE_PATH, null); } } private static Map<String, Object> getMessageParams(final Attributes attributes, final Locale locale, final String key) { List<String> excludeAttrNameList = EXCLUDE_ATTR_NAME_LIST; final Map<String, Object> paramMap = new HashMap<>(); for (Attribute attribute : attributes) { String attrKey = attribute.getKey(); if (excludeAttrNameList.contains(attrKey)) { continue; } String value = attribute.getValue(); final String recursiveKey; if (attrKey.startsWith("@")) { attrKey = attrKey.substring(1); recursiveKey = value; } else if (attrKey.startsWith("#")) { attrKey = attrKey.substring(1); // we treat the # prefixed attribute value as a sub key of current key if (StringUtils.isEmpty(key)) { recursiveKey = value; } else { recursiveKey = key + "." + value; } } else { recursiveKey = null; } if (recursiveKey == null) { paramMap.put(attrKey, value); } else { paramMap.put(attrKey, new Object() { @Override public String toString() { switch (I18nMessageHelperTypeAssistant.configuredHelperType()) { case Mapped: // for the mapped helper, we can pass the parameter map recursively return I18nMessageHelperTypeAssistant.getConfiguredMappedHelper().getMessage(locale, recursiveKey, paramMap); case Ordered: default: return I18nMessageHelperTypeAssistant.getConfiguredOrderedHelper().getMessage(locale, recursiveKey); } } }); } } return paramMap; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-9,000,171,098,131,665,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.render.concurrent; import com.astamuse.asta4d.render.Renderer; public class FutureRendererHolder { String renderDeclaration; String snippetRefId; Renderer renderer; public FutureRendererHolder(String renderDeclaration, String snippetRefId, Renderer renderer) { super(); this.snippetRefId = snippetRefId; this.renderer = renderer; } public String getRenderDeclaration() { return renderDeclaration; } public void setRenderDeclaration(String renderDeclaration) { this.renderDeclaration = renderDeclaration; } public String getSnippetRefId() { return snippetRefId; } public void setSnippetRefId(String snippetRefId) { this.snippetRefId = snippetRefId; } public Renderer getRenderer() { return renderer; } public void setRenderer(Renderer renderer) { this.renderer = renderer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,240,438,103,453,234,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.render.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.util.concurrent.SnippetExecutorServiceUtil; public class ConcurrentRenderHelper { private final static Logger logger = LoggerFactory.getLogger(ConcurrentRenderHelper.class); private final static String INSTANCE_KEY = ConcurrentRenderHelper.class.getName() + "##instance-key##"; private CompletionService<FutureRendererHolder> cs; private int executionCount = 0; private ConcurrentRenderHelper(ExecutorService es) { cs = new ExecutorCompletionService<>(es); } public final static ConcurrentRenderHelper getInstance(Context context, Document doc) { String docRef = doc.attr(ExtNodeConstants.ATTR_DOC_REF); String key = INSTANCE_KEY + docRef; ConcurrentRenderHelper instance = context.getData(key); if (instance == null) { instance = new ConcurrentRenderHelper(SnippetExecutorServiceUtil.getExecutorService()); context.setData(key, instance); } return instance; } public void submitWithContext(final Context context, final String renderDeclaration, final String snippetRef, final Callable<Renderer> caller) { cs.submit(new Callable<FutureRendererHolder>() { @Override public FutureRendererHolder call() throws Exception { /* * An exception from paralleled snippet may be ignored when there is another exception * being thrown on head. * * In multiple threads, the original exception may cause some other exceptions in other threads, * which may be identified before the original exception so that the following #take() * method will never be called thus the original exception will never be identified. * * Commonly, it is not a problem, but it is difficult to debug since the original exception had been * ignored and there is no any information about it at anywhere. So at least, we output the exception * in log to help debug. */ try { Renderer renderer = Context.with(context, caller); return new FutureRendererHolder(renderDeclaration, snippetRef, renderer); } catch (Exception ex) { Exception nex = new Exception("Error occured when execute rendering:[" + renderDeclaration + "]", ex); logger.error("", nex); throw nex; } } }); executionCount++; } public boolean hasUnCompletedTask() { return executionCount > 0; } public FutureRendererHolder take() throws InterruptedException, ExecutionException { FutureRendererHolder holder = cs.take().get(); executionCount--; return holder; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,482,480,479,746,947,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.render.test; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.AttributeSetter; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.RendererTestHelper; import com.astamuse.asta4d.render.RendererType; import com.astamuse.asta4d.render.transformer.Transformer; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; public class RendererTester { private Renderer renderer; private RendererTester(Renderer renderer) { this.renderer = renderer; } public final static RendererTester forRenderer(Renderer renderer) { return new RendererTester(renderer); } public final static List<RendererTester> forRendererList(List<Renderer> rendererList) { return ListConvertUtil.transform(rendererList, new RowConvertor<Renderer, RendererTester>() { @Override public RendererTester convert(int rowIndex, Renderer obj) { return new RendererTester(obj); } }); } private List<List<Transformer<?>>> retrieveNonAttrTransformer(String selector) { List<List<Transformer<?>>> rtnList = new LinkedList<>(); List<Renderer> rendererList = renderer.asUnmodifiableList(); for (Renderer r : rendererList) { if (r.getSelector().equals(selector)) { List<Transformer<?>> list = r.getTransformerList(); if (list.isEmpty()) { rtnList.add(list); } else { Transformer<?> t = list.get(0); if (t.getContent() instanceof AttributeSetter) { continue; } else { rtnList.add(list); } } } } return rtnList; } private List<Transformer<?>> retrieveSingleTransformerListOnSelector(String selector) { List<List<Transformer<?>>> list = retrieveNonAttrTransformer(selector); if (list.isEmpty()) { throw new RendererTestException("There is no value to be rendered for selector:[" + selector + "]"); } else if (list.size() > 1) { throw new RendererTestException( "There are more than one value to be rendered for selector:[" + selector + "], maybe it is rendered multiple times?"); } else { return list.get(0); } } // following are simple render value accessores for simple test cases private Transformer<?> retrieveSingleTransformerOnSelector(String selector) { List<Transformer<?>> list = retrieveSingleTransformerListOnSelector(selector); if (list.isEmpty()) { throw new RendererTestException( "There is no value to be rendered for selector:[" + selector + "], maybe it is rendered as a empty list?"); } else if (list.size() > 1) { throw new RendererTestException( "There are more than one value to be rendered for selector:[" + selector + "], maybe it is rendered as a list?"); } else { return list.get(0); } } /** * * @return true - the current Renderer will do nothing */ public boolean noOp() { return renderer.asUnmodifiableList().size() == 1 && RendererTestHelper.getRendererType(renderer) == RendererType.GO_THROUGH; } /** * * * @param selector * @return true - there is no actual rendering operation on the given selector */ public boolean noOp(String selector) { List<List<Transformer<?>>> list = retrieveNonAttrTransformer(selector); return list.isEmpty(); } /** * * * @param selector * @param attr * @return true - there is no actual rendering operation on the given selector and attribute */ public boolean noOp(String selector, String attr) { List list = (List) getAttrAsObject(selector, attr, true, true); return list.isEmpty(); } /** * * @param selector * @return the rendered operation on given selector * @throws RendererTestException * if there is no operation or more than one operation on given selector, RendererTestException will be thrown */ @SuppressWarnings("rawtypes") public Object get(String selector) throws RendererTestException { Transformer t = retrieveSingleTransformerOnSelector(selector); Object content = retrieveTestContentFromTransformer(t); return content; } /** * * @param selector * @return the rendered operation list on given selector * @throws RendererTestException * if there is no operation on given selector, RendererTestException will be thrown */ public List<Object> getAsList(String selector) throws RendererTestException { return getAsList(selector, Object.class); } public List<RendererTester> getAsRendererTesterList(String selector) throws RendererTestException { return getAsList(selector, Renderer.class).stream().map(r -> RendererTester.forRenderer(r)).collect(Collectors.toList()); } /** * * @param selector * @param targetCls * @return the rendered operation list on given selector * @throws RendererTestException * if there is no operation on given selector, RendererTestException will be thrown */ public <T> List<T> getAsList(String selector, final Class<T> targetCls) throws RendererTestException { List<Transformer<?>> list = retrieveSingleTransformerListOnSelector(selector); return ListConvertUtil.transform(list, new RowConvertor<Transformer<?>, T>() { @SuppressWarnings("unchecked") @Override public T convert(int rowIndex, Transformer<?> transformer) { Object content = retrieveTestContentFromTransformer(transformer); return (T) content; } }); } private Object retrieveTestContentFromTransformer(Transformer<?> transformer) { Object content = null; if (transformer instanceof TestableRendering) { content = ((TestableRendering) transformer).retrieveTestableData(); } if (content != null && content instanceof TestableRendering) { content = ((TestableRendering) content).retrieveTestableData(); } if (content != null && content instanceof Element) { content = new TestableElementWrapper((Element) content); } return content; } /** * * @param selector * @param attr * @return * @throws RendererTestException * if there is no operation or more than one operation on given selector and attr, RendererTestException will be thrown */ public Object getAttr(String selector, String attr) throws RendererTestException { return getAttrAsObject(selector, attr, false, false); } /** * This method is only for retrieving rendered value of "+class" and "-class" attr action * * @param selector * @param attr * @return * @throws RendererTestException * if there is no operation on given selector and attr, RendererTestException will be thrown */ @SuppressWarnings("unchecked") public List<String> getAttrAsList(String selector, String attr) throws RendererTestException { if (attr.equals("+class") || attr.equals("-class")) { return (List<String>) getAttrAsObject(selector, attr, true, false); } else { throw new RendererTestException("This method is only for retrieving rendered value of \"+class\" and \"-class\" attr action"); } } private Object getAttrAsObject(String selector, String attr, boolean allowList, boolean allowEmpty) { List<Renderer> rendererList = renderer.asUnmodifiableList(); List<Object> valueList = new LinkedList<>(); for (Renderer r : rendererList) { if (r.getSelector().equals(selector)) { List<Transformer<?>> list = r.getTransformerList(); if (list.isEmpty()) { continue; } else { Transformer<?> t = list.get(0); if (t.getContent() instanceof AttributeSetter) { AttributeSetter setter = (AttributeSetter) t.getContent(); @SuppressWarnings("unchecked") Pair<String, Object> data = (Pair<String, Object>) setter.retrieveTestableData(); if (data.getKey().equals(attr)) { Object obj = data.getValue(); valueList.add(obj); } } else { continue; } } } } if (!allowEmpty && valueList.isEmpty()) { throw new RendererTestException("There is no value to be rendered for attr:[" + attr + "] of selector:[" + selector + "]"); } else if (valueList.size() > 1) { if (allowList) { return valueList; } else { throw new RendererTestException("There are more than one values(" + valueList.toString() + ") to be rendered for attr:[" + attr + "] of selector:[" + selector + "]"); } } else { if (allowList) { return valueList; } else { return valueList.get(0); } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,983,400,134,532,552,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.render.test; public class RendererTestException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public RendererTestException() { super(); } public RendererTestException(String message, Throwable cause) { super(message, cause); } public RendererTestException(String message) { super(message); } public RendererTestException(Throwable cause) { super(cause); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,799,210,089,858,461,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.render.test; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.jsoup.select.NodeVisitor; import com.astamuse.asta4d.util.ElementUtil; public class TestableElementWrapper extends Element { private Element originElement; public TestableElementWrapper(Element originElement) { super(Tag.valueOf("div"), ""); this.originElement = originElement; } public final static TestableElementWrapper parse(String html) { return new TestableElementWrapper(ElementUtil.parseAsSingle(html)); } public String attr(String attributeKey) { return originElement.attr(attributeKey); } public String nodeName() { return originElement.nodeName(); } public String tagName() { return originElement.tagName(); } public Element tagName(String tagName) { return originElement.tagName(tagName); } public Tag tag() { return originElement.tag(); } public Attributes attributes() { return originElement.attributes(); } public boolean isBlock() { return originElement.isBlock(); } public String id() { return originElement.id(); } public Element attr(String attributeKey, String attributeValue) { return originElement.attr(attributeKey, attributeValue); } public boolean hasAttr(String attributeKey) { return originElement.hasAttr(attributeKey); } public Map<String, String> dataset() { return originElement.dataset(); } public Node removeAttr(String attributeKey) { return originElement.removeAttr(attributeKey); } public String baseUri() { return originElement.baseUri(); } public void setBaseUri(String baseUri) { originElement.setBaseUri(baseUri); } public Elements parents() { return originElement.parents(); } public String absUrl(String attributeKey) { return originElement.absUrl(attributeKey); } public Element child(int index) { return originElement.child(index); } public Elements children() { return originElement.children(); } public List<TextNode> textNodes() { return originElement.textNodes(); } public Node childNode(int index) { return originElement.childNode(index); } public List<Node> childNodes() { return originElement.childNodes(); } public List<DataNode> dataNodes() { return originElement.dataNodes(); } public Document ownerDocument() { return originElement.ownerDocument(); } public void remove() { originElement.remove(); } public Elements select(String cssQuery) { return originElement.select(cssQuery); } public Element appendChild(Node child) { return originElement.appendChild(child); } public Element prependChild(Node child) { return originElement.prependChild(child); } public Element appendElement(String tagName) { return originElement.appendElement(tagName); } public Element prependElement(String tagName) { return originElement.prependElement(tagName); } public Element appendText(String text) { return originElement.appendText(text); } public Element prependText(String text) { return originElement.prependText(text); } public Node unwrap() { return originElement.unwrap(); } public Element append(String html) { return originElement.append(html); } public Element prepend(String html) { return originElement.prepend(html); } public Element before(String html) { return originElement.before(html); } public void replaceWith(Node in) { originElement.replaceWith(in); } public Element before(Node node) { return originElement.before(node); } public Element after(String html) { return originElement.after(html); } public Element after(Node node) { return originElement.after(node); } public Element empty() { return originElement.empty(); } public Element wrap(String html) { return originElement.wrap(html); } public Elements siblingElements() { return originElement.siblingElements(); } public List<Node> siblingNodes() { return originElement.siblingNodes(); } public Element nextElementSibling() { return originElement.nextElementSibling(); } public Node nextSibling() { return originElement.nextSibling(); } public Element previousElementSibling() { return originElement.previousElementSibling(); } public Node previousSibling() { return originElement.previousSibling(); } public int siblingIndex() { return originElement.siblingIndex(); } public Element firstElementSibling() { return originElement.firstElementSibling(); } public Integer elementSiblingIndex() { return originElement.elementSiblingIndex(); } public Node traverse(NodeVisitor nodeVisitor) { return originElement.traverse(nodeVisitor); } public Element lastElementSibling() { return originElement.lastElementSibling(); } public String outerHtml() { return originElement.outerHtml(); } public Elements getElementsByTag(String tagName) { return originElement.getElementsByTag(tagName); } public Element getElementById(String id) { return originElement.getElementById(id); } public Elements getElementsByClass(String className) { return originElement.getElementsByClass(className); } public Elements getElementsByAttribute(String key) { return originElement.getElementsByAttribute(key); } public Elements getElementsByAttributeStarting(String keyPrefix) { return originElement.getElementsByAttributeStarting(keyPrefix); } public Elements getElementsByAttributeValue(String key, String value) { return originElement.getElementsByAttributeValue(key, value); } public Elements getElementsByAttributeValueNot(String key, String value) { return originElement.getElementsByAttributeValueNot(key, value); } public Elements getElementsByAttributeValueStarting(String key, String valuePrefix) { return originElement.getElementsByAttributeValueStarting(key, valuePrefix); } public Elements getElementsByAttributeValueEnding(String key, String valueSuffix) { return originElement.getElementsByAttributeValueEnding(key, valueSuffix); } public Elements getElementsByAttributeValueContaining(String key, String match) { return originElement.getElementsByAttributeValueContaining(key, match); } public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) { return originElement.getElementsByAttributeValueMatching(key, pattern); } public Elements getElementsByAttributeValueMatching(String key, String regex) { return originElement.getElementsByAttributeValueMatching(key, regex); } public Elements getElementsByIndexLessThan(int index) { return originElement.getElementsByIndexLessThan(index); } public Elements getElementsByIndexGreaterThan(int index) { return originElement.getElementsByIndexGreaterThan(index); } public Elements getElementsByIndexEquals(int index) { return originElement.getElementsByIndexEquals(index); } public Elements getElementsContainingText(String searchText) { return originElement.getElementsContainingText(searchText); } public Elements getElementsContainingOwnText(String searchText) { return originElement.getElementsContainingOwnText(searchText); } public Elements getElementsMatchingText(Pattern pattern) { return originElement.getElementsMatchingText(pattern); } public Elements getElementsMatchingText(String regex) { return originElement.getElementsMatchingText(regex); } public Elements getElementsMatchingOwnText(Pattern pattern) { return originElement.getElementsMatchingOwnText(pattern); } public Elements getElementsMatchingOwnText(String regex) { return originElement.getElementsMatchingOwnText(regex); } public Elements getAllElements() { return originElement.getAllElements(); } public String text() { return originElement.text(); } public String ownText() { return originElement.ownText(); } public Element text(String text) { return originElement.text(text); } public boolean hasText() { return originElement.hasText(); } public String data() { return originElement.data(); } public String className() { return originElement.className(); } public Set<String> classNames() { return originElement.classNames(); } public Element classNames(Set<String> classNames) { return originElement.classNames(classNames); } public boolean hasClass(String className) { return originElement.hasClass(className); } public Element addClass(String className) { return originElement.addClass(className); } public Element removeClass(String className) { return originElement.removeClass(className); } public Element toggleClass(String className) { return originElement.toggleClass(className); } public String val() { return originElement.val(); } public Element val(String value) { return originElement.val(value); } public String html() { return originElement.html(); } public Element html(String html) { return originElement.html(html); } public String toString() { return originElement.toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } TestableElementWrapper other = (TestableElementWrapper) obj; if (originElement == null) { if (other.originElement != null) return false; } else if (!originElement.outerHtml().equals(other.originElement.outerHtml())) return false; return true; } @Override public int hashCode() { return originElement.hashCode(); } public Element clone() { return originElement.clone(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,416,696,372,179,708,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.render.test; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.transformer.Transformer; /** * This interface is used by {@link RendererTester} to retrieve the testable data from a {@link Transformer}.<br> * * A content that passed to transformer can implement this interface too. Especially for customized implementations of {@link ElementSetter} * , implementing this interface can afford better testability. * * @author e-ryu * */ public interface TestableRendering { /** * return a testable value for test purpose * * @return */ public Object retrieveTestableData(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,508,351,664,427,920,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.render.transformer; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.extnode.GroupNode; public class FutureTransformer extends Transformer<Future<?>> { private final static Logger logger = LoggerFactory.getLogger(FutureTransformer.class); public FutureTransformer(Future<?> content) { super(content); } @Override protected Element transform(Element elem, Future<?> future) { try { Object result = future.get(); Transformer<?> transformer = TransformerFactory.generateTransformer(result); return transformer.invoke(elem); } catch (InterruptedException | ExecutionException e) { logger.error("Failed retrieve result from future:" + e.getMessage(), e); return new GroupNode(); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,641,290,101,984,643,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.render.transformer; import java.util.concurrent.Future; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Component; import com.astamuse.asta4d.render.ElementRemover; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.SpecialRenderer; import com.astamuse.asta4d.render.TextSetter; public class TransformerFactory { private final static boolean treatNullAsRemoveNode; static { String treat = System.getProperty("com.astamuse.asta4d.render.treatNullAsRemoveNode"); if (treat == null) { treatNullAsRemoveNode = true; } else { treatNullAsRemoveNode = Boolean.parseBoolean(treat); } } private final static Logger logger = LoggerFactory.getLogger(TransformerFactory.class); public final static Transformer<?> generateTransformer(Object action) { Transformer<?> transformer; if (action == null && treatNullAsRemoveNode) { transformer = new ElementRemover(); } else if (action instanceof Renderer) { // most of list rendering will return a list of Renderer, so put it at the first place transformer = new RendererTransformer((Renderer) action); } else if (action instanceof SpecialRenderer) { transformer = SpecialRenderer.retrieveTransformer((SpecialRenderer) action); } else if (action instanceof ElementSetter) { transformer = new ElementSetterTransformer((ElementSetter) action); } else if (action instanceof Future) { transformer = new FutureTransformer((Future<?>) action); } else if (action instanceof Element) { transformer = new ElementTransformer((Element) action); } else if (action instanceof Component) { transformer = new ElementTransformer(((Component) action).toElement()); } else if (action instanceof Renderable) { transformer = new RenderableTransformer((Renderable) action); } else { transformer = new ElementSetterTransformer(new TextSetter(action)); } return transformer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,460,504,360,016,334,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.render.transformer; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.ElementSetter; public class ElementSetterTransformer extends Transformer<ElementSetter> { public ElementSetterTransformer(ElementSetter content) { super(content); } public ElementSetterTransformer(ElementSetter content, Object originalData) { super(content, originalData); } @Override public Element transform(Element elem, ElementSetter content) { Element result = elem.clone(); content.set(result); return result; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,895,682,746,344,362,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.render.transformer; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; public class RenderableTransformer extends Transformer<Renderable> { public RenderableTransformer(Renderable content) { super(content); } @Override protected Element transform(Element elem, Renderable content) { Renderer render = content.render(); if (render == null) { throw new NullPointerException(); } RendererTransformer delegatedTransformer = new RendererTransformer(render); return delegatedTransformer.invoke(elem); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,931,760,867,807,433,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.render.transformer; import org.jsoup.nodes.Element; public class ElementTransformer extends Transformer<Element> { public ElementTransformer(Element content, Object originalData) { super(content, originalData); } public ElementTransformer(Element content) { super(content); } @Override protected Element transform(Element elem, Element content) { return content.clone(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,357,378,526,771,357,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.render.transformer; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.test.TestableRendering; public abstract class Transformer<T> implements TestableRendering { // I want Optional in java 8 private boolean originalDataConfigured = false; private Object originalData = null; private T content; public Transformer(T content) { this.content = content; } public Transformer(T content, Object originalData) { this.content = content; this.originalDataConfigured = true; this.originalData = originalData; } public Element invoke(Element elem) { return transform(elem, content); } protected abstract Element transform(Element elem, T content); @Override public String toString() { return this.getClass().getName() + ":[" + this.content.toString() + "]"; } public T getContent() { return content; } @Override public Object retrieveTestableData() { if (originalDataConfigured) { return originalData; } else { return content; } } public void setOringialData(Object originalData) { this.originalData = originalData; this.originalDataConfigured = true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((content == null) ? 0 : content.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Transformer other = (Transformer) obj; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; return true; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,120,705,987,353,020,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.render.transformer; import org.jsoup.nodes.Element; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.RenderUtil; import com.astamuse.asta4d.render.Renderer; public class RendererTransformer extends Transformer<Renderer> { public RendererTransformer(Renderer content) { super(content); } @Override protected Element transform(Element elem, Renderer content) { Element result = elem.clone(); // add a dummy parent so that the result element can be replaced by the // sub renderer. GroupNode wrapper = new GroupNode(); wrapper.appendChild(result); RenderUtil.apply(result, content); return wrapper; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,042,548,725,849,120,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.extnode; import java.util.Iterator; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; /** * A node used for extending purpose. * * @author e-ryu * */ public class ExtNode extends Element { public ExtNode(String tag) { super(Tag.valueOf(tag), ""); } public ExtNode(String tag, String cssClass) { this(tag); this.addClass(cssClass); } public void copyAttributes(Element src) { Attributes attrs = src.attributes(); Iterator<Attribute> it = attrs.iterator(); Attribute attr; while (it.hasNext()) { attr = it.next(); this.attr(attr.getKey(), attr.getValue()); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,099,594,429,523,866,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.extnode; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.util.IdGenerator; import com.astamuse.asta4d.util.SelectorUtil; public class ExtNodeConstants { public final static String ID_PREFIX = Configuration.getConfiguration().getTagNameSpace(); private final static String addNS(String name) { return ID_PREFIX + ":" + name; } /* We add non-conflict suffix to non-exposed attributes to avoid conflict with client source. * We do not need to add the suffix the exposed attributes which are treated as api convention. */ private final static String UniqAttrSufffix = "-" + IdGenerator.createId(); public final static String BLOCK_NODE_NAME = "block"; public final static String BLOCK_NODE_TAG = addNS(BLOCK_NODE_NAME); public final static String BLOCK_NODE_TAG_SELECTOR = SelectorUtil.tag(BLOCK_NODE_TAG); public final static String BLOCK_NODE_ATTR_OVERRIDE = "override"; public final static String BLOCK_NODE_ATTR_APPEND = "append"; public final static String BLOCK_NODE_ATTR_INSERT = "insert"; public final static String EXTENSION_NODE_NAME = "extension"; public final static String EXTENSION_NODE_TAG = addNS(EXTENSION_NODE_NAME); public final static String EXTENSION_NODE_TAG_SELECTOR = SelectorUtil.tag(EXTENSION_NODE_TAG); public final static String EXTENSION_NODE_ATTR_PARENT = "parent"; public final static String EMBED_NODE_NAME = "embed"; public final static String EMBED_NODE_TAG = addNS(EMBED_NODE_NAME); public final static String EMBED_NODE_TAG_SELECTOR = SelectorUtil.tag(EMBED_NODE_TAG); public final static String EMBED_NODE_ATTR_TARGET = "target"; public final static String EMBED_NODE_ATTR_STATIC = "static"; public final static String EMBED_NODE_ATTR_BLOCK = "block" + UniqAttrSufffix; public final static String SNIPPET_NODE_NAME = "snippet"; public final static String SNIPPET_NODE_TAG = addNS(SNIPPET_NODE_NAME); public final static String SNIPPET_NODE_TAG_SELECTOR = SelectorUtil.tag(SNIPPET_NODE_TAG); public final static String SNIPPET_NODE_ATTR_RENDER = "render"; public final static String SNIPPET_NODE_ATTR_RENDER_WITH_NS = addNS(SNIPPET_NODE_ATTR_RENDER); public final static String SNIPPET_NODE_ATTR_PARALLEL = "parallel"; public final static String SNIPPET_NODE_ATTR_PARALLEL_WITH_NS = addNS(SNIPPET_NODE_ATTR_PARALLEL); public final static String SNIPPET_NODE_ATTR_TYPE = "type" + UniqAttrSufffix; public final static String SNIPPET_NODE_ATTR_TYPE_USERDEFINE = "userdefine"; public final static String SNIPPET_NODE_ATTR_TYPE_FAKE = "fake"; public final static String SNIPPET_NODE_ATTR_STATUS = "status" + UniqAttrSufffix; public final static String SNIPPET_NODE_ATTR_STATUS_READY = "ready"; public final static String SNIPPET_NODE_ATTR_STATUS_WAITING = "waiting"; public final static String SNIPPET_NODE_ATTR_STATUS_FINISHED = "finished"; public final static String SNIPPET_NODE_ATTR_BLOCK = "block" + UniqAttrSufffix; public final static String GROUP_NODE_NAME = "group"; public final static String GROUP_NODE_TAG = addNS(GROUP_NODE_NAME); public final static String GROUP_NODE_TAG_SELECTOR = SelectorUtil.tag(GROUP_NODE_TAG); public final static String GROUP_NODE_ATTR_TYPE = "type" + UniqAttrSufffix; public final static String GROUP_NODE_ATTR_TYPE_USERDEFINE = "userdefine"; public final static String GROUP_NODE_ATTR_TYPE_FAKE = "fake"; public final static String GROUP_NODE_ATTR_TYPE_EMBED_WRAPPER = "embed_wrapper"; public final static String COMMENT_NODE_NAME = "comment"; public final static String COMMENT_NODE_TAG = addNS(COMMENT_NODE_NAME); public final static String COMMENT_NODE_TAG_SELECTOR = SelectorUtil.tag(COMMENT_NODE_TAG); public final static String MSG_NODE_NAME = "msg"; public final static String MSG_NODE_TAG = addNS(MSG_NODE_NAME); public final static String MSG_NODE_TAG_SELECTOR = SelectorUtil.tag(MSG_NODE_TAG); public final static String MSG_NODE_ATTR_KEY = "key"; public final static String MSG_NODE_ATTRVALUE_TEXT_PREFIX = "text:"; public final static String MSG_NODE_ATTRVALUE_HTML_PREFIX = "html:"; public final static String MSG_NODE_ATTR_PARAM_PREFIX = "p"; public final static String MSG_NODE_ATTR_LOCALE = "locale"; public final static String ATTR_TEMPLATE_PATH = "template-path"; public final static String ATTR_SNIPPET_REF = "snippet-ref"; public final static String ATTR_DOC_REF = "doc-ref"; public final static String ATTR_CLEAR = "clear"; public final static String ATTR_CLEAR_WITH_NS = addNS(ATTR_CLEAR); /** * sample of attr with body tag: <br> * * <pre> * &lt;body afd:bodyonly&gt; * &lt;div&gt;aaa&lt;/div&gt; * &lt;/body&gt; * </pre> * * sample of attr in meta: <br> * * * <pre> * &lt;html&gt; * &lt;head&gt; * &lt;meta afd:bodyonly&gt; * &lt;/head&gt; * &lt;body&gt; * &lt;div&gt;aaa&lt;/div&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * The output of both of above are as same as following: * * <pre> * &lt;div&gt;aaa&lt;/div&gt; * </pre> */ public final static String ATTR_BODY_ONLY_WITH_NS = addNS("bodyonly"); public final static String ATTR_DATAREF_PREFIX = "dataref-"; public final static String ATTR_DATAREF_PREFIX_WITH_NS = addNS(ATTR_DATAREF_PREFIX); //@formatter:off public final static String[] ASTA4D_IN_HEAD_NODE_TAGS = { BLOCK_NODE_TAG, EMBED_NODE_TAG, SNIPPET_NODE_TAG, GROUP_NODE_TAG, COMMENT_NODE_TAG, MSG_NODE_TAG }; //@formatter:on }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,310,356,393,703,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.extnode; /** * This node is intended to be used for a variety of purposes, such as combining multi nodes to a single node or being a place holder. * * @author e-ryu * */ public class GroupNode extends ExtNode { public GroupNode() { this(ExtNodeConstants.GROUP_NODE_ATTR_TYPE_FAKE); } public GroupNode(String type) { super(ExtNodeConstants.GROUP_NODE_TAG); this.attr(ExtNodeConstants.GROUP_NODE_ATTR_TYPE, type); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,381,073,126,065,654,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.extnode; import com.astamuse.asta4d.render.SpecialRenderer; /** * * A ClearNode will be removed after rendering. There is no warranty about when * a ClearNode will be removed but it was warranted that a ClearNode will be * eventually removed at the last of rendering process. <br> * Further, a formal html element with attribute "afd:clear" will be treated as * a ClearNode too. * * This class has been deprecated and you don't need to use this class for * removing nodes, {@link SpecialRenderer#Clear} can be used for remove a * certain node, and a null value passed to Renderer will remove the target node * too. * * @author e-ryu * @see SpecialRenderer#Clear */ @Deprecated public class ClearNode extends GroupNode { public ClearNode() { super(); this.attr(ExtNodeConstants.ATTR_CLEAR, ""); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,068,213,736,926,806,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.data; /** * The policy of how to handle the unmatched type on data conversion. * * @author e-ryu * */ public enum TypeUnMacthPolicy { /** * throw exception */ EXCEPTION, /** * assign default value to target */ DEFAULT_VALUE, /** * assign default value to target, also save the trace information in context */ DEFAULT_VALUE_AND_TRACE }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
331,223,012,985,406,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.data; class TypeInfo { private final Class<?> type; private final Object defaultValue; TypeInfo(Class<?> type) { // convert primitive types to their box types if (type.isPrimitive()) { String name = type.getName(); switch (name) { case "char": this.type = Character.class; this.defaultValue = ' '; break; case "byte": this.type = Byte.class; this.defaultValue = Byte.valueOf((byte) 0); break; case "short": this.type = Short.class; this.defaultValue = Short.valueOf((short) 0); break; case "int": this.type = Integer.class; this.defaultValue = Integer.valueOf(0); break; case "long": this.type = Long.class; this.defaultValue = Long.valueOf(0L); break; case "float": this.type = Float.class; this.defaultValue = Float.valueOf(0.0F); break; case "double": this.type = Double.class; this.defaultValue = Double.valueOf(0.0D); break; case "boolean": this.type = Boolean.class; this.defaultValue = Boolean.FALSE; break; default: throw new IllegalArgumentException("Unexpected Primitive Type Name : " + name); } } else if (type.isArray() && type.getComponentType().isPrimitive()) { String name = type.getComponentType().getName(); switch (name) { case "char": this.type = Character[].class; this.defaultValue = new Character[0]; break; case "byte": this.type = Byte[].class; this.defaultValue = new Byte[0]; break; case "short": this.type = Short[].class; this.defaultValue = new Short[0]; break; case "int": this.type = Integer[].class; this.defaultValue = new Integer[0]; break; case "long": this.type = Long[].class; this.defaultValue = new Long[0]; break; case "float": this.type = Float[].class; this.defaultValue = new Float[0]; break; case "double": this.type = Double[].class; this.defaultValue = new Double[0]; break; case "boolean": this.type = Boolean[].class; this.defaultValue = new Boolean[0]; break; default: throw new IllegalArgumentException("Unexpected Primitive Type Name : " + name); } } else { this.type = type; this.defaultValue = null; } } Class<?> getType() { return type; } Object getDefaultValue() { return defaultValue; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,000,385,424,406,731,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.data; public interface ContextDataSetFactory { @SuppressWarnings("rawtypes") public Object createInstance(Class cls); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,130,651,904,694,547,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.data; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.data.annotation.ContextDataSet; import com.astamuse.asta4d.util.Java8Paranamer; import com.astamuse.asta4d.util.Java8ParanamerBytecodeScanWrapper; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil; import com.astamuse.asta4d.util.annotation.ConvertableAnnotationRetriever; import com.thoughtworks.paranamer.AdaptiveParanamer; import com.thoughtworks.paranamer.AnnotationParanamer; import com.thoughtworks.paranamer.DefaultParanamer; import com.thoughtworks.paranamer.Paranamer; /** * This class is a function holder to supply functionalities about data injection * * @author e-ryu * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class InjectUtil { private final static Logger logger = LoggerFactory.getLogger(InjectUtil.class); private static final String ContextDataSetSingletonMapKey = "ContextDataSetSingletonMapKey#" + InjectUtil.class.getName(); public static final String ContextDataNotFoundScope = "#ContextDataNotFoundScope"; public static final String ContextDataTypeUnMatchScope = "#ContextDataTypeUnMatchScope"; /** * A class that present the injectable target information * * @author e-ryu * */ private static class TargetInfo { AnnotatedPropertyInfo propertyInfo; String name; String scope; TypeUnMacthPolicy typeUnMatch; ContextDataSetFactory contextDataSetFactory; boolean isContextDataSetSingletonInContext; Class<?> type; boolean isContextDataHolder; Object defaultValue; void fixForPrimitiveType() { TypeInfo typeInfo = new TypeInfo(type); type = typeInfo.getType(); defaultValue = typeInfo.getDefaultValue(); } ContextDataHolder createDataHolderInstance() throws InstantiationException, IllegalAccessException { if (isContextDataHolder) { return (ContextDataHolder) type.newInstance(); } else { return new ContextDataHolder(type); } } } private static class MethodInfo extends TargetInfo { Method method; } private static class FieldInfo extends TargetInfo { Field field; } private static class InstanceWireTarget { List<FieldInfo> setFieldList = new ArrayList<>(); List<FieldInfo> getFieldList = new ArrayList<>(); List<MethodInfo> setMethodList = new ArrayList<>(); List<MethodInfo> getMethodList = new ArrayList<>(); } private final static ConcurrentHashMap<String, InstanceWireTarget> InstanceTargetCache = new ConcurrentHashMap<>(); private final static ConcurrentHashMap<Method, List<TargetInfo>> MethodTargetCache = new ConcurrentHashMap<>(); private final static Paranamer paranamer = new AdaptiveParanamer(new DefaultParanamer(), new Java8ParanamerBytecodeScanWrapper(), new AnnotationParanamer(), new Java8Paranamer()); public final static Object retrieveContextDataSetInstance(Class cls, String searchName, String searchScope) throws DataOperationException { try { ContextDataSet cds = ConvertableAnnotationRetriever.retrieveAnnotation(ContextDataSet.class, cls.getAnnotations()); if (cds == null) { throw new NullPointerException("Could not find any ContextDataSet convertable annotation on given class:" + cls.getName()); } TargetInfo info = new TargetInfo(); info.contextDataSetFactory = cds.factory().newInstance(); info.isContextDataSetSingletonInContext = cds.singletonInContext(); info.defaultValue = null; info.name = searchName; info.scope = searchScope; info.type = cls; info.typeUnMatch = TypeUnMacthPolicy.EXCEPTION; ContextDataHolder result = findValueForTarget(info, null); if (result == null) { return null; } else { return result.getValue(); } } catch (IllegalAccessException | InstantiationException e) { throw new DataOperationException(e.getMessage(), e); } } /** * Set the value of all the fields marked by {@link ContextData} of the given instance. * * @param instance * @throws DataOperationException */ public final static void injectToInstance(Object instance) throws DataOperationException { InstanceWireTarget target = getInstanceTarget(instance); for (FieldInfo fi : target.setFieldList) { try { ContextDataHolder valueHolder = null; if (fi.isContextDataHolder) { valueHolder = (ContextDataHolder) FieldUtils.readField(fi.field, instance); } if (valueHolder == null) { valueHolder = fi.createDataHolderInstance(); } Class searchType = valueHolder.getTypeCls(); if (searchType == null) { throw new DataOperationException( fi.field.getName() + " should be initialized at first or we can not retrieve the type you want since it is a type of CotnextDataHolder. " + "You can also define an extended class to return the type class, in this case, you do not need to initialized it by your self"); } ContextDataHolder foundData = findValueForTarget(fi, searchType); handleTypeUnMatch(instance, fi, foundData); if (fi.isContextDataHolder) { transferDataHolder(foundData, valueHolder); FieldUtils.writeField(fi.field, instance, valueHolder, true); } else { FieldUtils.writeField(fi.field, instance, foundData.getValue(), true); } } catch (IllegalAccessException | IllegalArgumentException | InstantiationException e) { throw new DataOperationException("Exception when inject value to " + fi.field.toString(), e); } } for (MethodInfo mi : target.setMethodList) { try { ContextDataHolder valueHolder = mi.createDataHolderInstance(); Class searchType = valueHolder.getTypeCls(); if (searchType == null) { throw new DataOperationException(mi.method.getName() + " cannot initialize an instance of " + valueHolder.getClass().getName() + ". You should define an extended class to return the type class"); } ContextDataHolder foundData = findValueForTarget(mi, searchType); handleTypeUnMatch(instance, mi, foundData); if (mi.isContextDataHolder) { transferDataHolder(foundData, valueHolder); mi.method.invoke(instance, valueHolder); } else { mi.method.invoke(instance, foundData.getValue()); } } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | InvocationTargetException e) { throw new DataOperationException("Exception when inject value to " + mi.method.toString(), e); } } } private static void handleTypeUnMatch(Object instance, FieldInfo target, ContextDataHolder valueHolder) throws DataOperationException { handleTypeUnMatch(instance, target.field, null, null, -1, target, valueHolder); } private static void handleTypeUnMatch(Object instance, MethodInfo target, ContextDataHolder valueHolder) throws DataOperationException { handleTypeUnMatch(instance, null, target.method, null, -1, target, valueHolder); } private static void handleTypeUnMatch(Method method, int methodParameterIndex, TargetInfo target, ContextDataHolder valueHolder) throws DataOperationException { handleTypeUnMatch(null, null, null, method, methodParameterIndex, target, valueHolder); } private static void handleTypeUnMatch(Object instance, Field field, Method setter, Method method, int methodParameterIndex, TargetInfo target, ContextDataHolder valueHolder) throws DataOperationException { // type unmatched if (ContextDataTypeUnMatchScope.equals(valueHolder.getScope())) { switch (target.typeUnMatch) { case EXCEPTION: String msg = "Found data(%s) cannot be coverted from [%s] to [%s]."; msg = String.format(msg, valueHolder.getFoundOriginalData(), valueHolder.getFoundOriginalData().getClass(), target.type); throw new DataOperationException(msg); case DEFAULT_VALUE: valueHolder.setData(valueHolder.getName(), valueHolder.getScope(), target.defaultValue); break; case DEFAULT_VALUE_AND_TRACE: ContextDataHolder traceHolder = new ContextDataHolder(); transferDataHolder(valueHolder, traceHolder); if (field != null) { InjectTrace.saveInstanceInjectionTraceInfo(instance, field, traceHolder); } else if (setter != null) { InjectTrace.saveInstanceInjectionTraceInfo(instance, setter, traceHolder); } else if (method != null) { InjectTrace.saveMethodInjectionTraceInfo(method, methodParameterIndex, traceHolder); } valueHolder.setData(valueHolder.getName(), valueHolder.getScope(), target.defaultValue); break; } } } private static void transferDataHolder(ContextDataHolder from, ContextDataHolder to) { to.setData(from.getName(), from.getScope(), from.getFoundOriginalData(), from.getValue()); } private static ContextDataHolder findValueForTarget(TargetInfo targetInfo, Class overrideSearchType) throws DataOperationException { Context context = Context.getCurrentThreadContext(); ContextDataFinder dataFinder = Configuration.getConfiguration().getContextDataFinder(); Class searchType = overrideSearchType == null ? targetInfo.type : overrideSearchType; ContextDataHolder valueHolder = dataFinder.findDataInContext(context, targetInfo.scope, targetInfo.name, searchType); if (valueHolder == null && targetInfo.contextDataSetFactory != null) { Object value; if (targetInfo.isContextDataSetSingletonInContext) { // this map was initialized when the context was initialized HashMap<String, Object> cdSetSingletonMap = context.getData(ContextDataSetSingletonMapKey); // we must synchronize it to avoid concurrent access on the map synchronized (cdSetSingletonMap) { String clsName = targetInfo.type.getName(); value = cdSetSingletonMap.get(clsName); if (value == null) { value = targetInfo.contextDataSetFactory.createInstance(targetInfo.type); injectToInstance(value); cdSetSingletonMap.put(clsName, value); } } } else { value = targetInfo.contextDataSetFactory.createInstance(targetInfo.type); injectToInstance(value); } valueHolder = new ContextDataHolder(targetInfo.name, targetInfo.scope, value); } else if (valueHolder == null) { valueHolder = new ContextDataHolder(targetInfo.name, ContextDataNotFoundScope, targetInfo.defaultValue); } return valueHolder; } /** * Retrieve values from fields marked as reverse injectable of given instance. * * There are only limited scopes can be marked as injectable. See {@link Configuration#setReverseInjectableScopes(List)}. * * NOT SUPPORTED ANY MORE!!! * * @param instance * @throws DataOperationException */ @Deprecated public final static void setContextDataFromInstance(Object instance) throws DataOperationException { try { Context context = Context.getCurrentThreadContext(); InstanceWireTarget target = getInstanceTarget(instance); Object value; for (FieldInfo fi : target.getFieldList) { value = FieldUtils.readField(fi.field, instance, true); context.setData(fi.scope, fi.name, value); } for (MethodInfo mi : target.getMethodList) { value = mi.method.invoke(instance); context.setData(mi.scope, mi.name, value); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { String msg = String.format("Exception when inject value from instance of [%s] to Context.", instance.getClass().toString()); throw new DataOperationException(msg, e); } } private final static InstanceWireTarget getInstanceTarget(Object instance) throws DataOperationException { boolean cacheEnable = Configuration.getConfiguration().isCacheEnable(); InstanceWireTarget target = null; if (cacheEnable) { String key = instance.getClass().getName(); target = InstanceTargetCache.get(key); if (target == null) { target = createInstanceTarget(instance); InstanceTargetCache.put(key, target); } } else { target = createInstanceTarget(instance); } return target; } private final static InstanceWireTarget createInstanceTarget(Object instance) throws DataOperationException { InstanceWireTarget target = new InstanceWireTarget(); Class<?> cls = instance.getClass(); List<AnnotatedPropertyInfo> propertyList = AnnotatedPropertyUtil.retrieveProperties(cls); try { for (AnnotatedPropertyInfo prop : propertyList) { ContextData cd = prop.getAnnotation(ContextData.class); if (prop.getField() != null) { Field field = prop.getField(); FieldInfo fi = new FieldInfo(); fi.propertyInfo = prop; fi.name = prop.getName(); fi.field = field; fi.type = field.getType(); fi.isContextDataHolder = ContextDataHolder.class.isAssignableFrom(fi.type); fi.scope = cd.scope(); fi.typeUnMatch = cd.typeUnMatch(); fi.fixForPrimitiveType(); ContextDataSet cdSet = ConvertableAnnotationRetriever .retrieveAnnotation(ContextDataSet.class, fi.type.getAnnotations()); if (cdSet == null) { fi.contextDataSetFactory = null; } else { fi.contextDataSetFactory = cdSet.factory().newInstance(); fi.isContextDataSetSingletonInContext = cdSet.singletonInContext(); } target.setFieldList.add(fi); } else {// for method MethodInfo mi = new MethodInfo(); mi.propertyInfo = prop; mi.name = prop.getName(); mi.method = prop.getSetter(); if (mi.method == null) { throw new DataOperationException("Could not find setter method for annotated property:" + prop.getName()); } mi.type = mi.method.getParameterTypes()[0]; mi.isContextDataHolder = ContextDataHolder.class.isAssignableFrom(mi.type); mi.scope = cd.scope(); mi.typeUnMatch = cd.typeUnMatch(); mi.fixForPrimitiveType(); ContextDataSet cdSet = ConvertableAnnotationRetriever .retrieveAnnotation(ContextDataSet.class, mi.type.getAnnotations()); if (cdSet == null) { mi.contextDataSetFactory = null; } else { mi.contextDataSetFactory = cdSet.factory().newInstance(); mi.isContextDataSetSingletonInContext = cdSet.singletonInContext(); } target.setMethodList.add(mi); } } } catch (InstantiationException | IllegalAccessException e) { throw new DataOperationException("Exception occured on generating injection information of " + instance.getClass(), e); } return target; } /** * Retrieve value from {@link Context} for given Method by configured {@link ContextDataFinder} * * @param method * given method * @return Retrieved values * @throws DataOperationException */ public final static Object[] getMethodInjectParams(Method method) throws DataOperationException { ContextDataFinder dataFinder = Configuration.getConfiguration().getContextDataFinder(); return getMethodInjectParams(method, dataFinder); } /** * Retrieve value from {@link Context} for given Method by given {@link ContextDataFinder} * * @param method * given method * @param dataFinder * given ContextDataFinder * @return Retrieved values * @throws DataOperationException */ public final static Object[] getMethodInjectParams(Method method, ContextDataFinder dataFinder) throws DataOperationException { try { List<TargetInfo> targetList = getMethodTarget(method); Object[] params = new Object[targetList.size()]; if (params.length == 0) { return params; } TargetInfo target; ContextDataHolder valueHolder, foundData; Class searchType; for (int i = 0; i < params.length; i++) { target = targetList.get(i); valueHolder = target.createDataHolderInstance(); searchType = valueHolder.getTypeCls(); if (searchType == null) { throw new DataOperationException(method.getName() + " cannot initialize an instance of " + valueHolder.getClass().getName() + ". You should define an extended class to return the type class"); } foundData = findValueForTarget(target, searchType); handleTypeUnMatch(method, i, target, foundData); if (target.isContextDataHolder) { transferDataHolder(foundData, valueHolder); params[i] = valueHolder; } else { params[i] = foundData.getValue(); } } return params; } catch (InstantiationException | IllegalAccessException e) { throw new DataOperationException("create instance failed.", e); } } private final static List<TargetInfo> getMethodTarget(Method method) throws InstantiationException, IllegalAccessException { boolean cacheEnable = Configuration.getConfiguration().isCacheEnable(); List<TargetInfo> targetList = null; if (cacheEnable) { targetList = MethodTargetCache.get(method); if (targetList == null) { targetList = createMethodTarget(method); MethodTargetCache.put(method, targetList); } } else { targetList = createMethodTarget(method); } return targetList; } private final static List<TargetInfo> createMethodTarget(Method method) throws InstantiationException, IllegalAccessException { Class<?>[] types = method.getParameterTypes(); List<TargetInfo> targetList = new ArrayList<>(); if (types.length == 0) { return targetList; } Annotation[][] annotations = method.getParameterAnnotations(); String[] parameterNames = paranamer.lookupParameterNames(method); TargetInfo target; ContextData cd; ContextDataSet cdSet; for (int i = 0; i < types.length; i++) { target = new TargetInfo(); target.type = types[i]; target.isContextDataHolder = ContextDataHolder.class.isAssignableFrom(target.type); cd = ConvertableAnnotationRetriever.retrieveAnnotation(ContextData.class, annotations[i]); cdSet = ConvertableAnnotationRetriever.retrieveAnnotation(ContextDataSet.class, target.type.getAnnotations()); target.name = cd == null ? "" : cd.name(); target.scope = cd == null ? "" : cd.scope(); target.typeUnMatch = cd == null ? TypeUnMacthPolicy.EXCEPTION : cd.typeUnMatch(); if (StringUtils.isEmpty(target.name)) { target.name = parameterNames[i]; } if (cdSet == null) { target.contextDataSetFactory = null; } else { target.contextDataSetFactory = cdSet.factory().newInstance(); target.isContextDataSetSingletonInContext = cdSet.singletonInContext(); } target.fixForPrimitiveType(); targetList.add(target); } return targetList; } public static final void initContext(Context context) { context.setData(ContextDataSetSingletonMapKey, new HashMap()); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,264,491,711,541,365,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.data; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import com.astamuse.asta4d.Context; @SuppressWarnings("rawtypes") public class InjectTrace { private static class TraceMap extends HashMap<String, ContextDataHolder>implements Serializable { /** * */ private static final long serialVersionUID = 1L; Object targetInstance; } private static class InstanceTraceList extends LinkedList<TraceMap>implements Serializable { /** * */ private static final long serialVersionUID = 1L; } private static final String InstanceTraceListSaveKey = InjectTrace.class.getName() + "#InstanceTraceListSaveKey"; public static final void saveInstanceInjectionTraceInfo(Object instance, Method setter, ContextDataHolder valueHolder) { saveInstanceInjectionTraceInfoInner(instance, createTraceKey(setter), valueHolder); } public static final void saveInstanceInjectionTraceInfo(Object instance, Field field, ContextDataHolder valueHolder) { saveInstanceInjectionTraceInfoInner(instance, createTraceKey(field), valueHolder); } public static final void saveInstanceInjectionTraceInfo(Object instance, String propertyName, ContextDataHolder valueHolder) { saveInstanceInjectionTraceInfoInner(instance, "pn:" + propertyName, valueHolder); } public static final void saveMethodInjectionTraceInfo(Method method, int parameterIndex, ContextDataHolder valueHolder) { saveInstanceInjectionTraceInfoInner(null, createTraceKey(method, parameterIndex), valueHolder); } private static final void saveInstanceInjectionTraceInfoInner(Object instance, String traceKey, ContextDataHolder valueHolder) { Context context = Context.getCurrentThreadContext(); InstanceTraceList traceList = context.getData(InstanceTraceListSaveKey); if (traceList == null) { traceList = new InstanceTraceList(); context.setData(InstanceTraceListSaveKey, traceList); } synchronized (traceList) { TraceMap traceMap = null; for (TraceMap map : traceList) { if (map.targetInstance == instance) { traceMap = map; break; } } if (traceMap == null) { traceMap = new TraceMap(); traceMap.targetInstance = instance; traceList.add(traceMap); } traceMap.put(traceKey, valueHolder); } } public static final ContextDataHolder getInstanceInjectionTraceInfo(Object instance, Method setter) { return getInstanceInjectionTraceInfoInner(instance, createTraceKey(setter)); } public static final ContextDataHolder getInstanceInjectionTraceInfo(Object instance, Field field) { return getInstanceInjectionTraceInfoInner(instance, createTraceKey(field)); } public static final ContextDataHolder getInstanceInjectionTraceInfo(Object instance, String propertyName) { return getInstanceInjectionTraceInfoInner(instance, "pn:" + propertyName); } public static final ContextDataHolder getMethodInjectionTraceInfo(Method method, int parameterIndex) { return getInstanceInjectionTraceInfoInner(null, createTraceKey(method, parameterIndex)); } private static final ContextDataHolder getInstanceInjectionTraceInfoInner(Object instance, String traceKey) { Context context = Context.getCurrentThreadContext(); InstanceTraceList traceList = context.getData(InstanceTraceListSaveKey); if (traceList == null) { return null; } synchronized (traceList) { TraceMap traceMap = null; for (TraceMap map : traceList) { if (map.targetInstance == instance) { traceMap = map; break; } } if (traceMap == null) { return null; } return traceMap.get(traceKey); } } private static final String createTraceKey(Method m) { return m.getDeclaringClass().getName() + ":" + m.toString(); } private static final String createTraceKey(Field f) { return f.getDeclaringClass().getName() + ":" + f.toString(); } private static final String createTraceKey(Method m, int parameterIndex) { return m.getDeclaringClass().getName() + ":" + m.toString() + ":" + parameterIndex; } public static final List retrieveTraceList() { Context context = Context.getCurrentThreadContext(); return context.getData(InstanceTraceListSaveKey); } public static final void restoreTraceList(List restoreList) { if (restoreList == null) { return; } for (TraceMap map : (InstanceTraceList) restoreList) { for (Entry<String, ContextDataHolder> entry : map.entrySet()) { saveInstanceInjectionTraceInfo(map.targetInstance, entry.getKey(), entry.getValue()); } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
764,880,397,586,244,900
/* * 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.data; /** * A DataOperationException is thrown when error occurs in injection process. * * @author e-ryu * */ public class DataOperationException extends Exception { private static final long serialVersionUID = 7731788993198703931L; public DataOperationException(String message, Throwable cause) { super(message, cause); } public DataOperationException(String message) { super(message); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,238,262,668,485,472,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.data; import java.io.Serializable; public class ContextDataHolder<T> implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; private String scope; private Object foundOriginalData; private T value; private Class<T> typeCls; public ContextDataHolder() { super(); } public ContextDataHolder(Class<T> typeCls) { super(); this.typeCls = typeCls; } public ContextDataHolder(String name, String scope, T value) { super(); this.name = name; this.scope = scope; this.value = value; this.foundOriginalData = value; } public String getName() { return name; } public String getScope() { return scope; } public Object getFoundOriginalData() { return foundOriginalData; } public T getValue() { return value; } public Class<T> getTypeCls() { return typeCls; } public void setData(String name, String scope, T value) { setData(name, scope, value, value); } public void setData(String name, String scope, Object foundValue, T transformedValue) { this.name = name; this.scope = scope; this.value = transformedValue; this.foundOriginalData = foundValue; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,238,983,683,554,134,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.data; public class DefaultContextDataSetFactory implements ContextDataSetFactory { @SuppressWarnings("rawtypes") @Override public Object createInstance(Class cls) { try { return cls.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,787,242,456,089,054,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.data; import com.astamuse.asta4d.Context; /** * This interface declares how to find a certain data in Context. Because there * are customized scopes, so an implementation can customize the search logic * against special scope. * * @author e-ryu * */ public interface ContextDataFinder { /** * find data from given context by certain logic * * @param context * {@link Context} * @param scope * scope * @param name * data saved key * @param type * data type * @return the data saved in context or null if not found * @throws DataOperationException */ @SuppressWarnings("rawtypes") public ContextDataHolder findDataInContext(Context context, String scope, String name, Class<?> type) throws DataOperationException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,129,016,993,591,506,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.data; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.convertor.DataValueConvertor; import com.astamuse.asta4d.data.convertor.UnsupportedValueException; import com.astamuse.asta4d.util.i18n.I18nMessageHelper; /** * A default implementation of {@link ContextDataFinder}. It will search data in a given order (if scope is not specified) and try to apply * predefined {@link ContextDataFinder} list to convert data to appropriate type. * * @author e-ryu * */ public class DefaultContextDataFinder implements ContextDataFinder { private final static String ByTypeScope = DefaultContextDataFinder.class.getName() + "#findByType"; private List<String> dataSearchScopeOrder = getDefaultScopeOrder(); private final static List<String> getDefaultScopeOrder() { List<String> list = new ArrayList<>(); list.add(Context.SCOPE_ATTR); list.add(Context.SCOPE_DEFAULT); list.add(Context.SCOPE_GLOBAL); return list; } public List<String> getDataSearchScopeOrder() { return dataSearchScopeOrder; } public void setDataSearchScopeOrder(List<String> dataSearchScopeOrder) { this.dataSearchScopeOrder = dataSearchScopeOrder; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public ContextDataHolder findDataInContext(Context context, String scope, String name, Class<?> targetType) throws DataOperationException { ContextDataHolder dataHolder = findByType(context, scope, name, targetType); if (dataHolder != null) { return dataHolder; } if (StringUtils.isEmpty(scope)) { dataHolder = findDataByScopeOrder(context, 0, name); } else { dataHolder = context.getDataHolder(scope, name); } if (dataHolder == null) { return null; } Object foundData = dataHolder.getValue(); Object transformedData = null; UnsupportedValueException usve = null; Class<?> srcType = new TypeInfo(foundData.getClass()).getType(); if (targetType.isAssignableFrom(srcType)) { transformedData = foundData; } else if (srcType.isArray() && targetType.isAssignableFrom(srcType.getComponentType())) { transformedData = Array.get(foundData, 0); } else if (targetType.isArray() && targetType.getComponentType().isAssignableFrom(srcType)) { Object array = Array.newInstance(srcType, 1); Array.set(array, 0, foundData); transformedData = array; } else { try { transformedData = Configuration.getConfiguration().getDataTypeTransformer().transform(srcType, targetType, foundData); } catch (UnsupportedValueException ex) { usve = ex; } } if (usve == null) { dataHolder.setData(dataHolder.getName(), dataHolder.getScope(), foundData, transformedData); } else { dataHolder.setData(dataHolder.getName(), InjectUtil.ContextDataTypeUnMatchScope, foundData, transformedData); } return dataHolder; } @SuppressWarnings("rawtypes") private ContextDataHolder findByType(Context context, String scope, String name, Class<?> targetType) { if (Context.class.isAssignableFrom(targetType)) { return new ContextDataHolder<>(Context.class.getName(), ByTypeScope, context); } if (I18nMessageHelper.class.isAssignableFrom(targetType)) { I18nMessageHelper helper = Configuration.getConfiguration().getI18nMessageHelper(); return new ContextDataHolder<>(helper.getClass().getName(), ByTypeScope, helper); } else { return null; } } @SuppressWarnings("rawtypes") private ContextDataHolder findDataByScopeOrder(Context context, int scopeIndex, String name) { if (scopeIndex >= dataSearchScopeOrder.size()) { return null; } else { String searchScope = dataSearchScopeOrder.get(scopeIndex); ContextDataHolder<?> holder = context.getDataHolder(searchScope, name); if (holder == null) { holder = findDataByScopeOrder(context, scopeIndex + 1, name); } return holder; } } private Method findConvertMethod(DataValueConvertor<?, ?> convertor) { Method[] methods = convertor.getClass().getMethods(); Method rtnMethod = null; for (Method m : methods) { if (m.getName().equals("convert") && !m.isBridge()) { rtnMethod = m; break; } } return rtnMethod; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-656,035,328,803,857,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.data; import com.astamuse.asta4d.data.convertor.UnsupportedValueException; public interface DataTypeTransformer { public Object transform(Class<?> srcType, Class<?> targetType, Object data) throws UnsupportedValueException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,116,362,884,967,311,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.data; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.astamuse.asta4d.Context; /** * a ContextBindData is supposed to be cache in the current thread Context and should only be initialized once * * @author e-ryu * * @param <T> */ public abstract class ContextBindData<T> { private final static String MapKey = "##MapKey##" + ContextBindData.class.getName(); private static class DataWithLock { volatile Object data = null; volatile boolean valid = false; // final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); } private String bindKey = this.getClass().getName() + "##bind-key##23@23@@23"; private boolean contextSynchronizable; /** * The default constructor is for convenience of lazy load data */ public ContextBindData() { this(false); } /** * If contextSynchronizable is set to false, no synchronization operations will be performed and it is just a convenience for lazy load * data. * * Otherwise, if contextSynchronizable is set to true, a Context based lock will be performed and the data will be load only once in the * current context environment. * * @param doSynchronize */ public ContextBindData(boolean contextSynchronizable) { this.contextSynchronizable = contextSynchronizable; } public final static void initConext(Context context) { ConcurrentMap<String, Object> map = new ConcurrentHashMap<>(); context.setData(MapKey, map); } public T get() { if (contextSynchronizable) { return getDataSynchronously(); } else { Context context = Context.getCurrentThreadContext(); T data = context.getData(bindKey); if (data == null) { data = buildData(); context.setData(bindKey, data); } return data; } } @SuppressWarnings("unchecked") private T getDataSynchronously() { Context context = Context.getCurrentThreadContext(); ConcurrentMap<String, Object> map = context.getData(MapKey); // map will not be null since we have initialized it in constructor DataWithLock dl = (DataWithLock) map.get(bindKey); if (dl == null) { dl = new DataWithLock(); DataWithLock prev = (DataWithLock) map.putIfAbsent(bindKey, dl); if (prev != null) { dl = prev; } } if (!dl.valid) { Object data; // TODO I want to read jvm code... synchronized (dl) { if (!dl.valid) { data = dl.data; if (data == null) { data = buildData(); dl.data = data; } dl.valid = true; } } } return (T) dl.data; } protected abstract T buildData(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,959,617,963,137,805,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.data; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.data.convertor.DataValueConvertor; import com.astamuse.asta4d.data.convertor.DataValueConvertorTargetTypeConvertable; import com.astamuse.asta4d.data.convertor.String2Bool; import com.astamuse.asta4d.data.convertor.String2Date; import com.astamuse.asta4d.data.convertor.String2Enum; import com.astamuse.asta4d.data.convertor.String2Int; import com.astamuse.asta4d.data.convertor.String2Java8Instant; import com.astamuse.asta4d.data.convertor.String2Java8LocalDate; 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; import com.astamuse.asta4d.data.convertor.String2Long; import com.astamuse.asta4d.data.convertor.UnsupportedValueException; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; @SuppressWarnings({ "rawtypes", "unchecked" }) public class DefaultDataTypeTransformer implements DataTypeTransformer { private static final Logger logger = LoggerFactory.getLogger(DefaultDataTypeTransformer.class); private static final class DataTypeConvertorKey { private String srcTypeName; private String targetTypeName; private int hashCode; DataTypeConvertorKey(Class srcType, Class targetType) { this.srcTypeName = srcType.getName(); this.targetTypeName = targetType.getName(); this.hashCode = this.srcTypeName.hashCode() ^ this.targetTypeName.hashCode(); } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataTypeConvertorKey other = (DataTypeConvertorKey) obj; if (srcTypeName == null) { if (other.srcTypeName != null) return false; } else if (!srcTypeName.equals(other.srcTypeName)) return false; if (targetTypeName == null) { if (other.targetTypeName != null) return false; } else if (!targetTypeName.equals(other.targetTypeName)) return false; return true; } } private Map<DataTypeConvertorKey, List<DataValueConvertor>> convertorCacheMap = new ConcurrentHashMap<>(); private List<DataValueConvertor> DataTypeConvertorList = getDefaultDataTypeConvertorList(); private final static List<DataValueConvertor> getDefaultDataTypeConvertorList() { List<DataValueConvertor> defaultList = new ArrayList<>(); defaultList.add(new String2Long()); defaultList.add(new String2Int()); defaultList.add(new String2Bool()); defaultList.add(new String2Enum()); defaultList.add(new String2Date()); defaultList.add(new String2Java8Instant()); defaultList.add(new String2Java8LocalDate()); defaultList.add(new String2Java8LocalDateTime()); defaultList.add(new String2Java8LocalTime()); defaultList.add(new String2Java8YearMonth()); defaultList.add(new String2JodaDateTime()); defaultList.add(new String2JodaLocalDate()); defaultList.add(new String2JodaLocalDateTime()); defaultList.add(new String2JodaLocalTime()); defaultList.add(new String2JodaYearMonth()); return defaultList; } public List<DataValueConvertor> getDataTypeConvertorList() { return DataTypeConvertorList; } public void setDataTypeConvertorList(List<DataValueConvertor> DataTypeConvertorList) { List<DataValueConvertor> list = new LinkedList<>(DataTypeConvertorList); list.addAll(getDefaultDataTypeConvertorList()); this.DataTypeConvertorList = list; } public Object transform(Class<?> srcType, Class<?> targetType, Object data) throws UnsupportedValueException { List<DataValueConvertor> convertorList = findConvertor(srcType, targetType); if (convertorList.isEmpty()) { throw new UnsupportedValueException(); } Object ret = null; for (DataValueConvertor DataTypeConvertor : convertorList) { try { ret = DataTypeConvertor.convert(data); } catch (UnsupportedValueException e) { continue; } return ret; } throw new UnsupportedValueException(); } private List<DataValueConvertor> findConvertor(Class<?> srcType, Class<?> targetType) { DataTypeConvertorKey cacheKey = new DataTypeConvertorKey(srcType, targetType); List<DataValueConvertor> foundConvertorList = null; // find in cache if (Configuration.getConfiguration().isCacheEnable()) { foundConvertorList = convertorCacheMap.get(cacheKey); } if (foundConvertorList != null) { return foundConvertorList; } else { foundConvertorList = extractConvertors(srcType, targetType); convertorCacheMap.put(cacheKey, foundConvertorList); return foundConvertorList; } } private List<DataValueConvertor> extractConvertors(final Class<?> srcType, final Class<?> targetType) { List<DataValueConvertor> foundConvertorList = new LinkedList<DataValueConvertor>(); // find in list as element to element for (DataValueConvertor convertor : DataTypeConvertorList) { Pair<Class, Class> typePair = extractConvertorTypeInfo(convertor); if (typePair == null) { continue; } if (typePair.getLeft().isAssignableFrom(srcType)) { if (targetType.isAssignableFrom(typePair.getRight())) {// found one foundConvertorList.add(convertor); } else if (convertor instanceof DataValueConvertorTargetTypeConvertable && typePair.getRight().isAssignableFrom(targetType)) { foundConvertorList.add(((DataValueConvertorTargetTypeConvertable) convertor).convert(targetType)); } } // @formatter:on } if (!foundConvertorList.isEmpty()) { return foundConvertorList; } // find as array to array if (srcType.isArray() && targetType.isArray()) { List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(), targetType.getComponentType()); List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList, new RowConvertor<DataValueConvertor, DataValueConvertor>() { @Override public DataValueConvertor convert(int rowIndex, final DataValueConvertor originalConvertor) { return new DataValueConvertor() { Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor); @Override public Object convert(Object obj) throws UnsupportedValueException { if (typePair == null) { return null; } int length = Array.getLength(obj); Object targetArray = Array.newInstance(targetType.getComponentType(), length); for (int i = 0; i < length; i++) { Array.set(targetArray, i, originalConvertor.convert(Array.get(obj, i))); } return targetArray; } }; } }); foundConvertorList.addAll(toArrayConvertorList); } if (!foundConvertorList.isEmpty()) { return foundConvertorList; } // find as element to array if (targetType.isArray()) { List<DataValueConvertor> componentConvertorList = findConvertor(srcType, targetType.getComponentType()); List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList, new RowConvertor<DataValueConvertor, DataValueConvertor>() { @Override public DataValueConvertor convert(int rowIndex, final DataValueConvertor originalConvertor) { return new DataValueConvertor() { private Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor); @Override public Object convert(Object obj) throws UnsupportedValueException { if (typePair == null) { return null; } Object array = Array.newInstance(targetType.getComponentType(), 1); Array.set(array, 0, originalConvertor.convert(obj)); return array; } }; } }); foundConvertorList.addAll(toArrayConvertorList); } if (!foundConvertorList.isEmpty()) { return foundConvertorList; } // find as array to element if (srcType.isArray()) { List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(), targetType); List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList, new RowConvertor<DataValueConvertor, DataValueConvertor>() { @Override public DataValueConvertor convert(int rowIndex, final DataValueConvertor originalConvertor) { return new DataValueConvertor() { @Override public Object convert(Object obj) throws UnsupportedValueException { int length = Array.getLength(obj); if (length == 0) { return null; } else { return originalConvertor.convert(Array.get(obj, 0)); } } }; } }); foundConvertorList.addAll(toArrayConvertorList); } if (!foundConvertorList.isEmpty()) { return foundConvertorList; } return foundConvertorList; } private Pair<Class, Class> extractConvertorTypeInfo(DataValueConvertor convertor) { Type[] intfs = convertor.getClass().getGenericInterfaces(); Class rawCls; for (Type intf : intfs) { if (intf instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) intf; rawCls = (Class) pt.getRawType(); if (rawCls.getName().equals(DataValueConvertor.class.getName()) || rawCls.getName().equals(DataValueConvertorTargetTypeConvertable.class.getName())) { Type[] typeArgs = pt.getActualTypeArguments(); return Pair.of((Class) typeArgs[0], (Class) typeArgs[1]); } } } logger.warn("Could not extract type information from DataTypeConvertor:" + convertor.getClass().getName()); return null; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,108,087,753,628,454,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.data.annotation; import java.lang.annotation.Annotation; import com.astamuse.asta4d.util.annotation.AnnotatedProperty; import com.astamuse.asta4d.util.annotation.AnnotationConvertor; public class ContextDataAnnotationConvertor implements AnnotationConvertor<ContextData, AnnotatedProperty> { @Override public AnnotatedProperty convert(final ContextData originalAnnotation) { return new AnnotatedProperty() { @Override public Class<? extends Annotation> annotationType() { return AnnotatedProperty.class; } @Override public String name() { return originalAnnotation.name(); } }; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,763,149,261,991,510,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.data.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.InjectUtil; import com.astamuse.asta4d.data.TypeUnMacthPolicy; import com.astamuse.asta4d.util.annotation.ConvertableAnnotation; /** * This annotation is for marking a field (including getter/setter method) or a method parameter as {@link Context} associated. * * @author e-ryu * @see InjectUtil */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @ConvertableAnnotation(ContextDataAnnotationConvertor.class) public @interface ContextData { /** * The name of associated context data, if not specified, the inject process will use the field/parameter name as context data name. */ String name() default ""; /** * The scope of associated context data, if not specified, the inject process will try to find it in a predefined search order in all * scopes. */ String scope() default ""; /** * the policy of how to handle the unmatched type on data conversion. * */ TypeUnMacthPolicy typeUnMatch() default TypeUnMacthPolicy.EXCEPTION; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-899,550,924,634,832,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.data.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.ContextDataSetFactory; import com.astamuse.asta4d.data.DefaultContextDataSetFactory; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ContextDataSet { public boolean singletonInContext() default false; public Class<? extends ContextDataSetFactory> factory() default DefaultContextDataSetFactory.class; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-9,158,366,702,618,583,000