code
stringlengths
73
34.1k
label
stringclasses
1 value
public Map<String, String> getValueMap() { if (tokensMap == null) { return null; } if (tokensMap.isEmpty()) { return new LinkedHashMap<>(); } else { Map<String, String> map = new LinkedHashMap<>(tokensMap.size()); for (Map.Entry<String, Tok...
java
public void setValue(Map<String, Token[]> tokensMap) { if (type == null) { type = ItemType.MAP; } if (!isMappableType()) { throw new IllegalArgumentException("The type of this item must be 'map' or 'properties'"); } this.tokensMap = tokensMap; }
java
public void setValue(Properties properties) { if (properties == null) { throw new IllegalArgumentException("properties must not be null"); } if (type == null) { type = ItemType.PROPERTIES; } if (!isMappableType()) { throw new IllegalArgumentEx...
java
public void setValue(List<Token[]> tokensList) { if (type == null) { type = ItemType.LIST; } if (!isListableType()) { throw new IllegalArgumentException("The item type must be 'array', 'list' or 'set' for this item " + this); } this.tokensList = tokensList...
java
public void setValue(Set<Token[]> tokensSet) { if (tokensSet == null) { throw new IllegalArgumentException("tokensSet must not be null"); } if (type == null) { type = ItemType.SET; } if (!isListableType()) { throw new IllegalArgumentException("...
java
public boolean isListableType() { return (type == ItemType.ARRAY || type == ItemType.LIST || type == ItemType.SET); }
java
public static ItemRule newInstance(String type, String name, String valueType, String defaultValue, Boolean tokenize, Boolean mandatory, Boolean secret) throws IllegalRuleException { ItemRule itemRule = new ItemRule(); ItemTy...
java
public static Token makeReferenceToken(String bean, String template, String parameter, String attribute, String property) { Token token; if (bean != null) { token = new Token(TokenType.BEAN, bean); } else if (template != null) { ...
java
@Override public InputStream getInputStream() throws IOException { InputStream inputStream = fileItem.getInputStream(); return (inputStream != null ? inputStream : new ByteArrayInputStream(new byte[0])); }
java
@Override public File saveAs(File destFile, boolean overwrite) throws IOException { if (destFile == null) { throw new IllegalArgumentException("destFile can not be null"); } validateFile(); try { destFile = determineDestinationFile(destFile, overwrite); ...
java
private static String makeMessage(int lineNumber, String line, String tline, String msg) { int columnNumber = (tline != null ? line.indexOf(tline) : 0); StringBuilder sb = new StringBuilder(); if (msg != null) { sb.append(msg); } sb.append(" [lineNumber: ").append(lin...
java
private void prepare(String requestName, MethodType requestMethod, TransletRule transletRule, Translet parentTranslet) { try { if (log.isDebugEnabled()) { log.debug("Translet " + transletRule); } newTranslet(requestMethod, requestName...
java
private void produce() { ContentList contentList = getTransletRule().getContentList(); if (contentList != null) { ProcessResult processResult = translet.getProcessResult(); if (processResult == null) { processResult = new ProcessResult(contentList.size()); ...
java
protected String resolveRequestEncoding() { String encoding = getRequestRule().getEncoding(); if (encoding == null) { encoding = getSetting(RequestRule.CHARACTER_ENCODING_SETTING_NAME); } return encoding; }
java
protected String resolveResponseEncoding() { String encoding = getRequestRule().getEncoding(); if (encoding == null) { encoding = resolveRequestEncoding(); } return encoding; }
java
protected LocaleResolver resolveLocale() { LocaleResolver localeResolver = null; String localeResolverBeanId = getSetting(RequestRule.LOCALE_RESOLVER_SETTING_NAME); if (localeResolverBeanId != null) { localeResolver = getBean(localeResolverBeanId, LocaleResolver.class); l...
java
protected void parseDeclaredParameters() { ItemRuleMap parameterItemRuleMap = getRequestRule().getParameterItemRuleMap(); if (parameterItemRuleMap != null && !parameterItemRuleMap.isEmpty()) { ItemEvaluator evaluator = null; ItemRuleList missingItemRules = null; for (...
java
protected void parseDeclaredAttributes() { ItemRuleMap attributeItemRuleMap = getRequestRule().getAttributeItemRuleMap(); if (attributeItemRuleMap != null && !attributeItemRuleMap.isEmpty()) { ItemEvaluator evaluator = new ItemExpression(this); for (ItemRule itemRule : attributeI...
java
protected void execute(ActionList actionList) { ProcessResult processResult = translet.getProcessResult(); if (processResult == null) { processResult = new ProcessResult(1); translet.setProcessResult(processResult); } ContentResult contentResult = processResult.g...
java
private void execute(Executable action, ContentResult contentResult) { try { ChooseWhenRule chooseWhenRule = null; if (action.getCaseNo() > 0) { ChooseRuleMap chooseRuleMap = getTransletRule().getChooseRuleMap(); if (chooseRuleMap == null || chooseRuleMap....
java
public void scanConfigurableBeans(String... basePackages) throws BeanRuleException { if (basePackages == null || basePackages.length == 0) { return; } log.info("Auto component scanning on packages [" + StringUtils.joinCommaDelimitedList(basePackages) + "]"); for (String bas...
java
public void addBeanRule(final BeanRule beanRule) throws IllegalRuleException { PrefixSuffixPattern prefixSuffixPattern = PrefixSuffixPattern.parse(beanRule.getId()); String scanPattern = beanRule.getScanPattern(); if (scanPattern != null) { BeanClassScanner scanner = createBeanClassS...
java
protected String getMessageFromParent(String code, Object[] args, Locale locale) { MessageSource parent = getParentMessageSource(); if (parent != null) { if (parent instanceof AbstractMessageSource) { // Call internal method to avoid getting the default code back ...
java
public void reserve(String beanId, Class<?> beanClass, BeanReferenceable referenceable, RuleAppender ruleAppender) { RefererKey key = new RefererKey(beanClass, beanId); Set<RefererInfo> refererInfoSet = refererInfoMap.get(key); if (refererInfoSet == null) { refererInfoSet = new Linke...
java
public void inspect(BeanRuleRegistry beanRuleRegistry) throws BeanReferenceException, BeanRuleException { Set<Object> brokenReferences = new LinkedHashSet<>(); for (Map.Entry<RefererKey, Set<RefererInfo>> entry : refererInfoMap.entrySet()) { RefererKey refererKey = entry.getKey(); ...
java
public ItemRule putItemRule(ItemRule itemRule) { if (itemRule.isAutoNamed()) { autoNaming(itemRule); } return put(itemRule.getName(), itemRule); }
java
protected void rejectRequest(Translet translet, CorsException ce) throws CorsException { HttpServletResponse res = translet.getResponseAdaptee(); res.setStatus(ce.getHttpStatusCode()); translet.setAttribute(CORS_HTTP_STATUS_CODE, ce.getHttpStatusCode()); translet.setAttribute(CORS_HTTP_...
java
private boolean isAllowedAddress(String ipAddress) { if (allowedAddresses == null) { return false; } // IPv4 int offset = ipAddress.lastIndexOf('.'); if (offset == -1) { // IPv6 offset = ipAddress.lastIndexOf(':'); if (offset == -1...
java
public byte[] getBytes() throws IOException { InputStream input = getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int len; try { while ((len = input.read(buffer)) != -1) { ...
java
public File saveAs(File destFile, boolean overwrite) throws IOException { if (destFile == null) { throw new IllegalArgumentException("destFile can not be null"); } try { destFile = determineDestinationFile(destFile, overwrite); final byte[] buffer = new byte...
java
public void release() { if (file != null) { file.setWritable(true); } if (savedFile != null) { savedFile.setWritable(true); } }
java
public static ActivityContext getActivityContext(ServletContext servletContext) { ActivityContext activityContext = getActivityContext(servletContext, ROOT_WEB_SERVICE_ATTRIBUTE); if (activityContext == null) { throw new IllegalStateException("No Root AspectranWebService found; " + ...
java
public static ActivityContext getActivityContext(HttpServlet servlet) { ServletContext servletContext = servlet.getServletContext(); String attrName = STANDALONE_WEB_SERVICE_ATTRIBUTE_PREFIX + servlet.getServletName(); ActivityContext activityContext = getActivityContext(servletContext, attrName...
java
private static ActivityContext getActivityContext(ServletContext servletContext, String attrName) { Object attr = servletContext.getAttribute(attrName); if (attr == null) { return null; } if (!(attr instanceof AspectranWebService)) { throw new IllegalStateExceptio...
java
private boolean deleteFile(String filename) throws Exception { if (filename == null) { return false; } File file = new File(storeDir, filename); return Files.deleteIfExists(file.toPath()); }
java
@Override public Set<String> doGetExpired(final Set<String> candidates) { final long now = System.currentTimeMillis(); Set<String> expired = new HashSet<>(); // iterate over the files and work out which have expired for (String filename : sessionFileMap.values()) { ...
java
private String getIdFromFilename(String filename) { if (!StringUtils.hasText(filename) || filename.indexOf('_') < 0) { return null; } return filename.substring(0, filename.lastIndexOf('_')); }
java
private boolean isSessionFilename(String filename) { if (!StringUtils.hasText(filename)) { return false; } String[] parts = filename.split("_"); // Need at least 2 parts for a valid filename return (parts.length >= 2); }
java
public void sweepFile(long now, Path p) throws Exception { if (p == null) { return; } long expiry = getExpiryFromFilename(p.getFileName().toString()); // files with 0 expiry never expire if (expiry > 0 && ((now - expiry) >= (5 * TimeUnit.SECONDS.toMillis(gracePe...
java
private void save(OutputStream os, String id, SessionData data) throws IOException { DataOutputStream out = new DataOutputStream(os); out.writeUTF(id); out.writeLong(data.getCreationTime()); out.writeLong(data.getAccessedTime()); out.writeLong(data.getLastAccessedTime()); ...
java
private SessionData load(InputStream is, String expectedId) throws Exception { try { DataInputStream di = new DataInputStream(is); String id = di.readUTF(); // the actual id from inside the file long created = di.readLong(); long accessed = di.readLong(); ...
java
private void restoreAttributes(InputStream is, int size, SessionData data) throws Exception { if (size > 0) { // input stream should not be closed here Map<String, Object> attributes = new HashMap<>(); ObjectInputStream ois = new CustomObjectInputStream(is); ...
java
private void parseMultipartParameters(Map<String, List<FileItem>> fileItemListMap, RequestAdapter requestAdapter) { String encoding = requestAdapter.getEncoding(); MultiValueMap<String, String> parameterMap = new LinkedMultiValueMap<>(); MultiValueMap<String, FileParameter> fileParameterMap = ne...
java
public Configuration createConfiguration() throws IOException, TemplateException { Configuration config = newConfiguration(); Properties props = new Properties(); // Merge local properties if specified. if (this.freemarkerSettings != null) { props.putAll(this.freemarkerSetti...
java
protected TemplateLoader getAggregateTemplateLoader(TemplateLoader[] templateLoaders) { int loaderCount = (templateLoaders != null ? templateLoaders.length : 0); switch (loaderCount) { case 0: if (log.isDebugEnabled()) { log.debug("No FreeMarker TemplateLo...
java
protected TemplateLoader getTemplateLoaderForPath(String templateLoaderPath) throws IOException { if (templateLoaderPath.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { String basePackagePath = templateLoaderPath.substring(ResourceUtils.CLASSPATH_URL_PREFIX.length()); if (log.isDebugEn...
java
public Options addOption(Option opt) { String key = opt.getKey(); // add it to the long option list if (opt.hasLongName()) { longOpts.put(opt.getLongName(), opt); } // if the option is required add it to the required list if (opt.isRequired()) { ...
java
public ItemRule newHeaderItemRule(String headerName) { ItemRule itemRule = new ItemRule(); itemRule.setName(headerName); addHeaderItemRule(itemRule); return itemRule; }
java
public void addHeaderItemRule(ItemRule headerItemRule) { if (headerItemRuleMap == null) { headerItemRuleMap = new ItemRuleMap(); } headerItemRuleMap.putItemRule(headerItemRule); }
java
public static HeaderActionRule newInstance(String id, Boolean hidden) { HeaderActionRule headerActionRule = new HeaderActionRule(); headerActionRule.setActionId(id); headerActionRule.setHidden(hidden); return headerActionRule; }
java
protected Object getBean(Token token) { Object value; if (token.getAlternativeValue() != null) { if (token.getDirectiveType() == TokenDirectiveType.FIELD) { Field field = (Field)token.getAlternativeValue(); if (Modifier.isStatic(field.getModifiers())) { ...
java
protected Object getBeanProperty(final Object object, String propertyName) { Object value; try { value = BeanUtils.getProperty(object, propertyName); } catch (InvocationTargetException e) { // ignore value = null; } return value; }
java
protected Object getProperty(Token token) throws IOException { if (token.getDirectiveType() == TokenDirectiveType.CLASSPATH) { Properties props = PropertiesLoaderUtils.loadProperties(token.getValue(), activity.getEnvironment().getClassLoader()); Object value = (token.getGetterName() != n...
java
protected String getTemplate(Token token) { TemplateRenderer templateRenderer = activity.getActivityContext().getTemplateRenderer(); StringWriter writer = new StringWriter(); templateRenderer.render(token.getName(), activity, writer); String result = writer.toString(); return (...
java
public String stringify() { if (type == TokenType.TEXT) { return defaultValue; } StringBuilder sb = new StringBuilder(); if (type == TokenType.BEAN) { sb.append(BEAN_SYMBOL); sb.append(START_BRACKET); if (name != null) { sb....
java
public static boolean isTokenSymbol(char c) { return (c == BEAN_SYMBOL || c == TEMPLATE_SYMBOL || c == PARAMETER_SYMBOL || c == ATTRIBUTE_SYMBOL || c == PROPERTY_SYMBOL); }
java
public static TokenType resolveTypeAsSymbol(char symbol) { TokenType type; if (symbol == Token.BEAN_SYMBOL) { type = TokenType.BEAN; } else if (symbol == Token.TEMPLATE_SYMBOL) { type = TokenType.TEMPLATE; } else if (symbol == Token.PARAMETER_SYMBOL) { ...
java
public void setTransformType(TransformType transformType) { this.transformType = transformType; if (contentType == null && transformType != null) { if (transformType == TransformType.TEXT) { contentType = ContentType.TEXT_PLAIN.toString(); } else if (transformTyp...
java
public void setTemplateRule(TemplateRule templateRule) { this.templateRule = templateRule; if (templateRule != null) { if (this.transformType == null) { setTransformType(TransformType.TEXT); } if (templateRule.getEncoding() != null && this.encoding == ...
java
public void setResultValue(String actionId, Object resultValue) { if (actionId == null || !actionId.contains(ActivityContext.ID_SEPARATOR)) { this.actionId = actionId; this.resultValue = resultValue; } else { String[] ids = StringUtils.tokenize(actionId, ActivityConte...
java
public static URL getResource(String resource, ClassLoader classLoader) throws IOException { URL url = null; if (classLoader != null) { url = classLoader.getResource(resource); } if (url == null) { url = ClassLoader.getSystemResource(resource); } i...
java
public static Reader getReader(final File file, String encoding) throws IOException { InputStream stream; try { stream = AccessController.doPrivileged( new PrivilegedExceptionAction<InputStream>() { @Override public InputStr...
java
public static Reader getReader(final URL url, String encoding) throws IOException { InputStream stream; try { stream = AccessController.doPrivileged( new PrivilegedExceptionAction<InputStream>() { @Override public InputStrea...
java
public static String read(File file, String encoding) throws IOException { Reader reader = getReader(file, encoding); String source; try { source = read(reader); } finally { reader.close(); } return source; }
java
public static String read(URL url, String encoding) throws IOException { Reader reader = getReader(url, encoding); String source; try { source = read(reader); } finally { reader.close(); } return source; }
java
public static String read(Reader reader) throws IOException { final char[] buffer = new char[1024]; StringBuilder sb = new StringBuilder(); int len; while ((len = reader.read(buffer)) != -1) { sb.append(buffer, 0, len); } return sb.toString(); }
java
private ViewDispatcher getViewDispatcher(Activity activity) throws ViewDispatcherException { if (dispatchRule.getViewDispatcher() != null) { return dispatchRule.getViewDispatcher(); } try { String dispatcherName; if (dispatchRule.getDispatcherName() != null) ...
java
public static void fetchAttributes(RequestAdapter requestAdapter, ProcessResult processResult) { if (processResult != null) { for (ContentResult contentResult : processResult) { for (ActionResult actionResult : contentResult) { Object actionResultValue = actionRes...
java
public void excludePackage(String... packageNames) { if (packageNames == null) { excludePackageNames = null; } else { for (String packageName : packageNames) { if (excludePackageNames == null) { excludePackageNames = new HashSet<>(); ...
java
public void excludeClass(String... classNames) { if (classNames == null) { excludeClassNames = null; } else { for (String className : classNames) { if (!isExcludePackage(className)) { if (excludeClassNames == null) { exc...
java
public void open() { if(sqlSession == null) { if (executorType == null) { executorType = ExecutorType.SIMPLE; } sqlSession = sqlSessionFactory.openSession(executorType, autoCommit); if (log.isDebugEnabled()) { ToStringBuilder tsb ...
java
public void commit(boolean force) { if (checkSession()) { return; } if (log.isDebugEnabled()) { ToStringBuilder tsb = new ToStringBuilder(String.format("Committing transactional %s@%x", sqlSession.getClass().getSimpleName(),sqlSession.hashCode())); ...
java
public void close(boolean arbitrarily) { if (checkSession()) { return; } arbitrarilyClosed = arbitrarily; sqlSession.close(); if (log.isDebugEnabled()) { log.debug(String.format("Closed %s@%x", sqlSession.getClass().getSimpleName(), ...
java
public void ifExceptionThrow() throws Exception { if(nested == null || nested.isEmpty()) { return; } if (nested.size() == 1) { Throwable th = nested.get(0); if (th instanceof Error) { throw (Error)th; } if (th instanceof...
java
public void ifExceptionThrowRuntime() throws Error { if(nested == null || nested.isEmpty()) { return; } if (nested.size() == 1) { Throwable th = nested.get(0); if (th instanceof Error) { throw (Error)th; } else if (th instanceof Run...
java
public void printHelp(Command command) { if (command.getDescriptor().getUsage() != null) { printUsage(command.getDescriptor().getUsage()); } else { printUsage(command); } int leftWidth = printOptions(command.getOptions()); printArguments(command.getArgumen...
java
public void printUsage(Command command) { String commandName = command.getDescriptor().getName(); StringBuilder sb = new StringBuilder(getSyntaxPrefix()).append(commandName).append(" "); // create a list for processed option groups Collection<OptionGroup> processedGroups = new ArrayList...
java
private void appendOptionGroup(StringBuilder sb, OptionGroup group) { if (!group.isRequired()) { sb.append(OPTIONAL_BRACKET_OPEN); } List<Option> optList = new ArrayList<>(group.getOptions()); if (optList.size() > 1 && getOptionComparator() != null) { optList.sort...
java
public ItemRule newArgumentItemRule(String argumentName) { ItemRule itemRule = new ItemRule(); itemRule.setName(argumentName); addArgumentItemRule(itemRule); return itemRule; }
java
public void addArgumentItemRule(ItemRule argumentItemRule) { if (argumentItemRuleMap == null) { argumentItemRuleMap = new ItemRuleMap(); } argumentItemRuleMap.putItemRule(argumentItemRule); }
java
public static BeanMethodActionRule newInstance(String id, String beanId, String methodName, Boolean hidden) throws IllegalRuleException { if (methodName == null) { throw new IllegalRuleException("The 'action' element requires an 'method' attribute"); } BeanMethodActionRu...
java
public void setAll(Map<String, String> params) { for (Map.Entry<String, String> entry : params.entrySet()) { setParameter(entry.getKey(), entry.getValue()); } }
java
public Object getParameterWithoutCache(String name) { if (activity.getRequestAdapter() != null) { String[] values = activity.getRequestAdapter().getParameterValues(name); if (values != null) { if (values.length == 1) { return values[0]; ...
java
public Object getAttributeWithoutCache(String name) { if (activity.getRequestAdapter() != null) { return activity.getRequestAdapter().getAttribute(name); } else { return null; } }
java
public Object getActionResultWithoutCache(String name) { if (activity.getProcessResult() != null) { return activity.getProcessResult().getResultValue(name); } else { return null; } }
java
public Object getSessionAttributeWithoutCache(String name) { if (activity.getSessionAdapter() != null) { return activity.getSessionAdapter().getAttribute(name); } else { return null; } }
java
@Override public Session get(String id) throws Exception { Session session; Exception ex = null; while (true) { session = doGet(id); if (sessionDataStore == null) { break; // can't load any session data so just return null or the session object ...
java
private Session loadSession(String id) throws Exception { if (sessionDataStore == null) { return null; // can't load it } try { SessionData data = sessionDataStore.load(id); if (data == null) { // session doesn't exist return null; ...
java
@Override public void put(String id, Session session) throws Exception { if (id == null || session == null) { throw new IllegalArgumentException("Put key=" + id + " session=" + (session == null ? "null" : session.getId())); } try (Lock ignored = session.lock()) { if ...
java
@Override public boolean exists(String id) throws Exception { // try the object store first Session s = doGet(id); if (s != null) { try (Lock ignored = s.lock()) { // wait for the lock and check the validity of the session return s.isValid(); ...
java
@Override public Session delete(String id) throws Exception { // get the session, if its not in memory, this will load it Session session = get(id); // Always delete it from the backing data store if (sessionDataStore != null) { boolean deleted = sessionDataStore.delete(...
java
public void checkInactiveSession(Session session) { if (session == null) { return; } if (log.isDebugEnabled()) { log.debug("Checking for idle " + session.getId()); } try (Lock ignored = session.lock()) { if (getEvictionPolicy() > 0 && session....
java
public PebbleEngine createPebbleEngine() { PebbleEngine.Builder builder = new PebbleEngine.Builder(); builder.strictVariables(strictVariables); if (defaultLocale != null) { builder.defaultLocale(defaultLocale); } if (templateLoaders == null) { if (template...
java
protected Loader<?> getAggregateTemplateLoader(Loader<?>[] templateLoaders) { int loaderCount = (templateLoaders == null) ? 0 : templateLoaders.length; switch (loaderCount) { case 0: // Register default template loaders. Loader<?> stringLoader = new StringLoad...
java
protected Loader<?> getTemplateLoaderForPath(String templateLoaderPath) { if (templateLoaderPath.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { String basePackagePath = templateLoaderPath.substring(ResourceUtils.CLASSPATH_URL_PREFIX.length()); if (log.isDebugEnabled()) { ...
java
public String newSessionId(long seedTerm) { synchronized (random) { long r0; if (weakRandom) { r0 = hashCode() ^ Runtime.getRuntime().freeMemory() ^ random.nextInt() ^ (seedTerm << 32); } else { r0 = random.nextLong(); } ...
java
private void initRandom() { try { random = new SecureRandom(); } catch (Exception e) { log.warn("Could not generate SecureRandom for session-id randomness", e); random = new Random(); weakRandom = true; } }
java
public void write(Parameters parameters) throws IOException { if (parameters != null) { for (Parameter pv : parameters.getParameterValueMap().values()) { if (pv.isAssigned()) { write(pv); } } } }
java
public void comment(String message) throws IOException { if (message.indexOf(NEW_LINE_CHAR) != -1) { String line; int start = 0; while ((line = readLine(message, start)) != null) { writer.write(COMMENT_LINE_START); writer.write(SPACE_CHAR); ...
java
public static String stringify(Parameters parameters, String indentString) { if (parameters == null) { return null; } try { Writer writer = new StringWriter(); AponWriter aponWriter = new AponWriter(writer); aponWriter.setIndentString(indentString)...
java