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 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.mapping; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.astamuse.asta4d.web.dispatch.DispatcherRuleMatcher; import com.astamuse.asta4d.web.dispatch.HttpMethod; import com.astamuse.asta4d.web.dispatch.HttpMethod.ExtendHttpMethod; import com.astamuse.asta4d.web.dispatch.interceptor.RequestHandlerInterceptor; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public class UrlMappingRule { private int seq; private HttpMethod method; private ExtendHttpMethod extendMethod; private String sourcePath; private List<Object> handlerList; private List<RequestHandlerInterceptor> interceptorList; private Map<String, Object> extraVarMap; private List<String> attributeList; private List<ResultTransformer> resultTransformerList; private int priority; private DispatcherRuleMatcher ruleMatcher; private UrlMappingRule unModifiableDelegator; public UrlMappingRule(int seq, HttpMethod method, ExtendHttpMethod extendMethod, String sourcePath, List<Object> handlerList, List<RequestHandlerInterceptor> interceptorList, Map<String, Object> extraVarMap, List<String> attributeList, List<ResultTransformer> resultTransformerList, int priority, DispatcherRuleMatcher ruleMatcher) { super(); this.seq = seq; this.method = method; this.extendMethod = extendMethod; this.sourcePath = sourcePath; this.handlerList = handlerList; this.interceptorList = interceptorList; this.extraVarMap = extraVarMap; this.attributeList = attributeList; this.resultTransformerList = resultTransformerList; this.priority = priority; this.ruleMatcher = ruleMatcher; } public UrlMappingRule() { super(); this.handlerList = new ArrayList<>(); this.interceptorList = new ArrayList<>(); this.extraVarMap = new HashMap<>(); this.attributeList = new ArrayList<>(); this.resultTransformerList = new ArrayList<>(); } public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } public HttpMethod getMethod() { return method; } public void setMethod(HttpMethod method) { this.method = method; } public ExtendHttpMethod getExtendMethod() { return extendMethod; } public void setExtendMethod(ExtendHttpMethod extendMethod) { this.extendMethod = extendMethod; } public String getSourcePath() { return sourcePath; } public void setSourcePath(String sourcePath) { this.sourcePath = sourcePath; } public List<Object> getHandlerList() { return handlerList; } public void setHandlerList(List<Object> handlerList) { this.handlerList = handlerList; } public List<RequestHandlerInterceptor> getInterceptorList() { return interceptorList; } public void setInterceptorList(List<RequestHandlerInterceptor> interceptorList) { this.interceptorList = interceptorList; } public Map<String, Object> getExtraVarMap() { return extraVarMap; } public void setExtraVarMap(Map<String, Object> extraVarMap) { this.extraVarMap = extraVarMap; } public Object extraVar(String key) { return this.extraVarMap.get(key); } public List<String> getAttributeList() { return attributeList; } public void setAttributeList(List<String> attributeList) { this.attributeList = attributeList; } public boolean hasAttribute(String attr) { return this.attributeList.contains(attr); } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public DispatcherRuleMatcher getRuleMatcher() { return ruleMatcher; } public void setRuleMatcher(DispatcherRuleMatcher ruleMatcher) { this.ruleMatcher = ruleMatcher; } public List<ResultTransformer> getResultTransformerList() { return resultTransformerList; } public void setResultTransformerList(List<ResultTransformer> resultTransformerList) { this.resultTransformerList = resultTransformerList; } public UrlMappingRule asUnmodifiable() { // It is OK if unModifiableDelegator was initialized by multiple threads if (unModifiableDelegator == null) { unModifiableDelegator = new UnModifiableUrlMappingRule(this); } return unModifiableDelegator; } @Override public String toString() { return "UrlMappingRule [seq=" + seq + ", method=" + method + ", sourcePath=" + sourcePath + ", handlerList=" + handlerList + ", interceptorList=" + interceptorList + ", extraVarMap=" + extraVarMap + ", attributeList=" + attributeList + ", resultTransformerList=" + resultTransformerList + ", priority=" + priority + ", ruleMatcher=" + ruleMatcher + "]"; } private static class UnModifiableUrlMappingRule extends UrlMappingRule { private UrlMappingRule rule; private UnModifiableUrlMappingRule(UrlMappingRule rule) { this.rule = rule; } public int getSeq() { return rule.getSeq(); } public void setSeq(int seq) { throw new UnsupportedOperationException(); } public HttpMethod getMethod() { return rule.getMethod(); } public void setMethod(HttpMethod method) { throw new UnsupportedOperationException(); } public ExtendHttpMethod getExtendMethod() { return rule.getExtendMethod(); } public void setExtendMethod(ExtendHttpMethod extendMethod) { throw new UnsupportedOperationException(); } public String getSourcePath() { return rule.getSourcePath(); } public void setSourcePath(String sourcePath) { throw new UnsupportedOperationException(); } public List<Object> getHandlerList() { return Collections.unmodifiableList(rule.getHandlerList()); } public void setHandlerList(List<Object> handlerList) { throw new UnsupportedOperationException(); } public List<RequestHandlerInterceptor> getInterceptorList() { return Collections.unmodifiableList(rule.getInterceptorList()); } public void setInterceptorList(List<RequestHandlerInterceptor> interceptorList) { throw new UnsupportedOperationException(); } public Map<String, Object> getExtraVarMap() { return Collections.unmodifiableMap(rule.getExtraVarMap()); } public void setExtraVarMap(Map<String, Object> extraVarMap) { throw new UnsupportedOperationException(); } public Object extraVar(String key) { return rule.extraVar(key); } public List<String> getAttributeList() { return Collections.unmodifiableList(rule.getAttributeList()); } public void setAttributeList(List<String> attributeList) { throw new UnsupportedOperationException(); } public boolean hasAttribute(String attr) { return rule.hasAttribute(attr); } public int getPriority() { return rule.getPriority(); } public void setPriority(int priority) { throw new UnsupportedOperationException(); } public DispatcherRuleMatcher getRuleMatcher() { return rule.getRuleMatcher(); } public void setRuleMatcher(DispatcherRuleMatcher ruleMatcher) { throw new UnsupportedOperationException(); } public List<ResultTransformer> getResultTransformerList() { return Collections.unmodifiableList(rule.getResultTransformerList()); } public void setResultTransformerList(List<ResultTransformer> resultTransformerList) { throw new UnsupportedOperationException(); } @Override public String toString() { return "READONLY:" + rule.toString(); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,151,192,076,533,956,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.mapping; public interface UrlMappingRuleInitializer<T extends UrlMappingRuleSet<?, ?>> { public void initUrlMappingRules(T rules); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,406,176,741,816,176,000
package com.astamuse.asta4d.web.dispatch.mapping; import java.util.List; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public interface ResultTransformerReorganizer { public List<ResultTransformer> reorganize(List<ResultTransformer> transformerList); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,176,274,234,753,332,700
package com.astamuse.asta4d.web.dispatch.mapping; import java.util.ArrayList; import java.util.List; public class UrlMappingRuleSetHelper { private final static String RULE_TYPE_VAR_NAME = UrlMappingRuleSetHelper.class.getName() + "-rule-type"; private final static String BEFORE_SORT_RULE_REWRITTER_LIST_VAR_NAME = UrlMappingRuleSetHelper.class.getName() + "-before-sort-rule-rewritter-list"; public static final void addBeforeSortRuleRewritter(UrlMappingRule rule, UrlMappingRuleRewriter rewritter) { @SuppressWarnings("unchecked") List<UrlMappingRuleRewriter> list = (List<UrlMappingRuleRewriter>) rule.getExtraVarMap() .get(BEFORE_SORT_RULE_REWRITTER_LIST_VAR_NAME); if (list == null) { list = new ArrayList<>(); rule.getExtraVarMap().put(BEFORE_SORT_RULE_REWRITTER_LIST_VAR_NAME, list); } list.add(rewritter); } @SuppressWarnings("unchecked") public static final List<UrlMappingRuleRewriter> getBeforeSortRuleRewritter(UrlMappingRule rule) { return (List<UrlMappingRuleRewriter>) rule.getExtraVarMap().get(BEFORE_SORT_RULE_REWRITTER_LIST_VAR_NAME); } public static final void setRuleType(UrlMappingRule rule, String type) { rule.getExtraVarMap().put(RULE_TYPE_VAR_NAME, type); } public static final String getRuleType(UrlMappingRule rule) { return (String) rule.getExtraVarMap().get(RULE_TYPE_VAR_NAME); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,131,764,484,810,547,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.mapping; public interface UrlMappingRuleRewriter { public void rewrite(UrlMappingRule rule); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,888,960,571,378,977,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.mapping; import java.util.Map; public class UrlMappingResult { private UrlMappingRule rule; private Map<String, Object> pathVarMap; public UrlMappingResult() { // } public UrlMappingResult(UrlMappingRule rule, Map<String, Object> pathVarMap) { super(); this.rule = rule; this.pathVarMap = pathVarMap; } public UrlMappingRule getRule() { return rule.asUnmodifiable(); } public void setRule(UrlMappingRule rule) { this.rule = rule; } public Map<String, Object> getPathVarMap() { return pathVarMap; } public void setPathVarMap(Map<String, Object> pathVarMap) { this.pathVarMap = pathVarMap; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-674,568,793,396,776,400
package com.astamuse.asta4d.web.dispatch.mapping.handy; import java.util.ArrayList; import java.util.List; import com.astamuse.asta4d.web.dispatch.HttpMethod; import com.astamuse.asta4d.web.dispatch.HttpMethod.ExtendHttpMethod; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleRewriter; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSet; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSetHelper; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleConfigurer; import com.astamuse.asta4d.web.dispatch.mapping.handy.rest.JsonSupportRuleSet; import com.astamuse.asta4d.web.dispatch.mapping.handy.rest.XmlSupportRuleSet; import com.astamuse.asta4d.web.dispatch.mapping.handy.template.TemplateRuleHelper; import com.astamuse.asta4d.web.dispatch.mapping.handy.template.TemplateRuleWithForward; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.Asta4DPageTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultExceptionTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultStringTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultTemplateNotFoundExceptionTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.SimpleTypeMatchTransformer; @SuppressWarnings("unchecked") public class HandyRuleSet<A extends HandyRuleAfterAddSrc<?, ?, ?>, D extends HandyRuleAfterAddSrcAndTarget<?>> extends UrlMappingRuleSet<A, D>implements JsonSupportRuleSet, XmlSupportRuleSet, HandyRuleBuilder { private static final String DEFAULT_RULE_TYPE = "template"; protected final static class GlobalForwardHolder { Object result; String targetPath; Integer status; boolean isRedirect; public GlobalForwardHolder(Object result, String targetPath, Integer status, boolean isRedirect) { super(); this.result = result; this.targetPath = targetPath; this.status = status; this.isRedirect = isRedirect; } } protected List<GlobalForwardHolder> forwardHolderList = new ArrayList<>(); protected UrlMappingRule createDefaultRule(HttpMethod method, ExtendHttpMethod extendMethod, String sourcePath) { UrlMappingRule rule = new UrlMappingRule(); ruleList.add(rule); rule.setMethod(method); rule.setExtendMethod(extendMethod); rule.setSourcePath(sourcePath); rule.setSeq(Sequencer.incrementAndGet()); rule.setPriority(DEFAULT_PRIORITY); rule.setRuleMatcher(defaultRuleMatcher); // register the default result transformer reorganizer, can be overridden by other apis UrlMappingRuleSetHelper.setRuleType(rule, DEFAULT_RULE_TYPE); UrlMappingRuleSetHelper.addBeforeSortRuleRewritter(rule, new UrlMappingRuleRewriter() { @Override public void rewrite(UrlMappingRule rule) { if (DEFAULT_RULE_TYPE.equals(UrlMappingRuleSetHelper.getRuleType(rule))) { // OK } else { return; } List<ResultTransformer> transformerList = rule.getResultTransformerList(); // find out the default forward rule ResultTransformer transformer, defaultTransformer = null; int size = transformerList.size(); for (int i = size - 1; i >= 0; i--) { transformer = transformerList.get(i); if (transformer instanceof SimpleTypeMatchTransformer) { if (((SimpleTypeMatchTransformer) transformer).isAsDefaultMatch()) { defaultTransformer = transformer; transformerList.remove(i); break; } } } boolean hasHandler = !rule.getHandlerList().isEmpty(); if (hasHandler) { // add global forward addGlobalForwardTransformers(transformerList); // add String transformers for non default forward rules(forward // by result) transformerList.add(new DefaultStringTransformer()); // add global forward again for possible // exceptions on the above transformers addGlobalForwardTransformers(transformerList); // add String transformers for the global forword rules transformerList.add(new DefaultStringTransformer()); } // add default forward rule if (defaultTransformer != null) { transformerList.add(defaultTransformer); // add default String transformers for the default forward rule transformerList.add(new DefaultStringTransformer()); // add global forward of Throwable result again again (!!!) for // possible exceptions on the above transformers addGlobalForwardTransformers(transformerList); // add String transformers for the global throwable result // forword rules transformerList.add(new DefaultStringTransformer()); } // add the last insured transformers transformerList.add(new DefaultTemplateNotFoundExceptionTransformer()); transformerList.add(new DefaultExceptionTransformer()); transformerList.add(new Asta4DPageTransformer()); } }); return rule; } protected void addGlobalForwardTransformers(List<ResultTransformer> transformerList) { for (GlobalForwardHolder forwardHolder : forwardHolderList) { if (forwardHolder.isRedirect) { transformerList.add(TemplateRuleHelper.redirectTransformer(forwardHolder.result, forwardHolder.targetPath)); } else if (forwardHolder.status == null) { transformerList.add(TemplateRuleHelper.forwardTransformer(forwardHolder.result, forwardHolder.targetPath)); } else { transformerList .add(TemplateRuleHelper.forwardTransformer(forwardHolder.result, forwardHolder.targetPath, forwardHolder.status)); } } } public void addGlobalForward(Object result, String targetPath, int status) { forwardHolderList.add(new GlobalForwardHolder(result, targetPath, status, false)); } public void addGlobalForward(Object result, String targetPath) { forwardHolderList.add(new GlobalForwardHolder(result, targetPath, null, false)); } public void addGlobalRedirect(Object result, String targetPath) { forwardHolderList.add(new GlobalForwardHolder(result, targetPath, null, true)); } public A add(String sourcePath) { return add(defaultMethod, sourcePath); } public A add(HttpMethod method, String sourcePath) { UrlMappingRule rule = createDefaultRule(method, null, sourcePath); A handyRule = buildHandyRuleAfterAddSrc(rule); return handyRule; } public A add(ExtendHttpMethod extendMethod, String sourcePath) { UrlMappingRule rule = createDefaultRule(HttpMethod.UNKNOWN, extendMethod, sourcePath); A handyRule = buildHandyRuleAfterAddSrc(rule); return handyRule; } public D add(String sourcePath, String targetPath) { return add(defaultMethod, sourcePath, targetPath); } public D add(HttpMethod method, String sourcePath, String targetPath) { UrlMappingRule rule = createDefaultRule(method, null, sourcePath); @SuppressWarnings("rawtypes") TemplateRuleWithForward trf = new TemplateRuleWithForward() { @Override public void configureRule(HandyRuleConfigurer configure) { configure.configure(rule); } }; trf.forward(targetPath); return buildHandyRuleAfterAddSrcAndTarget(rule); } public D add(ExtendHttpMethod extendMethod, String sourcePath, String targetPath) { UrlMappingRule rule = createDefaultRule(HttpMethod.UNKNOWN, extendMethod, sourcePath); @SuppressWarnings("rawtypes") TemplateRuleWithForward trf = new TemplateRuleWithForward() { @Override public void configureRule(HandyRuleConfigurer configure) { configure.configure(rule); } }; trf.forward(targetPath); return buildHandyRuleAfterAddSrcAndTarget(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
230,948,688,096,078,530
package com.astamuse.asta4d.web.dispatch.mapping.handy; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleBase; import com.astamuse.asta4d.web.dispatch.mapping.handy.rest.JsonSupportRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.rest.XmlSupportRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.template.TemplateRuleWithForward; public class HandyRuleAfterHandler<C extends HandyRuleAfterHandler<?>> extends HandyRuleBase implements TemplateRuleWithForward<C>, JsonSupportRule, XmlSupportRule { public HandyRuleAfterHandler(UrlMappingRule rule) { super(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,093,791,296,178,048,000
package com.astamuse.asta4d.web.dispatch.mapping.handy; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSet; /** * From the entry methods at {@link UrlMappingRuleSet}, there are two possible flow of rule configuration: * * <ul> * <li>{@link UrlMappingRuleSet#add(String, String)}: Once the target path is configured by entry method, the only operations can be * performed is to set rule attributes related values, such as id, rule attribute, extra path variables, rule matcher, priority, etc. * {@link #buildHandyRuleWithAttrOnly(UrlMappingRule)}} returns a sub class of {@link HandyRuleWithAttrOnly} to perform this restriction. * <li>{@link UrlMappingRuleSet#add(String)}: If the target is not set by entry method, the following steps are enabled to guide developers * to configure the current rule: * <ol> * <li>remap(via {@link HandyRuleWithRemap})-> attribution related operations(via {@link HandyRuleWithAttrOnly} ) * <li>attribution related operations (via {@link HandyRuleWithAttrAndHandler})-> handler setting(via {@link HandyRuleWithHandler}) -> * forward/redirect setting(via {@link HandyRuleWithForward}) * </ol> * </ul> * * {@link HandyRuleWithAttrOnly} is dependent and others follow the following extending relationship: * <p> * * {@link HandyRuleWithForward} <--(extend with handler settable)-- {@link HandyRuleWithHandler} <--(extend with attr op)-- * {@link HandyRuleWithAttrAndHandler}) <--(extend with remap op)-- {@link HandyRuleWithRemap} * * <p> * * This builder interface affords the default build policy of how to create the above instances with the default handy rule implementations. * To extend the url rule configuration DSL, developers must supply their own set of above classes' sub classes, as well as the extended * implementation of {@link UrlMappingRuleSet}. * * @author e-ryu * */ public interface HandyRuleBuilder { @SuppressWarnings("unchecked") default <A extends HandyRuleAfterAddSrc<?, ?, ?>> A buildHandyRuleAfterAddSrc(UrlMappingRule rule) { return (A) new HandyRuleAfterAddSrc<>(rule); } @SuppressWarnings("unchecked") default <B extends HandyRuleAfterAttr<?, ?>> B buildHandyRuleAfterAttr(UrlMappingRule rule) { return (B) new HandyRuleAfterAddSrc<>(rule); } @SuppressWarnings("unchecked") default <C extends HandyRuleAfterHandler<?>> C buildHandyRuleAfterHandler(UrlMappingRule rule) { return (C) new HandyRuleAfterHandler<>(rule); } @SuppressWarnings("unchecked") default <D extends HandyRuleAfterAddSrcAndTarget<?>> D buildHandyRuleAfterAddSrcAndTarget(UrlMappingRule rule) { return (D) new HandyRuleAfterAddSrcAndTarget<>(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,820,860,157,305,960,400
package com.astamuse.asta4d.web.dispatch.mapping.handy; import com.astamuse.asta4d.web.dispatch.DispatcherRuleMatcher; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSet; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.AttrConfigurableRule; public class HandyRuleAfterAddSrc<A extends HandyRuleAfterAddSrc<?, ?, ?>, B extends HandyRuleAfterAttr<?, ?>, C extends HandyRuleAfterHandler<?>> extends HandyRuleAfterAttr<B, C>implements AttrConfigurableRule<A>, HandyRuleBuilder { public HandyRuleAfterAddSrc(UrlMappingRule rule) { super(rule); } public <D extends HandyRuleAfterAddSrcAndTarget<?>> D reMapTo(String ruleId) { this.var(UrlMappingRuleSet.REMAP_ID_VAR_NAME, ruleId); return buildHandyRuleAfterAddSrcAndTarget(rule); } /* The following overriding is not necessary but we have to override to address the compile error due to Java's bad type inference ability */ @Override public A priority(int priority) { return AttrConfigurableRule.super.priority(priority); } @Override public A pathVar(String key, Object value) { return AttrConfigurableRule.super.pathVar(key, value); } @Override public A var(String key, Object value) { return AttrConfigurableRule.super.var(key, value); } @Override public A attribute(String attribute) { return AttrConfigurableRule.super.attribute(attribute); } @Override public A id(String id) { return AttrConfigurableRule.super.id(id); } @Override public A matcher(DispatcherRuleMatcher ruleMatcher) { return AttrConfigurableRule.super.matcher(ruleMatcher); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,577,853,523,636,067,300
package com.astamuse.asta4d.web.dispatch.mapping.handy; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandlerConfigurableRule; public class HandyRuleAfterAttr<B extends HandyRuleAfterAttr<?, ?>, C extends HandyRuleAfterHandler<?>> extends HandyRuleAfterHandler<C> implements HandlerConfigurableRule<B> { public HandyRuleAfterAttr(UrlMappingRule rule) { super(rule); } /* The following overriding is not necessary but we have to override to address the compile error due to Java's bad type inference ability */ @Override public B handler(Object... handlerList) { return HandlerConfigurableRule.super.handler(handlerList); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,988,956,180,774,785,000
package com.astamuse.asta4d.web.dispatch.mapping.handy; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.AttrConfigurableRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleBase; public class HandyRuleAfterAddSrcAndTarget<D extends HandyRuleAfterAddSrcAndTarget<?>> extends HandyRuleBase implements AttrConfigurableRule<D> { public HandyRuleAfterAddSrcAndTarget(UrlMappingRule rule) { super(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
472,062,786,653,622,200
package com.astamuse.asta4d.web.dispatch.mapping.handy.rest; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultExceptionTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultXmlTransformer; public class XmlSupportRuleHelper { static ResultTransformer registeredTransformer = null; static final ResultTransformer FallbackXmlTransformer = new DefaultXmlTransformer(); static final ResultTransformer ExceptionTransformer = new DefaultExceptionTransformer(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,279,227,676,606,671,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.rest; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public interface JsonSupportRuleSet { default void registerJsonTransformer(ResultTransformer transformer) { JsonSupportRuleHelper.registeredTransformer = transformer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,238,330,503,593,316,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.rest; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultExceptionTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.DefaultJsonTransformer; public class JsonSupportRuleHelper { static ResultTransformer registeredTransformer = null; static final ResultTransformer FallbackJsonTransformer = new DefaultJsonTransformer(); static final ResultTransformer ExceptionTransformer = new DefaultExceptionTransformer(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,225,081,591,655,511,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.rest; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public interface XmlSupportRuleSet { default void registerXmlTransformer(ResultTransformer transformer) { XmlSupportRuleHelper.registeredTransformer = transformer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,102,913,425,926,803,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.rest; import java.util.List; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSetHelper; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleConfigurable; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public interface XmlSupportRule extends HandyRuleConfigurable { public static final String JSON_RESULT_TRANSFORMER = XmlSupportRule.class.getName() + "#JSON_RESULT_TRANSFORMER"; default void xml() { this.configureRule(rule -> { List<ResultTransformer> transformerList = rule.getResultTransformerList(); if (!transformerList.isEmpty()) { throw new RuntimeException( "Cannot declare json transforming on a rule in which there has been forward/redirect declaration."); } if (XmlSupportRuleHelper.registeredTransformer != null) { transformerList.add(XmlSupportRuleHelper.registeredTransformer); } transformerList.add(XmlSupportRuleHelper.ExceptionTransformer); transformerList.add(XmlSupportRuleHelper.FallbackXmlTransformer); UrlMappingRuleSetHelper.setRuleType(rule, "xml"); }); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,089,846,145,416,727,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.rest; import java.util.List; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSetHelper; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleConfigurable; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public interface JsonSupportRule extends HandyRuleConfigurable { public static final String JSON_RESULT_TRANSFORMER = JsonSupportRule.class.getName() + "#JSON_RESULT_TRANSFORMER"; default void json() { this.configureRule(rule -> { List<ResultTransformer> transformerList = rule.getResultTransformerList(); if (!transformerList.isEmpty()) { throw new RuntimeException( "Cannot declare json transforming on a rule in which there has been forward/redirect declaration."); } if (JsonSupportRuleHelper.registeredTransformer != null) { transformerList.add(JsonSupportRuleHelper.registeredTransformer); } transformerList.add(JsonSupportRuleHelper.ExceptionTransformer); transformerList.add(JsonSupportRuleHelper.FallbackJsonTransformer); UrlMappingRuleSetHelper.setRuleType(rule, "json"); }); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,043,048,138,384,623,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.template; import com.astamuse.asta4d.web.dispatch.request.MultiResultHolder; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.request.transformer.SimpleTypeMatchTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.HeaderInfoProvider; public class TemplateRuleHelper { public static ResultTransformer redirectTransformer(Object result, String targetUrl) { return new SimpleTypeMatchTransformer(result, "redirect:" + targetUrl); } public static ResultTransformer forwardTransformer(Object result, String target) { return new SimpleTypeMatchTransformer(result, target); } public static ResultTransformer forwardTransformer(Object result, String targetPath, int status) { MultiResultHolder mrh = new MultiResultHolder(); mrh.addResult(new HeaderInfoProvider(status)); mrh.addResult(targetPath); return new SimpleTypeMatchTransformer(result, mrh); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,399,337,998,943,177,700
package com.astamuse.asta4d.web.dispatch.mapping.handy.template; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleConfigurable; public interface TemplateRuleWithForward<T extends TemplateRuleWithForward<?>> extends HandyRuleConfigurable { @SuppressWarnings("unchecked") default T forward(Object result, String targetPath) { configureRule(rule -> { rule.getResultTransformerList().add(TemplateRuleHelper.forwardTransformer(result, targetPath)); }); return (T) this; } @SuppressWarnings("unchecked") default T forward(Object result, String targetPath, int status) { configureRule(rule -> { rule.getResultTransformerList().add(TemplateRuleHelper.forwardTransformer(result, targetPath, status)); }); return (T) this; } default void forward(String targetPath) { this.forward(null, targetPath); } default void forward(String targetPath, int status) { this.forward(null, targetPath, status); } default void redirect(String targetUrl) { this.redirect(null, targetUrl); } @SuppressWarnings("unchecked") default T redirect(Object result, String targetUrl) { configureRule(rule -> { rule.getResultTransformerList().add(TemplateRuleHelper.redirectTransformer(result, targetUrl)); }); return (T) this; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,464,053,695,080,197,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.base; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; @FunctionalInterface public interface HandyRuleConfigurer { public void configure(UrlMappingRule rule); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,612,458,661,282,185,200
package com.astamuse.asta4d.web.dispatch.mapping.handy.base; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public abstract class HandyRuleBase implements HandyRuleConfigurable { protected UrlMappingRule rule; public HandyRuleBase(UrlMappingRule rule) { this.rule = rule; } @Override public void configureRule(HandyRuleConfigurer configure) { configure.configure(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,695,850,421,681,526,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.base; public interface HandyRuleConfigurable { public void configureRule(HandyRuleConfigurer configure); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,753,906,198,110,518,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.base; import java.util.HashMap; import java.util.List; import java.util.Map; import com.astamuse.asta4d.web.dispatch.DispatcherRuleMatcher; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleSet; @SuppressWarnings({ "unchecked", "rawtypes" }) public interface AttrConfigurableRule<T extends AttrConfigurableRule> extends HandyRuleConfigurable { default T priority(int priority) { configureRule(rule -> { rule.setPriority(priority); }); return (T) this; } default T pathVar(String key, Object value) { return var(key, value); } default T var(String key, Object value) { configureRule(rule -> { Map<String, Object> map = rule.getExtraVarMap(); if (map == null) { map = new HashMap<String, Object>(); } map.put(key, value); rule.setExtraVarMap(map); }); return (T) this; } default T attribute(String attribute) { configureRule(rule -> { List<String> attrList = rule.getAttributeList(); attrList.add(attribute); }); return (T) this; } default T id(String id) { configureRule(rule -> { this.var(UrlMappingRuleSet.ID_VAR_NAME, id); }); return (T) this; } default T matcher(DispatcherRuleMatcher ruleMatcher) { configureRule(rule -> { rule.setRuleMatcher(ruleMatcher); }); return (T) this; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,106,734,487,895,953,000
package com.astamuse.asta4d.web.dispatch.mapping.handy.base; import java.util.List; import com.astamuse.asta4d.web.util.bean.DeclareInstanceUtil; public interface HandlerConfigurableRule<T extends HandlerConfigurableRule<?>> extends HandyRuleConfigurable { default T handler(Object... handlerList) { configureRule(rule -> { List<Object> list = rule.getHandlerList(); for (Object handler : handlerList) { list.add(DeclareInstanceUtil.createInstance((handler))); } }); return (T) this; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,141,173,992,266,507,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.interceptor; import java.util.List; import com.astamuse.asta4d.web.dispatch.response.provider.ContentProvider; public class RequestHandlerResultHolder { private List<ContentProvider> contentProviderList = null; public RequestHandlerResultHolder() { } public List<ContentProvider> getContentProviderList() { return contentProviderList; } public void setContentProviderList(List<ContentProvider> contentProviderList) { this.contentProviderList = contentProviderList; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,055,534,630,273,966,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.interceptor; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public interface RequestHandlerInterceptor { public void preHandle(UrlMappingRule rule, RequestHandlerResultHolder holder); public void postHandle(UrlMappingRule rule, RequestHandlerResultHolder holder, ExceptionHandler exceptionHandler); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,808,407,286,860,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.web.dispatch.response.provider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public class HeaderInfoProvider implements ContentProvider { private HashMap<String, String> headerMap; private List<Cookie> cookieList; private Integer status; private boolean continuable = true; public HeaderInfoProvider() { this(null); } public HeaderInfoProvider(Integer status) { this.status = status; headerMap = new HashMap<>(); cookieList = new ArrayList<>(); } public HeaderInfoProvider(Integer status, boolean continuable) { this.status = status; this.continuable = continuable; headerMap = new HashMap<>(); cookieList = new ArrayList<>(); } public Integer getStatus() { return status; } public void addHeader(String name, String value) { headerMap.put(name, value); } public void addCookie(String name, String value) { cookieList.add(new Cookie(name, value)); } public void addCookie(Cookie cookie) { cookieList.add(cookie); } public HashMap<String, String> getHeaderMap() { return headerMap; } public List<Cookie> getCookieList() { return cookieList; } @Override public boolean isContinuable() { return continuable; } public void setContinuable(boolean continuable) { this.continuable = continuable; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { if (status != null) { response.setStatus(status); } Set<Entry<String, String>> headers = headerMap.entrySet(); for (Entry<String, String> h : headers) { response.addHeader(h.getKey(), h.getValue()); } for (Cookie c : cookieList) { response.addCookie(c); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,355,509,767,393,227,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public class EmptyContentProvider implements ContentProvider { @Override public boolean isContinuable() { return false; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { // do nothing } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,205,584,384,390,955,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public interface ContentProvider { public boolean isContinuable(); public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,296,616,137,732,744,700
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.util.data.XmlUtil; public class XmlDataProvider implements ContentProvider { private Object data; public XmlDataProvider() { this(null); } public XmlDataProvider(Object data) { this.data = data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } @Override public boolean isContinuable() { return false; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { response.setContentType("application/xml"); XmlUtil.toXml(response.getOutputStream(), data); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,640,688,524,148,297,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; @SuppressWarnings("rawtypes") public class SerialProvider implements ContentProvider { private List<ContentProvider> contentProviderList = new ArrayList<>(); public SerialProvider() { } public SerialProvider(ContentProvider... contentProviders) { for (ContentProvider contentProvider : contentProviders) { contentProviderList.add(contentProvider); } } public SerialProvider(List<ContentProvider> contentProviders) { contentProviderList.addAll(contentProviders); } public List<ContentProvider> getContentProviderList() { return contentProviderList; } @Override public boolean isContinuable() { for (ContentProvider cp : contentProviderList) { if (!cp.isContinuable()) { return false; } } return true; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { for (ContentProvider cp : contentProviderList) { cp.produce(currentRule, response); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
447,503,120,436,502,900
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javax.servlet.ServletContext; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.util.data.BinaryDataUtil; public class BinaryDataProvider implements ContentProvider { private InputStream input = null; public BinaryDataProvider(InputStream input) { this.input = input; } public BinaryDataProvider(ServletContext servletContext, String inPackageFile) { this(servletContext.getResourceAsStream(inPackageFile)); } public BinaryDataProvider(File commonFile) { this(retrieveInputStreamFromFile(commonFile)); } public BinaryDataProvider(ServletContext servletContext, ClassLoader classLoader, String path) { this(BinaryDataUtil.retrieveInputStreamByPath(servletContext, classLoader, path)); } private static final InputStream retrieveInputStreamFromFile(File file) { try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public BinaryDataProvider(byte[] bytes) { this(new ByteArrayInputStream(bytes)); } @Override public boolean isContinuable() { return true; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { try { byte[] bs = new byte[4096]; ServletOutputStream out = response.getOutputStream(); int len = 0; while ((len = input.read(bs)) != -1) { out.write(bs, 0, len); } // we do not need to close servlet output stream since the container // will close it. } finally { // since we have depleted this stream, there is no reason for not // closing it. input.close(); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,422,966,868,789,057,500
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.util.data.JsonUtil; public class JsonDataProvider implements ContentProvider { private Object data; public JsonDataProvider() { this(null); } public JsonDataProvider(Object data) { this.data = data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } @Override public boolean isContinuable() { return false; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { response.setContentType("application/json"); JsonUtil.toJson(response.getOutputStream(), data); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,203,418,765,944,764,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import java.net.HttpURLConnection; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.dispatch.RedirectUtil; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public class RedirectTargetProvider implements ContentProvider { private int status; private String targetPath; private Map<String, Object> flashScopeData; public RedirectTargetProvider() { // } public RedirectTargetProvider(String targetPath) { this(targetPath, null); } public RedirectTargetProvider(String targetPath, Map<String, Object> flashScopeData) { this(HttpURLConnection.HTTP_MOVED_TEMP, targetPath, flashScopeData); } public RedirectTargetProvider(int status, String targetPath, Map<String, Object> flashScopeData) { this.targetPath = targetPath; this.flashScopeData = flashScopeData; this.setStatus(status); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getTargetPath() { return targetPath; } public void setTargetPath(String targetPath) { this.targetPath = targetPath; } public Map<String, Object> getFlashScopeData() { return flashScopeData; } public void setFlashScopeData(Map<String, Object> flashScopeData) { this.flashScopeData = flashScopeData; } @Override public boolean isContinuable() { return targetPath == null; } @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { RedirectUtil.addFlashScopeData(flashScopeData); if (targetPath == null) { return; } String url = targetPath; if (url.startsWith("/")) { WebApplicationContext context = WebApplicationContext.getCurrentThreadWebApplicationContext(); url = context.getRequest().getContextPath() + url; } RedirectUtil.redirectToUrlWithSavedFlashScopeData(response, status, url); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,888,764,434,838,051,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.response.provider; import javax.servlet.http.HttpServletResponse; import com.astamuse.asta4d.Page; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; public class Asta4DPageProvider implements ContentProvider { /** * This attribute hash been deprecated and you should use afd:bodyonly in template file or just create a template file without body * tag(also without html and head tags). * * @see ExtNodeConstants#ATTR_BODY_ONLY_WITH_NS */ @Deprecated public final static String AttrBodyOnly = Asta4DPageProvider.class.getName() + "##bodyOnly"; private Page page; public Asta4DPageProvider() { this.page = null; } public Asta4DPageProvider(Page page) { this.page = page; } public void setPage(Page page) { this.page = page; } @Override public boolean isContinuable() { return false; } @SuppressWarnings("deprecation") @Override public void produce(UrlMappingRule currentRule, HttpServletResponse response) throws Exception { response.setContentType(page.getContentType()); if (currentRule.hasAttribute(AttrBodyOnly)) { page.outputBodyOnly(response.getOutputStream()); } else { page.output(response.getOutputStream()); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,107,955,332,755,726,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request; public interface ResultTransformer { public Object transformToContentProvider(Object result); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,182,378,095,377,480,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.web.dispatch.request; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.web.dispatch.response.provider.ContentProvider; import com.astamuse.asta4d.web.dispatch.response.provider.SerialProvider; public class ResultTransformerUtil { private final static Logger logger = LoggerFactory.getLogger(ResultTransformerUtil.class); public final static ContentProvider transform(Object result, List<ResultTransformer> transformerList) { if (result instanceof ContentProvider) { return (ContentProvider) result; } ContentProvider cp = null; Object before, after; before = result; ResultTransformer resultTransformer; int size = transformerList.size(); for (int i = 0; i < size; i++) { if (before instanceof MultiResultHolder) { List<ResultTransformer> subList = transformerList.subList(i, size); return transformMultiResult((MultiResultHolder) before, subList); } resultTransformer = transformerList.get(i); try { after = resultTransformer.transformToContentProvider(before); if (after instanceof Exception) { logger.error("Error occured on result transform.", (Exception) after); } } catch (Exception ex) { logger.error("Error occured on result transform.", ex); after = ex; } if (after == null) { continue; } else if (after instanceof ContentProvider) { cp = (ContentProvider) after; break; } else { before = after; continue; } } if (cp == null) { if (result == null) { String msg = "Cannot recognize the result null. Maybe a default ResultTransformer is neccessory(Usually a non result default forward/rediredt declaration of current url rule is missing)."; throw new UnsupportedOperationException(msg); } else { String msg = "Cannot recognize the result :[%s:%s]. Maybe a ResultTransformer is neccessory(Usually a result specified forward/rediredt declaration of current url rule is missing)."; msg = String.format(msg, result.getClass().getName(), result.toString()); throw new UnsupportedOperationException(msg); } } else { return cp; } } private final static ContentProvider transformMultiResult(MultiResultHolder resultHolder, List<ResultTransformer> transformerList) { List<Object> resultList = resultHolder.getResultList(); if (resultList == null || resultList.isEmpty()) { String msg = "MultiResultHolder should must hold some result but we got one with an empty list."; throw new UnsupportedOperationException(msg); } List<ContentProvider> cpList = new ArrayList<>(resultList.size()); for (Object object : resultList) { cpList.add(transform(object, transformerList)); } ContentProvider sp = new SerialProvider(cpList); return sp; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,453,218,505,812,967,400
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class MultiResultHolder { private List<Object> resultList; public MultiResultHolder() { resultList = new LinkedList<>(); } public void addResult(Object result) { resultList.add(result); } public List<Object> getResultList() { return Collections.unmodifiableList(resultList); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,056,657,474,041,182,700
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request; 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 RequestHandler { // }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,229,087,822,892,265,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import java.net.HttpURLConnection; import com.astamuse.asta4d.Page; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.Asta4DPageProvider; import com.astamuse.asta4d.web.dispatch.response.provider.RedirectTargetProvider; import com.astamuse.asta4d.web.util.bean.DeclareInstanceUtil; public class DefaultStringTransformer implements ResultTransformer { @Override public Object transformToContentProvider(Object result) { if (result instanceof String) { String target = result.toString(); if (target.startsWith("redirect:")) {// redirect String path = target.substring("redirect:".length()); int status = HttpURLConnection.HTTP_MOVED_TEMP; int nextColonIndex = path.indexOf(":"); if (nextColonIndex >= 0) { String possibleStatus = path.substring(0, nextColonIndex); if (possibleStatus.equalsIgnoreCase("p")) { status = HttpURLConnection.HTTP_MOVED_PERM; } else if (possibleStatus.equalsIgnoreCase("t")) { status = HttpURLConnection.HTTP_MOVED_TEMP; } else { try { status = Integer.parseInt(possibleStatus); } catch (NumberFormatException nfe) { // do nothing } } path = path.substring(possibleStatus.length() + 1); } RedirectTargetProvider provider = DeclareInstanceUtil.createInstance(RedirectTargetProvider.class); provider.setStatus(status); provider.setTargetPath(path); return provider; } else {// asta4d page try { Page page = Page.buildFromPath(result.toString()); Asta4DPageProvider provider = DeclareInstanceUtil.createInstance(Asta4DPageProvider.class); provider.setPage(page); return provider; } catch (TemplateNotFoundException tne) { return tne; } catch (Exception e) { throw new RuntimeException(e); } } } else { return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,834,444,542,775,461,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.EmptyContentProvider; public class StopTransformer implements ResultTransformer { @Override public Object transformToContentProvider(Object result) { return new EmptyContentProvider(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,344,241,921,800,460,300
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.XmlDataProvider; public class DefaultXmlTransformer implements ResultTransformer { @Override public Object transformToContentProvider(Object result) { return new XmlDataProvider(result); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,510,033,338,138,972,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.JsonDataProvider; public class DefaultJsonTransformer implements ResultTransformer { @Override public Object transformToContentProvider(Object result) { return new JsonDataProvider(result); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,411,613,651,823,905,300
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.HeaderInfoProvider; public class DefaultTemplateNotFoundExceptionTransformer implements ResultTransformer { @Override public Object transformToContentProvider(Object result) { if (result instanceof TemplateNotFoundException) { return new HeaderInfoProvider(404, false); } else { return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,913,598,229,330,291,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.HeaderInfoProvider; public class DefaultExceptionTransformer implements ResultTransformer { private static final Logger logger = LoggerFactory.getLogger(DefaultExceptionTransformer.class); @Override public Object transformToContentProvider(Object result) { if (result instanceof Throwable) { Throwable t = (Throwable) result; logger.error(t.getMessage(), t); return new HeaderInfoProvider(500, false); } else { return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
294,713,787,671,977,540
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; public class SimpleTypeMatchTransformer implements ResultTransformer { private Class<?> resultTypeIdentifier = null; private Object resultInstanceIdentifier = null; private Object transformedResult; public SimpleTypeMatchTransformer(Object obj, Object transformedResult) { super(); this.transformedResult = transformedResult; if (obj instanceof Class) { resultTypeIdentifier = (Class<?>) obj; } else { resultInstanceIdentifier = obj; } } public boolean isAsDefaultMatch() { return resultTypeIdentifier == null && resultInstanceIdentifier == null; } @Override public Object transformToContentProvider(Object result) { if (resultTypeIdentifier == null && resultInstanceIdentifier == null) { return this.transformedResult; } else if (result == null) { return null; } else if (resultTypeIdentifier != null) { if (resultTypeIdentifier.isAssignableFrom(result.getClass())) { return this.transformedResult; } else if (resultTypeIdentifier.equals(result.getClass())) { return this.transformedResult; } } else if (resultInstanceIdentifier != null) { if (resultInstanceIdentifier == result || resultInstanceIdentifier.equals(result)) { return this.transformedResult; } } return null; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,229,052,718,618,954,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.dispatch.request.transformer; import com.astamuse.asta4d.Page; import com.astamuse.asta4d.web.dispatch.request.ResultTransformer; import com.astamuse.asta4d.web.dispatch.response.provider.Asta4DPageProvider; import com.astamuse.asta4d.web.util.bean.DeclareInstanceUtil; public class Asta4DPageTransformer implements ResultTransformer { @Override public Object transformToContentProvider(Object result) { if (result instanceof Page) { Asta4DPageProvider provider = DeclareInstanceUtil.createInstance(Asta4DPageProvider.class); provider.setPage((Page) result); return provider; } else { return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,202,389,388,394,719,700
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.net.util.Base64; import com.astamuse.asta4d.util.IdGenerator; public class SecureIdGenerator { private final static SecureRandom sr; static { // use the last 32 bit of current time as the seed ByteBuffer bb = ByteBuffer.allocate(64); bb.putLong(System.nanoTime()); byte[] bytes = bb.array(); byte[] seed = new byte[4]; System.arraycopy(bytes, 4, seed, 0, 4); sr = new SecureRandom(seed); } public static String createEncryptedURLSafeId() { try { byte[] idBytes = IdGenerator.createIdBytes(); ByteBuffer bb = ByteBuffer.allocate(idBytes.length + 4); bb.put(idBytes); // add random salt bb.putInt(sr.nextInt()); MessageDigest crypt = MessageDigest.getInstance("SHA-1"); return Base64.encodeBase64URLSafeString(crypt.digest(bb.array())); } catch (NoSuchAlgorithmException e) { // impossible throw new RuntimeException(e); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,580,352,077,607,108,000
package com.astamuse.asta4d.web.util; public class ClosureVarRef<T> { private T data; public ClosureVarRef() { this.data = null; } public ClosureVarRef(T data) { this.data = data; } public void set(T data) { this.data = data; } public T get() { return this.data; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,266,882,026,267,673,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SystemPropertyUtil { private final static Logger logger = LoggerFactory.getLogger(SystemPropertyUtil.class); public static enum PropertyScope { ServletConfig, JNDI, SystemProperty } public final static String retrievePropertyValue(String key, PropertyScope... scopes) { return retrievePropertyValue(null, key, scopes); } public final static String retrievePropertyValue(ServletConfig sc, String key, PropertyScope... scopes) { String v = null; for (PropertyScope scope : scopes) { switch (scope) { case ServletConfig: v = retrieveFromServletConfig(sc, key); break; case JNDI: v = retrieveFromJDNI(key); break; case SystemProperty: v = retrieveFromSystemProperty(key); break; } if (v == null) { logger.info("[{}] is not being configured in {}.", key, scope); } else { logger.info("[{}] is found in {} with value:[{}].", new Object[] { key, scope, v }); break; } } return v; } private final static String retrieveFromServletConfig(ServletConfig sc, String key) { return sc.getInitParameter(key); } private final static String retrieveFromJDNI(String key) { InitialContext context = null; try { try { context = new InitialContext(); return (String) context.lookup("java:comp/env/" + key); } finally { if (context != null) { context.close(); } } } catch (NamingException e) { return null; } } private final static String retrieveFromSystemProperty(String key) { return System.getProperty(key); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,534,294,535,767,219,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.context; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.astamuse.asta4d.ContextMap; public class SessionMap implements ContextMap { private HttpServletRequest request; public SessionMap(HttpServletRequest request) { this.request = request; } @Override public void put(String key, Object data) { request.getSession(true).setAttribute(key, data); } @SuppressWarnings("unchecked") @Override public <T> T get(String key) { HttpSession session = request.getSession(false); if (session == null) { return null; } else { return (T) session.getAttribute(key); } } @Override public ContextMap createClone() { return this; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,146,694,780,923,919,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.timeout; public interface ExpirableDataManager { public void start(); public void stop(); public <T> T get(String dataId, boolean remove); public void put(String dataId, Object data, long expireMilliSeconds); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,872,360,539,113,485,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.timeout; public class TooManyDataException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public TooManyDataException(String message) { super(message); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,095,842,730,829,181,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.web.util.timeout; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.util.IdGenerator; import com.astamuse.asta4d.web.WebApplicationContext; public class DefaultSessionAwareExpirableDataManager implements ExpirableDataManager { private static final String SessionCheckIdKey = DefaultSessionAwareExpirableDataManager.class + "#SessionCheckIdKey"; private Map<String, DataHolder> dataMap = null; private AtomicInteger dataCounter = null; private ScheduledExecutorService service = null; // 3 minutes private long expirationCheckPeriodInMilliseconds = 3 * 60 * 1000; private int maxDataSize = 10_000; private boolean sessionAware = true; private long spinTimeInMilliseconds = 1000; // 5 times spinning private long maxSpinTimeInMilliseconds = 1000 * 5; private String checkThreadName = this.getClass().getSimpleName() + "-check-thread"; public DefaultSessionAwareExpirableDataManager() { dataMap = createThreadSafeDataMap(); dataCounter = new AtomicInteger(); } public void setExpirationCheckPeriodInMilliseconds(long expirationCheckPeriodInMilliseconds) { this.expirationCheckPeriodInMilliseconds = expirationCheckPeriodInMilliseconds; } public void setMaxDataSize(int maxDataSize) { this.maxDataSize = maxDataSize; } public void setSessionAware(boolean sessionAware) { this.sessionAware = sessionAware; } public void setSpinTimeInMilliseconds(long spinTimeInMilliseconds) { this.spinTimeInMilliseconds = spinTimeInMilliseconds; } public void setMaxSpinTimeInMilliseconds(long maxSpinTimeInMilliseconds) { this.maxSpinTimeInMilliseconds = maxSpinTimeInMilliseconds; } protected Map<String, DataHolder> createThreadSafeDataMap() { return new ConcurrentHashMap<>(); } protected void decreaseCount() { dataCounter.decrementAndGet(); } protected void addCount(int delta) { dataCounter.addAndGet(delta); } protected void increaseCount() { dataCounter.incrementAndGet(); } protected int getCurrentCount() { return dataCounter.get(); } @Override public void start() { service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, checkThreadName); } }); // start check thread service.scheduleAtFixedRate(new Runnable() { @Override public void run() { List<Entry<String, DataHolder>> entries = new ArrayList<>(dataMap.entrySet()); long currentTime = System.currentTimeMillis(); int removedCounter = 0; Object existing; for (Entry<String, DataHolder> entry : entries) { if (entry.getValue().isExpired(currentTime)) { existing = dataMap.remove(entry.getKey()); if (existing != null) {// we removed it successfully removedCounter++; } } } if (removedCounter > 0) { addCount(-removedCounter); } } }, expirationCheckPeriodInMilliseconds, expirationCheckPeriodInMilliseconds, TimeUnit.MILLISECONDS); } @Override public void stop() { // release all resources service.shutdownNow(); dataCounter = null; dataMap = null; } @SuppressWarnings("unchecked") public <T> T get(String dataId, boolean remove) { DataHolder holder; if (remove) { holder = dataMap.remove(dataId); if (holder != null) { decreaseCount(); if (holder.isExpired(System.currentTimeMillis())) { holder = null; } } } else { holder = dataMap.get(dataId); if (holder != null) { if (holder.isExpired(System.currentTimeMillis())) { holder = dataMap.remove(dataId); if (holder != null) { decreaseCount(); holder = null; } } } } if (holder == null) { return null; } else { if (StringUtils.equals(retrieveSessionCheckId(false), holder.sessionId)) { return (T) holder.getData(); } else { return null; } } } public void put(String dataId, Object data, long expireMilliSeconds) { checkSize(); Object existing = dataMap.put(dataId, new DataHolder(data, expireMilliSeconds, retrieveSessionCheckId(true))); if (existing == null) { increaseCount(); } } protected void checkSize() { if (getCurrentCount() >= maxDataSize) { try { long spinTimeTotal = 0; while (getCurrentCount() >= maxDataSize) { if (spinTimeTotal >= maxSpinTimeInMilliseconds) { String msg = "There are too many data in %s and we could not get empty space after waiting for %d milliseconds." + " The configured max size is %d and perhaps you should increase the value."; msg = String.format(msg, this.getClass().getName(), spinTimeTotal, maxDataSize); throw new TooManyDataException(msg); } Thread.sleep(spinTimeInMilliseconds); spinTimeTotal += spinTimeInMilliseconds; } } catch (InterruptedException e) { throw new RuntimeException(e); } } } /** * NOTE: Because there is no way to retrieve the session id via WebApplicationContext, thus we use a independent check id which is * different from the http request session id to check whether current request client is the same client from previous request. * * @param create * @return */ protected String retrieveSessionCheckId(boolean create) { String sessionCheckId = null; if (sessionAware) { WebApplicationContext context = WebApplicationContext.getCurrentThreadWebApplicationContext(); sessionCheckId = context.getData(WebApplicationContext.SCOPE_SESSION, SessionCheckIdKey); if (sessionCheckId == null && create) { sessionCheckId = IdGenerator.createId(); context.setData(WebApplicationContext.SCOPE_SESSION, SessionCheckIdKey, sessionCheckId); } } return sessionCheckId; } @Override protected void finalize() throws Throwable { stop(); super.finalize(); } protected static class DataHolder implements Serializable { /** * */ private static final long serialVersionUID = 1L; private final Object data; private final long creationTime; private final long expireMilliSeconds; private final String sessionId; private DataHolder(Object data, long expireMilliSeconds, String sessionId) { this.sessionId = sessionId; this.data = data; this.expireMilliSeconds = expireMilliSeconds; this.creationTime = System.currentTimeMillis(); } private Object getData() { return data; } private boolean isExpired(long currentTime) { return (currentTime - creationTime) > expireMilliSeconds; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,079,808,458,919,070,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.message; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Context; import com.astamuse.asta4d.data.ContextBindData; import com.astamuse.asta4d.render.ElementNotFoundHandler; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.template.ClasspathTemplateResolver; import com.astamuse.asta4d.template.Template; import com.astamuse.asta4d.template.TemplateException; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.template.TemplateResolver; import com.astamuse.asta4d.util.SelectorUtil; import com.astamuse.asta4d.web.WebApplicationConfiguration; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.dispatch.RedirectInterceptor; import com.astamuse.asta4d.web.dispatch.RedirectUtil; public class DefaultMessageRenderingHelper implements MessageRenderingHelper { private static final Logger logger = LoggerFactory.getLogger(DefaultMessageRenderingHelper.class); private final static String FLASH_MSG_LIST_KEY = "FLASH_MSG_LIST_KEY#" + DefaultMessageRenderingHelper.class; protected final static class MessageHolder { MessageRenderingSelector selector; MessageRenderingSelector alternativeSelector; String message; public MessageHolder(MessageRenderingSelector selector, MessageRenderingSelector alternativeSelector, String message) { super(); this.selector = selector; this.alternativeSelector = alternativeSelector; this.message = message; } } public final static class MessageRenderingSelector { private String duplicator; private String valueTarget; public MessageRenderingSelector() { } public MessageRenderingSelector(String duplicator, String valueTarget) { super(); this.duplicator = duplicator; this.valueTarget = valueTarget; } public String getDuplicator() { return duplicator; } public void setDuplicator(String duplicator) { this.duplicator = duplicator; } public String getValueTarget() { return valueTarget; } public void setValueTarget(String valueTarget) { this.valueTarget = valueTarget; } @Override public int hashCode() { return ((duplicator == null) ? 0 : duplicator.hashCode()) ^ ((valueTarget == null) ? 0 : valueTarget.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageRenderingSelector other = (MessageRenderingSelector) obj; if (duplicator == null) { if (other.duplicator != null) return false; } else if (!duplicator.equals(other.duplicator)) return false; if (valueTarget == null) { if (other.valueTarget != null) return false; } else if (!valueTarget.equals(other.valueTarget)) return false; return true; } } private TemplateResolver fallbackMessageContainerResolver = new ClasspathTemplateResolver(); private String messageGlobalContainerParentSelector = "body"; private String messageGlobalContainerSelector = "#global-msg-container"; private String messageGlobalContainerSnippetFilePath = "/com/astamuse/asta4d/web/util/message/DefaultMessageContainerSnippet.html"; private MessageRenderingSelector messageGlobalInfoSelector = new MessageRenderingSelector("#info-msg li", ":root"); private MessageRenderingSelector messageGlobalWarnSelector = new MessageRenderingSelector("#warn-msg li", ":root"); private MessageRenderingSelector messageGlobalErrSelector = new MessageRenderingSelector("#err-msg li", ":root"); private String messageDuplicatorIndicatorAttrName = "afd:message-duplicator"; private Elements cachedSnippet = null; private ContextBindData<List<MessageHolder>> messageList = new ContextBindData<List<MessageHolder>>(true) { @Override protected List<MessageHolder> buildData() { return new LinkedList<>(); } }; public DefaultMessageRenderingHelper() { super(); } public static DefaultMessageRenderingHelper getConfiguredInstance() { return (DefaultMessageRenderingHelper) WebApplicationConfiguration.getWebApplicationConfiguration().getMessageRenderingHelper(); } public String getMessageGlobalContainerParentSelector() { return messageGlobalContainerParentSelector; } public void setMessageGlobalContainerParentSelector(String messageGlobalContainerParentSelector) { this.messageGlobalContainerParentSelector = messageGlobalContainerParentSelector; } public String getMessageGlobalContainerSelector() { return messageGlobalContainerSelector; } public void setMessageGlobalContainerSelector(String messageGlobalContainerSelector) { this.messageGlobalContainerSelector = messageGlobalContainerSelector; } public String getMessageGlobalContainerSnippetFilePath() { return messageGlobalContainerSnippetFilePath; } public void setMessageGlobalContainerSnippetFilePath(String messageGlobalContainerSnippetFilePath) { this.messageGlobalContainerSnippetFilePath = messageGlobalContainerSnippetFilePath; } public MessageRenderingSelector getMessageGlobalInfoSelector() { return messageGlobalInfoSelector; } public void setMessageGlobalInfoSelector(MessageRenderingSelector messageGlobalInfoSelector) { this.messageGlobalInfoSelector = messageGlobalInfoSelector; } public MessageRenderingSelector getMessageGlobalWarnSelector() { return messageGlobalWarnSelector; } public void setMessageGlobalWarnSelector(MessageRenderingSelector messageGlobalWarnSelector) { this.messageGlobalWarnSelector = messageGlobalWarnSelector; } public MessageRenderingSelector getMessageGlobalErrSelector() { return messageGlobalErrSelector; } public void setMessageGlobalErrSelector(MessageRenderingSelector messageGlobalErrSelector) { this.messageGlobalErrSelector = messageGlobalErrSelector; } public String getMessageDuplicatorIndicatorAttrName() { return messageDuplicatorIndicatorAttrName; } public void setMessageDuplicatorIndicatorAttrName(String messageDuplicatorIndicatorAttrName) { this.messageDuplicatorIndicatorAttrName = messageDuplicatorIndicatorAttrName; } public Renderer createMessageRenderer() { Renderer renderer = Renderer.create(); Renderer message = renderMesssages(); if (message != null) { renderer.add(message); } renderer.add(postMessageRendering()); return renderer; } protected Renderer postMessageRendering() { // remove all the remaining message duplicators which may not be referenced in message outputting, which is why they are remaining Renderer render = Renderer.create(); render.disableMissingSelectorWarning(); render.add(SelectorUtil.attr(messageDuplicatorIndicatorAttrName), Clear); render.enableMissingSelectorWarning(); return render; } /** * * @return Pair.left: whether the alternative message container is necessary <br> * Pair.right: the actual renderer */ protected Renderer renderMesssages() { List<MessageHolder> allMsgList = new LinkedList<>(); allMsgList.addAll(messageList.get()); if (allMsgList.isEmpty()) { return null; } Renderer renderer = Renderer.create(); final Map<MessageRenderingSelector, List<MessageHolder>> msgMap = new HashMap<>(); final Map<MessageRenderingSelector, List<String>> alternativeMsgMap = new HashMap<>(); List<MessageHolder> tmpList; for (MessageHolder mh : allMsgList) { tmpList = msgMap.get(mh.selector); if (tmpList == null) { tmpList = new LinkedList<>(); msgMap.put(mh.selector, tmpList); } tmpList.add(mh); } renderer.disableMissingSelectorWarning(); for (final Entry<MessageRenderingSelector, List<MessageHolder>> item : msgMap.entrySet()) { if (item.getKey() == null) { List<String> list; for (MessageHolder mh : item.getValue()) { list = alternativeMsgMap.get(mh.alternativeSelector); if (list == null) { list = new LinkedList<>(); alternativeMsgMap.put(mh.alternativeSelector, list); } list.add(mh.message); } } else { final MessageRenderingSelector selector = item.getKey(); renderer.add(selector.duplicator, item.getValue(), (MessageHolder obj) -> { Renderer render = Renderer.create(selector.valueTarget, obj.message); render.add(":root", messageDuplicatorIndicatorAttrName, Clear); return render; }); renderer.add(new ElementNotFoundHandler(selector.duplicator) { @Override public Renderer alternativeRenderer() { List<String> list; for (MessageHolder mh : item.getValue()) { list = alternativeMsgMap.get(mh.alternativeSelector); if (list == null) { list = new LinkedList<>(); alternativeMsgMap.put(mh.alternativeSelector, list); } list.add(mh.message); } return Renderer.create(); } }); } } // end for loop renderer.enableMissingSelectorWarning(); renderer.add(messageGlobalContainerParentSelector, new Renderable() { @Override public Renderer render() { Renderer renderer = Renderer.create(); if (!alternativeMsgMap.isEmpty()) { renderer.add(new ElementNotFoundHandler(messageGlobalContainerSelector) { @Override public Renderer alternativeRenderer() { // add global message container if not exists return Renderer.create(":root", new ElementSetter() { @Override public void set(Element elem) { List<Element> elems = new ArrayList<>(retrieveCachedContainerSnippet()); Collections.reverse(elems); for (Element child : elems) { elem.prependChild(child.clone()); } } }); }// alternativeRenderer });// ElementNotFoundHandler renderer.add(messageGlobalContainerSelector, new Renderable() { @Override public Renderer render() { Renderer alternativeMsgRenderer = Renderer.create(); for (final Entry<MessageRenderingSelector, List<String>> item : alternativeMsgMap.entrySet()) { final MessageRenderingSelector selector = item.getKey(); alternativeMsgRenderer.add(selector.duplicator, item.getValue(), (String msg) -> { Renderer render = Renderer.create(selector.valueTarget, msg); render.add(":root", messageDuplicatorIndicatorAttrName, Clear); return render; }); } return alternativeMsgRenderer; } });// messageGlobalContainerSelector } return renderer; } }); return renderer; } protected Elements retrieveCachedContainerSnippet() { if (WebApplicationConfiguration.getWebApplicationConfiguration().isCacheEnable()) { if (cachedSnippet == null) { cachedSnippet = retrieveContainerSnippet(); } return cachedSnippet; } else { return retrieveContainerSnippet(); } } protected Elements retrieveContainerSnippet() { WebApplicationConfiguration conf = WebApplicationConfiguration.getWebApplicationConfiguration(); Template template; try { // at first, we treat the configured snippet file as a template file try { template = conf.getTemplateResolver().findTemplate(messageGlobalContainerSnippetFilePath); } catch (TemplateNotFoundException e) { // then treat it as classpath resource template = fallbackMessageContainerResolver.findTemplate(messageGlobalContainerSnippetFilePath); } return template.getDocumentClone().body().children(); } catch (TemplateException | TemplateNotFoundException e) { throw new RuntimeException(e); } } public void outputMessage(final MessageRenderingSelector selector, final MessageRenderingSelector alternativeSelector, final String msg) { messageList.get().add(new MessageHolder(selector, alternativeSelector, msg)); RedirectUtil.registerRedirectInterceptor(this.getClass().getName() + "#outputMessage", new RedirectInterceptor() { @Override public void beforeRedirect() { List<MessageHolder> list = new ArrayList<>(messageList.get()); if (!list.isEmpty()) { RedirectUtil.addFlashScopeData(FLASH_MSG_LIST_KEY, list); } } @Override public void afterRedirectDataRestore() { List<MessageHolder> flashedList = Context.getCurrentThreadContext().getData(WebApplicationContext.SCOPE_FLASH, FLASH_MSG_LIST_KEY); if (flashedList != null) { messageList.get().addAll(flashedList); } } }); } private void outputMessage(String duplicator, String msgTargetSelector, MessageRenderingSelector alternativeSelector, String msg) { MessageRenderingSelector selector = null; if (duplicator == null) { // do nothing } else { if (msgTargetSelector == null) { msgTargetSelector = ":root"; } selector = new MessageRenderingSelector(duplicator, msgTargetSelector); } outputMessage(selector, alternativeSelector, msg); } public void info(String msg) { info(null, null, msg); } public void info(String selector, String msg) { info(selector, null, msg); } public void info(String duplicator, String msgTargetSelector, String msg) { outputMessage(duplicator, msgTargetSelector, messageGlobalInfoSelector, msg); } public void warn(String msg) { warn(null, null, msg); } public void warn(String selector, String msg) { warn(selector, null, msg); } public void warn(String duplicator, String msgTargetSelector, String msg) { outputMessage(duplicator, msgTargetSelector, messageGlobalWarnSelector, msg); } public void err(String msg) { err(null, null, msg); } public void err(String selector, String msg) { err(selector, null, msg); } public void err(String duplicator, String msgTargetSelector, String msg) { outputMessage(duplicator, msgTargetSelector, messageGlobalErrSelector, msg); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,488,306,988,298,964,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.message; import com.astamuse.asta4d.render.Renderer; public interface MessageRenderingHelper { public Renderer createMessageRenderer(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,414,025,792,204,166,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.data; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import javax.servlet.ServletContext; public class BinaryDataUtil { public final static InputStream retrieveInputStreamByPath(ServletContext servletContext, ClassLoader classLoader, String path) { if (path.startsWith("file:")) { try { return new URL(path).openStream(); } catch (FileNotFoundException e) { return null; } catch (Exception e) { throw new RuntimeException(e); } } else if (path.startsWith("classpath:")) { String cls = path.substring("classpath:".length()); if (cls.startsWith("/")) { cls = cls.substring(1); } return classLoader.getResourceAsStream(cls); } else { return servletContext.getResourceAsStream(path); } } /** * * @param servletContext * @param classLoader * @param path * @return 0 when something is wrong or the actual last modified time of the resource for given path */ public final static long retrieveLastModifiedByPath(ServletContext servletContext, ClassLoader classLoader, String path) { if (path.startsWith("file:")) { try { URL url = new URL(path); return retriveLastModifiedFromURL(url); } catch (MalformedURLException e) { throw new RuntimeException(e); } } else if (path.startsWith("classpath:")) { String cls = path.substring("classpath:".length()); if (cls.startsWith("/")) { cls = cls.substring(1); } return retriveLastModifiedFromURL(classLoader.getResource(cls)); } else { try { return retriveLastModifiedFromURL(servletContext.getResource(path)); } catch (MalformedURLException e) { return 0L; } } } private final static long retriveLastModifiedFromURL(URL url) { try { URLConnection con = url.openConnection(); try { return con.getLastModified(); } catch (Exception ex) { return 0L; } finally { con.getInputStream().close(); } } catch (IOException e) { return 0L; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,098,647,402,157,264,400
package com.astamuse.asta4d.web.util.data; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class XmlUtil { // private static final xmlm private static final XmlMapper mapper = new XmlMapper(); public final static void toXml(OutputStream out, Object obj) throws IOException { mapper.writeValue(out, obj); } public final static String toXml(Object obj) throws JsonProcessingException { return mapper.writeValueAsString(obj); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,413,140,029,005,193,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.data; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtil { private final static ObjectMapper mapper = new ObjectMapper(); static { // mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); } public final static void toJson(OutputStream out, Object obj) throws IOException { mapper.writeValue(out, obj); } public final static String toJson(Object obj) throws JsonProcessingException { return mapper.writeValueAsString(obj); } public final static <T> T fromJson(String json, Class<T> cls) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(json, cls); } public final static Object fromJson(String json) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(json, Object.class); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,687,751,476,982,448,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.bean; public interface DeclareInstanceAdapter { public Object asTargetInstance(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,057,631,506,096,005,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.bean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.web.WebApplicationConfiguration; public class DeclareInstanceUtil { private final static DeclareInstanceResolver defaultResolver = new DefaultDeclareInstanceResolver(); private final static Logger logger = LoggerFactory.getLogger(AnnotationMethodHelper.class); @SuppressWarnings("unchecked") public final static <T> T createInstance(Object declaration) { WebApplicationConfiguration conf = WebApplicationConfiguration.getWebApplicationConfiguration(); List<DeclareInstanceResolver> resolverList = conf.getInstanceResolverList(); Object handler = null; for (DeclareInstanceResolver resolver : resolverList) { handler = resolver.resolve(declaration); if (handler != null) { break; } } if (handler == null) { handler = defaultResolver.resolve(declaration); } return (T) handler; } public final static Object retrieveInovkeTargetObject(Object instance) { return instance instanceof DeclareInstanceAdapter ? ((DeclareInstanceAdapter) instance).asTargetInstance() : instance; } public final static Object invokeMethod(Object obj, Method m) throws Exception { Object[] params = InjectUtil.getMethodInjectParams(m); if (params == null) { params = new Object[0]; } try { return m.invoke(obj, params); } catch (Exception e) { Exception throwEx = e; if (e instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException) e).getTargetException(); if (t instanceof Exception) { throwEx = (Exception) t; } } String msg = "Error occured when invoke method for method:%s on %s, with params:%s"; msg = String.format(msg, m.toString(), obj.getClass().getName(), params); logger.error(msg, throwEx); throw throwEx; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,872,728,503,641,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.web.util.bean; public interface DeclareInstanceResolver { public Object resolve(Object declaration); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,076,720,485,649,319,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.bean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultDeclareInstanceResolver implements DeclareInstanceResolver { private final static Logger logger = LoggerFactory.getLogger(DefaultDeclareInstanceResolver.class); @SuppressWarnings("rawtypes") @Override public Object resolve(Object declaration) { try { if (declaration instanceof Class) { return ((Class) declaration).newInstance(); } else if (declaration instanceof String) { Class<?> clz = Class.forName(declaration.toString()); return clz.newInstance(); } else { return declaration; } } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { logger.warn("Can not create instance for:" + declaration.toString(), e); return null; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,287,501,552,499,804,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.util.bean; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; public class AnnotationMethodHelper { private final static Logger logger = LoggerFactory.getLogger(AnnotationMethodHelper.class); private final static ConcurrentHashMap<String, Method> methodCache = new ConcurrentHashMap<>(); private final static String getCacheKey(Class<?> cls, Class<? extends Annotation> annotation) { return cls.getName() + "###annotation##" + annotation.getName(); } public final static Method findMethod(Object obj, Class<? extends Annotation> annotation) { Method m = null; String cacheKey = getCacheKey(obj.getClass(), annotation); if (Configuration.getConfiguration().isCacheEnable()) { m = methodCache.get(cacheKey); if (m != null) { return m; } } m = findMethod(obj.getClass(), annotation); if (m != null) { m.setAccessible(true); methodCache.put(cacheKey, m); } return m; } private final static Method findMethod(Class<?> cls, Class<? extends Annotation> annotation) { if (cls == null || cls.getName().equals(Object.class.getName())) { return null; } Method[] methodList = cls.getMethods(); Method m = null; for (Method method : methodList) { if (method.isAnnotationPresent(annotation)) { m = method; break; } } if (m == null) { m = findMethod(cls.getSuperclass(), annotation); if (m == null) { Class<?>[] intfs = cls.getInterfaces(); for (Class<?> intf : intfs) { m = findMethod(intf, annotation); if (m != null) { break; } } /* * we need to find out the implemented method rather than the interface declared method because * we need retrieve the actual parameter names later. */ if (m != null) { try { m = cls.getMethod(m.getName(), m.getParameterTypes()); } catch (Exception e) { // it seems impossible throw new RuntimeException(e); } } } } return m; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,439,148,671,982,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.web.sitecategory; import java.io.FileNotFoundException; import java.io.IOException; import javax.servlet.ServletContext; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.builtin.StaticResourceHandler; public class SiteCategoryAwaredStaticResourceHandler extends StaticResourceHandler implements SiteCategoryAwaredPathConvertor { private SiteCategoryAwaredResourceLoader<StaticFileInfo> resourceLoader = new SiteCategoryAwaredResourceLoader<StaticFileInfo>() { @Override public StaticFileInfo load(String path, Object extraInfomation) throws Exception { return _super_retrieveStaticFileInfo(WebApplicationContext.getCurrentThreadWebApplicationContext().getServletContext(), path); } @Override protected String createCategorySpecifiedPath(String category, String path) { return convertCategorySpecifiedPath(category, path); } }; public SiteCategoryAwaredStaticResourceHandler() { super(); } public SiteCategoryAwaredStaticResourceHandler(String basePath) { super(basePath); } private StaticFileInfo _super_retrieveStaticFileInfo(ServletContext servletContext, String path) throws FileNotFoundException, IOException { return super.retrieveStaticFileInfo(servletContext, path); } @Override protected StaticFileInfo retrieveStaticFileInfo(ServletContext servletContext, String path) throws FileNotFoundException, IOException { String[] categories = SiteCategoryUtil.getCurrentRequestSearchCategories(); try { return resourceLoader.load(categories, path); } catch (Exception e) { throw new IOException(e); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,857,909,520,373,746,200
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.sitecategory; import com.astamuse.asta4d.web.WebApplicationContext; public class SiteCategoryUtil { private static final String CategoryKey = SiteCategoryUtil.class.getName() + "#CategoryKey"; public static final void setCurrentRequestSearchCategories(String... categories) { WebApplicationContext.getCurrentThreadContext().setData(CategoryKey, categories); } public static final String[] getCurrentRequestSearchCategories() { return WebApplicationContext.getCurrentThreadContext().getData(CategoryKey); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,287,831,849,327,535,000
package com.astamuse.asta4d.web.sitecategory; public interface SiteCategoryAwaredPathConvertor { default String convertCategorySpecifiedPath(String category, String path) { if (category.isEmpty()) {// category would not be null return path; } else { if (path.startsWith("/")) { return "/" + category + path; } else { return "/" + category + "/" + path; } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,399,710,817,972,936,200
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.sitecategory; import javax.servlet.ServletContext; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.template.Template; import com.astamuse.asta4d.template.TemplateException; import com.astamuse.asta4d.template.TemplateNotFoundException; import com.astamuse.asta4d.template.TemplateResolver; import com.astamuse.asta4d.util.MemorySafeResourceCache; import com.astamuse.asta4d.util.MemorySafeResourceCache.ResouceHolder; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.WebApplicationTemplateResolver; public class SiteCategoryAwaredTemplateResolver implements TemplateResolver, SiteCategoryAwaredPathConvertor { private Class<? extends TemplateResolver> underlineTemplateResolverCls = null; private MemorySafeResourceCache<Object, TemplateResolver> underlineTemplateResolverCache = new MemorySafeResourceCache<>(); private SiteCategoryAwaredResourceLoader<Template> siteCategoryAwaredResourceLoader = new SiteCategoryAwaredResourceLoader<Template>() { @Override public Template load(String path, Object extraInfomation) throws Exception { try { TemplateResolver underlineTemplateResolver = null; ResouceHolder<TemplateResolver> rh = underlineTemplateResolverCache.get(extraInfomation); if (rh == null) { underlineTemplateResolver = createUnderlineTemplateResolverInstance(underlineTemplateResolverCls); if (underlineTemplateResolver instanceof WebApplicationTemplateResolver) { ServletContext sc = WebApplicationContext.getCurrentThreadWebApplicationContext().getServletContext(); ((WebApplicationTemplateResolver) underlineTemplateResolver).setServletContext(sc); } underlineTemplateResolverCache.put(extraInfomation, underlineTemplateResolver); } else { underlineTemplateResolver = rh.get();// there must be } return underlineTemplateResolver.findTemplate(path); } catch (TemplateNotFoundException ex) { return null; } } @Override protected String createCategorySpecifiedPath(String category, String path) { return convertCategorySpecifiedPath(category, path); } }; public SiteCategoryAwaredTemplateResolver() { this(WebApplicationTemplateResolver.class); } public SiteCategoryAwaredTemplateResolver(Class<? extends TemplateResolver> underlineTemplateResolverCls) { this.underlineTemplateResolverCls = underlineTemplateResolverCls; } public Class<? extends TemplateResolver> getUnderlineTemplateResolver() { return underlineTemplateResolverCls; } public void setUnderlineTemplateResolver(Class<? extends TemplateResolver> underlineTemplateResolverCls) { this.underlineTemplateResolverCls = underlineTemplateResolverCls; } @Override public Template findTemplate(final String path) throws TemplateException, TemplateNotFoundException { try { final String[] categories = SiteCategoryUtil.getCurrentRequestSearchCategories(); String categoryKey = createCategoryKey(categories); Template template = siteCategoryAwaredResourceLoader.load(categories, path, categoryKey); if (template == null) { throw new TemplateNotFoundException(path, "(in all the categories:" + StringUtils.join(categories, ",") + ")"); } else { return template; } } catch (TemplateNotFoundException e) { throw e; } catch (TemplateException e) { throw e; } catch (Exception e) { throw new TemplateException(e); } } protected String createCategoryKey(String[] categories) { return StringUtils.join(categories, ","); } protected TemplateResolver createUnderlineTemplateResolverInstance(Class<? extends TemplateResolver> cls) throws Exception { return cls.newInstance(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,290,185,059,289,728,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.sitecategory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.util.MemorySafeResourceCache; import com.astamuse.asta4d.util.MemorySafeResourceCache.ResouceHolder; /** * * We will cache the existing path only instead of the actual found resource, the cache of resources is assumed to be performed at the * underline load mechanism. * * @author e-ryu * * @param <T> */ public abstract class SiteCategoryAwaredResourceLoader<T> { private static class CacheKey { String category; String path; static CacheKey of(String category, String path) { CacheKey key = new CacheKey(); key.category = category; key.path = path; return key; } @Override public int hashCode() { return path.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; CacheKey other = (CacheKey) obj; // category and path would not be null return category.equals(other.category) && path.equals(other.path); } } private MemorySafeResourceCache<CacheKey, String> existingPathCache = new MemorySafeResourceCache<>(); public SiteCategoryAwaredResourceLoader() { } protected abstract String createCategorySpecifiedPath(String category, String path); /** * * @param path * @return null means the target resource is not found * @throws Exception */ public abstract T load(String path, Object extraInfomation) throws Exception; public T load(String[] categories, String path) throws Exception { return load(categories, path, null); } public T load(String[] categories, String path, Object extraInfomation) throws Exception { boolean cacheEnable = Configuration.getConfiguration().isCacheEnable(); ResouceHolder<String> existingPath = null; CacheKey key; for (String category : categories) { key = CacheKey.of(category, path); existingPath = cacheEnable ? existingPathCache.get(key) : null; if (existingPath == null) {// not check yet String tryPath = createCategorySpecifiedPath(category, path); T res = load(tryPath, extraInfomation); if (res == null) { existingPathCache.put(key, null); continue; } else { existingPathCache.put(key, tryPath); return res; } } else if (existingPath.exists()) { return load(existingPath.get(), extraInfomation); } else { continue; } } // it also means not found return null; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,902,971,497,435,234,300
package com.astamuse.asta4d.web.form; public interface CascadeArrayFunctions { public static final int[] EMPTY_INDEXES = new int[0]; /** * Sub classes can override this method to supply a customized array index placeholder mechanism. * * @param s * @param indexes * @return */ default String rewriteArrayIndexPlaceHolder(String s, int[] indexes) { String ret = s; for (int i = indexes.length - 1; i >= 0; i--) { ret = CascadeArrayFunctionsHelper.PlaceHolderSearchPattern[i].matcher(ret).replaceAll("$1\\" + indexes[i] + "$3"); } return ret; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,767,362,955,319,805,400
package com.astamuse.asta4d.web.form; import java.util.regex.Pattern; public class CascadeArrayFunctionsHelper { static final Pattern[] PlaceHolderSearchPattern = new Pattern[100]; static { for (int i = 0; i < PlaceHolderSearchPattern.length; i++) { PlaceHolderSearchPattern[i] = Pattern.compile("(^|.*[^@])(@{" + (i + 1) + "})([^@].*|$)"); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,504,546,853,958,499,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; public class OptionValueMap implements Serializable { /** * */ private static final long serialVersionUID = 1L; private List<OptionValuePair> optionList; private Map<String, String> valueMap; public OptionValueMap(List<OptionValuePair> optionList) { this.optionList = optionList; valueMap = new HashMap<>(); for (OptionValuePair op : optionList) { valueMap.put(op.getValue(), op.getDisplayText()); } } public static final <S> OptionValueMap build(List<S> list, RowConvertor<S, OptionValuePair> convertor) { return new OptionValueMap(ListConvertUtil.transform(list, convertor)); } public static final <S> OptionValueMap build(S[] array, RowConvertor<S, OptionValuePair> convertor) { return new OptionValueMap(ListConvertUtil.transform(Arrays.asList(array), convertor)); } public List<OptionValuePair> getOptionList() { return Collections.unmodifiableList(optionList); } public String getDisplayText(String value) { return valueMap.get(value); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,244,320,310,930,296,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; public interface FormFieldPrepareRenderer { public AnnotatedPropertyInfo targetField(); public Renderer preRender(String editSelector, String displaySelector); public Renderer postRender(String editSelector, String displaySelector); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
640,561,579,933,868,400
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; public abstract class SimpleFormFieldWithOptionValueRenderer extends SimpleFormFieldValueRenderer { protected String retrieveDisplayStringFromStoredOptionValueMap(String selector, String nonNullString) { OptionValueMap storedOptionMap = PrepareRenderingDataUtil.retrieveStoredDataFromContextBySelector(selector); if (storedOptionMap == null) { return nonNullString; } String value = storedOptionMap.getDisplayText(nonNullString); return value == null ? "" : value; } @SuppressWarnings({ "unchecked", "rawtypes" }) protected List<String> convertValueToList(Object value) { if (value == null) { return new LinkedList<>(); } else if (value.getClass().isArray()) { List<Object> list = Arrays.asList((Object[]) value); return ListConvertUtil.transform(list, new RowConvertor<Object, String>() { @Override public String convert(int rowIndex, Object obj) { return getNonNullString(obj); } }); } else if (value instanceof Iterable) { return ListConvertUtil.transform((Iterable) value, new RowConvertor<Object, String>() { @Override public String convert(int rowIndex, Object obj) { return getNonNullString(obj); } }); } else { return Arrays.asList(getNonNullString(value)); } } @Override protected Renderer renderForEdit(String nonNullString) { throw new UnsupportedOperationException(); } @Override protected Renderer addAlternativeDom(String editTargetSelector, String nonNullString) { throw new UnsupportedOperationException(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,616,703,628,322,767,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import com.astamuse.asta4d.Context; public class PrepareRenderingDataUtil { private static final String dataStoreKey(String selector) { return selector + "#" + PrepareRenderingDataUtil.class.getName(); } public static final void storeDataToContextBySelector(String editTargetSelector, String displayTargetSelector, Object data) { Context context = Context.getCurrentThreadContext(); String storeKey = dataStoreKey(editTargetSelector); context.setData(storeKey, data); storeKey = dataStoreKey(displayTargetSelector); context.setData(storeKey, data); } public static <T> T retrieveStoredDataFromContextBySelector(String selector) { String storeKey = dataStoreKey(selector); Context context = Context.getCurrentThreadContext(); return context.getData(storeKey); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,563,494,641,786,612,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil; public abstract class SimpleFormFieldPrepareRenderer implements FormFieldPrepareRenderer { private AnnotatedPropertyInfo field; /** * for test purpose */ @SuppressWarnings("unused") private String givenFieldName; public SimpleFormFieldPrepareRenderer(AnnotatedPropertyInfo field) { this.field = field; } @SuppressWarnings("rawtypes") public SimpleFormFieldPrepareRenderer(Class cls, String fieldName) { this(AnnotatedPropertyUtil.retrievePropertyByName(cls, fieldName).get(0)); } /** * this constructor is for test purpose, DO NOT USE IT!!! * * @param fieldName */ @Deprecated public SimpleFormFieldPrepareRenderer(String fieldName) { givenFieldName = fieldName; } /** * this method is for test purpose, DO NOT USE IT!!! * * @return */ @Deprecated public String getGivenFieldName() { return givenFieldName; } @Override public AnnotatedPropertyInfo targetField() { return field; } @Override public Renderer preRender(String editSelector, String displaySelector) { return Renderer.create(); } @Override public Renderer postRender(String editSelector, String displaySelector) { return Renderer.create(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
276,173,281,265,072,930
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import org.apache.commons.lang3.StringUtils; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.ElementNotFoundHandler; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.transformer.ElementTransformer; public abstract class SimpleFormFieldValueRenderer implements FormFieldValueRenderer { protected String getNonNullString(Object value) { String v = value == null ? "" : value.toString(); if (v == null) { v = ""; } return v; } @Override public Renderer renderForEdit(String editTargetSelector, Object value) { return Renderer.create(editTargetSelector, renderForEdit(getNonNullString(value))); } @Override public Renderer renderForDisplay(String editTargetSelector, String displayTargetSelector, Object value) { return renderForDisplay(editTargetSelector, displayTargetSelector, getNonNullString(value)); } protected abstract Renderer renderForEdit(String nonNullString); /** * * All the sub rendering is delayed by {@link Renderable}. * * @param editTargetSelector * @param displayTargetSelector * @param nonNullString * @return */ protected Renderer renderForDisplay(final String editTargetSelector, final String displayTargetSelector, final String nonNullString) { // hide the edit element Renderer render = Renderer.create(":root", new Renderable() { @Override public Renderer render() { return hideTarget(editTargetSelector); } }); render.disableMissingSelectorWarning(); // render.addDebugger("before " + displayTargetSelector); // render the shown value to target element by displayTargetSelector render.add(displayTargetSelector, new Renderable() { @Override public Renderer render() { return renderToDisplayTarget(displayTargetSelector, nonNullString); } }); // if the element by displayTargetSelector does not exists, simply add a span to show the value. // since ElementNotFoundHandler has been delayed, so the Renderable is not necessary render.add(new ElementNotFoundHandler(displayTargetSelector) { @Override public Renderer alternativeRenderer() { return addAlternativeDom(editTargetSelector, nonNullString); } }); render.enableMissingSelectorWarning(); return render; } protected Renderer hideTarget(final String targetSelector) { Renderer render = Renderer.create().disableMissingSelectorWarning(); return render.add(targetSelector, new ElementSetter() { @Override public void set(Element elem) { String style = elem.attr("style"); if (style != null) { style = style.trim(); } if (StringUtils.isEmpty(style)) { style = "display:none"; } else { if (style.endsWith(";")) { style = style + "display:none"; } else { style = style + ";display:none"; } } elem.attr("style", style); } }).enableMissingSelectorWarning(); } protected Renderer renderToDisplayTarget(String displayTargetSelector, String nonNullString) { return Renderer.create(displayTargetSelector, nonNullString); } protected Renderer addAlternativeDom(final String editTargetSelector, final String nonNullString) { Renderer renderer = Renderer.create(); // renderer.addDebugger("before alternative display for " + editTargetSelector); renderer.add(new Renderer(editTargetSelector, new ElementTransformer(null) { @Override public Element invoke(Element elem) { GroupNode group = new GroupNode(); Element editClone = elem.clone(); group.appendChild(editClone); group.appendChild(createAlternativeDisplayElement(nonNullString)); return group; } })); // renderer.addDebugger("after alternative display for " + editTargetSelector); return renderer; } protected Element createAlternativeDisplayElement(String nonNullString) { Element span = new Element(Tag.valueOf("span"), ""); span.text(nonNullString); return span; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
448,135,848,372,654,200
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import com.astamuse.asta4d.render.Renderer; public interface FormFieldValueRenderer { public Renderer renderForEdit(String editTargetSelector, Object value); public Renderer renderForDisplay(String editTargetSelector, String displayTargetSelector, Object value); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,671,684,345,808,518,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field; import java.io.Serializable; public class OptionValuePair implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String value; private String displayText; public OptionValuePair(String value, String displayText) { super(); this.value = value; this.displayText = displayText; } public String getValue() { return value; } public String getDisplayText() { return displayText; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,321,840,658,595,236,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.render.Renderer; public class HiddenRenderer extends InputDefaultRenderer { @Override protected Renderer renderForDisplay(String editTargetSelector, String displayTargetSelector, String nonNullString) { return Renderer.create(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,423,867,056,874,646,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.web.form.field.SimpleFormFieldValueRenderer; public class InputDefaultRenderer extends SimpleFormFieldValueRenderer { @Override public Renderer renderForEdit(String nonNullString) { return Renderer.create("input", "value", nonNullString); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,205,555,061,090,681,900
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.render.Renderer; public class SelectSingleRenderer extends AbstractSelectRenderer { @Override public Renderer renderForEdit(String editTargetSelector, Object value) { if (value == null) { // for a null value, we need to cheat it as an array with one null element return super.renderForEdit(editTargetSelector, new Object[] { getNonNullString(null) }); } else { return super.renderForEdit(editTargetSelector, value); } } @Override public Renderer renderForDisplay(final String editTargetSelector, final String displayTargetSelector, final Object value) { if (value == null) { // for a null value, we need to cheat it as an array with one null element return super.renderForDisplay(editTargetSelector, displayTargetSelector, new Object[] { getNonNullString(null) }); } else { return super.renderForDisplay(editTargetSelector, displayTargetSelector, value); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,202,788,394,522,274,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; public class SelectMultipleRenderer extends AbstractSelectRenderer { protected Element createAlternativeDisplayElement(String nonNullString) { Element span = new Element(Tag.valueOf("div"), ""); span.text(nonNullString); return span; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,987,875,808,677,116,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.transformer.ElementTransformer; import com.astamuse.asta4d.util.IdGenerator; import com.astamuse.asta4d.util.SelectorUtil; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.PrepareRenderingDataUtil; import com.astamuse.asta4d.web.form.field.SimpleFormFieldPrepareRenderer; @SuppressWarnings("rawtypes") public abstract class AbstractRadioAndCheckboxPrepareRenderer<T extends AbstractRadioAndCheckboxPrepareRenderer> extends SimpleFormFieldPrepareRenderer { public static final String LABEL_REF_ATTR = Configuration.getConfiguration().getTagNameSpace() + ":" + "label-ref-for-inputbox-id"; public static final String DUPLICATOR_REF_ID_ATTR = Configuration.getConfiguration().getTagNameSpace() + ":" + "input-radioandcheck-duplicator-ref-id"; public static final String DUPLICATOR_REF_ATTR = Configuration.getConfiguration().getTagNameSpace() + ":" + "input-radioandcheck-duplicator-ref"; private final static class WrapperIdHolder { String inputId = null; String wrapperId = null; String labelSelector = null; List<Element> relocatingLabels = new LinkedList<>(); } private String labelWrapperIndicatorAttr = null; private boolean inputIdByValue = false; private String duplicateSelector = null; private OptionValueMap optionMap = null; /** * For test purpose * * @param fieldName */ @Deprecated public AbstractRadioAndCheckboxPrepareRenderer(String fieldName) { super(fieldName); } public AbstractRadioAndCheckboxPrepareRenderer(AnnotatedPropertyInfo field) { super(field); } public AbstractRadioAndCheckboxPrepareRenderer(Class cls, String fieldName) { super(cls, fieldName); } @SuppressWarnings("unchecked") public T setOptionData(OptionValueMap optionMap) { this.optionMap = optionMap; return (T) this; } /** * for log purpose, "radio" or "checkbox" is expected. * * @return */ protected abstract String getTypeString(); /** * By default, there must be a label tag which "for" attribute is specified to the against input element, then this prepare renderer * will use a select as "label[for=id]" to retrieve the label element of the input element. <br> * User can specify a special attribute name to tell this prepare renderer to use selector as "[attrName=id]" to retrieve the against * label element which may be a label element with some decorating outer parent elements. * * * @param attrName * @return */ @SuppressWarnings("unchecked") public T setLabelWrapperIndicatorAttr(String attrName) { this.labelWrapperIndicatorAttr = attrName; return (T) this; } /** * This prepare renderer will generate new uuids for duplicated input elements but it make test verification difficult. specify true for * inputIdByValue will make the generated id fixed to the test value. * <p> * <b>NOTE:</b> This method is for test purpose and we do not recommend to use it in normal rendering logic. * * @param inputIdByValue * @return */ @SuppressWarnings("unchecked") public T setInputIdByValue(boolean inputIdByValue) { this.inputIdByValue = inputIdByValue; return (T) this; } /** * This prepare renderer will simply duplicate the continuous input/label pair. If the duplicateSelector is specified, the * duplicateSelector will be used to duplicate the target element which is assumed to be containing the actual input/label pair. * * @param duplicateSelector * @return */ @SuppressWarnings("unchecked") public T setDuplicateSelector(String duplicateSelector) { this.duplicateSelector = duplicateSelector; return (T) this; } @Override public Renderer preRender(final String editSelector, final String displaySelector) { if (duplicateSelector != null && labelWrapperIndicatorAttr != null) { String msg = "duplicateSelector (%s) and labelWrapperIndicatorAttr (%s) cannot be specified at same time."; throw new IllegalArgumentException(String.format(msg, duplicateSelector, labelWrapperIndicatorAttr)); } Renderer renderer = super.preRender(editSelector, displaySelector); renderer.disableMissingSelectorWarning(); // create wrapper for input element final WrapperIdHolder wrapperIdHolder = new WrapperIdHolder(); if (duplicateSelector == null && optionMap != null) { renderer.add(new Renderer(editSelector, new ElementTransformer(null) { @Override public Element invoke(Element elem) { if (wrapperIdHolder.wrapperId != null) { throw new RuntimeException( "The target of selector[" + editSelector + "] must be unique but over than 1 target was found." + "Perhaps you have specified an option value map on a group of elements " + "which is intented to be treated as predefined static options by html directly."); } String id = elem.id(); if (StringUtils.isEmpty(id)) { String msg = "A %s input element must have id value being configured:%s"; throw new RuntimeException(String.format(msg, getTypeString(), elem.outerHtml())); } GroupNode wrapper = new GroupNode(); // cheating the rendering engine for not skipping the rendering on group node wrapper.attr(ExtNodeConstants.GROUP_NODE_ATTR_TYPE, ExtNodeConstants.GROUP_NODE_ATTR_TYPE_USERDEFINE); // put the input element under the wrapper node wrapper.appendChild(elem.clone()); String wrapperId = IdGenerator.createId(); wrapper.attr("id", wrapperId); wrapperIdHolder.inputId = id; wrapperIdHolder.wrapperId = wrapperId; // record the selector for against label if (labelWrapperIndicatorAttr == null) { wrapperIdHolder.labelSelector = SelectorUtil.attr("label", "for", wrapperIdHolder.inputId); } else { wrapperIdHolder.labelSelector = SelectorUtil.attr(labelWrapperIndicatorAttr, wrapperIdHolder.inputId); } return wrapper; } })); renderer.add(":root", new Renderable() { @Override public Renderer render() { if (wrapperIdHolder.wrapperId == null) { // for display mode? return Renderer.create(); } // remove the label element and cache it in warpperIdHolder, we will relocate it later(since we have to duplicate the // input // and label pair by given option value map, we have to make sure that the input and label elements are in same parent // node // which can be duplicated) Renderer renderer = Renderer.create().disableMissingSelectorWarning(); renderer.add(new Renderer(wrapperIdHolder.labelSelector, new ElementTransformer(null) { @Override public Element invoke(Element elem) { wrapperIdHolder.relocatingLabels.add(elem.clone()); return new GroupNode(); } })); return renderer.enableMissingSelectorWarning(); } }); renderer.add(":root", new Renderable() { @Override public Renderer render() { if (wrapperIdHolder.wrapperId == null) { // for display mode? return Renderer.create(); } String selector = SelectorUtil.id(wrapperIdHolder.wrapperId); // relocate the label element to the wrapper node return Renderer.create(selector, new ElementSetter() { @Override public void set(Element elem) { if (wrapperIdHolder.relocatingLabels.isEmpty()) {// no existing label found Element label = new Element(Tag.valueOf("label"), ""); label.attr("for", wrapperIdHolder.inputId); elem.appendChild(label); } else { for (Element label : wrapperIdHolder.relocatingLabels) { elem.appendChild(label); } } } }); } }); } else { if (duplicateSelector != null && optionMap != null) { // if duplicateSelector is specified, we just only need to store the input element id renderer.add(editSelector, new ElementSetter() { @Override public void set(Element elem) { if (wrapperIdHolder.inputId != null) { String msg = "The target of selector[%s] (inside duplicator:%s) must be unique but over than 1 target was found."; throw new RuntimeException(String.format(msg, editSelector, duplicateSelector)); } String id = elem.id(); if (StringUtils.isEmpty(id)) { String msg = "A %s input element (inside duplicator:%s) must have id value being configured:%s"; throw new RuntimeException(String.format(msg, getTypeString(), duplicateSelector, elem.outerHtml())); } wrapperIdHolder.inputId = id; // record the selector for against label // labelWrapperIndicatorAttr would not be null since we checked it at the entry of this method. wrapperIdHolder.labelSelector = SelectorUtil.attr("label", "for", wrapperIdHolder.inputId); } }); } } // here we finished restructure the input element and its related label element and then we begin to manufacture all the input/label // pairs for option list renderer.add(":root", new Renderable() { @Override public Renderer render() { if (optionMap == null) { // for static options Renderer renderer = Renderer.create(); final List<String> inputIdList = new LinkedList<>(); renderer.add(editSelector, new ElementSetter() { @Override public void set(Element elem) { inputIdList.add(elem.id()); } }); renderer.add(":root", new Renderable() { @Override public Renderer render() { Renderer render = Renderer.create().disableMissingSelectorWarning(); for (String id : inputIdList) { render.add(SelectorUtil.attr(labelWrapperIndicatorAttr, id), LABEL_REF_ATTR, id); render.add(SelectorUtil.attr("label", "for", id), LABEL_REF_ATTR, id); } return render.enableMissingSelectorWarning(); } }); if (duplicateSelector != null) { renderer.add(duplicateSelector, new Renderable() { @Override public Renderer render() { String duplicatorRef = IdGenerator.createId(); Renderer render = Renderer.create(":root", DUPLICATOR_REF_ID_ATTR, duplicatorRef); render.add("input", DUPLICATOR_REF_ATTR, duplicatorRef); String labelSelector; if (labelWrapperIndicatorAttr == null) { labelSelector = SelectorUtil.tag("label"); } else { labelSelector = SelectorUtil.attr(labelWrapperIndicatorAttr); } render.add(labelSelector, DUPLICATOR_REF_ATTR, duplicatorRef); return render; } }); } return renderer; } else { if (wrapperIdHolder.wrapperId == null && duplicateSelector == null) { // for display mode? return Renderer.create(); } if (wrapperIdHolder.inputId == null) { // target input element not found return Renderer.create(); } String selector = duplicateSelector == null ? SelectorUtil.id(wrapperIdHolder.wrapperId) : duplicateSelector; return Renderer.create(selector, optionMap.getOptionList(), row -> { Renderer renderer = Renderer.create().disableMissingSelectorWarning(); String inputSelector = SelectorUtil.id("input", wrapperIdHolder.inputId); renderer.add(inputSelector, "value", row.getValue()); // we have to generate a new uuid for the input element to make sure its id is unique even we duplicated it. String newInputId = inputIdByValue ? row.getValue() : IdGenerator.createId(); // make the generated id more understandable by prefixing with original id newInputId = wrapperIdHolder.inputId + "-" + newInputId; String duplicatorRef = null; if (duplicateSelector != null) { duplicatorRef = IdGenerator.createId(); } renderer.add(":root", DUPLICATOR_REF_ID_ATTR, duplicatorRef); renderer.add(inputSelector, DUPLICATOR_REF_ATTR, duplicatorRef); renderer.add(inputSelector, "id", newInputId); // may be a wrapper container of label renderer.add(wrapperIdHolder.labelSelector, LABEL_REF_ATTR, newInputId); if (labelWrapperIndicatorAttr != null) { renderer.add(wrapperIdHolder.labelSelector, labelWrapperIndicatorAttr, newInputId); } renderer.add(wrapperIdHolder.labelSelector, DUPLICATOR_REF_ATTR, duplicatorRef); renderer.add("label", "for", newInputId); renderer.add("label", row.getDisplayText()); return renderer.enableMissingSelectorWarning(); }); } } }); // since we cheated the rendering engine, we should set the type of group node created to faked for fast clean up renderer.add(":root", new Renderable() { @Override public Renderer render() { if (wrapperIdHolder.wrapperId == null) { // for display mode? return Renderer.create(); } String selector = SelectorUtil.id(wrapperIdHolder.wrapperId); return Renderer.create(selector, new ElementSetter() { @Override public void set(Element elem) { elem.attr(ExtNodeConstants.GROUP_NODE_ATTR_TYPE, ExtNodeConstants.GROUP_NODE_ATTR_TYPE_FAKE); } }); } }); PrepareRenderingDataUtil.storeDataToContextBySelector(editSelector, displaySelector, optionMap); return renderer.enableMissingSelectorWarning(); } @Override public Renderer postRender(String editSelector, String displaySelector) { Renderer render = Renderer.create().disableMissingSelectorWarning(); String[] clearAttrs = { LABEL_REF_ATTR, DUPLICATOR_REF_ATTR, DUPLICATOR_REF_ID_ATTR }; for (String attr : clearAttrs) { render.add(SelectorUtil.attr(attr), attr, Clear); } render.add(super.postRender(editSelector, displaySelector)); return render.enableMissingSelectorWarning(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,082,707,759,082,784,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.render.Renderer; public class PasswordRenderer extends InputDefaultRenderer { @Override protected Renderer renderForDisplay(String editTargetSelector, String displayTargetSelector, String nonNullString) { return super.renderForDisplay(editTargetSelector, displayTargetSelector, "******"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,226,738,068,037,644,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; import org.joda.time.LocalTime; import org.joda.time.base.BaseDateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class TimeRenderer extends InputDefaultRenderer { protected static final DateTimeFormatter jodaFormatter = DateTimeFormat.forPattern("HH:mm:ss.SSS"); protected static final java.time.format.DateTimeFormatter java8Formatter = java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); protected String getNonNullString(Object value) { if (value instanceof Date) { return jodaFormatter.print(((Date) value).getTime()); } else if (value instanceof BaseDateTime) { return jodaFormatter.print(((BaseDateTime) value).getMillis()); } else if (value instanceof LocalTime) { return ((LocalTime) value).toString(jodaFormatter); } else if (value instanceof java.time.LocalTime) { return java8Formatter.format((java.time.LocalTime) value); } else if (value instanceof java.time.LocalDateTime) { return java8Formatter.format((java.time.LocalDateTime) value); } else if (value instanceof Instant) { Instant ins = (Instant) value; java.time.LocalDateTime ld = ZonedDateTime.ofInstant(ins, ZoneId.systemDefault()).toLocalDateTime(); return java8Formatter.format(ld); } else { return super.getNonNullString(value); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,531,632,272,945,337,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; public class CheckboxRenderer extends AbstractRadioAndCheckboxRenderer { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,000,607,404,415,580,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; public class RadioPrepareRenderer extends AbstractRadioAndCheckboxPrepareRenderer<RadioPrepareRenderer> { public RadioPrepareRenderer(AnnotatedPropertyInfo field) { super(field); } @SuppressWarnings("rawtypes") public RadioPrepareRenderer(Class cls, String fieldName) { super(cls, fieldName); } /** * for test purpose, DO NOT USE IT! * * @param fieldName */ @Deprecated public RadioPrepareRenderer(String fieldName) { super(fieldName); } @Override protected String getTypeString() { return "radio"; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
582,375,110,349,706,400
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; public class CheckboxPrepareRenderer extends AbstractRadioAndCheckboxPrepareRenderer<CheckboxPrepareRenderer> { public CheckboxPrepareRenderer(@SuppressWarnings("rawtypes") Class cls, String fieldName) { super(cls, fieldName); } public CheckboxPrepareRenderer(AnnotatedPropertyInfo field) { super(field); } /** * For test purpose, DO NOT USE IT! * * @param fieldName */ @Deprecated public CheckboxPrepareRenderer(String fieldName) { super(fieldName); } @Override protected String getTypeString() { return "checkbox"; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,945,985,285,856,276,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; import org.joda.time.LocalDate; import org.joda.time.base.BaseDateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class DateRenderer extends InputDefaultRenderer { protected static final DateTimeFormatter jodaFormatter = DateTimeFormat.forPattern("yyyy-MM-dd"); protected static final java.time.format.DateTimeFormatter java8Formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"); protected String getNonNullString(Object value) { /* * For the java 8 LocalDate, default #toString() is good enough, * and for java 8 Instant, converting to LocalDate is not bad. * */ if (value instanceof Date) { return jodaFormatter.print(((Date) value).getTime()); } else if (value instanceof BaseDateTime) { return jodaFormatter.print(((BaseDateTime) value).getMillis()); } else if (value instanceof LocalDate) { return ((LocalDate) value).toString(jodaFormatter); } else if (value instanceof java.time.LocalDate) { return java8Formatter.format((java.time.LocalDate) value); } else if (value instanceof java.time.LocalDateTime) { return java8Formatter.format((java.time.LocalDateTime) value); } else if (value instanceof Instant) { Instant ins = (Instant) value; java.time.LocalDate ld = ZonedDateTime.ofInstant(ins, ZoneId.systemDefault()).toLocalDate(); return java8Formatter.format(ld); } else { return super.getNonNullString(value); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,188,182,574,494,311,200
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.web.form.field.FormFieldValueRenderer; public class AvailableWhenEditOnlyRenderer implements FormFieldValueRenderer { @Override public Renderer renderForEdit(String editTargetSelector, Object value) { return Renderer.create(); } @Override public Renderer renderForDisplay(String editTargetSelector, String displayTargetSelector, Object value) { Renderer render = Renderer.create().disableMissingSelectorWarning(); render.add(editTargetSelector, Clear).add(displayTargetSelector, Clear); return render.enableMissingSelectorWarning(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,030,305,747,686,742,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import java.util.LinkedList; import java.util.List; import org.apache.commons.collections.CollectionUtils; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; import com.astamuse.asta4d.web.form.field.PrepareRenderingDataUtil; import com.astamuse.asta4d.web.form.field.SimpleFormFieldPrepareRenderer; public class SelectPrepareRenderer extends SimpleFormFieldPrepareRenderer { private static class OptGroup { String groupName; OptionValueMap optionMap; public OptGroup(String groupName, OptionValueMap optionMap) { super(); this.groupName = groupName; this.optionMap = optionMap; } } private List<OptGroup> optGroupList = new LinkedList<>(); private OptionValueMap optionMap; public SelectPrepareRenderer(AnnotatedPropertyInfo field) { super(field); } public SelectPrepareRenderer(Class cls, String fieldName) { super(cls, fieldName); } /** * for test purpose, DO NOT USE IT!!! * * @param fieldName */ @Deprecated public SelectPrepareRenderer(String fieldName) { super(fieldName); } public SelectPrepareRenderer setOptionData(OptionValueMap optionMap) { if (CollectionUtils.isNotEmpty(optGroupList)) { throw new RuntimeException("Option list without group is not allowed because there are existing option groups"); } this.optionMap = optionMap; return this; } public SelectPrepareRenderer addOptionGroup(String groupName, OptionValueMap optionMap) { if (this.optionMap != null) { throw new RuntimeException("Option list group is not allowed because there are existing option list without group"); } this.optGroupList.add(new OptGroup(groupName, optionMap)); return this; } @Override public Renderer preRender(String editSelector, String displaySelector) { Renderer renderer = super.preRender(editSelector, displaySelector); if (CollectionUtils.isNotEmpty(optGroupList)) { renderer.add(renderOptionGroup(editSelector, optGroupList)); List<OptionValuePair> allList = new LinkedList<>(); for (OptGroup optGrp : optGroupList) { allList.addAll(optGrp.optionMap.getOptionList()); } OptionValueMap allMap = new OptionValueMap(allList); PrepareRenderingDataUtil.storeDataToContextBySelector(editSelector, displaySelector, allMap); } else if (optionMap != null) { renderer.add(renderOptionList(editSelector, optionMap)); PrepareRenderingDataUtil.storeDataToContextBySelector(editSelector, displaySelector, optionMap); } return renderer; } private Renderer renderOptionGroup(String editSelector, List<OptGroup> groupList) { Renderer render = Renderer.create().disableMissingSelectorWarning(); return render.add(editSelector, Renderer.create("optGroup:eq(0)", groupList, row -> { return Renderer.create("optGroup", "label", row.groupName).add(renderOptionList("optGroup", row.optionMap)); })).enableMissingSelectorWarning(); } private Renderer renderOptionList(String editSelector, final OptionValueMap valueMap) { return Renderer.create(editSelector, Renderer.create("option:eq(0)", valueMap.getOptionList(), row -> { return Renderer.create("option", "value", row.getValue()).add("option", row.getDisplayText()); })); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,724,950,036,566,147,800
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.render.Renderer; public class RadioRenderer extends AbstractRadioAndCheckboxRenderer { @Override public Renderer renderForEdit(String editTargetSelector, Object value) { if (value == null) { // for a null value, we need to cheat it as an array with one null element return super.renderForEdit(editTargetSelector, new Object[] { getNonNullString(null) }); } else { return super.renderForEdit(editTargetSelector, value); } } @Override public Renderer renderForDisplay(final String editTargetSelector, final String displayTargetSelector, final Object value) { if (value == null) { // for a null value, we need to cheat it as an array with one null element return super.renderForDisplay(editTargetSelector, displayTargetSelector, new Object[] { getNonNullString(null) }); } else { return super.renderForDisplay(editTargetSelector, displayTargetSelector, value); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,443,179,187,915,593,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.jsoup.nodes.Element; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.ElementNotFoundHandler; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.transformer.ElementTransformer; import com.astamuse.asta4d.util.SelectorUtil; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; import com.astamuse.asta4d.web.form.field.PrepareRenderingDataUtil; import com.astamuse.asta4d.web.form.field.SimpleFormFieldWithOptionValueRenderer; import com.astamuse.asta4d.web.util.ClosureVarRef; public class AbstractRadioAndCheckboxRenderer extends SimpleFormFieldWithOptionValueRenderer { private static final String ToBeHiddenLaterFlagAttr = Configuration.getConfiguration().getTagNameSpace() + ":" + "ToBeHiddenLaterFlagAttr"; @Override public Renderer renderForEdit(String editTargetSelector, Object value) { final List<String> valueList = convertValueToList(value); Renderer renderer = Renderer.create("input", "checked", Clear); // we have to iterate the elements because the attr selector would not work for blank values. renderer.add("input", new ElementSetter() { @Override public void set(Element elem) { String val = elem.attr("value"); if (valueList.contains(val)) { elem.attr("checked", ""); } } }); return Renderer.create(editTargetSelector, renderer); } /** * By default, there must be an id for every radio/checkbox item. * * @return */ protected boolean allowNonIdItems() { return false; } protected Renderer retrieveAndCreateValueMap(final String editTargetSelector, final String displayTargetSelector) { Renderer render = Renderer.create(); if (PrepareRenderingDataUtil.retrieveStoredDataFromContextBySelector(editTargetSelector) == null) { final List<Pair<String, String>> inputList = new LinkedList<>(); final List<OptionValuePair> optionList = new LinkedList<>(); render.add(editTargetSelector, new ElementSetter() { @Override public void set(Element elem) { inputList.add(Pair.of(elem.id(), elem.attr("value"))); } }); render.add(":root", new Renderable() { @Override public Renderer render() { Renderer render = Renderer.create(); for (Pair<String, String> input : inputList) { String id = input.getLeft(); final String value = input.getRight(); if (StringUtils.isEmpty(id)) { if (allowNonIdItems()) { optionList.add(new OptionValuePair(value, value)); } else { String msg = "The target item[%s] must have id specified."; throw new IllegalArgumentException(String.format(msg, editTargetSelector)); } } else { render.add(SelectorUtil.attr("for", id), Renderer.create("label", new ElementSetter() { @Override public void set(Element elem) { optionList.add(new OptionValuePair(value, elem.text())); } })); render.add(":root", new Renderable() { @Override public Renderer render() { PrepareRenderingDataUtil.storeDataToContextBySelector(editTargetSelector, displayTargetSelector, new OptionValueMap(optionList)); return Renderer.create(); } }); } } // end for loop return render; } }); } return render; } protected Renderer setDelayedHiddenFlag(final String targetSelector) { // hide the input element final List<String> duplicatorRefList = new LinkedList<>(); final List<String> idList = new LinkedList<>(); Renderer renderer = Renderer.create(targetSelector, new ElementSetter() { @Override public void set(Element elem) { String duplicatorRef = elem.attr(RadioPrepareRenderer.DUPLICATOR_REF_ATTR); if (StringUtils.isNotEmpty(duplicatorRef)) { duplicatorRefList.add(duplicatorRef); } idList.add(elem.id()); } }); return renderer.add(":root", new Renderable() { @Override public Renderer render() { Renderer render = Renderer.create().disableMissingSelectorWarning(); for (String ref : duplicatorRefList) { render.add(SelectorUtil.attr(RadioPrepareRenderer.DUPLICATOR_REF_ID_ATTR, ref), ToBeHiddenLaterFlagAttr, ""); } for (String id : idList) { render.add(SelectorUtil.attr(RadioPrepareRenderer.LABEL_REF_ATTR, id), ToBeHiddenLaterFlagAttr, ""); } for (String id : idList) { render.add(SelectorUtil.attr("label", "for", id), ToBeHiddenLaterFlagAttr, ""); } render.add(targetSelector, ToBeHiddenLaterFlagAttr, ""); // render.addDebugger("after set hidden flag"); return render.enableMissingSelectorWarning(); } }); } @Override public Renderer renderForDisplay(final String editTargetSelector, final String displayTargetSelector, final Object value) { Renderer render = Renderer.create().disableMissingSelectorWarning(); // retrieve and create a value map here render.add(retrieveAndCreateValueMap(editTargetSelector, displayTargetSelector)); // render.add(super.renderForDisplay(editTargetSelector, displayTargetSelector, nonNullString)); // hide the edit element render.add(setDelayedHiddenFlag(editTargetSelector)); final List<String> valueList = convertValueToList(value); // render the shown value to target element by displayTargetSelector render.add(displayTargetSelector, new Renderable() { @Override public Renderer render() { return Renderer.create(displayTargetSelector, valueList, v -> { return renderToDisplayTarget(displayTargetSelector, retrieveDisplayStringFromStoredOptionValueMap(displayTargetSelector, v)); }); } }); // if the element by displayTargetSelector does not exists, simply add a span to show the value. // since ElementNotFoundHandler has been delayed, so the Renderable is not necessary render.add(new ElementNotFoundHandler(displayTargetSelector) { @Override public Renderer alternativeRenderer() { return addAlternativeDom(editTargetSelector, valueList); } }); // delay to hide all render.add(":root", new Renderable() { @Override public Renderer render() { return hideTarget(SelectorUtil.attr(ToBeHiddenLaterFlagAttr)); } }); // delay to remove the redundant attr render.add(":root", new Renderable() { @Override public Renderer render() { Renderer render = Renderer.create().disableMissingSelectorWarning(); return render.add(SelectorUtil.attr(ToBeHiddenLaterFlagAttr), ToBeHiddenLaterFlagAttr, Clear) .enableMissingSelectorWarning(); } }); return render.enableMissingSelectorWarning(); } protected Renderer addAlternativeDom(final String editTargetSelector, final List<String> valueList) { Renderer renderer = Renderer.create(); // renderer.addDebugger("entry root"); // renderer.addDebugger("entry root:edit target:", editTargetSelector); final List<String> matchedIdList = new LinkedList<>(); final List<String> unMatchedIdList = new LinkedList<>(); renderer.add(editTargetSelector, new ElementSetter() { @Override public void set(Element elem) { if (valueList.contains((elem.attr("value")))) { matchedIdList.add(elem.id()); } else { unMatchedIdList.add(elem.id()); } } }); renderer.add(":root", new Renderable() { @Override public Renderer render() { Renderer renderer = Renderer.create().disableMissingSelectorWarning(); // renderer.addDebugger("before hide unmatch"); // renderer.addDebugger("before add match"); if (matchedIdList.isEmpty()) { renderer.add(addDefaultAlternativeDom(editTargetSelector, valueList)); } else { // do nothing for remaining the existing label element // but we still have to revive the possibly existing duplicate container for (final String inputId : matchedIdList) { final List<String> matchedDuplicatorRefList = new LinkedList<>(); final String labelRefSelector = SelectorUtil.attr(RadioPrepareRenderer.LABEL_REF_ATTR, inputId); final String labelDefaultSelector = SelectorUtil.attr(SelectorUtil.tag("label"), "for", inputId); renderer.add(labelRefSelector, new ElementSetter() { @Override public void set(Element elem) { String ref = elem.attr(RadioPrepareRenderer.DUPLICATOR_REF_ATTR); if (StringUtils.isNotEmpty(ref)) { matchedDuplicatorRefList.add(ref); } } }); renderer.add(new ElementNotFoundHandler(labelRefSelector) { @Override public Renderer alternativeRenderer() { return Renderer.create(labelDefaultSelector, new ElementSetter() { @Override public void set(Element elem) { String ref = elem.attr(RadioPrepareRenderer.DUPLICATOR_REF_ATTR); if (StringUtils.isNotEmpty(ref)) { matchedDuplicatorRefList.add(ref); } }// end set }); }// end alternativeRenderer });// end ElementNotFoundHandler renderer.add(":root", new Renderable() { @Override public Renderer render() { Renderer renderer = Renderer.create().disableMissingSelectorWarning(); for (String ref : matchedDuplicatorRefList) { renderer.add(SelectorUtil.attr(RadioPrepareRenderer.DUPLICATOR_REF_ID_ATTR, ref), ToBeHiddenLaterFlagAttr, Clear); } renderer.add(labelRefSelector, ToBeHiddenLaterFlagAttr, Clear); renderer.add(labelDefaultSelector, ToBeHiddenLaterFlagAttr, Clear); return renderer.enableMissingSelectorWarning(); } }); } } return renderer.enableMissingSelectorWarning(); } }); return renderer; } protected Renderer addDefaultAlternativeDom(final String editTargetSelector, final List<String> valueList) { final List<String> duplicatorRefList = new LinkedList<>(); final List<String> idList = new LinkedList<>(); ClosureVarRef<Boolean> editTargetExists = new ClosureVarRef<Boolean>(false); Renderer renderer = Renderer.create(editTargetSelector, new ElementSetter() { @Override public void set(Element elem) { String duplicatorRef = elem.attr(RadioPrepareRenderer.DUPLICATOR_REF_ATTR); if (StringUtils.isNotEmpty(duplicatorRef)) { duplicatorRefList.add(duplicatorRef); } idList.add(elem.id()); editTargetExists.set(true); } }); /* renderer.add(":root", () -> { return Renderer.create().addDebugger("current root for addDefaultAlternativeDom"); }); */ renderer.add(":root", new Renderable() { @Override public Renderer render() { // skip create display alternative DOM if edit target does not exist. if (editTargetExists.get()) { // it is OK } else { return Renderer.create(); } String attachTargetSelector; if (duplicatorRefList.size() > 0) { attachTargetSelector = SelectorUtil.attr(RadioPrepareRenderer.DUPLICATOR_REF_ID_ATTR, duplicatorRefList.get(duplicatorRefList.size() - 1)); } else if (idList.size() == 0) { String msg = "The target item[%s] must have id specified."; throw new IllegalArgumentException(String.format(msg, editTargetSelector)); } else { attachTargetSelector = SelectorUtil.id(idList.get(idList.size() - 1)); } return new Renderer(attachTargetSelector, new ElementTransformer(null) { @Override public Element invoke(Element elem) { GroupNode group = new GroupNode(); Element editClone = elem.clone(); group.appendChild(editClone); for (String v : valueList) { String nonNullString = retrieveDisplayStringFromStoredOptionValueMap(editTargetSelector, v); group.appendChild(createAlternativeDisplayElement(nonNullString)); } return group; }// invoke });// new renderer }// render() });// renderable return renderer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,354,841,003,467,616,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.web.form.field.FormFieldValueRenderer; public class DoNothingFormFieldRenderer implements FormFieldValueRenderer { @Override public Renderer renderForEdit(String editTargetSelector, Object value) { return Renderer.create(); } @Override public Renderer renderForDisplay(String editTargetSelector, String displayTargetSelector, Object value) { return Renderer.create(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,925,425,612,898,144,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.LinkedList; import java.util.List; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.ElementNotFoundHandler; import com.astamuse.asta4d.render.ElementSetter; import com.astamuse.asta4d.render.Renderable; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.transformer.ElementTransformer; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; import com.astamuse.asta4d.web.form.field.PrepareRenderingDataUtil; import com.astamuse.asta4d.web.form.field.SimpleFormFieldWithOptionValueRenderer; public abstract class AbstractSelectRenderer extends SimpleFormFieldWithOptionValueRenderer { @Override public Renderer renderForEdit(String editTargetSelector, Object value) { final List<String> valueList = convertValueToList(value); Renderer renderer = Renderer.create("option", "selected", Clear); String selector = "option"; // we have to iterate the elements because the attr selector would not work for blank values. renderer.add(selector, new ElementSetter() { @Override public void set(Element elem) { String val = elem.attr("value"); if (valueList.contains(val)) { elem.attr("selected", ""); } } }); return Renderer.create(editTargetSelector, renderer); } @Override public Renderer renderForDisplay(final String editTargetSelector, final String displayTargetSelector, final Object value) { Renderer render = Renderer.create().disableMissingSelectorWarning(); // retrieve and create a value map here if (PrepareRenderingDataUtil.retrieveStoredDataFromContextBySelector(editTargetSelector) == null) { render.add(editTargetSelector, new ElementSetter() { @Override public void set(Element elem) { final List<OptionValuePair> optionList = new LinkedList<>(); Elements opts = elem.select("option"); String value, displayText; for (Element opt : opts) { value = opt.attr("value"); displayText = opt.text(); optionList.add(new OptionValuePair(value, displayText)); } PrepareRenderingDataUtil.storeDataToContextBySelector(editTargetSelector, displayTargetSelector, new OptionValueMap(optionList)); } }); } // hide target render.add(hideTarget(editTargetSelector)); final List<String> valueList = convertValueToList(value); // render the shown value to target element by displayTargetSelector render.add(displayTargetSelector, new Renderable() { @Override public Renderer render() { return Renderer.create(displayTargetSelector, valueList, v -> { return renderToDisplayTarget(displayTargetSelector, retrieveDisplayStringFromStoredOptionValueMap(displayTargetSelector, v)); }); } }); // if the element by displayTargetSelector does not exists, simply add a span to show the value. // since ElementNotFoundHandler has been delayed, so the Renderable is not necessary render.add(new ElementNotFoundHandler(displayTargetSelector) { @Override public Renderer alternativeRenderer() { return addAlternativeDom(editTargetSelector, valueList); } }); return render.enableMissingSelectorWarning(); } protected Renderer addAlternativeDom(final String editTargetSelector, final List<String> valueList) { return new Renderer(editTargetSelector, new ElementTransformer(null) { @Override public Element invoke(Element elem) { GroupNode group = new GroupNode(); Element editClone = elem.clone(); group.appendChild(editClone); for (String v : valueList) { String nonNullString = retrieveDisplayStringFromStoredOptionValueMap(editTargetSelector, v); group.appendChild(createAlternativeDisplayElement(nonNullString)); } return group; }// invoke }); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-52,271,336,503,719,740
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.field.impl; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.render.transformer.ElementTransformer; import com.astamuse.asta4d.web.form.field.SimpleFormFieldValueRenderer; public class TextareaRenderer extends SimpleFormFieldValueRenderer { @Override public Renderer renderForEdit(String nonNullString) { return Renderer.create("textarea", nonNullString); } @Override protected Renderer addAlternativeDom(final String editTargetSelector, final String nonNullString) { Renderer renderer = Renderer.create(); renderer.add(new Renderer(editTargetSelector, new ElementTransformer(null) { @Override public Element invoke(Element elem) { GroupNode group = new GroupNode(); Element editClone = elem.clone(); group.appendChild(editClone); Element newElem = new Element(Tag.valueOf("pre"), ""); newElem.text(nonNullString); group.appendChild(newElem); return group; } })); return renderer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,179,919,270,198,384,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.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.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.form.annotation.convert.FormAnnotationConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) @ConvertableAnnotation(FormAnnotationConvertor.class) public @interface Form { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
332,463,134,627,668,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.web.form.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.util.annotation.ConvertableAnnotation; import com.astamuse.asta4d.web.form.annotation.convert.CascadeFormFieldAnnotationConvertor; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) @ConvertableAnnotation(CascadeFormFieldAnnotationConvertor.class) public @interface CascadeFormField { String name() default ""; String nameLabel() default ""; String message() default ""; String arrayLengthField() default ""; String containerSelector() default ""; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
250,073,191,129,051,040