text
stringlengths
7
1.01M
/* * */ package com.synectiks.process.server.bootstrap; import static com.google.common.base.Strings.nullToEmpty; import java.lang.management.ManagementFactory; import java.nio.file.AccessDeniedException; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.jmx.JmxReporter; import com.codahale.metrics.log4j2.InstrumentedAppender; import com.github.joschi.jadconfig.JadConfig; import com.github.joschi.jadconfig.ParameterException; import com.github.joschi.jadconfig.Repository; import com.github.joschi.jadconfig.RepositoryException; import com.github.joschi.jadconfig.ValidationException; import com.github.joschi.jadconfig.guava.GuavaConverterFactory; import com.github.joschi.jadconfig.guice.NamedConfigParametersModule; import com.github.joschi.jadconfig.jodatime.JodaTimeConverterFactory; import com.github.joschi.jadconfig.repositories.EnvironmentRepository; import com.github.joschi.jadconfig.repositories.PropertiesRepository; import com.github.joschi.jadconfig.repositories.SystemPropertiesRepository; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Binder; import com.google.inject.CreationException; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.name.Names; import com.google.inject.spi.Message; import com.synectiks.process.server.plugin.BaseConfiguration; import com.synectiks.process.server.plugin.DocsHelper; import com.synectiks.process.server.plugin.Plugin; import com.synectiks.process.server.plugin.PluginConfigBean; import com.synectiks.process.server.plugin.PluginLoaderConfig; import com.synectiks.process.server.plugin.PluginMetaData; import com.synectiks.process.server.plugin.PluginModule; import com.synectiks.process.server.plugin.ServerStatus; import com.synectiks.process.server.plugin.Tools; import com.synectiks.process.server.plugin.Version; import com.synectiks.process.server.plugin.system.NodeIdPersistenceException; import com.synectiks.process.server.shared.UI; import com.synectiks.process.server.shared.bindings.GuiceInjectorHolder; import com.synectiks.process.server.shared.bindings.PluginBindings; import com.synectiks.process.server.shared.plugins.ChainingClassLoader; import com.synectiks.process.server.shared.plugins.PluginLoader; import com.synectiks.process.server.shared.utilities.ExceptionUtils; import com.synectiks.process.server.storage.UnsupportedElasticsearchException; import com.synectiks.process.server.storage.versionprobe.ElasticsearchProbeException; import com.synectiks.process.server.xformation.module.PostGsJpaModule; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.Slf4JLoggerFactory; public abstract class CmdLineTool implements CliCommand { static { // Set up JDK Logging adapter, https://logging.apache.org/log4j/2.x/log4j-jul/index.html System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager"); } private static final Logger LOG = LoggerFactory.getLogger(CmdLineTool.class); protected static final Version version = Version.CURRENT_CLASSPATH; protected static final String FILE_SEPARATOR = System.getProperty("file.separator"); protected static final String TMPDIR = System.getProperty("java.io.tmpdir", "/tmp"); protected final JadConfig jadConfig; protected final BaseConfiguration configuration; protected final ChainingClassLoader chainingClassLoader; @Option(name = "--dump-config", description = "Show the effective cataloguemanager configuration and exit") protected boolean dumpConfig = false; @Option(name = "--dump-default-config", description = "Show the default configuration and exit") protected boolean dumpDefaultConfig = false; @Option(name = {"-d", "--debug"}, description = "Run cataloguemanager in debug mode") private boolean debug = false; @Option(name = {"-f", "--configfile"}, description = "Configuration file for cataloguemanager") private String configFile = "/opt/cataloguemanager/server.conf"; protected String commandName = "command"; protected Injector injector; // protected Injector jpaInjector; protected CmdLineTool(BaseConfiguration configuration) { this(null, configuration); } protected CmdLineTool(String commandName, BaseConfiguration configuration) { jadConfig = new JadConfig(); jadConfig.addConverterFactory(new GuavaConverterFactory()); jadConfig.addConverterFactory(new JodaTimeConverterFactory()); if (commandName == null) { if (this.getClass().isAnnotationPresent(Command.class)) { this.commandName = this.getClass().getAnnotation(Command.class).name(); } else { this.commandName = "tool"; } } else { this.commandName = commandName; } this.configuration = configuration; this.chainingClassLoader = new ChainingClassLoader(this.getClass().getClassLoader()); } /** * Validate the given configuration for this command. * * @return {@code true} if the configuration is valid, {@code false}. */ protected boolean validateConfiguration() { return true; } public boolean isDumpConfig() { return dumpConfig; } public boolean isDumpDefaultConfig() { return dumpDefaultConfig; } public boolean isDebug() { return debug; } protected abstract List<Module> getCommandBindings(); protected abstract List<Object> getCommandConfigurationBeans(); /** * Things that have to run before the {@link #startCommand()} method is being called. */ protected void beforeStart() {} @Override public void run() { final Level logLevel = setupLogger(); final PluginBindings pluginBindings = installPluginConfigAndBindings(getPluginPath(configFile), chainingClassLoader); if (isDumpDefaultConfig()) { dumpDefaultConfigAndExit(); } final NamedConfigParametersModule configModule = readConfiguration(configFile); if (isDumpConfig()) { dumpCurrentConfigAndExit(); } if (!validateConfiguration()) { LOG.error("Validating configuration file failed - exiting."); System.exit(1); } beforeStart(); final List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); LOG.info("Running with JVM arguments: {}", Joiner.on(' ').join(arguments)); injector = setupInjector(configModule, pluginBindings, binder -> binder.bind(ChainingClassLoader.class).toInstance(chainingClassLoader)); // This is for JPA persistance service. // jpaInjector = GuiceInjectorHolder.createJpaInjector(); if (injector == null) { LOG.error("Injector could not be created, exiting! (Please include the previous error messages in bug reports.)"); System.exit(1); } // if (jpaInjector == null) { // LOG.error("JPA injector could not be created, exiting! (Please include the previous error messages in bug reports.)"); // System.exit(1); // } // This is holding all our metrics. final MetricRegistry metrics = injector.getInstance(MetricRegistry.class); addInstrumentedAppender(metrics, logLevel); // Report metrics via JMX. final JmxReporter reporter = JmxReporter.forRegistry(metrics).build(); reporter.start(); startCommand(); } protected abstract void startCommand(); protected Level setupLogger() { final Level logLevel; if (isDebug()) { LOG.info("Running in Debug mode"); logLevel = Level.DEBUG; // Enable logging for Netty when running in debug mode. InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE); } else if (onlyLogErrors()) { logLevel = Level.ERROR; } else { logLevel = Level.INFO; } initializeLogging(logLevel); return logLevel; } private void initializeLogging(final Level logLevel) { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final org.apache.logging.log4j.core.config.Configuration config = context.getConfiguration(); config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(logLevel); config.getLoggerConfig(Main.class.getPackage().getName()).setLevel(logLevel); context.updateLoggers(config); } private void addInstrumentedAppender(final MetricRegistry metrics, final Level level) { final InstrumentedAppender appender = new InstrumentedAppender(metrics, null, null, false); appender.start(); final LoggerContext context = (LoggerContext) LogManager.getContext(false); final org.apache.logging.log4j.core.config.Configuration config = context.getConfiguration(); config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, level, null); context.updateLoggers(config); } protected boolean onlyLogErrors() { return false; } private void dumpCurrentConfigAndExit() { System.out.println(dumpConfiguration(jadConfig.dump())); System.exit(0); } private void dumpDefaultConfigAndExit() { for (Object bean : getCommandConfigurationBeans()) jadConfig.addConfigurationBean(bean); dumpCurrentConfigAndExit(); } private PluginBindings installPluginConfigAndBindings(Path pluginPath, ChainingClassLoader classLoader) { final Set<Plugin> plugins = loadPlugins(pluginPath, classLoader); final PluginBindings pluginBindings = new PluginBindings(plugins); for (final Plugin plugin : plugins) { for (final PluginModule pluginModule : plugin.modules()) { for (final PluginConfigBean configBean : pluginModule.getConfigBeans()) { jadConfig.addConfigurationBean(configBean); } } } return pluginBindings; } private Path getPluginPath(String configFile) { final PluginLoaderConfig pluginLoaderConfig = new PluginLoaderConfig(); processConfiguration(new JadConfig(getConfigRepositories(configFile), pluginLoaderConfig)); return pluginLoaderConfig.getPluginDir(); } protected Set<Plugin> loadPlugins(Path pluginPath, ChainingClassLoader chainingClassLoader) { final Set<Plugin> plugins = new HashSet<>(); final PluginLoader pluginLoader = new PluginLoader(pluginPath.toFile(), chainingClassLoader); for (Plugin plugin : pluginLoader.loadPlugins()) { final PluginMetaData metadata = plugin.metadata(); if (capabilities().containsAll(metadata.getRequiredCapabilities())) { if (version.sameOrHigher(metadata.getRequiredVersion())) { LOG.info("Loaded plugin: {}", plugin); plugins.add(plugin); } else { LOG.error("Plugin \"" + metadata.getName() + "\" requires version " + metadata.getRequiredVersion() + " - not loading!"); } } else { LOG.debug("Skipping plugin \"{}\" because some capabilities are missing ({}).", metadata.getName(), Sets.difference(plugin.metadata().getRequiredCapabilities(), capabilities())); } } return plugins; } protected Collection<Repository> getConfigRepositories(String configFile) { return Arrays.asList( new EnvironmentRepository("CATALOGUEMANAGER_"), new SystemPropertiesRepository("cataloguemanager."), // Legacy prefixes new EnvironmentRepository("cataloguemanager2_"), new SystemPropertiesRepository("cataloguemanager2."), new PropertiesRepository(configFile) ); } private String dumpConfiguration(final Map<String, String> configMap) { final StringBuilder sb = new StringBuilder(); sb.append("# Configuration of cataloguemanager2-").append(commandName).append(" ").append(version).append(System.lineSeparator()); sb.append("# Generated on ").append(Tools.nowUTC()).append(System.lineSeparator()); for (Map.Entry<String, String> entry : configMap.entrySet()) { sb.append(entry.getKey()).append('=').append(nullToEmpty(entry.getValue())).append(System.lineSeparator()); } return sb.toString(); } protected NamedConfigParametersModule readConfiguration(final String configFile) { final List<Object> beans = getCommandConfigurationBeans(); for (Object bean : beans) { jadConfig.addConfigurationBean(bean); } jadConfig.setRepositories(getConfigRepositories(configFile)); LOG.debug("Loading configuration from config file: {}", configFile); processConfiguration(jadConfig); return new NamedConfigParametersModule(jadConfig.getConfigurationBeans()); } private void processConfiguration(JadConfig jadConfig) { try { jadConfig.process(); } catch (RepositoryException e) { LOG.error("Couldn't load configuration: {}", e.getMessage()); System.exit(1); } catch (ParameterException | ValidationException e) { LOG.error("Invalid configuration", e); System.exit(1); } } protected List<Module> getSharedBindingsModules() { return Lists.newArrayList(); } protected Injector setupInjector(NamedConfigParametersModule configModule, Module... otherModules) { try { final ImmutableList.Builder<Module> modules = ImmutableList.builder(); modules.add(configModule); modules.addAll(getSharedBindingsModules()); modules.addAll(getCommandBindings()); modules.addAll(Arrays.asList(otherModules)); modules.add(new Module() { @Override public void configure(Binder binder) { binder.bind(String.class).annotatedWith(Names.named("BootstrapCommand")).toInstance(commandName); } }); modules.add(new PostGsJpaModule()); // modules.add(new Module() { // @Override // public void configure(Binder binder) { // binder.bind(CollectorController.class); // } // },new JpaPersistModule("db_manager")); return GuiceInjectorHolder.createInjector(modules.build()); } catch (CreationException e) { annotateInjectorCreationException(e); return null; } catch (Exception e) { LOG.error("Injector creation failed!", e); return null; } } protected void annotateInjectorCreationException(CreationException e) { annotateInjectorExceptions(e.getErrorMessages()); throw e; } protected void annotateInjectorExceptions(Collection<Message> messages) { for (Message message : messages) { //noinspection ThrowableResultOfMethodCallIgnored final Throwable rootCause = ExceptionUtils.getRootCause(message.getCause()); if (rootCause instanceof NodeIdPersistenceException) { LOG.error(UI.wallString( "Unable to read or persist your NodeId file. This means your node id file (" + configuration.getNodeIdFile() + ") is not readable or writable by the current user. The following exception might give more information: " + message)); System.exit(-1); } else if (rootCause instanceof AccessDeniedException) { LOG.error(UI.wallString("Unable to access file " + rootCause.getMessage())); System.exit(-2); } else if (rootCause instanceof UnsupportedElasticsearchException) { final Version elasticsearchVersion = ((UnsupportedElasticsearchException) rootCause).getElasticsearchMajorVersion(); LOG.error(UI.wallString("Unsupported Elasticsearch version: " + elasticsearchVersion, DocsHelper.PAGE_ES_VERSIONS.toString())); System.exit(-3); } else if (rootCause instanceof ElasticsearchProbeException) { LOG.error(UI.wallString(rootCause.getMessage(), DocsHelper.PAGE_ES_CONFIGURATION.toString())); System.exit(-4); } else { // other guice error, still print the raw messages // TODO this could potentially print duplicate messages depending on what a subclass does... LOG.error("Guice error (more detail on log level debug): {}", message.getMessage()); if (rootCause != null) { LOG.debug("Stacktrace:", rootCause); } } } } protected Set<ServerStatus.Capability> capabilities() { return Collections.emptySet(); } }
package com.yugandhar.mdm.config.app.properties; /* Generated Aug 7, 2017 3:52:46 PM by Hibernate Tools 5.2.1.Final using Yugandhar custom templates. Generated and to be used in accordance with Yugandhar Licensing Terms. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.yugandhar.common.constant.yugandharConstants; import org.springframework.transaction.annotation.Transactional; import com.yugandhar.common.transobj.TxnTransferObj; import com.yugandhar.common.util.CommonValidationUtil; import com.yugandhar.common.exception.YugandharCommonException; /** *@author Yugandhar *@version 1.0 *@since 1.0 * */ @Scope(value = "prototype") @Service("com.yugandhar.mdm.config.app.properties.ConfigAppPropertiesService") public class ConfigAppPropertiesService { private static final Logger logger = LoggerFactory.getLogger(yugandharConstants.YUGANDHAR_COMMON_LOGGER); TxnTransferObj txnTransferObjResponse; @Autowired CommonValidationUtil commonValidationUtil; @Autowired private ConfigAppPropertiesComponent theConfigAppPropertiesComponent; public ConfigAppPropertiesService() { txnTransferObjResponse = new TxnTransferObj(); } /** *This service creates a record in database. generates the idpk if not provided in the request and *populate the updatedByUser, updatedTxnRefId, createdTsString, updatedTsString attributes. *@since 1.0 *@param txnTransferObj Transfer Object TxnTransferObj instance *@return txnTransferObj Returns the Transfer Object TxnTransferObj instance populated with persisted instance *@throws YugandharCommonException if ConfigAppPropertiesDO object is not present in the request or other mandatory attributes not present * */ @Transactional public TxnTransferObj add(TxnTransferObj txnTransferObj) throws YugandharCommonException { TxnTransferObj respTxnTransferObj; try { respTxnTransferObj = theConfigAppPropertiesComponent.persist(txnTransferObj); } catch (YugandharCommonException yce) { logger.error("ConfigAppPropertiesService.add failed", yce); throw yce; } catch (Exception e) { //write the logic to get error message based on error code. Error code is hard-coded here logger.error("ConfigAppPropertiesService.add failed", e); e.printStackTrace(); throw commonValidationUtil.populateErrorResponse(txnTransferObj, "1", e, "ConfigAppPropertiesService.add failed unexpectedly"); } return respTxnTransferObj; } /**This service updates the record in database. populate the updatedByUser, updatedTxnRefId, updatedTsString attributes *@since 1.0 *@param txnTransferObj Transfer Object TxnTransferObj instance *@return txnTransferObj Returns the Transfer Object TxnTransferObj instance populated with database instance *@throws YugandharCommonException if ConfigAppPropertiesDO object is not present in the request or mandatory attributes primary key is not present */ @Transactional public TxnTransferObj merge(TxnTransferObj txnTransferObj) throws YugandharCommonException { TxnTransferObj respTxnTransferObj; try { respTxnTransferObj = theConfigAppPropertiesComponent.merge(txnTransferObj); } catch (YugandharCommonException yce) { logger.error("ConfigAppPropertiesService.merge failed", yce); throw yce; } catch (Exception e) { //write the logic to get error message based on error code. Error code is hard-coded here logger.error("ConfigAppPropertiesService.merge failed", e); e.printStackTrace(); throw commonValidationUtil.populateErrorResponse(txnTransferObj, "1", e, "ConfigAppPropertiesService.merge failed unexpectedly"); } return respTxnTransferObj; } /** * This method search the database record based on primary key. *@since 1.0 *@param txnTransferObj Transfer Object TxnTransferObj instance *@return txnTransferObj Returns the Transfer Object TxnTransferObj instance populated with database instance *@throws YugandharCommonException if ConfigAppPropertiesDO object is not present in the request or mandatory attributes primary key is not present */ @Transactional(readOnly = true) public TxnTransferObj findById(TxnTransferObj txnTransferObj) throws YugandharCommonException { TxnTransferObj respTxnTransferObj; try { respTxnTransferObj = theConfigAppPropertiesComponent.findById(txnTransferObj); } catch (YugandharCommonException yce) { logger.error("ConfigAppPropertiesService.findById failed", yce); throw yce; } catch (Exception e) { //write the logic to get error message based on error code. Error code is hard-coded here logger.error("ConfigAppPropertiesService.findById failed", e); e.printStackTrace(); throw commonValidationUtil.populateErrorResponse(txnTransferObj, "1", e, "ConfigAppPropertiesService.findById failed unexpectedly"); } return respTxnTransferObj; } /** * This method search the database record based on business key (e.g.LanguageCode and Key) *@since 1.0 *@param txnTransferObj Transfer Object TxnTransferObj instance *@return txnTransferObj Returns the Transfer Object TxnTransferObj instance populated with database instance *@throws YugandharCommonException if ConfigAppPropertiesDO object is not present in the request or mandatory attributes business key is not present */ @Transactional(readOnly = true) public TxnTransferObj findByBusinessKey(TxnTransferObj txnTransferObj) throws YugandharCommonException { TxnTransferObj respTxnTransferObj; try { respTxnTransferObj = theConfigAppPropertiesComponent.findByBusinessKey(txnTransferObj); } catch (YugandharCommonException yce) { logger.error("ConfigAppPropertiesService.findByBusinessKey failed", yce); throw yce; } catch (Exception e) { //write the logic to get error message based on error code. Error code is hard-coded here logger.error("ConfigAppPropertiesService.findByBusinessKey failed", e); e.printStackTrace(); throw commonValidationUtil.populateErrorResponse(txnTransferObj, "1", e, "ConfigAppPropertiesService.findByBusinessKey failed unexpectedly"); } return respTxnTransferObj; } }
/* * #! * Ontopia Classify * #- * Copyright (C) 2001 - 2013 The Ontopia Project * #- * 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 net.ontopia.topicmaps.classify; /** * INTERNAL: */ public class DistanceAnalyzer extends AbstractDocumentAnalyzer { protected double high; protected int termCount; public DistanceAnalyzer() { super(2); } @Override public void startDocument(Document doc) { super.startDocument(doc); if (this.iteration == 1) this.high = 0d; else this.termCount = 0; } @Override public void endDocument(Document doc) { // calculate high if (this.iteration == 1) this.high = Math.log(termCount); } @Override public void analyzeToken(TextBlock parent, Token token, int index) { // ignore non variant tokens if (token.getType() != Token.TYPE_VARIANT) return; // count term this.termCount++; // adjust score by distance from start if (this.iteration > 1) { Term term = ((Variant)token).getTerm(); double score = term.getScore(); // if no existing score add distance score if (score > 0d) term.addScore(high - Math.log(termCount), "distance adjustment"); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.http; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.component.http.helper.HttpHelper; import org.apache.camel.impl.DefaultExchange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version */ public class CamelServlet extends HttpServlet { private static final long serialVersionUID = -7061982839117697829L; protected final Logger log = LoggerFactory.getLogger(getClass()); /** * We have to define this explicitly so the name can be set as we can not always be * sure that it is already set via the init method */ private String servletName; private ServletResolveConsumerStrategy servletResolveConsumerStrategy = new HttpServletResolveConsumerStrategy(); private final ConcurrentMap<String, HttpConsumer> consumers = new ConcurrentHashMap<String, HttpConsumer>(); @Override public void init(ServletConfig config) throws ServletException { super.init(config); this.servletName = config.getServletName(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.trace("Service: {}", request); // Is there a consumer registered for the request. HttpConsumer consumer = resolve(request); if (consumer == null) { log.debug("No consumer to service request {}", request); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // are we suspended? if (consumer.isSuspended()) { log.debug("Consumer suspended, cannot service request {}", request); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // if its an OPTIONS request then return which method is allowed if ("OPTIONS".equals(request.getMethod())) { String s; if (consumer.getEndpoint().getHttpMethodRestrict() != null) { s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict(); } else { // allow them all s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH"; } response.addHeader("Allow", s); response.setStatus(HttpServletResponse.SC_OK); return; } if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } if ("TRACE".equals(request.getMethod()) && !consumer.isTraceEnabled()) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // create exchange and set data on it Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut); if (consumer.getEndpoint().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE); } if (consumer.getEndpoint().isDisableStreamCache()) { exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE); } // we override the classloader before building the HttpMessage just in case the binding // does some class resolution ClassLoader oldTccl = overrideTccl(exchange); HttpHelper.setCharsetFromContentType(request.getContentType(), exchange); exchange.setIn(new HttpMessage(exchange, request, response)); // set context path as header String contextPath = consumer.getEndpoint().getPath(); exchange.getIn().setHeader("CamelServletContextPath", contextPath); String httpPath = (String)exchange.getIn().getHeader(Exchange.HTTP_PATH); // here we just remove the CamelServletContextPath part from the HTTP_PATH if (contextPath != null && httpPath.startsWith(contextPath)) { exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length())); } // we want to handle the UoW try { consumer.createUoW(exchange); } catch (Exception e) { log.error("Error processing request", e); throw new ServletException(e); } try { if (log.isTraceEnabled()) { log.trace("Processing request for exchangeId: {}", exchange.getExchangeId()); } // process the exchange consumer.getProcessor().process(exchange); } catch (Exception e) { exchange.setException(e); } try { // now lets output to the response if (log.isTraceEnabled()) { log.trace("Writing response for exchangeId: {}", exchange.getExchangeId()); } Integer bs = consumer.getEndpoint().getResponseBufferSize(); if (bs != null) { log.trace("Using response buffer size: {}", bs); response.setBufferSize(bs); } consumer.getBinding().writeResponse(exchange, response); } catch (IOException e) { log.error("Error processing request", e); throw e; } catch (Exception e) { log.error("Error processing request", e); throw new ServletException(e); } finally { consumer.doneUoW(exchange); restoreTccl(exchange, oldTccl); } } /** * @deprecated use {@link ServletResolveConsumerStrategy#resolve(javax.servlet.http.HttpServletRequest, java.util.Map)} */ @Deprecated protected HttpConsumer resolve(HttpServletRequest request) { return getServletResolveConsumerStrategy().resolve(request, getConsumers()); } public void connect(HttpConsumer consumer) { log.debug("Connecting consumer: {}", consumer); consumers.put(consumer.getPath(), consumer); } public void disconnect(HttpConsumer consumer) { log.debug("Disconnecting consumer: {}", consumer); consumers.remove(consumer.getPath()); } public String getServletName() { return servletName; } public void setServletName(String servletName) { this.servletName = servletName; } public ServletResolveConsumerStrategy getServletResolveConsumerStrategy() { return servletResolveConsumerStrategy; } public void setServletResolveConsumerStrategy(ServletResolveConsumerStrategy servletResolveConsumerStrategy) { this.servletResolveConsumerStrategy = servletResolveConsumerStrategy; } public Map<String, HttpConsumer> getConsumers() { return Collections.unmodifiableMap(consumers); } /** * Override the Thread Context ClassLoader if need be. * * @param exchange * @return old classloader if overridden; otherwise returns null */ protected ClassLoader overrideTccl(final Exchange exchange) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader appCtxCl = exchange.getContext().getApplicationContextClassLoader(); if (oldClassLoader == null || appCtxCl == null) { return null; } if (!oldClassLoader.equals(appCtxCl)) { Thread.currentThread().setContextClassLoader(appCtxCl); if (log.isTraceEnabled()) { log.trace("Overrode TCCL for exchangeId {} to {} on thread {}", new Object[] {exchange.getExchangeId(), appCtxCl, Thread.currentThread().getName()}); } return oldClassLoader; } return null; } /** * Restore the Thread Context ClassLoader if the old TCCL is not null. */ protected void restoreTccl(final Exchange exchange, ClassLoader oldTccl) { if (oldTccl == null) { return; } Thread.currentThread().setContextClassLoader(oldTccl); if (log.isTraceEnabled()) { log.trace("Restored TCCL for exchangeId {} to {} on thread {}", new String[] {exchange.getExchangeId(), oldTccl.toString(), Thread.currentThread().getName()}); } } }
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.ant; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * Tests for the net.sourceforge.pmd.ant package * * @author Boris Gruschko ( boris at gruschko.org ) */ @RunWith(Suite.class) @SuiteClasses({FormatterTest.class, PMDTaskTest.class}) public class AntTests { }
package com.jetfiretool.core.util; /** * Hash算法大全<br> * 推荐使用FNV1算法 * * @author Jetfire */ public class HashUtil { /** * 加法hash * * @param key 字符串 * @param prime 一个质数 * @return hash结果 */ public static int additiveHash(String key, int prime) { int hash, i; for (hash = key.length(), i = 0; i < key.length(); i++){ hash += key.charAt(i); } return hash % prime; } /** * 旋转hash * * @param key 输入字符串 * @param prime 质数 * @return hash值 */ public static int rotatingHash(String key, int prime) { int hash, i; for (hash = key.length(), i = 0; i < key.length(); ++i){ hash = (hash << 4) ^ (hash >> 28) ^ key.charAt(i); } // 使用:hash = (hash ^ (hash>>10) ^ (hash>>20)) & mask; // 替代:hash %= prime; // return (hash ^ (hash>>10) ^ (hash>>20)); return hash % prime; } /** * 一次一个hash * * @param key 输入字符串 * @return 输出hash值 */ public static int oneByOneHash(String key) { int hash, i; for (hash = 0, i = 0; i < key.length(); ++i) { hash += key.charAt(i); hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); // return (hash & M_MASK); return hash; } /** * Bernstein's hash * * @param key 输入字节数组 * @return 结果hash */ public static int bernstein(String key) { int hash = 0; int i; for (i = 0; i < key.length(); ++i){ hash = 33 * hash + key.charAt(i); } return hash; } /** * Universal Hashing * * @param key 字节数组 * @param mask 掩码 * @param tab tab * @return hash值 */ public static int universal(char[] key, int mask, int[] tab) { int hash = key.length, i, len = key.length; for (i = 0; i < (len << 3); i += 8) { char k = key[i >> 3]; if ((k & 0x01) == 0){ hash ^= tab[i + 0]; } if ((k & 0x02) == 0){ hash ^= tab[i + 1]; } if ((k & 0x04) == 0){ hash ^= tab[i + 2]; } if ((k & 0x08) == 0){ hash ^= tab[i + 3]; } if ((k & 0x10) == 0){ hash ^= tab[i + 4]; } if ((k & 0x20) == 0){ hash ^= tab[i + 5]; } if ((k & 0x40) == 0){ hash ^= tab[i + 6]; } if ((k & 0x80) == 0){ hash ^= tab[i + 7]; } } return (hash & mask); } /** * Zobrist Hashing * * @param key 字节数组 * @param mask 掩码 * @param tab tab * @return hash值 */ public static int zobrist(char[] key, int mask, int[][] tab) { int hash, i; for (hash = key.length, i = 0; i < key.length; ++i){ hash ^= tab[i][key[i]]; } return (hash & mask); } /** * 改进的32位FNV算法1 * * @param data 数组 * @return hash结果 */ public static int fnvHash(byte[] data) { final int p = 16777619; int hash = (int) 2166136261L; for (byte b : data){ hash = (hash ^ b) * p; } hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return hash; } /** * 改进的32位FNV算法1 * * @param data 字符串 * @return hash结果 */ public static int fnvHash(String data) { final int p = 16777619; int hash = (int) 2166136261L; for (int i = 0; i < data.length(); i++){ hash = (hash ^ data.charAt(i)) * p; } hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return hash; } /** * Thomas Wang的算法,整数hash * * @param key 整数 * @return hash值 */ public static int intHash(int key) { key += ~(key << 15); key ^= (key >>> 10); key += (key << 3); key ^= (key >>> 6); key += ~(key << 11); key ^= (key >>> 16); return key; } /** * RS算法hash * * @param str 字符串 * @return hash值 */ public static int rsHash(String str) { int b = 378551; int a = 63689; int hash = 0; for (int i = 0; i < str.length(); i++) { hash = hash * a + str.charAt(i); a = a * b; } return hash & 0x7FFFFFFF; } /** * JS算法 * * @param str 字符串 * @return hash值 */ public static int jsHash(String str) { int hash = 1315423911; for (int i = 0; i < str.length(); i++) { hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2)); } return hash & 0x7FFFFFFF; } /** * PJW算法 * * @param str 字符串 * @return hash值 */ public static int pjwHash(String str) { int bitsInUnsignedInt = 32; int threeQuarters = (bitsInUnsignedInt * 3) / 4; int oneEighth = bitsInUnsignedInt / 8; int highBits = 0xFFFFFFFF << (bitsInUnsignedInt - oneEighth); int hash = 0; int test = 0; for (int i = 0; i < str.length(); i++) { hash = (hash << oneEighth) + str.charAt(i); if ((test = hash & highBits) != 0) { hash = ((hash ^ (test >> threeQuarters)) & (~highBits)); } } return hash & 0x7FFFFFFF; } /** * ELF算法 * * @param str 字符串 * @return hash值 */ public static int elfHash(String str) { int hash = 0; int x = 0; for (int i = 0; i < str.length(); i++) { hash = (hash << 4) + str.charAt(i); if ((x = (int) (hash & 0xF0000000L)) != 0) { hash ^= (x >> 24); hash &= ~x; } } return hash & 0x7FFFFFFF; } /** * BKDR算法 * * @param str 字符串 * @return hash值 */ public static int bkdrHash(String str) { int seed = 131; // 31 131 1313 13131 131313 etc.. int hash = 0; for (int i = 0; i < str.length(); i++) { hash = (hash * seed) + str.charAt(i); } return hash & 0x7FFFFFFF; } /** * SDBM算法 * * @param str 字符串 * @return hash值 */ public static int sdbmHash(String str) { int hash = 0; for (int i = 0; i < str.length(); i++) { hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash; } return hash & 0x7FFFFFFF; } /** * DJB算法 * * @param str 字符串 * @return hash值 */ public static int djbHash(String str) { int hash = 5381; for (int i = 0; i < str.length(); i++) { hash = ((hash << 5) + hash) + str.charAt(i); } return hash & 0x7FFFFFFF; } /** * DEK算法 * * @param str 字符串 * @return hash值 */ public static int dekHash(String str) { int hash = str.length(); for (int i = 0; i < str.length(); i++) { hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i); } return hash & 0x7FFFFFFF; } /** * AP算法 * * @param str 字符串 * @return hash值 */ public static int apHash(String str) { int hash = 0; for (int i = 0; i < str.length(); i++) { hash ^= ((i & 1) == 0) ? ((hash << 7) ^ str.charAt(i) ^ (hash >> 3)) : (~((hash << 11) ^ str.charAt(i) ^ (hash >> 5))); } // return (hash & 0x7FFFFFFF); return hash; } /** * TianL Hash算法 * @param str 字符串 * @return Hash值 */ public static long tianlHash(String str) { long hash = 0; int iLength = str.length(); if (iLength == 0){ return 0; } if (iLength <= 256){ hash = 16777216L * (iLength - 1); }else{ hash = 4278190080L; } int i; char ucChar; if (iLength <= 96) { for (i = 1; i <= iLength; i++) { ucChar = str.charAt(i - 1); if (ucChar <= 'Z' && ucChar >= 'A') { ucChar = (char) (ucChar + 32); } hash += (3 * i * ucChar * ucChar + 5 * i * ucChar + 7 * i + 11 * ucChar) % 16777216; } } else { for (i = 1; i <= 96; i++) { ucChar = str.charAt(i + iLength - 96 - 1); if (ucChar <= 'Z' && ucChar >= 'A'){ ucChar = (char) (ucChar + 32); } hash += (3 * i * ucChar * ucChar + 5 * i * ucChar + 7 * i + 11 * ucChar) % 16777216; } } if (hash < 0) { hash *= -1; } return hash; } /** * JAVA自己带的算法 * * @param str 字符串 * @return hash值 */ public static int javaDefaultHash(String str) { int h = 0; int off = 0; int len = str.length(); for (int i = 0; i < len; i++) { h = 31 * h + str.charAt(off++); } return h; } /** * 混合hash算法,输出64位的值 * * @param str 字符串 * @return hash值 */ public static long mixHash(String str) { long hash = str.hashCode(); hash <<= 32; hash |= fnvHash(str); return hash; } }
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate licenses this file * to you under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.execution.engine.export; import com.google.common.collect.ImmutableSet; import io.crate.data.BatchIterator; import io.crate.data.InMemoryBatchIterator; import io.crate.exceptions.UnhandledServerException; import io.crate.execution.dsl.projection.WriterProjection; import io.crate.metadata.ColumnIdent; import io.crate.test.integration.CrateUnitTest; import io.crate.testing.RowGenerator; import io.crate.testing.TestingHelpers; import io.crate.testing.TestingRowConsumer; import org.apache.lucene.util.BytesRef; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import static io.crate.data.SentinelRow.SENTINEL; import static org.hamcrest.core.Is.is; public class FileWriterProjectorTest extends CrateUnitTest { private ExecutorService executorService = Executors.newSingleThreadExecutor(); @Rule public TemporaryFolder folder = new TemporaryFolder(); private Supplier<BatchIterator> sourceSupplier = () -> InMemoryBatchIterator.of(RowGenerator.fromSingleColValues( IntStream.range(0, 5) .mapToObj(i -> new BytesRef(String.format(Locale.ENGLISH, "input line %02d", i))) .collect(Collectors.toList())), SENTINEL); @Test public void testToNestedStringObjectMap() throws Exception { Map<ColumnIdent, Object> columnIdentMap = new HashMap<>(); columnIdentMap.put(new ColumnIdent("some", Arrays.asList("nested", "column")), "foo"); Map<String, Object> convertedMap = FileWriterCountCollector.toNestedStringObjectMap(columnIdentMap); Map someMap = (Map) convertedMap.get("some"); Map nestedMap = (Map) someMap.get("nested"); assertThat(nestedMap.get("column"), is("foo")); } @Test public void testWriteRawToFile() throws Exception { Path file = createTempFile("out", "json"); FileWriterProjector fileWriterProjector = new FileWriterProjector(executorService, file.toUri().toString(), null, null, ImmutableSet.of(), new HashMap<>(), null, WriterProjection.OutputFormat.JSON_OBJECT); new TestingRowConsumer().accept(fileWriterProjector.apply(sourceSupplier.get()), null); assertEquals("input line 00\n" + "input line 01\n" + "input line 02\n" + "input line 03\n" + "input line 04\n", TestingHelpers.readFile(file.toAbsolutePath().toString())); } @Test public void testDirectoryAsFile() throws Exception { expectedException.expect(UnhandledServerException.class); expectedException.expectMessage("Failed to open output: 'Output path is a directory: "); Path directory = createTempDir(); FileWriterProjector fileWriterProjector = new FileWriterProjector(executorService, directory.toUri().toString(), null, null, ImmutableSet.of(), new HashMap<>(), null, WriterProjection.OutputFormat.JSON_OBJECT); new TestingRowConsumer().accept(fileWriterProjector.apply(sourceSupplier.get()), null); } @Test public void testFileAsDirectory() throws Exception { expectedException.expect(UnhandledServerException.class); expectedException.expectMessage("Failed to open output"); String uri = Paths.get(folder.newFile().toURI()).resolve("out.json").toUri().toString(); FileWriterProjector fileWriterProjector = new FileWriterProjector(executorService, uri, null, null, ImmutableSet.of(), new HashMap<>(), null, WriterProjection.OutputFormat.JSON_OBJECT); new TestingRowConsumer().accept(fileWriterProjector.apply(sourceSupplier.get()), null); } }
package ch.ethz.scu.obit.microscopy.gui.viewers.data.model; import ch.ethz.scu.obit.at.gui.viewers.data.model.AbstractNode; import ch.ethz.scu.obit.at.interfaces.ILazyNode; import ch.ethz.scu.obit.processors.data.model.DatasetDescriptor; /** * Customized Node to be used in a JTree allowing different icons for different * Node types * @author Aaron Ponti */ public class MicroscopyFileNode extends AbstractNode implements ILazyNode { private static final long serialVersionUID = 1L; protected boolean isLoaded = false; /** * Constructor * @param object A dataset descriptor. */ public MicroscopyFileNode(DatasetDescriptor object) { super(object); this.type = object.getType(); } public javax.swing.Icon getIcon() { return new javax.swing.ImageIcon( getClass().getResource("icons/microscopyfile.png")); } public String getTooltip() { return "Microscopy file"; } /** * MicroscopyFileNode has children and is therefore not a leaf * @return false */ @Override public boolean isLeaf() { return false; } @Override public boolean isLoaded() { return isLoaded; } @Override public void setLoaded() { isLoaded = true; } }
/** * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2020 School of Business and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ package com.wegas.core.security.ejb; import com.wegas.core.ejb.cron.EjbTimerFacade; import com.wegas.core.exception.client.WegasConflictException; import com.wegas.core.exception.client.WegasErrorMessage; import com.wegas.core.security.jparealm.JpaAccount; import com.wegas.core.security.persistence.AbstractAccount; import com.wegas.core.security.persistence.Role; import com.wegas.core.security.persistence.User; import com.wegas.core.security.util.HashMethod; import com.wegas.core.security.util.JpaAuthentication; import com.wegas.test.arquillian.AbstractArquillianTestMinimal; import java.util.Calendar; import java.util.List; import javax.ejb.EJBException; import javax.inject.Inject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Yannick Lagger */ public class UserFacadeTest extends AbstractArquillianTestMinimal { private static final Logger logger = LoggerFactory.getLogger(UserFacadeTest.class); private JpaAccount abstractAccount; private WegasUser u; private Role role1; private Role role2; private static final String ROLE_1 = "Role_1"; private static final String ROLE_2 = "Role_2"; private static final String EMAIL = "userfacadetest@local"; @Inject private EjbTimerFacade ejbTimerFacade; @Inject SecurityTestFacade securityTestFacade; @Before public void setUp() throws Exception { login(admin); role1 = new Role(ROLE_1); roleFacade.create(role1); role2 = new Role(ROLE_2); roleFacade.create(role2); u = this.signup(EMAIL); login(u); abstractAccount = (JpaAccount) u.getUser().getMainAccount(); login(admin); addRoles(u, role1, role2); requestManager.clearEntities(); } /** * Test of find method, of class UserFacade. */ @Test public void testFind() { // findAll() List<User> users = userFacade.findAll(); Assert.assertTrue(users.contains(u.getUser())); Assert.assertTrue(users.contains(admin.getUser())); Assert.assertEquals(2l, users.size()); // admin + u // find Assert.assertEquals(u.getUser(), userFacade.find(u.getId())); Assert.assertEquals(admin.getUser(), userFacade.find(admin.getId())); } @Test public void testAccountUpdate() { final String PERM = "GameModel:*:*"; final String PERM2 = "Game2:*:*"; userFacade.addUserPermission(u.getUser(), PERM); accountFacade.update(abstractAccount.getId(), abstractAccount); AbstractAccount a = accountFacade.find(abstractAccount.getId()); Assert.assertEquals(PERM, u.getUser().getPermissions().get(0).getValue()); userFacade.addUserPermission(u.getUser(), PERM2); accountFacade.update(abstractAccount.getId(), a); a = accountFacade.find(abstractAccount.getId()); Assert.assertEquals(PERM2, u.getUser().getPermissions().get(1).getValue()); u.getUser().removePermission(PERM); u.getUser().removePermission(PERM2); accountFacade.update(a.getId(), a); a = accountFacade.find(abstractAccount.getId()); Assert.assertTrue(a.getPermissions().isEmpty()); } /** * */ @Test public void testSharing() { /* String gID = "g" + game.getId(); String gmID = "gm" + gameModel.getId(); List<User> findEditors = userFacade.findEditors(gID); userFacade.addUserPermission(u.getId(), "Game:Edit:" + gID); userFacade.addUserPermission(u.getId(), "GameModel:Edit:" + gmID); userFacade.removeScenarist(gameModel.getId(), u); userFacade.removeTrainer(game.getId(), u); */ } /** * Test SendNewPassword */ //@Test public void testSendNewPassword() throws Exception { JpaAccount acc = accountFacade.findJpaByEmail(EMAIL); //String oldToken = acc.getShadow().getToken(); accountFacade.requestPasswordReset(EMAIL, null); acc = accountFacade.findJpaByEmail(EMAIL); //Assert.assertFalse(oldToken.equals(acc.getShadow().getToken())); } /** * Test CreateSameUser */ @Test(expected = EJBException.class) public void testCreateSameUser() throws WegasErrorMessage { u.getUser().addAccount(abstractAccount); userFacade.create(u.getUser()); } @Test public void testLoginForbidden() { System.setProperty("guestallowed", "false"); try { this.guestLogin(); Assert.fail("Should throw exception !"); } catch (Exception ex) { } System.setProperty("guestallowed", "true"); } @Test(expected = WegasConflictException.class) public void testDuplicateUsername() { // first sign up is fine this.signup("user_1234@local"); // second with same address is not this.signup("user_1234@local"); } @Test public void testIdleGuestRemoval() { int nbUser = userFacade.findAll().size(); logout(); userFacade.guestLogin(); Assert.assertEquals(nbUser + 1, userFacade.findAll().size()); // Since guests are removed only oif they were create more than three month ago, // override this guest createdTime User newGuestUser = userFacade.getCurrentUser(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 13); AbstractAccount account = newGuestUser.getMainAccount(); account.setCreatedTime(calendar.getTime()); accountFacade.merge(account); login(admin); ejbTimerFacade.removeIdleGuests(); Assert.assertEquals(nbUser, userFacade.findAll().size()); } private void assertAuthMethodMatch(JpaAuthentication expected, JpaAuthentication actual) { Assert.assertEquals("Mandatory methods do not match", expected.getMandatoryMethod(), actual.getMandatoryMethod()); Assert.assertEquals("Optional methods do not match", expected.getOptionalMethod(), actual.getOptionalMethod()); } @Test public void testHashMethodMigration() { WegasUser user = this.signup("userHashTest@test", "myPasswordIsSecure"); login(admin); // assert new account use the default authentication method JpaAccount account = ((JpaAccount) user.getUser().getMainAccount()); assertAuthMethodMatch(userFacade.getDefaultAuthMethod(), (JpaAuthentication) account.getAuthenticationMethod()); String previousHash = account.getShadow().getPasswordHex(); String previousSalt = account.getShadow().getSalt(); login(user); login(admin); // migrate to new method accountFacade.setNextAuth(account.getId(), HashMethod.SHA_256); // do the change by authenticating the user login(user); // check hash has been updated login(admin); account = (JpaAccount) accountFacade.find(account.getId()); String newHash = account.getShadow().getPasswordHex(); String newSalt = account.getShadow().getSalt(); Assert.assertNotEquals("Hash has not been updated", previousHash, newHash); Assert.assertNotEquals("Salt has not been updated", previousSalt, newSalt); logout(); login(u); login(admin); // migrate to new method previousHash = newHash; previousSalt = newSalt; accountFacade.setNextAuth(account.getId(), HashMethod.SHA_256); // do the change by authenticating the user login(user); // check hash has been updated login(admin); account = (JpaAccount) accountFacade.find(account.getId()); newHash = account.getShadow().getPasswordHex(); newSalt = account.getShadow().getSalt(); Assert.assertNotEquals("Hash has not been updated", previousHash, newHash); Assert.assertNotEquals("Salt has not been updated", previousSalt, newSalt); // well, client to server hash method works fine, let's change internal hash method accountFacade.setNextShadowHashMethod(account.getId(), HashMethod.SHA_512); login(user); // check hash has been updated login(admin); account = (JpaAccount) accountFacade.find(account.getId()); newHash = account.getShadow().getPasswordHex(); newSalt = account.getShadow().getSalt(); Assert.assertNotEquals("Hash has not been updated", previousHash, newHash); Assert.assertNotEquals("Salt has not been updated", previousSalt, newSalt); login(user); } @Test(expected = WegasErrorMessage.class) public void testWrongPassword() { WegasUser dumb = this.signup("dumb@local", "abce123"); dumb.getPassword(); WegasUser dumber = new WegasUser(dumb.getUser(), "dumb@local", "123abcde"); this.login(dumber); } @Test public void testSu() { securityTestFacade.inFacadeSuTest(admin.getUser(), u.getUser()); } }
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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 org.kie.kogito.index.mongodb.storage; import java.util.UUID; import javax.inject.Inject; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.kie.kogito.index.model.UserTaskInstance; import org.kie.kogito.index.mongodb.TestUtils; import org.kie.kogito.index.mongodb.model.UserTaskInstanceEntity; import org.kie.kogito.index.mongodb.model.UserTaskInstanceEntityMapper; import org.kie.kogito.persistence.api.Storage; import org.kie.kogito.persistence.mongodb.MongoServerTestResource; import org.kie.kogito.persistence.mongodb.client.MongoClientManager; import org.kie.kogito.persistence.mongodb.storage.MongoStorage; import static org.kie.kogito.index.Constants.USER_TASK_INSTANCES_STORAGE; @QuarkusTest @QuarkusTestResource(MongoServerTestResource.class) class UserTaskInstanceStorageIT extends StorageTestBase<String, UserTaskInstance> { @Inject MongoClientManager mongoClientManager; Storage<String, UserTaskInstance> storage; @BeforeEach void setUp() { this.storage = new MongoStorage<>(mongoClientManager.getCollection(USER_TASK_INSTANCES_STORAGE, UserTaskInstanceEntity.class), mongoClientManager.getReactiveCollection(USER_TASK_INSTANCES_STORAGE, UserTaskInstanceEntity.class), UserTaskInstance.class.getName(), new UserTaskInstanceEntityMapper()); } @AfterEach void tearDown() { storage.clear(); } @Test void testCache() { String taskId = UUID.randomUUID().toString(); String processInstanceId = UUID.randomUUID().toString(); UserTaskInstance userTaskInstance1 = TestUtils.createUserTaskInstance(taskId, processInstanceId, RandomStringUtils.randomAlphabetic(5), UUID.randomUUID().toString(), RandomStringUtils.randomAlphabetic(10), "InProgress", 0L); UserTaskInstance userTaskInstance2 = TestUtils.createUserTaskInstance(taskId, processInstanceId, RandomStringUtils.randomAlphabetic(5), UUID.randomUUID().toString(), RandomStringUtils.randomAlphabetic(10), "Completed", 1000L); testStorage(storage, taskId, userTaskInstance1, userTaskInstance2); } }
package com.vicyor.application.repository; import com.vicyor.application.dto.SKUOrderDTO; import com.vicyor.application.po.UserShoppingCart; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; public interface UserShoppingCartRepository extends JpaRepository<UserShoppingCart,Long> { List<UserShoppingCart> findAllByUserIdEquals(Long userId); Optional<UserShoppingCart> findOneByUserIdEqualsAndShoppingSKU_SkuIdEquals(Long userId, Long skuId); /** * 加购若商品已存在则添加其数量 */ @Modifying @Query(nativeQuery = true,value = "update user_shopping_cart set count = count + ?3 where user_id = ?1 and sku_id = ?2") void addUserShoppingCart(Long userId, Long skuId, Long count); /** * 订单取消恢复用户购物车 * @param userId * @param skuId * @param count */ @Modifying @Query(nativeQuery = true,value = "update user_shopping_cart set count =count + ?3 where user_id =?1 and sku_id =?2") void restoreUserShoppingCart(Long userId, Long skuId, Long count); /** * 前端手动更新用户购物车 */ @Modifying @Query(nativeQuery = true,value = "update user_shopping_cart set count =?2,selected=?3 where id =?1") void updateUserShoppingCart(Long id, Long count, Integer selected); }
package com.threelambda.btsniffer.bt; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.junit.Test; import org.springframework.util.StringUtils; import java.util.Map; /** * @author ym * @date 2019/10/30 */ @Slf4j public class BDecodeTest { @Test public void test(){ String rawHex = "64 31 3a 61 64 32 3a 69 64 32 30 3a 3b ac e4 eb\n" + "b3 a6 db 3c 87 0c 3e 99 24 5e 0d 1c 06 b7 47 bb\n" + "31 32 3a 69 6d 70 6c 69 65 64 5f 70 6f 72 74 69\n" + "31 65 39 3a 69 6e 66 6f 5f 68 61 73 68 32 30 3a\n" + "4a 02 1d dd 65 11 e7 5d 12 97 cc b4 88 5a 83 c5\n" + "4b 14 7d c4 34 3a 6e 61 6d 65 33 33 3a 43 7a 65\n" + "63 68 20 66 69 72 73 74 20 76 69 64 65 6f 20 37\n" + "20 6d 6f 6e 69 6b 61 20 50 49 52 40 54 45 34 3a\n" + "70 6f 72 74 69 35 34 38 34 37 65 35 3a 74 6f 6b\n" + "65 6e 35 3a 41 48 68 50 6e 65 31 3a 71 31 33 3a\n" + "61 6e 6e 6f 75 6e 63 65 5f 70 65 65 72 31 3a 74\n" + "34 3a c1 43 00 00 31 3a 76 34 3a 55 54 b1 00 31\n" + "3a 79 31 3a 71 65"; String hexDump = StringUtils.deleteAny(rawHex, " \n"); byte[] bytes = ByteBufUtil.decodeHexDump(hexDump); Map<String, Object> map = Util.decode(bytes); assert ((Map<String, Object>) map.get("a")).get("port") instanceof Long ; } @Test public void test2() { String rawHex = "6431333a66696c652d6475726174696f6e6c693338386569306569306569306569306569306569306569306569306569306569343435656930656531303a66696c652d6d656469616c693065692d3165692d3165692d3165692d3165692d3165692d3165692d3165692d3165692d3165693065692d316565353a66696c65736c64363a6c656e67746869313837353238313665343a706174686c31393a312e20496e74726f64756374696f6e2e6d7034656564363a6c656e677468693930323033393865343a706174686c32333a31302e2050726f70657220466c616e67696e672e6d7034656564363a6c656e67746869313339323838383265343a706174686c31393a31312e2050726f706572204563686f2e6d7034656564363a6c656e677468693235363231353865343a706174686c31353a31322e20577261702d75702e6d7034656564363a6c656e67746869313332363532363965343a706174686c32333a322e20546865205269676874205265766572622e6d7034656564363a6c656e67746869313630393737373765343a706174686c32373a332e20526576657262204c656e677468204973737565732e6d7034656564363a6c656e67746869313435313439393165343a706174686c32373a342e205765742026204472792053657061726174696f6e2e6d7034656564363a6c656e67746869313231383039333165343a706174686c32363a352e2041766f69642042617373204275696c642055702e6d7034656564363a6c656e67746869313334343632353065343a706174686c32393a362e205265766572622053656e647320262052657475726e732e6d7034656564363a6c656e67746869313630333437323565343a706174686c33303a372e205573696e6720446966666572656e7420526576657262732e6d7034656564363a6c656e67746869313731333038363165343a706174686c32323a382e2050726f70657220446f75626c696e672e6d7034656564363a6c656e67746869313035393139373665343a706174686c32333a392e2050726f7065722043686f727573696e672e6d7034656565343a6e616d6536333a41736b20566964656f202d20417564696f204d697374616b6573203130332e20313020436f6d6d6f6e205265766572622d44656c6179204d697374616b657331323a7069656365206c656e6774686932363231343465363a70696563657331323032303a9f871299debee0643e3a66e6798d41e6f8cacc8168618fd2168df5adb6963ae8a7954d2bda4d4730ce1ae6bae7f3ab3e013f8ca236ffc796b642bd02641ffaf24261e3481a76a187046282401abfb6bf79984549e1c88be599850e7177321f1e11938937482762387b059e596b45be4a3631dee27d86482656c7f46d46f6f28b5691d15cfe0764933601c40cb814e01b609a5b407d0d7698f4d835a96ee63985f8ed60f2c6356f5b268bc1af4b298c479af05c62885fb43a801f5bbd98e39fd56208e2332ba33ec585f1bae2795916e311c965ba23a1cdba57f087413fdd272736bbea969c21d2a9d07282c7b326e4b6e705d3c9f90b95de11acc93a444a7a3ef8e71c9a06c6bb43050051e35993ae0057832fca1d585b246902a9cc34eedec8581b1459fa4d5f28cf9721bd3441d845dfc8d68dbd84b68f4797e200e7db036a8406a5a250b7fb964430cb95467db7e4b2905ce17c23c829122909298da0967f7c0e1c4bfe34058599a2c13816cb18688917b123902998959319b1738f95d97c6742e0c12616916acf242febd9b9b1ea0ce3c43d99f2617d65754c4cc9da0ad99cae7cb8f282f92b31610acb7198fbf6fd18dc05f7e9a114204d38d03085aac64f41cbfe22f125c3856c94d3c235c24f665844a31bdfd6254b57f9d0c7f4d4ea501988d528168a073871a1b345189227c9aa9fe8318a7869ce789dcb988d0a72f3f81ba6ab8196738cdee7a85dd7f12e1cd41eb837f19271b400995ed267e3cece062a6dcdc3121da665f845aefbdb2ead160378bd1eb8143b07d61e5f411fcf1b70b26ad41eea6b7092274b118b36b30809115909343dedb96109b113d6a4156bc9b0df612edf85c758a71735dab0711d9b58d5c533f4d0b9ad4232c251762a65d4f9e64b352b2e2c474ceef2db46d3ac12e8b679c41dc7294e70f67dc32ab9b8691db284a943b312860201f9ec7941d9cdd3820fd040eaec59cfbfff3840e24e5581b12b9a1dfb52aa3387f084369f33868f376204009e069a22fa0a67f38939b5418ff60d445467dac7ec1c401f69e1d80d2bb5a3cd771a9d83a7e32b4193ff3ee365cfe4eb33ad775277e2d659a171ae254c466608daf6c2ba48a682604c86ca96cb489c73c81c13e6e3cbfa8b789d305eef62e81e711b354d2aa85e7f54e446d2ccef4a4fd90620434cd6a2036f776f88ab1c6c32dcd34fba256a611476b9e4a7b815c077832147c0b347272a22c9092af4ccd69abe954bfaa7dff41127a44ea05058b7f2943ca679f7436fb7af97470710117c92b1cd19e60f95f894756c04d6406bc7498d3c017f2e3be2ab6cb3e8af124369a2d1083162249d1d9efd63c66c21fcbf09de98b13a06bb2d5a0fc6ea0bef6d2aeea83dfda678030ce5f2a4f98b3b888b9501da9037af3d8d3a203df01ec0cb0db4c25c2dc016d55fc2134378937a1b3b0981ffca66be04f0b5284277d4f4b37c004c14800c6dcae61166132b56b998d552b65b6e70b32fe66fba5290b07c0dd61f798780e8eefffa41aca022d194c6b2a19cbd239d15793fd726a85e0e1f3ca4a561d3d1dbe2161fc93e156809957d26c651447127a3ffcba19495965ff1e9f69f610267341cd67746db92da58c9a0c9b64203bfd6a2e1d9d47ffc498fe9196dc1f3e8ccd08688f2674ab83bcc641fbb7121057cc6e9568410e7190228b64d8286e09f71a92402881b1706da56a1c9262961797254fdbca3c3db4a7e2eb43d5265cca088297af9a8322138b421859bee331d8df18757ad139214d844a6e597952b25c802f8e700ed8dcae2e2e9df9232ad07c07c9d7841e67e739cf073605337b4e8ebb0a0e9bdfdecd2646b7859d9b8631cb70717b1419ffc2ff1043af72e58320068e2751a004daeddb163fce951a5a65b113a497524578afdd0716d4d7c55335aad05fb3818a465b2714ae7decdeff68538496fe9b747b2958dce8d28c9e0609a152878ceeb0309e7034a91c02130c5ab7d6f4f66ed44322327a3e1061ca354d0c2cb9d47df52421c39c27bfc011def74d2217023de3a2ff7c9982e7e2bf0178f96cb26236532174dc18d55dbdb80d04428becef41eafcfe8c452708e0424b2cfe7c84fe508fe54e57f723b9284f1ce95df812c605fb9fa7b4bf49df9f5599151c700a3de5bc29098abcf02639c8c994a264825bb86a2b1ea85d0dbea0610590771c1e67ebbb7c3a409a0c31f29fc0444a28916616d47f8097448f512c3e39ce40a243e44bfecd40a12413aefd52e412383cb0a9b2dc6bb9400fd04320b303b465b1737dbddb92f1eadc9c962888be2193c10699650909882631722b43c83c5f75e78042246aca024a7b3c9ff9592267ac7dbbae438eaee2f37f7c6b3011befd043090329887032f80b453847701e7e40e67509541695a778bd74853c0e70eec557dd172409d3c66207d822df132ce9657db8ccd9dba263615d176f8e4067707aa51d7d0dc6b3fccd507f79886cdc7360ce1389254bdcf7b234701ef28e43bea77ba93edb521264b673d923723ab5c7565f7c25313250d138f71118284b009af00be30454ee78d9baad33155bbd13ba8fb1d6d51dca20b70c170d91276e197be2eaa006c81641f8aaea46ff04efa03fbf8801ba699b7a1e4c250a09ca21ec4d00367bbc94d45adabc898c857498b8c3a84143955208c38c3328fb46eb554e49e9bd00b6e3f7a27028260cbc3c3f607d53bfd3b454ac38eac20242572f487e0f98001e7234d3d93439aa70bc603ac6b20915c3bcbcb2d3ff26659a86e4f01027b2cb9e449c8706630acd33c9865144eeefd5a4a4212c84a5b60730178d5cdcbe3b4abef57ba60534db00b660c8ca98202fa20691be90fcd976b0934ec7970967d0106be6fb131bac0eaf9d59f967822342e08e1f30f8250519c2f2faccc0a056efc95774c882d3f2813ad4853898a2c2d9c5e2a85d88a65360233bb2e816cbc758df2cd568be1598dcaf52016d4ac97d8acf645cf46771ff3bf6aef257710664c9f9b58c600ec607451da09c1f9a03d467deb56e11a42713712d23be09dfc29ece169b1f1c3db2f3d5bc7be4e5fdcc131302d805dd91d86f66b8de8d882150e92baeb225c2b217bf5148ebc6649c4ed0ae87b29e7495c1d36e381db49c2987dbedd5c7cf215b9e69aab4dc34051d28b4fc6a8174734e60973a132910a9dbe07c38df74a391a6441544088d3b86f2ef486ed4829e9d691d4c1e3d8718dae1afd6cc79465ec4339feba883d5e355254e36e18904880a14c1902295f8baa86f1588ffe2e8e68a54b3c5c61c27f0c8d689cb21c81faa54e51a0e34a75fc2e6996111a57106d03393a3d5acf74f0e1bf2de5982c980daad9603922bf7d8a2eba4744d4d1584d1c16c437210bee2993e82c3de1db9a9ff7133b45157ba1f83ad0eaf8f69ff099cfb8cc2478f55cbfc532f23ad6e73b49c2ed5a09216eeba6f52101111bcb8194c9437e141b1fd8cff2842c989d611bea44615ca55dcb3ebb082df0dc924665537cf0ca2347e7c949eee0772adc8da89acf0f96ca3c07aadc62d65078f6600c4cd5f53ffc977eb8ae2127b6ca98eaba9725eca66ac2badc3fb25f19d78820b830361878331e111fbb3c13e862bd8c9988559bf07111dc6b45e1b718cc6a11b9e2b6274308010401c823b1de0762f7b34f62815a6308b1cf1df9604e8ad175eedd99f623b4f9ab831fbf7f347e8a97341713804b7c31ccd1e74339dfa511cfae654efcff03629463d10d768942295553d380231eda66e350fe70947bec2bed346304db6c8abe0e792d4fbc45fa15eb7bc957661260d74f0c2e3d6995bd8133f8c490364e021749f17491efff8bad53b84430bde2ee922fd5ff4e0657b67fa230fdc3d3eb15a75498d9cf76d1b82dddbcaa1c9fd41913581ecef7d391cfbce4740e44ac7316e6da8adf683989f988c26a0591013cf6803f02d4dbdd8ef2779e73b9b647165b1c56991c7039544a9b37bd4cc304469bb996f7132f3600cd26ee79b5876d86246b63cb8f2a63907bfddd411e6f258d18ecaaf740fff14d5f7cc062214021d8130d3895fc326dbfe52894753c72b928fb75e3641daa2ac307a091e61ae0b2474f232d66641669a732d322e736ff80c9fe103d1f549d3d288f5652e11c01725873cd8447eae85661af50e09ef681144cc6986b3403a023ca519e0be89a440c56f528b2f3f681a4cfcea42f3f184a7ea28db406b469542bdb67481ee8d5d71f3bea38053b4cbb6d691bc9eb76475efd20ca24c610fd9e83c9aa4ebaa01e6bb8ea3ee8f09532c966d133f4983e33d7ce8f19c9991966ed7b4eaf6ce59c927390c90942fffd217b7c6bff9f49638341f10024b751f0d5de952cc5ce7eeeff61b691de22e1a053e16f55e27c1c79a94a967f32088b6e4a4034e893b3f19d757b404d9fb5b18b58eb5f91d4248787ad3107e2e8906d7bb14351e9076fbe85a7816a23a0d83e8356d86887e343b689e05b53dec31ef5bc0b48bdd4e83ee9c1e390342b06b984754a7836b5c458dbec8d114ef71b5c74b78b6482185474e1828c4acaf27060d2c06dfcac8e57c27572b51c8580bf1f843a6203b513a4734d854c796bc3892442283efcbfea7fd38acc328493c703bb7b8b0ebd164a3d6a1f0a233d52693a050e4c7ccac144564dedac26353d10ab664adc6894123c450f34beeef7e49a25c497584a08db6940c381f21ecb01a34aacc26d8227781f395777844eb7532ee61537c88a3f2ec6e4c2cf43a608178da2ac537e4473adc64d1d294a1588f0ae129c6f78c6ee2575c68fc77e745c475ac72e8ecea6f18baae766d2f18254d64e81dd8d1ab2c5653c212321ba4dfb15d6068c03ffac8af3d02ee623503dc9b939fbb5ba008ebf940ba33a60da99f44a0b5743c8803276c2ac2fd309d3161563aa2300f68cae6699d99680505ce6380b3387fa66b32bf3b67c456122286160c41cc9951322b2d56b9436ba17d51ac312cbd8e1b1c7197b0bc13782118eaffe17bc0eb393dac929a27d92d147853027a50709909e2110a71d8e65fe6aa0a94ce0efdb02db1376584615638f743acc647cd72e2443c899764054d81ccf7f2b3af0204eb28989cca1496fdcbd6c0ca523c02c68f7965a36a78d4ff3494ae42a3a74bfe5a2a9dabeb68a13f1f5ed882c0025f055f2153f00c50fdee52b4ced01c80a73f1bef4f339a5c8baaba9dc34034b17aff737d9321937b00197f9de801ec6875632cb9f3dd7dc2987df53b9384093b5dd5403eb90bc34ba66adba3f3746ef1e17c7accb5eb69e0b2de9fe92721ceb28bb97c7122fea06c779b411f470563085072a6e1fcfa7ad8a017301df7a2bc992ca399669c7a4b600db1ba53c1e8104f69562dd242b6aed4f1c2eba710a53184e652ee20966c4b20162118f07a860e7176b1db547f772fbc4b7aaae88956eaf844cf1ff7c0d8a31c210dfa16ebabc1165a9ed78fba81a199b621b483bf5d86830fad24ce7f0b8f443c3709df3f6fbb3af65d89a7597ca068a25b6b22af754fcc81555fe7d6c5327c255a06e4089bf2bfa91e910fd9016b0d94e4069e6cb9ce2e65be5521a164ef141c257e62b9e07c2e78b805c6ac41460100346458074fc64a02e7d19c0a1932449727f98cc988c99cad58f23d779568d7b159e3bdb8c8d4109e26ad9c3bd7c9dbb460253ab777510e9476a1e2e2a80e996d793030b485ac8025513b3b843f8e8fc54883bcb93eeb82b4c5b5df1424b58526cd57d1dc4cefc11701b7cf41a8b10b0c700b0e7a39e8eac34e68e1b85829fa84b1f1a88f481ada5490f972a4033603fd558ee4a655eaf3a1b00563b41899053f22d3fbde13b8732ee46059b466720b8abec49d8c851eac119f4d97de5e410f58d0da8b1bca7237f0a8d3493393a49517170a28365deb2a3ae3faa567a054b7c0d9d213098ec1845dac3fbc88578459e74f700e18bfba40640c79ea1a15e3fcf9eec2edc36c4a6d3b2fc4db4ea9390b3fa9db4665f252aae3d63c07327588e159e40feb8182b8bd435d01439b8515fac264e9f73e5b6cbb2d1700161d011f2c0eff73045c2380af5363b3841864373c38313906c36ade824545fda265dd7d96015f745b64e2f3dace14ec91dc3c6f4e8d5812169566018cfc1d4d220dade27fa0fc04bccf8b7e085166f6d21305bb05097e136de449b7060eb070cdd4deb6cec0b7dfaf0c3eada4272f581104affaaa161e4ffd174425af2d9050fe53e1fe56a3f5c872da8cc052957997451f45e565e7a16b81d39b4f43a03d5a3613d2b606a1eec0dfe3d393e77378988ff28ade35543f1b9271fa146b7f8e2a048ea49a021c78d0502b240d523ed0ad8eb10cbc520be14f6e3cd18af8fe4258b84c581d80c5dad091b1f55e1b47ca3c3a928a08f8fc45255eb05e9448e142c203c5b96a0a14b52ef4e2bdf87d7fb4cafe17d47374466a50481dcbd567e6c635d2ef23ff58e44582d79074691aaf69258bae6b01531697ab3c6981bdf209a0dccb7523b7b44eb68a8107f65d9216a7cc578dae374b986c38cedad8d1308fb62e56dae556e138b1805f146eed47919b6f5670ed66213ca10e45c9b3a884456a65692d827c5537ed9566795e3117c0dac00b33f745e3eb9af8afe33e1cce823993ad324b9a414ab5a726caa2bed37316436bc0afc26bd474b551bae553c130c391af42f1d75a24c62d29a471a48317f5617a70518d09d695852e0ba5e34619fad1f04438aeeaeb11b2378cf97796f9eab614dceab0f43c0f5465b43cde21032879e4706b70304a618922556775126df6b63a4952d9d6eb5c01b5f69d3b76b93bba932f4838d2d934dd636f0b7f9e39fce55987cc0a099eede53824f2b31b3bedf9c0cd85218f386fc988a4fdf254aac02f712929ef398ec16c7d39d6dcb0df20abdc8d29d3c379ea90d537d28bca13f87ce3db5bc9d2d380038d4bc3abc3424793ec6f8fbca03073bf27a1c7c99cd89cfadb316e56947b58b9510734130b21c04952fa005f4c2583620f45118bf687f35f828453547bfd62d29946341a7fb643d7c34d45700d9defdd844433280f94c14ee1eca1cae292c2491c38fcc7bc49246e7c68884374e0d3f4cb34d1b79cb0500d6329fa573eea87145e85397b5a0d40c1a2af0f2464fc75fc5c6930ec07de2a8b14e83fdc0a90ac04817ba70be828a145657257665520749566c6ce06ff9f95c33a59c34861497acd43630799a119fcd5afab5d7e20384ca42477e996f1ec383c5816047aeb7f41a4860e0c6d2a00c79319230c38dd067716b6ee7e7591d821070d7d9c1d3339421628f04479f353f1c565e55e1977d0e868871199045a3e9880f566fbbe69942f1bdb78a4e4ee8f0289fff685bb18c3002a366678c8c215a82469b3a1564c0fb160fd632ab8787847e07a5d7759c519a8a44f8b5756945e99b8b96b5cbc8b711637567e6f016981920018e99b185cd2410513252e9e2189f4185e5c2b24044fa29f1a352f5b7d7965512b56b769dd9ae8db830aa6912da7acb510b2cab2f17278fc1394fad4239fc7bf5e12e439d446174f610a4551db3c52289824930fbca07314b90583accaa295d8840dc8fb8599e9bc75decfb7f694d737aa58060086a05fe530f23d2e8aeda5145ab558cef121f7579b8219897167cb2a9a4c7839652520ee794026ddcc2ffedcf3f40aa9c903f6a49673edc1b9c5bbe4b8e71365706aec5f9a13cf49e5bdca3197015b38efa322ee255844d62280742407e9bf4ffab515e3d08dc4e439195d8349dc99bb1852d56c1780e69f98bb8e753883d696f7b9665cf97776aecc6d73ce113cdfd5277e9e8a2d55622ad8c70e1e52228cc0df3bddd67c7c4c21d16d43d085cd0e0bbb1f127dd132f9a2b7d758081b7ada584eb2cd95a9e956f86713066a554c8407f0a6a17d993aafa3f39bf0343d7c556b7634aab240012bbc3ff636e3c623703740451a5dbd9037e19d1e65bad28df69d0017309695f35bd89d1f049e79ba16115e87c2c9e7adadd37e0adbfac63b6e341ef84222d50e501343e224dd8ed13a3cb663646f2a9aa01d631ce2188a5dd47a3dc5953529562a407ce7ba623ae47bafc2e531dc4eddc9bf4ebcac4f28b0b8bdd5d9db305f1e068205c72cd9b359bdbf12dd35e1a425425617c1ce93e05b361c562cbc0eb6cf3b2f244c72b89ac9bfebff491e0b3b813760d77e307e874deedebb30d18b9d01777faed09e7f93eac38eb2cf9bc119bf84505270842ac9de7fe9f17cc55cdf401358819bf6944b7a5a406c34e94e88a57c332899bacabae12f9b391eb76330dc0f108dbb809d076bee7b9a02e0e6b95c300b1fbba4a3ce4c42958c4b06477f8b11f147fdae772d8de471232c0f8e16b31e47004a87cdd8841a8d6bf3a8be35c5ac5ba8e8bb046395e25a4478f8f877f31080b741a22850f32133bd239fcb8e7de65ea55b2398651b8e5d998f3d45b18bfeb52c60280972f591da91739e26b68a58d7ab1516912b42e09fa76f8ccfa31c05a9368c6d0616478097452220d994b662f274942c4a16872870d54828a8506d0d80c0737e0166f6e42437663c7c54c33c18949742d4be1822d3c4de274a01a1db2971e7c7102bb2323d73bc51fd4ad9c78390d5bab71982f2d8db292cff4497d7a50e170e04f66621242203b72c01646bebaf2fdedf6a71321caac218e876460854156d3a3718749ad4627cb96bc0ddf6b8c77eb4d9f688794d664033b833c34b6dc9106b5994a392259279e6843405ba4d091ac320d7f96e2847d34c9f15f734cb374ccbae4e3be4dc488728d7b84d79649370a11c4fa53011f1e39b807e08639ad99786cf051653b383273f7b32b017a5d0a3542d7b871b5c47dbfbb4eb1d01dbd2a18c0a6064cb307743566b635176e3d08cbfa63debc0a2f9195e86c925e7dc444c1c7d754f17d83bbaad20f863a994a146fa5978196fe203d14eaf399d80414da044fc5ba1a4757bba4dc3bdf1b5ccce0541a1ca7a24d21c4858ec90af7da78b8cb36675eb6d185b5d7fa8098b2d49fa8dd06cf8c84d54f66bf572ca5ee5c324fb9ccd832d43445b5ac5c0a482285cc317c6554d075f19394f695a4d53a61229ca44217ca2de91ed7654e514b6a3a96cb2190d54d567054c9983ce1ad5a61d7a9010edb173d62044e02ca08342297102f415222b5a2f55b1035938e9f21609858144313f01dce90ed0080b20a22aa702ef680a5fc22b0fc97ee826f269240e0f95aa26b92afec64956808c2b0f7aee0a5936502e161283a7987be0df59798d2df575ab0b44d3fb4b4e395f40b8eb361747809dffdd61238248f125209ac136ec8eb0bb1f53cb27a5c1e759f2d7adb3a3f609a4930a335c831f43dcf6e4f6385103d61893635134fe63532307584407c354aa5ebf6453196416f5bb3b44e2eff0d207676d3b4393e3cb69d97008182459beb25c6e29c4f23a8bdc2004aec88136a69192a5bf066912e5a7b0efa46d996eb280541694f68961bf22025c4c88a8ccf0076498eeca7ce97c4c3536ce42393339af670e87a17a69eb95913d62bba83f0387a8f7f0bfebb7cf475a9b6b165fecdd2602bb1c9f570813c9faa5f31498237de294f3b20e81b014707c7e5f6ccb69279d311e26de20129703b0037e1156321326119f23317e7cc7104935409fa8edc776c141023f293fee32ec192883194c6a6c7a6495d5cad68354f974d29ea5cb0239211e2bf97d9e5887f5f93dd44604f36cdf552d18cdc0ec34ef97045d7f745d08d1233009a4ab96129e7b0559d337572927f242f45281841316fc4d90c36217c45fdc304824db5db28d00fa43db3231ecb20973fe00f786099d7cc3dba6d6b3b333f5d5d3a675063fcdfd562348e1602aafa5174d98f7498e0d99ba5fb80054eb5a48c48c3c6d127f3088c325a2a311b90dd4f7bd73fa167b69dc2273bf6337943af77c2f38edf85e29d83870e7f58a1a2d2f1c68b6436f4a9ece707da3478c73a92bfe84f55428e2b8bd51929286496e716433d885eb1238a90bd9639e5ecd8c6ba0b829ebe961d93e4124889fa2d25cd353f8a4dfde40bc9ef3c57b15a96211e15020c9b0bbf895b7b32402fce3ec0e90499c9fc0ba62eeb6291e6c249ac4b15149a03a3dfe984c8a9069f9a5a3f6f9fd56446fca60032e283fcd2ab3b5b10908d2618e7e1ae14020a5054a7cd7165e083b5722421033ed77e6f8b09f7662ce674e4c8f101d8e6106a2012fd666bf9d26ed07dcbe9dee993d65f32ee067d84a3e22f70ad0a14f205c0b0a2bded2fa33105f1d4a6fc643b2ce664380d7f797062188970bfb42d9188fea696dd40fe7966f3905d0fd74f079c14a2f69ba624fd3a83cb5e44c573ada882e35eeecf42ab1c49e08d5bba7a42c95a3e2eb0b7c48d66b9d0f61392c429bca100db2639926cab8067d6b03be0bd0937eeb0d8ce235e3ac72dd02625ceab0cfb7409bb92d255465e108e9883a1fdf32c27d826e2aa75fb0f6ec072ed0c986c101ba93e5bb3d0898ce8ac7b2e441da2dfb2efc6e9c8fa08e2e067c883c11d54af7de0b62ff35d69059e3b5e91a7f96e46c55f56f013a667d18b0aaf920d9210db2266b56ab4816e29fe416d9f62eebccd4e033b1154b7f28ef2b7415045112e545eb607d60a7338776241b0dee3faf7ecb02900179e41e1578191b152553acc539429f8b82569d3e532107b899353cfecd5ec9b84e381f30606265cc6646cc93bb563c3a974aa4ec2739ca666da1017638a97c4296d73441e7c8235567bfba293149759273b3bc6d90d78d4e9e0d7711704d4a8de9378e0eddb856944e7086438c23761077f9302a6fc3d0020510655107490b93cb427f962c9b493415ce25d827c9a68a818a65173c93ccf8fa5139c043087b36a9b67efe421eeee8a2811ed4ca0d9db5eb86bb4e3b253fd478bbf441708fa257d5e1ec568bfe50babfe4fccd2b773341c728bd23387be0baad9ac5b58f1d4ddf06f2c712acd4277d0487d8569734c532d3b2cf253dce00a7147d71bb4c60a2d3e70e0662bf16307d6ce3015a1214d78525e50c5ac57f99147ac773d6b1d779524942786c61d6766a97eaae175d7d821ab8a6469799b3e4f6fd8ef4a0d013f71f744c351fbb07e96738fbb5fb9c4438451776f72d973b9873bc05c903197410c9340fa7309ed8024913975044a95c28367f2afa48dfb62302e5c90545ed90ac033fa02d6daf69e768d1b73a3eb88809276460bcc3caed4702724d9c8c8377d73e07a1c1474aaaa3cf8b43fb1d1753210dc1b6596463ff8b9e8ef490673bb4d758b40815302b59d46817bb0025841889674ec7f6a5085f6cbdc60b26ab0660b4dc13f76be8fcf14b0873172acc1b21c9b6c2af7e3246176bca8c86e501914b59c30ae4aeba1aba676ad053a25c4e85b8ba1d4d5fb3708eb721f449087febc8f6edf5a49c8bcbd1b47e3fa56219adfc0f42059502b0da46792f22a76e031798bbb030bcc7df0ae624e397f620acb2b6c594226014a7a676ed852b248d7eb4aafba33a8ced5b421d98ffb3f6b2de66932ecf9d83f438ea2d908d0f2dfcd4c8d705cd9aa11345e945b10ef12aeb34924065a2ef1b7c0b47397a71f26d8fb53513ad03914d334924251621d66284920cc52390feff1fa14114d631e1c71a40889f7eaf8b30ed97d9f3f976aa6e0956a4e3c28879f7a405b590d22b4e070243f6d73f0e45835cebb8ef1e5d7812873178fbbb1b92c03c8a86dc79e3b79164e5a0c63f312e9da02ba0f15019bd43042452bde5f03ed84e1a6063dc77f79dec090ece3fcdbe779f8a08d7260fe8c8c67c453f260e92fa29142474f862895dd276bec524a74e02f3cce3a9ea52254b789b4f9d724ad9f9ef68c18bc1d98c2c4f91dea699c8b15a4769a28070f31d7f9011d4456bae217ade77e36959e730542f3ad41cd6b9d25bd8fbfc35301c835538d896df866d82c9448dba647e592622b41839bd167d56a2c2e6ab0f70600a9740efb540d9dbcb5cb84930e614b2ccc44032407bea53a7268da64cd4328adcb7c3fe9e39e66dac73d23224386863f1f6210293016838b05b61a3b5418eacd25f0fbeb642b9199e3ae30491f07771d23c38b3709f69a9d9a77c180de9129f8b3f63a1ba5e1c1b338a05d1c7739c8db74880305f3942e79c6884e0e34782df6a8ade41ef3d2679491ddbfe31d9c1267fff45ab5efea1c671dbe284cd5fe125982315da39b6e99bf76110c5f1215e9d9839047c7d45836004837a1c53bb97d1a79fb35fd3d0ddc6d945c43cf3edf04e6989fb1dab8f9da52b47d403adde2223f4b49ee589254385097e66e5a9f9794c262916d221e19c0736f3dd2c3b80cb8aed3cfee32c6322f0e6e2a3eb9aa9b08b5f50a3da7a2290f44c48e4ca34a80c0e1be7c000314c81c8abbae190d95e7bf87cc71dd004df3675e5357c742ec42be3faff947519449b18293a69ff087a17a64c974176f1818f708d315d2f72b304d6e228968f729f3f4a1063d5a16358fb0d4cc4fa4d810e850ea7b102ee1c7fa66af76df03d332501c8e24281c9552d0e3eb9ab863096186543e4fb5476ea987ff86d9ae1d2019bc8cb6401cb1c27a2740a950678ecf6679fa732ac159a09922c93079afce1b366ec3f94eec9efc2bb2b4107eced5c1e6b1a70a31f4384b5699cf04ca9e965a4d312b2efe1424e75a6edb2d7b0dd56c0675bcbddc8de94809618b0f44ba2fcfa03512c4b22282576408b1baaddb6ca4f35ea50f97c5191a178b69ae7532e290f76412f6341695b18706a0707983c65d869891352e4d21c334d3043e260efc96c66b62da9e47410d9021d106e445c4343964c27cbb79fa673f183bd03ea09b0e426432cef55dd7288a22d4e534698589e0d3eb168ff8b4858def443fce99f0e18f097d8c9627bef9909f29ecd1860f5dea7e193763acd323089e61ba02a35e8dcdecea2f86437872acd784ee862e3d2bb0c984b5193dfa4e235ba137a3dfc9d669323fdf284914e5c54351327383fedbd5b9be005cfbc2b34221e9be8403b9b5dbb6dd190f0c3027dae3bfdd61c57f9298175b49a8348fb3df062a97358b9c2ab182dfdc9be73e30b76d98b2935e28e5675569523423605d7c0d9df16bd6f734c416ea9c5b2e1994d640e26917788640e28dc894a17e495cdcde92f86a5fba206bc34814557f3b74170fced8ce4fa987524221fea771cceff19c072f480694e28342081c71138951a5b8573e93ac4447b37dd96f5cead1e86fb3c3ae251b581257afabae1414ef9c53f48a9988163704d2616859706d5755ed23797b148fb9dc93e466804ec0b319370fbde644f4e645d89d36b2cdfaf0590e5e55f969ff695d263b7af2134214659d54a633a727d7911c32cbe315e9c2a7d9f47ba15dbfd76b2fd8159703f79139c5dd270ccbf1a30f48bac0a5e2dae2b760d06248a171e77dcbb6a0891b71594e4c7f90ca4e555dd4e3856c05bb21a4c31a46984af0d0b19ad9df163935d664bd785cbaa89ad0c20f65268838a6c1ba8a3608f58d10b09c1587111d4b6ca848f70575ca52566a7f980b233fb60b15ea23ea320a9cd1b16ca2201b543addd9d3e0a604528baaeffc0ae0c33bbb47d9a2a9096fe53f992df3543837d1e67588798eec9a2996ae9c3be510eef68dadb0154caaa2744861eae261204b50454081a7f5a71f61c19655b93da531c01cda62e247c94bf83db12fd067a53ab636638658b7a9e801ccbc6c9a6d288925b6b2e2710bb503ec32079b3a9a8cb060202c9fbccfbd1b7a0acc4aeeac8ed8d88df2b2b97a067ae04e839e00deed2c8ab06b4b138fa6e8e35f25e6a4321bc021693fa8ef2058e6dea7aecd074db8403b5b293893414f74b1826b52d870cb0f20483c532ee7f1197a05c4fd92a6b6ba8c9a63fba63e25aaefc10055c7c79ddfeefb9a11269e494d9579e87a567e483d6c2aaa4c0a7f6386a1a5cee2dbbe699122430fcb5fa27d88bd75b7c8883a0148cecb2a87e91c3172f25e9193c9529f9f7fe11ec413b78ea4c35a5e529563ad43efffb7a0f05a57458c03fe523879336750858cdc171ea954c62c1025e956d26d8d2d72e657d636db11577b9a7b530636785df0e265595d4d04a80b8a48ceb92edcfdf3514521382203ae16e44af63f403a3f37bbffe3f5b5abf0311314683369614228e1b10b40dd13661693297f726cd2d9e2c06c74262b9b639b94fb30c5ef25a64e1dc70f3e7078988c2948953235ca6992df273b8a9bf5afb355169f2a34a1c1f9c2ea2f192e426fc63499612b860245a2cf56ff881bc4d832a89107c95c6855d86cf0c09829bcade18595946d340c08f1d01c4b1c5a3d22191df48ce652eb3e0e086b2dfd3dfa5cafe82554b80ca7a8bbfb172837e05439960aea2a7cdf29563a866bb8c01ff5a772c7283b35b14e9e075f0126c5f443c503c3ecc1b5fe40dbf89f63150e2aa7fc72597c6584e93c1ffdfbad2d94c4394166da9168c97c3f8911f27b07ce6c50a79817d748a4dcf5870a245aad26f0eb58f0814779bfc4d6e6ad56530d4636f93e237d9eeb1bc1a04259b6984272aef02eb165731ff8ce9d240546df12570c8af033d8cd3be65f7a8ca5b147fca23c9bf010c18b0c1913d03e5d2c0138cec9529c35e574b2a65e526b78f811bca8cdc5deb59c4263c07fca7643030cf6786f5ffbb4bc6a1a22333cf96a5030ac0b4a2aa211a1f7cb14215ddc1c1569389be044ac6a50745ddf6dede5d006bbd79d8054cbc9a7f6816a319af18d9899364a3924a8542b5ae4a4b957d524ee9e430b393dfd08a152624a8946ac1490bc9add45ce13433b6a6cb3e725102992b15b3b786b8634eec65fad74d9890e58e81dc93dfd562e31b4d15a440b85b3bab07ca2d608cf1fccc1f5a6f349c25a3e722a2bb2d00d09a0aa7937e6f756b2c6c0d0ab0338e65fee9c66c492830696672f4c079590f2f5913d46b15379803535cb0afd90d874751019506b1c7f3eb0c79cc1c9717924d4358196bd4a3e05777e4209d935decf3cc8ca141e08ab8fcb98122f7678fe453000becf5a6357f3f96ba4480bfb7f3bbbc3c278372d8f92fae611de44d4cc10a4ab5e0caff4a0212ae7ee71e9f87ff53d8344e27d20b30f0eb37240499329b7f98cf280339c45a2c56f4be11906a391cb003545e571681f7eba3767e990411b0a7befd3a9f5f3201a821e5aedecda2ffd35be57d447c6848ba481fa651f66e7dcd9059da6220ff0628a9fc1c43d7c23823cde650f309d6132aa25da41a4c6451b461fccb380106b879f94560b4566d87935cb84fde81e36ab934013783cd291a0d14554c95958c062e6781391ab1d1482775d2ec1d7bbddc7ca47d6d8635096785e8af9706645b7ba64a938e4dc1c140bd49fff41908d32bc5419811af53bcaafd405cb8cecefd679ade391d8c409c3fa94fee6cde3801973694f3f6b7b958f75f4edf72c7a12aca2e3f5e8a82ba363fc4bffba9876598c7495fab887d60dec50015e264ced6ecd3a7ce97930fb11d522c5855878615635e1f230389a81171d22f413ce7ce8dc2a48b6da5baa0fe0fb8be0c0c3cfdde7d2a4570366db4465765c4febd5d9f30d70548ef1c11e63b13bc55dc3bbd1b2bcc9b3412a92fa53430ca118979d8a9dd41c1b6906e0f25b9fbd68e5a4be41ed170e24d4c1e746d64244a73d8483129d03d568454194a13981ef690fd416fc613b540f4f3761575d987ecfc479dfb7fa050d678c2f16f91525adb52229889ae37c57f16345280d4a518ba15cef8fa2f9bac8dd3d1f3d183d0feb29216b905126e926fd259159631b7222f7a873f227c794e20323e67b6ad77427501d1576e2f7cd75623bf992368188359776e855caf3cfb13ad462eacfec7e7ad6bdf4c69bde4aa1d3cbbc841b6355d57099f15adecd9e18c35fcf612d002745b22f8195a55b2796dace69d7c5c3fed2e9c59ee7933674b6d0a3656fd575772b925e86fae6176a5d414dd71b97e320dfdf0f326a9215a024662f16d34d329009af48581d28d7a70fb05b64aef824fc132dc035a5c933eff2240c141958b32904136ab01e0696f885588938b8d410b31cec90685dc7c0c52df7d5532e07978744fd574406d6a3cfd85c6b1d7b863656795a239086063f35d1dd627cef2e0091e90054aa3ae3e4cbfdd33a078ff0140ef4b650da9cd87bb5ac02c781ca41becae59676d662b989db5df5b5a1fbad912005437983e3a2dca7760b4fad89c25f7c29cc6e10831030cb545221aa771e5a7f71d2d1ba81b67f6901e43eb4f231e48152a4a52712283493177e66635da3d7480cd0cd1af6fa549af8f7f46b1ef72f6646a08431eabf98f8d11c3af0630422d141ee4b797125fa69b5ba011d593c5fe7ce67dd8b5bd8e9933d8edea8fb404e91ac4f4fdc1abef40854a518de1d834621fd49ed4d7c4976aadc46063a8a40d1b21dd863de671a64d62ac121176ddc5140198fa37fde4d80e70b16162ee014d89a580fed6abf3df64e70dd43a064165a5171f6b4ac65d8b644d331ecb3cc90edcd14d25f4b2b28786359005868f3bd06420eab06f17f8f379771901ab38b2dee82fa47543f258036984bde1109edfa89af04490802f93b293a1dd1675c0ff1dd404efb83d7f6f886859e023b45a36dd8fb5d5ab41184082f912feb943a0fcabc022e20ae3de9cca79a7aafb05cb8f5596d80607e99b36cfe69a68b1cc2c7b1408db49f881219906a108b5f58ff3355f9d4a892cf95f76e592e3e1174fce1ada79f7dc48bc8a5c437247ba40d1ca291f5abf212b5580de7885a929a8e2588065458b975bcea6d5fbb852262e364d6aeaf2bb17cb3da3d1ce03e4dda73c8d9a75b5778f29b0c07f58e4241f32828a40a784b8f42f036b0c400e28623f9f59c14c2061b4583e87a9e205a8b2e28455084fd349d5b125223f556cb595dd74093dbbd4c480a4da45bb973a92c929386944ab10443123af223deb6b661a87e62c41febf0d29383a70726f66696c65736c64363a61636f646563333a616163363a686569676874693065363a76636f646563303a353a7769647468693065656565"; String infoHashHex = "35af1a534b6d227aa51c9f23f746398d928ace01"; byte[] bytes = ByteBufUtil.decodeHexDump(rawHex); System.out.println(ByteBufUtil.prettyHexDump(Unpooled.copiedBuffer(bytes))); String infoHash = DigestUtils.sha1Hex(bytes); assert infoHash.equalsIgnoreCase(infoHashHex); Map<String, Object> dic = Util.decode(bytes); System.out.println(dic); bytes = Util.encode(dic); System.out.println(ByteBufUtil.prettyHexDump(Unpooled.copiedBuffer(bytes))); assert rawHex.equalsIgnoreCase(ByteBufUtil.hexDump(Unpooled.copiedBuffer(bytes))); } }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.Commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.OI; import frc.robot.Subsystems.Shooter; public class ShootBall extends CommandBase { private Shooter balls_shooter; public ShootBall(Shooter innerShooter) { balls_shooter = innerShooter; addRequirements(balls_shooter); } @Override public void initialize() { } @Override public void execute() { balls_shooter.startShoot(); } @Override public void end(boolean interrupted) { balls_shooter.stopShoot(); } @Override public boolean isFinished() { return (new OI().getJoystick().getTriggerPressed()); } }
import java.util.List; public class MaximumCoinsGain { /* 17.9 */ public static int computeMaximum(List<Integer> coins) { return 0; } }
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.map.impl; import com.hazelcast.client.impl.protocol.task.map.MapAssignAndGetUuidsOperation; import com.hazelcast.client.impl.protocol.task.map.MapAssignAndGetUuidsOperationFactory; import com.hazelcast.internal.nearcache.impl.invalidation.BatchNearCacheInvalidation; import com.hazelcast.internal.nearcache.impl.invalidation.SingleNearCacheInvalidation; import com.hazelcast.internal.serialization.DataSerializerHook; import com.hazelcast.internal.serialization.impl.ArrayDataSerializableFactory; import com.hazelcast.internal.serialization.impl.FactoryIdHelper; import com.hazelcast.map.impl.iterator.MapEntriesWithCursor; import com.hazelcast.map.impl.iterator.MapKeysWithCursor; import com.hazelcast.map.impl.journal.DeserializingEventJournalMapEvent; import com.hazelcast.map.impl.journal.InternalEventJournalMapEvent; import com.hazelcast.map.impl.journal.MapEventJournalReadOperation; import com.hazelcast.map.impl.journal.MapEventJournalReadResultSetImpl; import com.hazelcast.map.impl.journal.MapEventJournalSubscribeOperation; import com.hazelcast.map.impl.nearcache.invalidation.UuidFilter; import com.hazelcast.map.impl.operation.AccumulatorConsumerOperation; import com.hazelcast.map.impl.operation.AddIndexOperation; import com.hazelcast.map.impl.operation.AddIndexOperationFactory; import com.hazelcast.map.impl.operation.AddInterceptorOperation; import com.hazelcast.map.impl.operation.AwaitMapFlushOperation; import com.hazelcast.map.impl.operation.ClearBackupOperation; import com.hazelcast.map.impl.operation.ClearNearCacheOperation; import com.hazelcast.map.impl.operation.ClearOperation; import com.hazelcast.map.impl.operation.ClearOperationFactory; import com.hazelcast.map.impl.operation.ContainsKeyOperation; import com.hazelcast.map.impl.operation.ContainsValueOperation; import com.hazelcast.map.impl.operation.ContainsValueOperationFactory; import com.hazelcast.map.impl.operation.DeleteOperation; import com.hazelcast.map.impl.operation.EntryBackupOperation; import com.hazelcast.map.impl.operation.EntryOffloadableSetUnlockOperation; import com.hazelcast.map.impl.operation.EntryOperation; import com.hazelcast.map.impl.operation.EvictAllBackupOperation; import com.hazelcast.map.impl.operation.EvictAllOperation; import com.hazelcast.map.impl.operation.EvictAllOperationFactory; import com.hazelcast.map.impl.operation.EvictBackupOperation; import com.hazelcast.map.impl.operation.EvictBatchBackupOperation; import com.hazelcast.map.impl.operation.EvictOperation; import com.hazelcast.map.impl.operation.GetAllOperation; import com.hazelcast.map.impl.operation.GetEntryViewOperation; import com.hazelcast.map.impl.operation.GetOperation; import com.hazelcast.map.impl.operation.IsEmptyOperationFactory; import com.hazelcast.map.impl.operation.IsKeyLoadFinishedOperation; import com.hazelcast.map.impl.operation.IsPartitionLoadedOperation; import com.hazelcast.map.impl.operation.IsPartitionLoadedOperationFactory; import com.hazelcast.map.impl.operation.KeyLoadStatusOperation; import com.hazelcast.map.impl.operation.KeyLoadStatusOperationFactory; import com.hazelcast.map.impl.operation.LegacyMergeOperation; import com.hazelcast.map.impl.operation.LoadAllOperation; import com.hazelcast.map.impl.operation.LoadMapOperation; import com.hazelcast.map.impl.operation.MapFetchEntriesOperation; import com.hazelcast.map.impl.operation.MapFetchKeysOperation; import com.hazelcast.map.impl.operation.MapFetchWithQueryOperation; import com.hazelcast.map.impl.operation.MapFlushBackupOperation; import com.hazelcast.map.impl.operation.MapFlushOperation; import com.hazelcast.map.impl.operation.MapFlushOperationFactory; import com.hazelcast.map.impl.operation.MapGetAllOperationFactory; import com.hazelcast.map.impl.operation.MapGetInvalidationMetaDataOperation; import com.hazelcast.map.impl.operation.MapIsEmptyOperation; import com.hazelcast.map.impl.operation.MapLoadAllOperationFactory; import com.hazelcast.map.impl.operation.MapNearCacheStateHolder; import com.hazelcast.map.impl.operation.MapReplicationOperation; import com.hazelcast.map.impl.operation.MapReplicationStateHolder; import com.hazelcast.map.impl.operation.MapSizeOperation; import com.hazelcast.map.impl.operation.MergeOperation; import com.hazelcast.map.impl.operation.MergeOperationFactory; import com.hazelcast.map.impl.operation.MultipleEntryBackupOperation; import com.hazelcast.map.impl.operation.MultipleEntryOperation; import com.hazelcast.map.impl.operation.MultipleEntryOperationFactory; import com.hazelcast.map.impl.operation.MultipleEntryWithPredicateBackupOperation; import com.hazelcast.map.impl.operation.MultipleEntryWithPredicateOperation; import com.hazelcast.map.impl.operation.NotifyMapFlushOperation; import com.hazelcast.map.impl.operation.PartitionWideEntryBackupOperation; import com.hazelcast.map.impl.operation.PartitionWideEntryOperation; import com.hazelcast.map.impl.operation.PartitionWideEntryOperationFactory; import com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateBackupOperation; import com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateOperation; import com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateOperationFactory; import com.hazelcast.map.impl.operation.PostJoinMapOperation; import com.hazelcast.map.impl.operation.PutAllBackupOperation; import com.hazelcast.map.impl.operation.PutAllOperation; import com.hazelcast.map.impl.operation.PutAllPartitionAwareOperationFactory; import com.hazelcast.map.impl.operation.PutBackupOperation; import com.hazelcast.map.impl.operation.PutFromLoadAllBackupOperation; import com.hazelcast.map.impl.operation.PutFromLoadAllOperation; import com.hazelcast.map.impl.operation.PutIfAbsentOperation; import com.hazelcast.map.impl.operation.PutOperation; import com.hazelcast.map.impl.operation.PutTransientOperation; import com.hazelcast.map.impl.operation.RemoveBackupOperation; import com.hazelcast.map.impl.operation.RemoveFromLoadAllOperation; import com.hazelcast.map.impl.operation.RemoveIfSameOperation; import com.hazelcast.map.impl.operation.RemoveInterceptorOperation; import com.hazelcast.map.impl.operation.RemoveOperation; import com.hazelcast.map.impl.operation.ReplaceIfSameOperation; import com.hazelcast.map.impl.operation.ReplaceOperation; import com.hazelcast.map.impl.operation.SetOperation; import com.hazelcast.map.impl.operation.SetTtlBackupOperation; import com.hazelcast.map.impl.operation.SetTtlOperation; import com.hazelcast.map.impl.operation.SizeOperationFactory; import com.hazelcast.map.impl.operation.TriggerLoadIfNeededOperation; import com.hazelcast.map.impl.operation.TryPutOperation; import com.hazelcast.map.impl.operation.TryRemoveOperation; import com.hazelcast.map.impl.operation.WriteBehindStateHolder; import com.hazelcast.map.impl.query.AggregationResult; import com.hazelcast.map.impl.query.Query; import com.hazelcast.map.impl.query.QueryEventFilter; import com.hazelcast.map.impl.query.QueryOperation; import com.hazelcast.map.impl.query.QueryPartitionOperation; import com.hazelcast.map.impl.query.QueryResult; import com.hazelcast.map.impl.query.QueryResultRow; import com.hazelcast.map.impl.query.ResultSegment; import com.hazelcast.map.impl.query.Target; import com.hazelcast.map.impl.querycache.subscriber.operation.DestroyQueryCacheOperation; import com.hazelcast.map.impl.querycache.subscriber.operation.MadePublishableOperation; import com.hazelcast.map.impl.querycache.subscriber.operation.MadePublishableOperationFactory; import com.hazelcast.map.impl.querycache.subscriber.operation.PublisherCreateOperation; import com.hazelcast.map.impl.querycache.subscriber.operation.ReadAndResetAccumulatorOperation; import com.hazelcast.map.impl.querycache.subscriber.operation.SetReadCursorOperation; import com.hazelcast.map.impl.record.RecordInfo; import com.hazelcast.map.impl.record.RecordReplicationInfo; import com.hazelcast.map.impl.tx.MapTransactionLogRecord; import com.hazelcast.map.impl.tx.TxnDeleteOperation; import com.hazelcast.map.impl.tx.TxnLockAndGetOperation; import com.hazelcast.map.impl.tx.TxnPrepareBackupOperation; import com.hazelcast.map.impl.tx.TxnPrepareOperation; import com.hazelcast.map.impl.tx.TxnRollbackBackupOperation; import com.hazelcast.map.impl.tx.TxnRollbackOperation; import com.hazelcast.map.impl.tx.TxnSetOperation; import com.hazelcast.map.impl.tx.TxnUnlockBackupOperation; import com.hazelcast.map.impl.tx.TxnUnlockOperation; import com.hazelcast.map.impl.tx.VersionedValue; import com.hazelcast.map.merge.HigherHitsMapMergePolicy; import com.hazelcast.map.merge.LatestUpdateMapMergePolicy; import com.hazelcast.map.merge.PassThroughMergePolicy; import com.hazelcast.map.merge.PutIfAbsentMapMergePolicy; import com.hazelcast.nio.serialization.DataSerializableFactory; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.query.impl.IndexInfo; import com.hazelcast.query.impl.MapIndexInfo; import com.hazelcast.util.ConstructorFunction; import static com.hazelcast.internal.serialization.impl.FactoryIdHelper.MAP_DS_FACTORY; import static com.hazelcast.internal.serialization.impl.FactoryIdHelper.MAP_DS_FACTORY_ID; public final class MapDataSerializerHook implements DataSerializerHook { public static final int F_ID = FactoryIdHelper.getFactoryId(MAP_DS_FACTORY, MAP_DS_FACTORY_ID); public static final int PUT = 0; public static final int GET = 1; public static final int REMOVE = 2; public static final int PUT_BACKUP = 3; public static final int REMOVE_BACKUP = 4; public static final int KEY_SET = 5; public static final int VALUES = 6; public static final int ENTRIES = 7; public static final int ENTRY_VIEW = 8; public static final int QUERY_RESULT_ROW = 9; public static final int QUERY_RESULT = 10; public static final int EVICT_BACKUP = 11; public static final int CONTAINS_KEY = 12; public static final int KEYS_WITH_CURSOR = 13; public static final int ENTRIES_WITH_CURSOR = 14; public static final int SET = 15; public static final int LOAD_MAP = 16; public static final int KEY_LOAD_STATUS = 17; public static final int LOAD_ALL = 18; public static final int ENTRY_BACKUP = 19; public static final int ENTRY_OPERATION = 20; public static final int PUT_ALL = 21; public static final int PUT_ALL_BACKUP = 22; public static final int REMOVE_IF_SAME = 23; public static final int REPLACE = 24; public static final int SIZE = 25; public static final int CLEAR_BACKUP = 26; public static final int CLEAR_NEAR_CACHE = 27; public static final int CLEAR = 28; public static final int DELETE = 29; public static final int EVICT = 30; public static final int EVICT_ALL = 31; public static final int EVICT_ALL_BACKUP = 32; public static final int GET_ALL = 33; public static final int IS_EMPTY = 34; public static final int LEGACY_MERGE = 35; public static final int NEAR_CACHE_SINGLE_INVALIDATION = 36; public static final int NEAR_CACHE_BATCH_INVALIDATION = 37; public static final int IS_PARTITION_LOADED = 38; public static final int PARTITION_WIDE_ENTRY = 39; public static final int PARTITION_WIDE_ENTRY_BACKUP = 40; public static final int PARTITION_WIDE_PREDICATE_ENTRY = 41; public static final int PARTITION_WIDE_PREDICATE_ENTRY_BACKUP = 42; public static final int ADD_INDEX = 43; public static final int AWAIT_MAP_FLUSH = 44; public static final int CONTAINS_VALUE = 45; public static final int GET_ENTRY_VIEW = 46; public static final int FETCH_ENTRIES = 47; public static final int FETCH_KEYS = 48; public static final int FLUSH_BACKUP = 49; public static final int FLUSH = 50; public static final int MULTIPLE_ENTRY_BACKUP = 51; public static final int MULTIPLE_ENTRY = 52; public static final int MULTIPLE_ENTRY_PREDICATE_BACKUP = 53; public static final int MULTIPLE_ENTRY_PREDICATE = 54; public static final int NOTIFY_MAP_FLUSH = 55; public static final int PUT_IF_ABSENT = 56; public static final int PUT_FROM_LOAD_ALL = 57; public static final int PUT_FROM_LOAD_ALL_BACKUP = 58; public static final int QUERY_PARTITION = 59; public static final int QUERY_OPERATION = 60; public static final int PUT_TRANSIENT = 61; public static final int REPLACE_IF_SAME = 62; public static final int TRY_PUT = 63; public static final int TRY_REMOVE = 64; public static final int TXN_LOCK_AND_GET = 65; public static final int TXN_DELETE = 66; public static final int TXN_PREPARE = 67; public static final int TXN_PREPARE_BACKUP = 68; public static final int TXN_ROLLBACK = 69; public static final int TXN_ROLLBACK_BACKUP = 70; public static final int TXN_SET = 71; public static final int TXN_UNLOCK = 72; public static final int TXN_UNLOCK_BACKUP = 73; public static final int IS_PARTITION_LOADED_FACTORY = 74; public static final int ADD_INDEX_FACTORY = 75; public static final int ADD_INTERCEPTOR_FACTORY = 76; public static final int CLEAR_FACTORY = 77; public static final int CONTAINS_VALUE_FACTORY = 78; public static final int EVICT_ALL_FACTORY = 79; public static final int IS_EMPTY_FACTORY = 80; public static final int KEY_LOAD_STATUS_FACTORY = 81; public static final int MAP_FLUSH_FACTORY = 82; public static final int MAP_GET_ALL_FACTORY = 83; public static final int LOAD_ALL_FACTORY = 84; public static final int PARTITION_WIDE_ENTRY_FACTORY = 85; public static final int PARTITION_WIDE_PREDICATE_ENTRY_FACTORY = 86; public static final int PUT_ALL_PARTITION_AWARE_FACTORY = 87; public static final int REMOVE_INTERCEPTOR_FACTORY = 88; public static final int SIZE_FACTORY = 89; public static final int MULTIPLE_ENTRY_FACTORY = 90; public static final int ENTRY_EVENT_FILTER = 91; public static final int EVENT_LISTENER_FILTER = 92; public static final int PARTITION_LOST_EVENT_FILTER = 93; public static final int NEAR_CACHE_CLEAR_INVALIDATION = 94; public static final int ADD_INTERCEPTOR = 95; public static final int MAP_REPLICATION = 96; public static final int POST_JOIN_MAP_OPERATION = 97; public static final int INDEX_INFO = 98; public static final int MAP_INDEX_INFO = 99; public static final int INTERCEPTOR_INFO = 100; public static final int REMOVE_INTERCEPTOR = 101; public static final int QUERY_EVENT_FILTER = 102; public static final int RECORD_INFO = 103; public static final int RECORD_REPLICATION_INFO = 104; public static final int HIGHER_HITS_MERGE_POLICY = 105; public static final int LATEST_UPDATE_MERGE_POLICY = 106; public static final int PASS_THROUGH_MERGE_POLICY = 107; public static final int PUT_IF_ABSENT_MERGE_POLICY = 108; public static final int UUID_FILTER = 109; public static final int CLEAR_NEAR_CACHE_INVALIDATION = 110; public static final int MAP_TRANSACTION_LOG_RECORD = 111; public static final int VERSIONED_VALUE = 112; public static final int MAP_REPLICATION_STATE_HOLDER = 113; public static final int WRITE_BEHIND_STATE_HOLDER = 114; public static final int AGGREGATION_RESULT = 115; public static final int QUERY = 116; public static final int TARGET = 117; public static final int MAP_INVALIDATION_METADATA = 118; public static final int MAP_INVALIDATION_METADATA_RESPONSE = 119; public static final int MAP_NEAR_CACHE_STATE_HOLDER = 120; public static final int MAP_ASSIGN_AND_GET_UUIDS = 121; public static final int MAP_ASSIGN_AND_GET_UUIDS_FACTORY = 122; public static final int DESTROY_QUERY_CACHE = 123; public static final int MADE_PUBLISHABLE = 124; public static final int MADE_PUBLISHABLE_FACTORY = 125; public static final int PUBLISHER_CREATE = 126; public static final int READ_AND_RESET_ACCUMULATOR = 127; public static final int SET_READ_CURSOR = 128; public static final int ACCUMULATOR_CONSUMER = 129; public static final int LAZY_MAP_ENTRY = 131; public static final int TRIGGER_LOAD_IF_NEEDED = 132; public static final int IS_KEYLOAD_FINISHED = 133; public static final int REMOVE_FROM_LOAD_ALL = 134; public static final int ENTRY_REMOVING_PROCESSOR = 135; public static final int ENTRY_OFFLOADABLE_SET_UNLOCK = 136; public static final int LOCK_AWARE_LAZY_MAP_ENTRY = 137; public static final int FETCH_WITH_QUERY = 138; public static final int RESULT_SEGMENT = 139; public static final int EVICT_BATCH_BACKUP = 140; public static final int EVENT_JOURNAL_SUBSCRIBE_OPERATION = 141; public static final int EVENT_JOURNAL_READ = 142; public static final int EVENT_JOURNAL_DESERIALIZING_MAP_EVENT = 143; public static final int EVENT_JOURNAL_INTERNAL_MAP_EVENT = 144; public static final int EVENT_JOURNAL_READ_RESULT_SET = 145; public static final int MERGE_FACTORY = 146; public static final int MERGE = 147; public static final int SET_TTL = 148; public static final int SET_TTL_BACKUP = 149; public static final int MERKLE_TREE_NODE_ENTRIES = 150; private static final int LEN = MERKLE_TREE_NODE_ENTRIES + 1; @Override public int getFactoryId() { return F_ID; } @Override public DataSerializableFactory createFactory() { ConstructorFunction<Integer, IdentifiedDataSerializable>[] constructors = new ConstructorFunction[LEN]; constructors[PUT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutOperation(); } }; constructors[GET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new GetOperation(); } }; constructors[REMOVE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RemoveOperation(); } }; constructors[PUT_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutBackupOperation(); } }; constructors[REMOVE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RemoveBackupOperation(); } }; constructors[EVICT_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EvictBackupOperation(); } }; constructors[KEY_SET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapKeySet(); } }; constructors[VALUES] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapValueCollection(); } }; constructors[ENTRIES] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapEntries(); } }; constructors[ENTRY_VIEW] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return (IdentifiedDataSerializable) EntryViews.createSimpleEntryView(); } }; constructors[QUERY_RESULT_ROW] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new QueryResultRow(); } }; constructors[QUERY_RESULT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new QueryResult(); } }; constructors[CONTAINS_KEY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ContainsKeyOperation(); } }; constructors[KEYS_WITH_CURSOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapKeysWithCursor(); } }; constructors[ENTRIES_WITH_CURSOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapEntriesWithCursor(); } }; constructors[SET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new SetOperation(); } }; constructors[LOAD_MAP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new LoadMapOperation(); } }; constructors[KEY_LOAD_STATUS] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new KeyLoadStatusOperation(); } }; constructors[LOAD_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new LoadAllOperation(); } }; constructors[ENTRY_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EntryBackupOperation(); } }; constructors[ENTRY_OPERATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EntryOperation(); } }; constructors[PUT_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutAllOperation(); } }; constructors[PUT_ALL_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutAllBackupOperation(); } }; constructors[REMOVE_IF_SAME] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RemoveIfSameOperation(); } }; constructors[REPLACE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ReplaceOperation(); } }; constructors[SIZE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapSizeOperation(); } }; constructors[CLEAR_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ClearBackupOperation(); } }; constructors[CLEAR_NEAR_CACHE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ClearNearCacheOperation(); } }; constructors[CLEAR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ClearOperation(); } }; constructors[DELETE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new DeleteOperation(); } }; constructors[EVICT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EvictOperation(); } }; constructors[EVICT_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EvictAllOperation(); } }; constructors[EVICT_ALL_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EvictAllBackupOperation(); } }; constructors[GET_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new GetAllOperation(); } }; constructors[IS_EMPTY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapIsEmptyOperation(); } }; constructors[LEGACY_MERGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new LegacyMergeOperation(); } }; constructors[IS_PARTITION_LOADED] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new IsPartitionLoadedOperation(); } }; constructors[PARTITION_WIDE_ENTRY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PartitionWideEntryOperation(); } }; constructors[PARTITION_WIDE_ENTRY_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PartitionWideEntryBackupOperation(); } }; constructors[PARTITION_WIDE_PREDICATE_ENTRY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PartitionWideEntryWithPredicateOperation(); } }; constructors[PARTITION_WIDE_PREDICATE_ENTRY_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PartitionWideEntryWithPredicateBackupOperation(); } }; constructors[ADD_INDEX] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new AddIndexOperation(); } }; constructors[AWAIT_MAP_FLUSH] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new AwaitMapFlushOperation(); } }; constructors[CONTAINS_VALUE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ContainsValueOperation(); } }; constructors[GET_ENTRY_VIEW] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new GetEntryViewOperation(); } }; constructors[FETCH_ENTRIES] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapFetchEntriesOperation(); } }; constructors[FETCH_KEYS] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapFetchKeysOperation(); } }; constructors[FLUSH_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapFlushBackupOperation(); } }; constructors[FLUSH] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapFlushOperation(); } }; constructors[MULTIPLE_ENTRY_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MultipleEntryBackupOperation(); } }; constructors[MULTIPLE_ENTRY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MultipleEntryOperation(); } }; constructors[MULTIPLE_ENTRY_PREDICATE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MultipleEntryWithPredicateBackupOperation(); } }; constructors[MULTIPLE_ENTRY_PREDICATE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MultipleEntryWithPredicateOperation(); } }; constructors[NOTIFY_MAP_FLUSH] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new NotifyMapFlushOperation(); } }; constructors[PUT_IF_ABSENT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutIfAbsentOperation(); } }; constructors[PUT_FROM_LOAD_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutFromLoadAllOperation(); } }; constructors[PUT_FROM_LOAD_ALL_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutFromLoadAllBackupOperation(); } }; constructors[QUERY_PARTITION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new QueryPartitionOperation(); } }; constructors[QUERY_OPERATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new QueryOperation(); } }; constructors[PUT_TRANSIENT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutTransientOperation(); } }; constructors[REPLACE_IF_SAME] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ReplaceIfSameOperation(); } }; constructors[TRY_PUT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TryPutOperation(); } }; constructors[TRY_REMOVE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TryRemoveOperation(); } }; constructors[TXN_LOCK_AND_GET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnLockAndGetOperation(); } }; constructors[TXN_DELETE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnDeleteOperation(); } }; constructors[TXN_PREPARE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnPrepareOperation(); } }; constructors[TXN_PREPARE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnPrepareBackupOperation(); } }; constructors[TXN_ROLLBACK] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnRollbackOperation(); } }; constructors[TXN_ROLLBACK_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnRollbackBackupOperation(); } }; constructors[TXN_SET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnSetOperation(); } }; constructors[TXN_UNLOCK] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnUnlockOperation(); } }; constructors[TXN_UNLOCK_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TxnUnlockBackupOperation(); } }; constructors[IS_PARTITION_LOADED_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new IsPartitionLoadedOperationFactory(); } }; constructors[ADD_INDEX_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new AddIndexOperationFactory(); } }; constructors[CLEAR_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ClearOperationFactory(); } }; constructors[CONTAINS_VALUE_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ContainsValueOperationFactory(); } }; constructors[EVICT_ALL_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EvictAllOperationFactory(); } }; constructors[IS_EMPTY_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new IsEmptyOperationFactory(); } }; constructors[KEY_LOAD_STATUS_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new KeyLoadStatusOperationFactory(); } }; constructors[MAP_FLUSH_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapFlushOperationFactory(); } }; constructors[MAP_GET_ALL_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapGetAllOperationFactory(); } }; constructors[LOAD_ALL_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapLoadAllOperationFactory(); } }; constructors[PARTITION_WIDE_ENTRY_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PartitionWideEntryOperationFactory(); } }; constructors[PARTITION_WIDE_PREDICATE_ENTRY_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PartitionWideEntryWithPredicateOperationFactory(); } }; constructors[PUT_ALL_PARTITION_AWARE_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutAllPartitionAwareOperationFactory(); } }; constructors[SIZE_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new SizeOperationFactory(); } }; constructors[MULTIPLE_ENTRY_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MultipleEntryOperationFactory(); } }; constructors[ENTRY_EVENT_FILTER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EntryEventFilter(); } }; constructors[EVENT_LISTENER_FILTER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EventListenerFilter(); } }; constructors[PARTITION_LOST_EVENT_FILTER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapPartitionLostEventFilter(); } }; constructors[NEAR_CACHE_SINGLE_INVALIDATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new SingleNearCacheInvalidation(); } }; constructors[NEAR_CACHE_BATCH_INVALIDATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new BatchNearCacheInvalidation(); } }; constructors[ADD_INTERCEPTOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new AddInterceptorOperation(); } }; constructors[MAP_REPLICATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapReplicationOperation(); } }; constructors[POST_JOIN_MAP_OPERATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PostJoinMapOperation(); } }; constructors[INDEX_INFO] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new IndexInfo(); } }; constructors[MAP_INDEX_INFO] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapIndexInfo(); } }; constructors[INTERCEPTOR_INFO] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PostJoinMapOperation.InterceptorInfo(); } }; constructors[REMOVE_INTERCEPTOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RemoveInterceptorOperation(); } }; constructors[QUERY_EVENT_FILTER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new QueryEventFilter(); } }; constructors[RECORD_INFO] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RecordInfo(); } }; constructors[RECORD_REPLICATION_INFO] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RecordReplicationInfo(); } }; constructors[HIGHER_HITS_MERGE_POLICY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new HigherHitsMapMergePolicy(); } }; constructors[LATEST_UPDATE_MERGE_POLICY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new LatestUpdateMapMergePolicy(); } }; constructors[PASS_THROUGH_MERGE_POLICY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PassThroughMergePolicy(); } }; constructors[PUT_IF_ABSENT_MERGE_POLICY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutIfAbsentMapMergePolicy(); } }; constructors[UUID_FILTER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new UuidFilter(); } }; constructors[MAP_TRANSACTION_LOG_RECORD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapTransactionLogRecord(); } }; constructors[VERSIONED_VALUE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new VersionedValue(); } }; constructors[MAP_REPLICATION_STATE_HOLDER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapReplicationStateHolder(); } }; constructors[WRITE_BEHIND_STATE_HOLDER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new WriteBehindStateHolder(); } }; constructors[AGGREGATION_RESULT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new AggregationResult(); } }; constructors[QUERY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new Query(); } }; constructors[TARGET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new Target(); } }; constructors[MAP_INVALIDATION_METADATA] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new MapGetInvalidationMetaDataOperation(); } }; constructors[MAP_INVALIDATION_METADATA_RESPONSE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new MapGetInvalidationMetaDataOperation.MetaDataResponse(); } }; constructors[MAP_NEAR_CACHE_STATE_HOLDER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new MapNearCacheStateHolder(); } }; constructors[MAP_ASSIGN_AND_GET_UUIDS_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new MapAssignAndGetUuidsOperationFactory(); } }; constructors[MAP_ASSIGN_AND_GET_UUIDS] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new MapAssignAndGetUuidsOperation(); } }; constructors[DESTROY_QUERY_CACHE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new DestroyQueryCacheOperation(); } }; constructors[MADE_PUBLISHABLE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MadePublishableOperation(); } }; constructors[MADE_PUBLISHABLE_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MadePublishableOperationFactory(); } }; constructors[PUBLISHER_CREATE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PublisherCreateOperation(); } }; constructors[READ_AND_RESET_ACCUMULATOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ReadAndResetAccumulatorOperation(); } }; constructors[SET_READ_CURSOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new SetReadCursorOperation(); } }; constructors[ACCUMULATOR_CONSUMER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new AccumulatorConsumerOperation(); } }; constructors[LAZY_MAP_ENTRY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new LazyMapEntry(); } }; constructors[TRIGGER_LOAD_IF_NEEDED] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new TriggerLoadIfNeededOperation(); } }; constructors[IS_KEYLOAD_FINISHED] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new IsKeyLoadFinishedOperation(); } }; constructors[REMOVE_FROM_LOAD_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new RemoveFromLoadAllOperation(); } }; constructors[ENTRY_REMOVING_PROCESSOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return EntryRemovingProcessor.ENTRY_REMOVING_PROCESSOR; } }; constructors[ENTRY_OFFLOADABLE_SET_UNLOCK] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EntryOffloadableSetUnlockOperation(); } }; constructors[LOCK_AWARE_LAZY_MAP_ENTRY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new LockAwareLazyMapEntry(); } }; constructors[FETCH_WITH_QUERY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapFetchWithQueryOperation(); } }; constructors[RESULT_SEGMENT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ResultSegment(); } }; constructors[EVICT_BATCH_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new EvictBatchBackupOperation(); } }; constructors[EVENT_JOURNAL_SUBSCRIBE_OPERATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapEventJournalSubscribeOperation(); } }; constructors[EVENT_JOURNAL_READ] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapEventJournalReadOperation<Object, Object, Object>(); } }; constructors[EVENT_JOURNAL_DESERIALIZING_MAP_EVENT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new DeserializingEventJournalMapEvent<Object, Object>(); } }; constructors[EVENT_JOURNAL_INTERNAL_MAP_EVENT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new InternalEventJournalMapEvent(); } }; constructors[EVENT_JOURNAL_READ_RESULT_SET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapEventJournalReadResultSetImpl<Object, Object, Object>(); } }; constructors[MERGE_FACTORY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MergeOperationFactory(); } }; constructors[MERGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MergeOperation(); } }; constructors[SET_TTL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new SetTtlOperation(); } }; constructors[SET_TTL_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new SetTtlBackupOperation(); } }; constructors[MERKLE_TREE_NODE_ENTRIES] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { @Override public IdentifiedDataSerializable createNew(Integer arg) { return new MerkleTreeNodeEntries(); } }; return new ArrayDataSerializableFactory(constructors); } }
package com.redhat.mercury.service.contactdialog.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.redhat.mercury.service.contactdialog.model.CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordDepositTransaction; import com.redhat.mercury.service.contactdialog.model.CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordWithdrawalTransaction; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; /** * CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2020-05-08T15:54:49.785-04:00[America/New_York]") public class CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord { @JsonProperty("depositType") private String depositType; @JsonProperty("withdrawalType") private String withdrawalType; @JsonProperty("accountLimitBreachResponse") private String accountLimitBreachResponse; @JsonProperty("depositTransaction") private CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordDepositTransaction depositTransaction; @JsonProperty("withdrawalTransaction") private CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordWithdrawalTransaction withdrawalTransaction; public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord depositType(String depositType) { this.depositType = depositType; return this; } /** * `status: Registered` iso-link: https://www.iso20022.org/standardsrepository/public/wqt/Description/mx/dico/bc/_E5_m2sTGEeChad0JzLk7QA_-2008690148/elements/_E6IwwMTGEeChad0JzLk7QA_1495654231 bian-reference: DepositServicet.DepositType general-info: The type of deposit transaction that can be applied to the account (e.g. customer deposit, internal credit) * @return depositType */ @ApiModelProperty(value = "`status: Registered` iso-link: https://www.iso20022.org/standardsrepository/public/wqt/Description/mx/dico/bc/_E5_m2sTGEeChad0JzLk7QA_-2008690148/elements/_E6IwwMTGEeChad0JzLk7QA_1495654231 bian-reference: DepositServicet.DepositType general-info: The type of deposit transaction that can be applied to the account (e.g. customer deposit, internal credit) ") public String getDepositType() { return depositType; } public void setDepositType(String depositType) { this.depositType = depositType; } public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord withdrawalType(String withdrawalType) { this.withdrawalType = withdrawalType; return this; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The type of withdrawal transaction that can be applied to the account (e.g. customer withdrawal, internal service charge, disbursement) * @return withdrawalType */ @ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The type of withdrawal transaction that can be applied to the account (e.g. customer withdrawal, internal service charge, disbursement) ") public String getWithdrawalType() { return withdrawalType; } public void setWithdrawalType(String withdrawalType) { this.withdrawalType = withdrawalType; } public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord accountLimitBreachResponse(String accountLimitBreachResponse) { this.accountLimitBreachResponse = accountLimitBreachResponse; return this; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The handling options if a withdrawal results in a breach of an account limit * @return accountLimitBreachResponse */ @ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The handling options if a withdrawal results in a breach of an account limit ") public String getAccountLimitBreachResponse() { return accountLimitBreachResponse; } public void setAccountLimitBreachResponse(String accountLimitBreachResponse) { this.accountLimitBreachResponse = accountLimitBreachResponse; } public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord depositTransaction(CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordDepositTransaction depositTransaction) { this.depositTransaction = depositTransaction; return this; } /** * Get depositTransaction * @return depositTransaction */ @ApiModelProperty(value = "") @Valid public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordDepositTransaction getDepositTransaction() { return depositTransaction; } public void setDepositTransaction(CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordDepositTransaction depositTransaction) { this.depositTransaction = depositTransaction; } public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord withdrawalTransaction(CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordWithdrawalTransaction withdrawalTransaction) { this.withdrawalTransaction = withdrawalTransaction; return this; } /** * Get withdrawalTransaction * @return withdrawalTransaction */ @ApiModelProperty(value = "") @Valid public CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordWithdrawalTransaction getWithdrawalTransaction() { return withdrawalTransaction; } public void setWithdrawalTransaction(CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecordWithdrawalTransaction withdrawalTransaction) { this.withdrawalTransaction = withdrawalTransaction; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord currentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord = (CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord) o; return Objects.equals(this.depositType, currentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord.depositType) && Objects.equals(this.withdrawalType, currentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord.withdrawalType) && Objects.equals(this.accountLimitBreachResponse, currentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord.accountLimitBreachResponse) && Objects.equals(this.depositTransaction, currentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord.depositTransaction) && Objects.equals(this.withdrawalTransaction, currentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord.withdrawalTransaction); } @Override public int hashCode() { return Objects.hash(depositType, withdrawalType, accountLimitBreachResponse, depositTransaction, withdrawalTransaction); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CurrentAccountSdReferenceIdCurrentAccountFulfillmentArrangementCrReferenceIdDepositsandwithdrawalsBqReferenceIdUpdateDepositsAndWithdrawalsInstanceRecord {\n"); sb.append(" depositType: ").append(toIndentedString(depositType)).append("\n"); sb.append(" withdrawalType: ").append(toIndentedString(withdrawalType)).append("\n"); sb.append(" accountLimitBreachResponse: ").append(toIndentedString(accountLimitBreachResponse)).append("\n"); sb.append(" depositTransaction: ").append(toIndentedString(depositTransaction)).append("\n"); sb.append(" withdrawalTransaction: ").append(toIndentedString(withdrawalTransaction)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } TreeNode(int x, TreeNode left, TreeNode right){ this.val = x; this.left = left; this.right = right; } }
/* * 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 io.trino.plugin.cassandra; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import io.airlift.slice.Slice; import io.trino.plugin.cassandra.CassandraType.Kind; import io.trino.spi.connector.RecordCursor; import io.trino.spi.predicate.NullableValue; import io.trino.spi.type.TimeZoneKey; import io.trino.spi.type.Type; import java.util.List; import static io.airlift.slice.Slices.utf8Slice; import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone; import static java.lang.Float.floatToRawIntBits; public class CassandraRecordCursor implements RecordCursor { private final List<CassandraType> cassandraTypes; private final ResultSet rs; private Row currentRow; private long count; public CassandraRecordCursor(CassandraSession cassandraSession, List<CassandraType> cassandraTypes, String cql) { this.cassandraTypes = cassandraTypes; rs = cassandraSession.execute(cql); currentRow = null; } @Override public boolean advanceNextPosition() { if (!rs.isExhausted()) { currentRow = rs.one(); count++; return true; } return false; } @Override public void close() { } @Override public boolean getBoolean(int i) { return currentRow.getBool(i); } @Override public long getCompletedBytes() { return count; } @Override public long getReadTimeNanos() { return 0; } @Override public double getDouble(int i) { switch (getCassandraType(i).getKind()) { case DOUBLE: return currentRow.getDouble(i); case FLOAT: return currentRow.getFloat(i); case DECIMAL: return currentRow.getDecimal(i).doubleValue(); default: throw new IllegalStateException("Cannot retrieve double for " + getCassandraType(i)); } } @Override public long getLong(int i) { switch (getCassandraType(i).getKind()) { case INT: return currentRow.getInt(i); case SMALLINT: return currentRow.getShort(i); case TINYINT: return currentRow.getByte(i); case BIGINT: case COUNTER: return currentRow.getLong(i); case TIMESTAMP: return packDateTimeWithZone(currentRow.getTimestamp(i).getTime(), TimeZoneKey.UTC_KEY); case DATE: return currentRow.getDate(i).getDaysSinceEpoch(); case FLOAT: return floatToRawIntBits(currentRow.getFloat(i)); default: throw new IllegalStateException("Cannot retrieve long for " + getCassandraType(i)); } } private CassandraType getCassandraType(int i) { return cassandraTypes.get(i); } @Override public Slice getSlice(int i) { if (getCassandraType(i).getKind() == Kind.TIMESTAMP) { throw new IllegalArgumentException("Timestamp column can not be accessed with getSlice"); } NullableValue value = cassandraTypes.get(i).getColumnValue(currentRow, i); if (value.getValue() instanceof Slice) { return (Slice) value.getValue(); } return utf8Slice(value.getValue().toString()); } @Override public Object getObject(int i) { CassandraType cassandraType = cassandraTypes.get(i); switch (cassandraType.getKind()) { case TUPLE: case UDT: return cassandraType.getColumnValue(currentRow, i).getValue(); default: throw new IllegalArgumentException("getObject cannot be called for " + cassandraType); } } @Override public Type getType(int i) { return getCassandraType(i).getTrinoType(); } @Override public boolean isNull(int i) { if (getCassandraType(i).getKind() == Kind.TIMESTAMP) { return currentRow.getTimestamp(i) == null; } return currentRow.isNull(i); } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.GroupPolicyPresentationMultiTextBox; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Group Policy Presentation Multi Text Box Request Builder. */ public class GroupPolicyPresentationMultiTextBoxRequestBuilder extends BaseRequestBuilder implements IGroupPolicyPresentationMultiTextBoxRequestBuilder { /** * The request builder for the GroupPolicyPresentationMultiTextBox * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public GroupPolicyPresentationMultiTextBoxRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the IGroupPolicyPresentationMultiTextBoxRequest instance */ public IGroupPolicyPresentationMultiTextBoxRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the IGroupPolicyPresentationMultiTextBoxRequest instance */ public IGroupPolicyPresentationMultiTextBoxRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.requests.extensions.GroupPolicyPresentationMultiTextBoxRequest(getRequestUrl(), getClient(), requestOptions); } /** * Gets the request builder for GroupPolicyDefinition * * @return the IGroupPolicyDefinitionWithReferenceRequestBuilder instance */ public IGroupPolicyDefinitionWithReferenceRequestBuilder definition() { return new GroupPolicyDefinitionWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("definition"), getClient(), null); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huaweicloud.governance.service; import com.huaweicloud.governance.policy.Policy; import java.util.List; import java.util.Map; public interface PolicyService { Map<String, Policy> getAllPolicies(String mark); Policy getCustomPolicy(String kind, String mark); }
/* * 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.aliyuncs.iot.model.v20180120; import com.aliyuncs.AcsResponse; import com.aliyuncs.iot.transform.v20180120.BatchDeleteEdgeInstanceChannelResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class BatchDeleteEdgeInstanceChannelResponse extends AcsResponse { private String requestId; private Boolean success; private String code; private String errorMessage; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getErrorMessage() { return this.errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } @Override public BatchDeleteEdgeInstanceChannelResponse getInstance(UnmarshallerContext context) { return BatchDeleteEdgeInstanceChannelResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
/* Copyright (c) 2009-2010, J. M. Dieterich and B. Hartke 2010-2014, J. M. Dieterich 2016-2020, J. M. Dieterich and B. Hartke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software of the ogolem.org project developed by J. M. Dieterich and B. Hartke (Christian-Albrechts-University Kiel, Germany) and contributors. * Neither the name of the ogolem.org project, the University of Kiel nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.ogolem.core; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.ogolem.generic.Copyable; import org.ogolem.math.AcosLookup; /** * A value object representing a topology. Not everything needs to be filled in and it is highly * recommended to extend this when needed. * * @author Johannes Dieterich * @version 2020-12-30 */ public class Topology implements Copyable, Serializable { private static final long serialVersionUID = (long) 20160224; private BondInfo bonds; private String[] atomNames; private short[] atomicNumbers; private float[] charges; private short[] spins; private double[][] positions; // calculated on-the-fly private double[][] distances; private double[][][] angles; private double[][][] bondedAngles; private double[][][][] dihedrals; // calculated on-the-fly (upon request) private boolean calcDiffs = false; private double[][][] diffPos; // just if applicable private List<int[]> contributions13; private int[][] contri13; private List<int[]> contributions14; private int[][] contri14; // important for computations private final int wAcos; private final AcosLookup acosLook; // some internal scratch space private final double[] scr1 = new double[3]; private final double[] scr2 = new double[3]; private final double[] scr3 = new double[3]; public Topology(CartesianCoordinates cartes, BondInfo bonds) { this(cartes, bonds, false); } public Topology(CartesianCoordinates cartes, BondInfo bonds, int wAcos) { this(cartes, bonds, false, wAcos); } public Topology(CartesianCoordinates cartes, BondInfo bonds, boolean calcAllDiffs) { this(cartes, bonds, false, 0); } public Topology( CartesianCoordinates cartes, BondInfo bonds, boolean calcAllDiffs, int whichAcos) { this.calcDiffs = calcAllDiffs; this.bonds = bonds; this.atomNames = cartes.getAllAtomTypes(); this.atomicNumbers = cartes.getAllAtomNumbers(); this.charges = cartes.getAllCharges(); this.spins = cartes.getAllSpins(); /* * our lookup table (potential overhead!) */ switch (whichAcos) { case 0: acosLook = null; wAcos = 0; break; case 1: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[0]); wAcos = 1; break; case 2: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[1]); wAcos = 1; break; case 3: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[2]); wAcos = 1; break; case 4: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[3]); wAcos = 1; break; case 5: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[4]); wAcos = 1; break; case 11: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[0]); wAcos = 2; break; case 12: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[1]); wAcos = 2; break; case 13: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[2]); wAcos = 2; break; case 14: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[3]); wAcos = 2; break; case 15: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[4]); wAcos = 2; break; case 20: acosLook = null; wAcos = 3; break; default: acosLook = null; wAcos = 0; break; } // calculate distances final int iNoOfAtoms = cartes.getNoOfAtoms(); final double[][] daXYZ = cartes.getAllXYZCoord(); this.positions = daXYZ; this.distances = new double[iNoOfAtoms][iNoOfAtoms]; if (calcDiffs) { this.diffPos = new double[iNoOfAtoms][iNoOfAtoms][3]; } if (calcDiffs) { for (int i = 0; i < iNoOfAtoms - 1; i++) { for (int j = i + 1; j < iNoOfAtoms; j++) { final double dX = daXYZ[0][i] - daXYZ[0][j]; final double dY = daXYZ[1][i] - daXYZ[1][j]; final double dZ = daXYZ[2][i] - daXYZ[2][j]; distances[i][j] = Math.sqrt(dX * dX + dY * dY + dZ * dZ); diffPos[i][j][0] = dX; diffPos[i][j][1] = dY; diffPos[i][j][2] = dZ; // it's kind of symmetric diffPos[j][i][0] = -dX; diffPos[j][i][1] = -dY; diffPos[j][i][2] = -dZ; distances[j][i] = distances[i][j]; } } } else { for (int i = 0; i < iNoOfAtoms - 1; i++) { for (int j = i + 1; j < iNoOfAtoms; j++) { distances[i][j] = CoordTranslation.distance(daXYZ, i, j); // it's symmetric distances[j][i] = distances[i][j]; } } } } public Topology( String[] atoms, double[][] xyz, BondInfo bonds, float[] charges, short[] spins, short[] numbers, List<int[]> contr13, List<int[]> contr14) { this(atoms, xyz, bonds, charges, spins, numbers, contr13, contr14, false); } public Topology( String[] atoms, double[][] xyz, BondInfo bonds, float[] charges, short[] spins, short[] numbers, List<int[]> contr13, List<int[]> contr14, int whichAcos) { this(atoms, xyz, bonds, charges, spins, numbers, contr13, contr14, false, whichAcos); } public Topology( String[] atoms, double[][] xyz, BondInfo bonds, float[] charges, short[] spins, short[] numbers, List<int[]> contr13, List<int[]> contr14, boolean calcAllDiffs) { this(atoms, xyz, bonds, charges, spins, numbers, contr13, contr14, false, 0); } public Topology( String[] atoms, double[][] xyz, BondInfo bonds, float[] charges, short[] spins, short[] numbers, List<int[]> contr13, List<int[]> contr14, boolean calcAllDiffs, int whichAcos) { this.calcDiffs = calcAllDiffs; this.bonds = bonds; this.atomNames = atoms; this.atomicNumbers = numbers; this.positions = xyz; this.charges = charges; this.spins = spins; /* * our lookup table (potential overhead!) */ switch (whichAcos) { case 0: acosLook = null; wAcos = 0; break; case 1: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[0]); wAcos = 1; break; case 2: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[1]); wAcos = 1; break; case 3: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[2]); wAcos = 1; break; case 4: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[3]); wAcos = 1; break; case 5: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[4]); wAcos = 1; break; case 11: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[0]); wAcos = 2; break; case 12: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[1]); wAcos = 2; break; case 13: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[2]); wAcos = 2; break; case 14: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[3]); wAcos = 2; break; case 15: acosLook = new AcosLookup(AcosLookup.POSSIBLE_SIZES[4]); wAcos = 2; break; default: acosLook = null; wAcos = 0; break; } this.contributions13 = contr13; if (contr13 != null) { this.contri13 = new int[contr13.size()][3]; for (int i = 0; i < contr13.size(); i++) { contri13[i] = contr13.get(i); } } this.contributions14 = contr14; if (contr14 != null) { this.contri14 = new int[contr14.size()][4]; for (int i = 0; i < contr14.size(); i++) { contri14[i] = contr14.get(i); } } // calculate distances final int iNoOfAtoms = atoms.length; final double[][] daXYZ = xyz; this.distances = new double[iNoOfAtoms][iNoOfAtoms]; if (calcDiffs) { this.diffPos = new double[iNoOfAtoms][iNoOfAtoms][3]; } if (calcDiffs) { for (int i = 0; i < iNoOfAtoms - 1; i++) { for (int j = i + 1; j < iNoOfAtoms; j++) { final double dX = daXYZ[0][i] - daXYZ[0][j]; final double dY = daXYZ[1][i] - daXYZ[1][j]; final double dZ = daXYZ[2][i] - daXYZ[2][j]; distances[i][j] = Math.sqrt(dX * dX + dY * dY + dZ * dZ); diffPos[i][j][0] = dX; diffPos[i][j][1] = dY; diffPos[i][j][2] = dZ; // it's kind of symmetric diffPos[j][i][0] = -dX; diffPos[j][i][1] = -dY; diffPos[j][i][2] = -dZ; distances[j][i] = distances[i][j]; } } } else { for (int i = 0; i < iNoOfAtoms - 1; i++) { for (int j = i + 1; j < iNoOfAtoms; j++) { distances[i][j] = CoordTranslation.distance(daXYZ, i, j); // it's symmetric distances[j][i] = distances[i][j]; } } } } public Topology(final Topology orig, final boolean shallow) { /* * we need to be careful not to rise any NullPointerExceptions! * Thou shalt not follow the NULL pointer, for chaos and madness await * thee at its end. * ;-) * Some things (bonds and contributions) will always only be shallow copies! */ if (orig.bonds != null) { this.bonds = orig.bonds.copy(); } if (orig.contributions13 != null) { this.contributions13 = new ArrayList<>(orig.contributions13); } if (orig.contri13 != null) { this.contri13 = orig.contri13.clone(); } if (orig.contri14 != null) { this.contri14 = orig.contri14.clone(); } if (orig.contributions14 != null) { this.contributions14 = new ArrayList<>(orig.contributions14); } if (orig.charges != null) { this.charges = orig.charges.clone(); } if (orig.spins != null) { this.spins = orig.spins.clone(); } if (orig.atomNames != null) { this.atomNames = orig.atomNames.clone(); } if (orig.atomicNumbers != null) { this.atomicNumbers = orig.atomicNumbers.clone(); } if (orig.positions != null) { // deep copy this.positions = new double[orig.positions.length][orig.positions[0].length]; for (int i = 0; i < orig.positions.length; i++) { System.arraycopy(orig.positions[i], 0, positions[i], 0, orig.positions[0].length); } } if (orig.distances != null) { if (!shallow) { // deep copy this.distances = new double[orig.distances.length][orig.distances[0].length]; for (int i = 0; i < orig.distances.length; i++) { System.arraycopy(orig.distances[i], 0, distances[i], 0, orig.distances[0].length); } } else { this.distances = orig.distances.clone(); } } this.calcDiffs = orig.calcDiffs; if (orig.diffPos != null) { if (!shallow) { // deep copy this.diffPos = new double[orig.diffPos.length][orig.diffPos.length][3]; for (int i = 0; i < orig.diffPos.length; i++) { for (int j = 0; j < orig.diffPos.length; j++) { System.arraycopy(orig.diffPos[i][j], 0, this.diffPos[i][j], 0, 3); } } } else { this.diffPos = orig.diffPos.clone(); } } this.wAcos = orig.wAcos; if (orig.acosLook != null) { this.acosLook = orig.acosLook.copy(); } // XXX do we need a clone w/ deep copy?! else { this.acosLook = null; } if (orig.angles != null) { if (!shallow) { this.angles = new double[orig.angles.length][orig.angles[0].length][orig.angles[0][0].length]; for (int i = 0; i < angles.length; i++) { for (int j = 0; j < angles[j].length; j++) { System.arraycopy(orig.angles[i][j], 0, angles[i][j], 0, angles[i][j].length); } } } else { this.angles = orig.angles.clone(); // XXX think about this... } } if (orig.bondedAngles != null) { if (!shallow) { // TODO implement } else { this.bondedAngles = orig.bondedAngles.clone(); // XXX think about this! } } /* * We leave the rest null'd on purpose since we assume that the cost to * deep copy it is not much less than computing it again (if needed). * Also it is unlikely to be != null. */ } public Topology(Topology orig) { this(orig, false); } /** @return a shallow copy of this topology */ @Override public Topology copy() { return new Topology(this, true); } public int getNumberOfAtoms() { return atomNames.length; } public void setPositions(final double[][] positions) { this.positions = positions; // make the differences invalid this.positions = null; this.diffPos = null; } public double[][] getPositions() { return positions; } public void setCharges(final float[] charges) { this.charges = charges; } public float[] getCharges() { return charges; } public void setSpins(final short[] spins) { this.spins = spins; } public short[] getSpins() { return spins; } public void setBonds(final BondInfo bonding) { bonds = bonding; } public BondInfo getBonds() { return bonds; } public void setAtomNames(final String[] atomNames) { this.atomNames = atomNames; } public String[] getAtomNames() { return atomNames; } public void setAtomicNumbers(final short[] nos) { atomicNumbers = nos; } public short[] getAtomicNumbers() { return atomicNumbers; } public void setDistances(final double[][] distances) { this.distances = distances; // make the position differences invalid (what they are now) this.diffPos = null; } public double[][] getDistances() { // XXX think about calculating them only upon request... return distances; } public double[][][] getPosDiffs() { if (diffPos != null) { return diffPos; } this.diffPos = new double[distances.length][distances.length][3]; for (int i = 0; i < distances.length - 1; i++) { for (int j = i + 1; j < distances.length; j++) { final double dX = positions[0][i] - positions[0][j]; final double dY = positions[1][i] - positions[1][j]; final double dZ = positions[2][i] - positions[2][j]; diffPos[i][j][0] = dX; diffPos[i][j][1] = dY; diffPos[i][j][2] = dZ; // it's kind of symmetric diffPos[j][i][0] = -dX; diffPos[j][i][1] = -dY; diffPos[j][i][2] = -dZ; } } return diffPos; } public void setAngles(final double[][][] angles) { this.angles = angles; } public double getAngle(final int i, final int j, final int k) { assert (i != j); assert (j != k); assert (i != k); // only compute if necessary if (angles != null) { return angles[i][j][k]; } // XXX acos()?! else { return CoordTranslation.calcAngle(positions, i, j, k); } } /** * Computes all internal angles in a triangle IJK. * * @param i * @param j * @param k * @param angles will contain all internal angles in order IJK/JKI/KIJ. */ public void getTriangle(final int i, final int j, final int k, final double[] angles) { assert (i != j); assert (j != k); assert (i != k); assert (angles.length >= 3); // only compute if necessary if (this.angles != null) { angles[0] = this.angles[i][j][k]; angles[1] = this.angles[j][k][i]; angles[2] = this.angles[k][i][j]; } else { // compute (but try to be smart) if (diffPos != null) { final double[] dIJ = diffPos[i][j]; final double[] dIK = diffPos[i][k]; final double[] dKJ = diffPos[k][j]; final double lIJ = Math.sqrt(dIJ[0] * dIJ[0] + dIJ[1] * dIJ[1] + dIJ[2] * dIJ[2]); final double lIK = Math.sqrt(dIK[0] * dIK[0] + dIK[1] * dIK[1] + dIK[2] * dIK[2]); final double lKJ = Math.sqrt(dKJ[0] * dKJ[0] + dKJ[1] * dKJ[1] + dKJ[2] * dKJ[2]); final double dotIJwKJ = org.ogolem.math.TrivialLinearAlgebra.dotProduct(dIJ, dKJ); final double dotJKwIK = -org.ogolem.math.TrivialLinearAlgebra.dotProduct(dKJ, dIK); final double normIJ_KJ = dotIJwKJ / (lIJ * lKJ); final double normJK_IK = dotJKwIK / (lKJ * lIK); angles[0] = acos(normIJ_KJ); angles[1] = acos(normJK_IK); } else { for (int z = 0; z < 3; z++) { scr1[z] = positions[z][i] - positions[z][j]; scr2[z] = positions[z][i] - positions[z][k]; scr3[z] = positions[z][k] - positions[z][j]; } final double lIJ = Math.sqrt(scr1[0] * scr1[0] + scr1[1] * scr1[1] + scr1[2] * scr1[2]); final double lIK = Math.sqrt(scr2[0] * scr2[0] + scr2[1] * scr2[1] + scr2[2] * scr2[2]); final double lKJ = Math.sqrt(scr3[0] * scr3[0] + scr3[1] * scr3[1] + scr3[2] * scr3[2]); final double dotIJwKJ = org.ogolem.math.TrivialLinearAlgebra.dotProduct(scr1, scr3); final double dotJKwIK = -org.ogolem.math.TrivialLinearAlgebra.dotProduct(scr3, scr2); final double normIJ_KJ = dotIJwKJ / (lIJ * lKJ); final double normJK_IK = dotJKwIK / (lKJ * lIK); angles[0] = acos(normIJ_KJ); angles[1] = acos(normJK_IK); } angles[2] = Math.PI - angles[0] - angles[1]; } } /** * Should only be used when knowing what the memory footprint of this method is. * * @return angles A field of all angles in the system. */ public double[][][] getAngles() { if (angles == null) { calcAllAngles(); } return angles; } public void calcAllAngles() { final int noOfAngles = distances.length; angles = new double[noOfAngles][noOfAngles][noOfAngles]; for (int i = 0; i < noOfAngles; i++) { for (int j = 0; j < noOfAngles; j++) { if (i == j) { continue; } for (int k = 0; k < noOfAngles; k++) { if (i == k || j == k) { continue; } // XXX symmetry! angles[i][j][k] = CoordTranslation.calcAngle(positions, i, j, k); } } } } public double[][][] getBondedAngles() { // XXX this method is unused and makes little sense, IMHO. if (bondedAngles != null) { return bondedAngles; } final int noOfAngles = distances.length; bondedAngles = new double[noOfAngles][noOfAngles][noOfAngles]; for (int i = 0; i < noOfAngles; i++) { for (int j = 0; j < noOfAngles; j++) { if (i == j || !bonds.hasBond(i, j)) { continue; } for (int k = 0; k < noOfAngles; k++) { if (i == k || j == k || !bonds.hasBond(j, k)) { continue; } // XXX symmetry! bondedAngles[i][j][k] = CoordTranslation.calcAngle(positions, i, j, k); } } } return bondedAngles; } public void setDihedrals(double[][][][] dihedrals) { this.dihedrals = dihedrals; } /** * Should only be used when knowing what the memory footprint of this method is. * * @return dihedrals A field of all dihedrals in the system. */ public double[][][][] getDihedrals() { if (dihedrals != null) { return dihedrals; } // initialize dihedrals int iNoOfAngles = distances.length; dihedrals = new double[iNoOfAngles][iNoOfAngles][iNoOfAngles][iNoOfAngles]; for (int i = 0; i < iNoOfAngles; i++) { final double[] daPos1 = {positions[0][i], positions[1][i], positions[2][i]}; for (int j = 0; j < iNoOfAngles; j++) { final double[] daPos2 = {positions[0][j], positions[1][j], positions[2][j]}; for (int k = 0; k < iNoOfAngles; k++) { final double[] daPos3 = {positions[0][k], positions[1][k], positions[2][k]}; for (int l = 0; l < iNoOfAngles; l++) { final double[] daPos4 = {positions[0][l], positions[1][l], positions[2][l]}; if ((i == j) || (j == k) || (i == k) || (i == l) || (j == l) || (k == l)) { dihedrals[i][j][k][l] = Double.NaN; continue; } // compute dihedral // XXX is also not acos aware... if it matters? who knows... dihedrals[i][j][k][l] = CoordTranslation.calcDihedral(daPos1, daPos2, daPos3, daPos4); } } } } return dihedrals; } public boolean does13exist(int i, int j) { for (final int[] c13 : contributions13) { if ((i == c13[0] && j == c13[2]) || (j == c13[0] && i == c13[2])) { return true; } } return false; } public boolean does14exist(int i, int j) { for (final int[] c14 : contributions14) { if ((i == c14[0] && j == c14[3]) || (j == c14[0] && i == c14[3])) { return true; } } return false; } public List<int[]> get13Contributions() { return contributions13; } public List<int[]> get14Contributions() { return contributions14; } public int[][] get13ContributionsField() { return contri13; } public int[][] get14ContributionsField() { return contri14; } public String[] createPrintableCartesians() { final int noAtoms = positions[0].length; final String[] sa = new String[noAtoms + 2]; sa[0] = "" + noAtoms; sa[1] = ""; for (int i = 0; i < noAtoms; i++) { sa[i + 2] = atomNames[i] + "\t" + positions[0][i] * Constants.BOHRTOANG + "\t" + positions[1][i] * Constants.BOHRTOANG + "\t" + positions[2][i] * Constants.BOHRTOANG; } return sa; } private double acos(final double x) { switch (wAcos) { case 0: return Math.acos(x); case 1: return acosLook.acosInter(x); case 2: return acosLook.acosNonInter(x); case 3: return org.apache.commons.math3.util.FastMath.acos(x); default: return Math.acos(x); } } }
package playground.algorithm; public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int middle = left + ((right - left) >> 1); if (nums[middle] == target) { return middle; } if (nums[left] <= nums[middle]) { // 这种情况下数组下面[left, middle]区间内元素递增,包括只有1个元素时的情况,此时nums[left] = nums[middle]。 if (nums[left] <= target && target < nums[middle]) { right = middle - 1; } else { left = middle + 1; } } else { // 这种情况下数组下面[left, middle]区间内元素递增后递减。 if (nums[middle] < target && target <= nums[right]) { left = middle + 1; } else { right = middle - 1; } } } return -1; } }
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Specification of the tax type. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TaxType1", propOrder = { "strd", "addtlInf" }) public class TaxType1 { @XmlElement(name = "Strd", required = true) @XmlSchemaType(name = "string") protected TaxType7Code strd; @XmlElement(name = "AddtlInf") protected String addtlInf; /** * Gets the value of the strd property. * * @return * possible object is * {@link TaxType7Code } * */ public TaxType7Code getStrd() { return strd; } /** * Sets the value of the strd property. * * @param value * allowed object is * {@link TaxType7Code } * */ public TaxType1 setStrd(TaxType7Code value) { this.strd = value; return this; } /** * Gets the value of the addtlInf property. * * @return * possible object is * {@link String } * */ public String getAddtlInf() { return addtlInf; } /** * Sets the value of the addtlInf property. * * @param value * allowed object is * {@link String } * */ public TaxType1 setAddtlInf(String value) { this.addtlInf = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
package ArithmeticCode.SwordToOffer.code; /** * 翻转单词顺序列.md */ public class Test44 { public static void main(String[] args) { System.out.println(new Test44().ReverseSentence("I am a student.")); System.out.println(new Test44().ReverseSentence2("I am a student.")); System.out.println(new Test44().ReverseSentence2("Wonderful")); System.out.println(new Test44().ReverseSentence2("Hello World!")); } //通过空格分隔成字符串组,然后再从后向前拼接 //这里的区分用了api,也可以换成遍历去自己拆分 public String ReverseSentence(String str) { if (str == null || str.length() == 0 || str.trim().equals("")) { return str; } String[] words = str.split(" "); StringBuilder builder = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { builder.append(words[i]); if (i > 0) { builder.append(" "); } } return builder.toString(); } public String ReverseSentence2(String str) { if (str == null || str.length() == 0 || str.trim().equals("")) { return str; } char[] chars = str.toCharArray(); //先翻转整个字符串 reverse(chars, 0, chars.length - 1); //再翻转每个单词 int start = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == ' ') { reverse(chars, start, i - 1); start = i + 1; } } //翻转最后一个单词 reverse(chars, start, chars.length - 1); return String.valueOf(chars); } //翻转chars从start 到 end的字符串 private void reverse(char[] chars, int start, int end) { char temp; while (start < end) { temp = chars[start]; chars[start] = chars[end]; chars[end] = temp; start++; end--; } } }
/* * Copyright (c) 2018 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * Contributors: * Otavio Santana */ package org.eclipse.jnosql.communication.query; import jakarta.nosql.QueryException; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.eclipse.jnosql.communication.query.provider.SelectQueryArgumentProvider; import org.eclipse.jnosql.communication.query.provider.WrongSelectQueryArgumentProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class SelectQueryTest { @ParameterizedTest @ArgumentsSource(SelectQueryArgumentProvider.class) public void shouldExecuteQuery(String query) { testQuery(query); } @Test public void shouldIgnoreComments() { testQuery("//ignore this line \n select * from Person"); } @ParameterizedTest @ArgumentsSource(WrongSelectQueryArgumentProvider.class) public void shouldNotExecute(String query) { Assertions.assertThrows(QueryException.class, () -> testQuery(query)); } private void testQuery(String query) { CharStream stream = CharStreams.fromString(query); QueryLexer lexer = new QueryLexer(stream); CommonTokenStream tokens = new CommonTokenStream(lexer); QueryParser parser = new QueryParser(tokens); lexer.removeErrorListeners(); parser.removeErrorListeners(); lexer.addErrorListener(QueryErrorListener.INSTANCE); parser.addErrorListener(QueryErrorListener.INSTANCE); ParseTree tree = parser.select(); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(new QueryBaseListener(), tree); } }
package io.github.vampirestudios.artifice.api.builder.data.worldgen; import com.google.gson.JsonObject; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.levelgen.DensityFunction; import net.minecraft.world.level.levelgen.synth.NormalNoise; public class JsonHelper { private JsonObject jsonObject; public JsonHelper(JsonObject jsonObject) { this.jsonObject = jsonObject; } public JsonHelper setJsonObject(JsonObject jsonObject) { this.jsonObject = jsonObject; return this; } public JsonHelper minMax(Number min, Number max) { number("min", min); number("max", max); return this; } public JsonHelper minMaxInclusiveExclusive(Number min, Number max) { number("min_inclusive", min); number("max_exclusive", max); return this; } public JsonHelper type(DensityType densityType) { jsonObject.addProperty("type", densityType.getName()); return this; } public JsonHelper input(ResourceKey<DensityFunction> noise) { densityFunction("input", noise); return this; } public JsonHelper string(String name, String string) { jsonObject.addProperty(name, string); return this; } public JsonHelper noise(ResourceKey<NormalNoise.NoiseParameters> string) { jsonObject.addProperty("noise", string.location().toString()); return this; } public JsonHelper noise(String name, ResourceKey<NormalNoise.NoiseParameters> string) { jsonObject.addProperty(name, string.location().toString()); return this; } public JsonHelper densityFunction(String name, ResourceKey<DensityFunction> string) { jsonObject.addProperty(name, string.location().toString()); return this; } public JsonHelper number(String name, Number number) { jsonObject.addProperty(name, number); return this; } public JsonHelper jsonObject(String name, JsonObject innerJsonObject) { jsonObject.add(name, innerJsonObject); return this; } public enum DensityType { INTERPOLATED("minecraft:interpolated"), BLEND_DENSITY("minecraft:blend_density"), SLIDE("minecraft:slide"), RANGE_CHOICE("minecraft:range_choice"), ADD("minecraft:add"), MIN("minecraft:min"), MAX("minecraft:max"), MUL("minecraft:mul"), ABS("minecraft:abs"), NOISE("minecraft:noise"), SHIFTED_NOISE("minecraft:shifted_noise"), CLAMP("minecraft:clamp"), SQUARE("minecraft:square"), SQUEEZE("minecraft:squeeze"), QUARTER_NEGATIVE("minecraft:quarter_negative"), CACHE_2D("minecraft:cache_2d"); private final String name; DensityType(String name) { this.name = name; } public String getName() { return name; } } }
package com.codenameflip.chatchannels.commands; import com.codenameflip.chatchannels.ChatChannels; import com.codenameflip.chatchannels.structure.IChannelRegistry; import org.bukkit.command.CommandExecutor; /** * ChatChannels * * @author Cameron Fletcher * @since 06/03/2018 */ public interface ChatChannelsCommand extends CommandExecutor { default ChatChannels get() { return ChatChannels.getInstance(); } default IChannelRegistry getRegistry() { return ChatChannels.getInstance().getRegistry(); } }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * {@link Resource} implementation for a given byte array. Creates a ByteArrayInputStreams for the given byte array. * * <p> * Useful for loading content from any given byte array, without having to resort to a single-use * {@link InputStreamResource}. * * @author Juergen Hoeller * @since 1.0 * @see java.io.ByteArrayInputStream * @see InputStreamResource */ public class ByteArrayResource extends AbstractResource { private final byte[] byteArray; private final String description; /** * Create a new ByteArrayResource. * @param byteArray the byte array to wrap */ public ByteArrayResource(byte[] byteArray) { this(byteArray, "resource loaded from byte array"); } /** * Create a new ByteArrayResource. * @param byteArray the byte array to wrap * @param description where the byte array comes from */ public ByteArrayResource(byte[] byteArray, String description) { if (byteArray == null) { throw new IllegalArgumentException("Byte array must not be null"); } this.byteArray = byteArray; this.description = (description != null ? description : ""); } /** * Return the underlying byte array. */ public final byte[] getByteArray() { return this.byteArray; } /** * This implementation always returns <code>true</code>. */ @Override public boolean exists() { return true; } /** * This implementation returns the length of the underlying byte array. */ @Override public long contentLength() { return this.byteArray.length; } /** * This implementation returns a ByteArrayInputStream for the underlying byte array. * @see java.io.ByteArrayInputStream */ public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(this.byteArray); } /** * This implementation returns the passed-in description, if any. */ public String getDescription() { return this.description; } /** * This implementation compares the underlying byte array. * @see java.util.Arrays#equals(byte[], byte[]) */ @Override public boolean equals(Object obj) { return (obj == this || (obj instanceof ByteArrayResource && Arrays.equals(((ByteArrayResource) obj).byteArray, this.byteArray))); } /** * This implementation returns the hash code based on the underlying byte array. */ @Override public int hashCode() { return (byte[].class.hashCode() * 29 * this.byteArray.length); } }
@org.checkerframework.framework.qual.DefaultQualifier(org.checkerframework.checker.nullness.qual.Nullable.class) public class MyException extends Exception { public MyException() { } public final String getTotalTrace() { final StringBuilder sb = new StringBuilder(); //:: error: (iterating.over.nullable) for (StackTraceElement st: getStackTrace()) { //:: error: (dereference.of.nullable) sb.append(st.toString()); sb.append("\n"); } return sb.toString(); } @SuppressWarnings("nullness") public StackTraceElement[] getStackTrace() { throw new RuntimeException("not implemented yet"); } }
package ke.co.skyworld.wso2_monitoring; public class UserAccounts { private int user_id; private String user_status; private String user_status_description; private String user_status_date; private String account_access_mode; private String username; private String first_name; private String last_name; private int mobile_number; private String email_address; private String user_pwd_status; private String user_pwd; private String user_pwd_status_date; private int login_attempts; private int max_login_attempts; private String allowed_access_sources_status; private String allowed_access_sources_match_type; private int max_allowed_access_sources; private String allowed_access_sources; private String restricted_access_sources_status; private String restricted_access_sources_match_type; private int max_restricted_access_sources; private String restricted_access_sources; private String tracking_id; private String tracking_source_ip; private String tracking_url; private String tracking_time; private String tracking_referrer; private String gender; private String designation; private String date_created; private String date_modified; public UserAccounts(int user_id, String user_status, String user_status_description, String user_status_date, String account_access_mode, String username, String first_name, String last_name, int mobile_number, String email_address, String user_pwd_status, String user_pwd, String user_pwd_status_date, int login_attempts, int max_login_attempts, String allowed_access_sources_status, String allowed_access_sources_match_type, int max_allowed_access_sources, String allowed_access_sources, String restricted_access_sources_status, String restricted_access_sources_match_type, int max_restricted_access_sources, String restricted_access_sources, String tracking_id, String tracking_source_ip, String tracking_url, String tracking_time, String tracking_referrer, String gender, String designation, String date_created, String date_modified) { this.user_id = user_id; this.user_status = user_status; this.user_status_description = user_status_description; this.user_status_date = user_status_date; this.account_access_mode = account_access_mode; this.username = username; this.first_name = first_name; this.last_name = last_name; this.mobile_number = mobile_number; this.email_address = email_address; this.user_pwd_status = user_pwd_status; this.user_pwd = user_pwd; this.user_pwd_status_date = user_pwd_status_date; this.login_attempts = login_attempts; this.max_login_attempts = max_login_attempts; this.allowed_access_sources_status = allowed_access_sources_status; this.allowed_access_sources_match_type = allowed_access_sources_match_type; this.max_allowed_access_sources = max_allowed_access_sources; this.allowed_access_sources = allowed_access_sources; this.restricted_access_sources_status = restricted_access_sources_status; this.restricted_access_sources_match_type = restricted_access_sources_match_type; this.max_restricted_access_sources = max_restricted_access_sources; this.restricted_access_sources = restricted_access_sources; this.tracking_id = tracking_id; this.tracking_source_ip = tracking_source_ip; this.tracking_url = tracking_url; this.tracking_time = tracking_time; this.tracking_referrer = tracking_referrer; this.gender = gender; this.designation = designation; this.date_created = date_created; this.date_modified = date_modified; } public UserAccounts(){ } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getUser_status() { return user_status; } public void setUser_status(String user_status) { this.user_status = user_status; } public String getUser_status_description() { return user_status_description; } public void setUser_status_description(String user_status_description) { this.user_status_description = user_status_description; } public String getUser_status_date() { return user_status_date; } public void setUser_status_date(String user_status_date) { this.user_status_date = user_status_date; } public String getAccount_access_mode() { return account_access_mode; } public void setAccount_access_mode(String account_access_mode) { this.account_access_mode = account_access_mode; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public int getMobile_number() { return mobile_number; } public void setMobile_number(int mobile_number) { this.mobile_number = mobile_number; } public String getEmail_address() { return email_address; } public void setEmail_address(String email_address) { this.email_address = email_address; } public String getUser_pwd_status() { return user_pwd_status; } public void setUser_pwd_status(String user_pwd_status) { this.user_pwd_status = user_pwd_status; } public String getUser_pwd() { return user_pwd; } public void setUser_pwd(String user_pwd) { this.user_pwd = user_pwd; } public String getUser_pwd_status_date() { return user_pwd_status_date; } public void setUser_pwd_status_date(String user_pwd_status_date) { this.user_pwd_status_date = user_pwd_status_date; } public int getLogin_attempts() { return login_attempts; } public void setLogin_attempts(int login_attempts) { this.login_attempts = login_attempts; } public int getMax_login_attempts() { return max_login_attempts; } public void setMax_login_attempts(int max_login_attempts) { this.max_login_attempts = max_login_attempts; } public String getAllowed_access_sources_status() { return allowed_access_sources_status; } public void setAllowed_access_sources_status(String allowed_access_sources_status) { this.allowed_access_sources_status = allowed_access_sources_status; } public String getAllowed_access_sources_match_type() { return allowed_access_sources_match_type; } public void setAllowed_access_sources_match_type(String allowed_access_sources_match_type) { this.allowed_access_sources_match_type = allowed_access_sources_match_type; } public int getMax_allowed_access_sources() { return max_allowed_access_sources; } public void setMax_allowed_access_sources(int max_allowed_access_sources) { this.max_allowed_access_sources = max_allowed_access_sources; } public String getAllowed_access_sources() { return allowed_access_sources; } public void setAllowed_access_sources(String allowed_access_sources) { this.allowed_access_sources = allowed_access_sources; } public String getRestricted_access_sources_status() { return restricted_access_sources_status; } public void setRestricted_access_sources_status(String restricted_access_sources_status) { this.restricted_access_sources_status = restricted_access_sources_status; } public String getRestricted_access_sources_match_type() { return restricted_access_sources_match_type; } public void setRestricted_access_sources_match_type(String restricted_access_sources_match_type) { this.restricted_access_sources_match_type = restricted_access_sources_match_type; } public int getMax_restricted_access_sources() { return max_restricted_access_sources; } public void setMax_restricted_access_sources(int max_restricted_access_sources) { this.max_restricted_access_sources = max_restricted_access_sources; } public String getRestricted_access_sources() { return restricted_access_sources; } public void setRestricted_access_sources(String restricted_access_sources) { this.restricted_access_sources = restricted_access_sources; } public String getTracking_id() { return tracking_id; } public void setTracking_id(String tracking_id) { this.tracking_id = tracking_id; } public String getTracking_source_ip() { return tracking_source_ip; } public void setTracking_source_ip(String tracking_source_ip) { this.tracking_source_ip = tracking_source_ip; } public String getTracking_url() { return tracking_url; } public void setTracking_url(String tracking_url) { this.tracking_url = tracking_url; } public String getTracking_time() { return tracking_time; } public void setTracking_time(String tracking_time) { this.tracking_time = tracking_time; } public String getTracking_referrer() { return tracking_referrer; } public void setTracking_referrer(String tracking_referrer) { this.tracking_referrer = tracking_referrer; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getDate_created() { return date_created; } public void setDate_created(String date_created) { this.date_created = date_created; } public String getDate_modified() { return date_modified; } public void setDate_modified(String date_modified) { this.date_modified = date_modified; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.spi.java.project.support.ui; import java.awt.EventQueue; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.JComponent; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.netbeans.api.queries.VisibilityQuery; import org.netbeans.spi.project.support.ant.PathMatcher; import org.openide.util.Parameters; import org.openide.util.RequestProcessor; /** * Utility permitting a user to easily see the effect of changing include * and exclude patterns on a source group (or several). * Intended for use in project creation wizards and project properties dialogs. * The exact appearance of the panel is not specified but it should * permit the user to see, and edit, the current set of includes and excludes; * and display the set of files included and excluded by the current pattern. * @see PathMatcher * @since org.netbeans.modules.java.project/1 1.12 * @author Jesse Glick */ public class IncludeExcludeVisualizer { private File[] roots = {}; private String includes = "**"; // NOI18N private String excludes = ""; // NOI18N private final List<ChangeListener> listeners = new ArrayList<ChangeListener>(1); private IncludeExcludeVisualizerPanel panel; private SortedSet<File> included = new TreeSet<File>(); private SortedSet<File> excluded = new TreeSet<File>(); private boolean busy = false; private boolean interrupted = false; private static final RequestProcessor RP = new RequestProcessor(IncludeExcludeVisualizer.class.getName()); private final RequestProcessor.Task task = RP.create(new RecalculateTask()); /** * Create a new visualizer. * Initially has no roots and includes anything (equivalent to * an include pattern of <samp>**</samp> and an empty exclude pattern). */ public IncludeExcludeVisualizer() {} /** * Configure a set of root directories to which the includes and excludes apply. * @param roots a set of valid root directories to search * @throws IllegalArgumentException if roots contains a non-directory or * directory does not exist */ public synchronized void setRoots(File[] roots) throws IllegalArgumentException { Parameters.notNull("roots", roots); for (File root : roots) { if (!root.isDirectory()) { throw new IllegalArgumentException(root.getAbsolutePath()); } } this.roots = roots; recalculate(); } /** * Get the current include pattern. * @return the current pattern (never null) */ public synchronized String getIncludePattern() { return includes; } /** * Set the include pattern. * This does not fire a change event. * @param pattern the new pattern (never null) */ public synchronized void setIncludePattern(String pattern) { Parameters.notNull("pattern", pattern); includes = pattern; updateIncludesExcludes(); recalculate(); } /** * Get the current exclude pattern. * @return the current pattern (never null) */ public synchronized String getExcludePattern() { return excludes; } /** * Set the exclude pattern. * This does not fire a change event. * @param pattern the new pattern (never null) */ public synchronized void setExcludePattern(String pattern) { Parameters.notNull("pattern", pattern); excludes = pattern; updateIncludesExcludes(); recalculate(); } private synchronized void updateIncludesExcludes() { if (panel != null) { EventQueue.invokeLater(new Runnable() { public void run() { panel.setFields(includes, excludes); } }); } } /** * Add a listener to changes made by the user in the includes or excludes. * @param l the listener */ public synchronized void addChangeListener(ChangeListener l) { listeners.add(l); } /** * Remove a change listener. * @param l the listener */ public synchronized void removeChangeListener(ChangeListener l) { listeners.remove(l); } /** * Can be called from IncludeExcludeVisualizerPanel. */ synchronized void changedPatterns(String includes, String excludes) { this.includes = includes; this.excludes = excludes; recalculate(); fireChange(); } private synchronized void fireChange() { ChangeEvent e = new ChangeEvent(this); for (ChangeListener l : listeners) { l.stateChanged(e); } } /** * Get the associated visual panel. * @return a panel displaying this include and exclude information * @throws IllegalThreadStateException if not called in the event thread */ public synchronized JComponent getVisualizerPanel() { if (!EventQueue.isDispatchThread()) { throw new IllegalThreadStateException("must be called in EQ"); } if (panel == null) { panel = new IncludeExcludeVisualizerPanel(this); panel.setFields(includes, excludes); updatePanelFiles(); } return panel; } private void updatePanelFiles() { panel.setFiles(included.toArray(new File[included.size()]), excluded.toArray(new File[excluded.size()]), busy, roots.length == 1 ? roots[0] : null); } private static final int DELAY = 200; private synchronized void recalculate() { interrupted = true; task.schedule(DELAY); } private void updateFiles() { assert Thread.holdsLock(this); EventQueue.invokeLater(new Runnable() { public void run() { synchronized (IncludeExcludeVisualizer.this) { if (panel != null) { updatePanelFiles(); } } } }); } private int scanCounter; private static final int GRANULARITY = 1000; private void scan(File d, String prefix, PathMatcher matcher) { String[] children = d.list(); if (children == null) { return; } for (String child : children) { File f = new File(d, child); if (!VisibilityQuery.getDefault().isVisible(f)) { continue; } boolean dir = f.isDirectory(); if (dir) { scan(f, prefix + child + "/", matcher); // NOI18N } else { synchronized (this) { if (interrupted) { return; } if (matcher.matches(prefix + child, false)) { included.add(f); } else { excluded.add(f); } if (++scanCounter % GRANULARITY == 0) { updateFiles(); } } } } } private final class RecalculateTask implements Runnable { public void run() { File[] _roots; String _includes, _excludes; synchronized (IncludeExcludeVisualizer.this) { busy = true; included.clear(); excluded.clear(); _roots = roots.clone(); _includes = includes; _excludes = excludes; interrupted = false; updateFiles(); } PathMatcher matcher = new PathMatcher(_includes, _excludes, null); for (File root : _roots) { scan(root, "", matcher); } synchronized (IncludeExcludeVisualizer.this) { busy = false; updateFiles(); } } } }
/* * ResponseListener * Connect SDK * * Copyright (c) 2014 LG Electronics. * Created by Hyun Kook Khang on 19 Jan 2014 * * 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.connectsdk.service.capability.listeners; /** * Generic asynchronous operation response success handler block. If there is any response data to be processed, it will be provided via the responseObject parameter. * * @param responseObject Contains the output data as a generic object reference. This value may be any of a number of types as defined by T in subclasses of ResponseListener. It is also possible that responseObject will be nil for operations that don't require data to be returned (move mouse, send key code, etc). */ public interface ResponseListener<T> extends ErrorListener { /** * Returns the success of the call of type T. * * @param object Response object, can be any number of object types, depending on the protocol/capability/etc */ abstract public void onSuccess(T object); }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.portfolio.savings.service; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.math.BigDecimal; import java.security.SecureRandom; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.concurrent.Callable; import org.apache.fineract.accounting.journalentry.domain.JournalEntryType; import org.apache.fineract.batch.command.CommandStrategyProvider; import org.apache.fineract.batch.service.ResolutionHelper; import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService; import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant; import org.apache.fineract.infrastructure.core.service.DateUtils; import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil; import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException; import org.apache.fineract.portfolio.savings.data.SavingsAccountData; import org.apache.fineract.portfolio.savings.data.SavingsAccountSummaryData; import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData; import org.apache.fineract.portfolio.savings.domain.SavingsAccountAssembler; import org.apache.fineract.portfolio.savings.domain.SavingsAccountRepositoryWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.dao.CannotAcquireLockException; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; /** * @author manoj */ @Component @Scope("prototype") public class SavingsSchedularInterestPoster implements Callable<Void> { private static final Logger LOG = LoggerFactory.getLogger(SavingsSchedularInterestPoster.class); private static final SecureRandom random = new SecureRandom(); private static final String SAVINGS_TRANSACTION_IDENTIFIER = "S"; private Collection<SavingsAccountData> savingAccounts; private SavingsAccountWritePlatformService savingsAccountWritePlatformService; private SavingsAccountRepositoryWrapper savingsAccountRepository; private SavingsAccountAssembler savingAccountAssembler; private FineractPlatformTenant tenant; private ConfigurationDomainService configurationDomainService; private boolean backdatedTxnsAllowedTill; private List<SavingsAccountData> savingsAccountDataList = new ArrayList<>(); private JdbcTemplate jdbcTemplate; private TransactionTemplate transactionTemplate; private CommandStrategyProvider strategyProvider; private ResolutionHelper resolutionHelper; private SavingsAccountReadPlatformService savingsAccountReadPlatformService; public void setSavings(Collection<SavingsAccountData> savingAccounts) { this.savingAccounts = savingAccounts; } public void setBackdatedTxnsAllowedTill(final boolean backdatedTxnsAllowedTill) { this.backdatedTxnsAllowedTill = backdatedTxnsAllowedTill; } public void setSavingsAccountWritePlatformService(SavingsAccountWritePlatformService savingsAccountWritePlatformService) { this.savingsAccountWritePlatformService = savingsAccountWritePlatformService; } public void setSavingsAccountReadPlatformService(SavingsAccountReadPlatformService savingsAccountReadPlatformService) { this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; } public void setSavingsAccountRepository(SavingsAccountRepositoryWrapper savingsAccountRepository) { this.savingsAccountRepository = savingsAccountRepository; } public void setSavingAccountAssembler(SavingsAccountAssembler savingAccountAssembler) { this.savingAccountAssembler = savingAccountAssembler; } public void setTenant(FineractPlatformTenant tenant) { this.tenant = tenant; } public void setConfigurationDomainService(ConfigurationDomainService configurationDomainService) { this.configurationDomainService = configurationDomainService; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void setResolutionHelper(ResolutionHelper resolutionHelper) { this.resolutionHelper = resolutionHelper; } public void setStrategyProvider(CommandStrategyProvider commandStrategyProvider) { this.strategyProvider = commandStrategyProvider; } @Override @SuppressFBWarnings(value = { "DMI_RANDOM_USED_ONLY_ONCE" }, justification = "False positive for random object created and used only once") public Void call() throws org.apache.fineract.infrastructure.jobs.exception.JobExecutionException { ThreadLocalContextUtil.setTenant(tenant); Integer maxNumberOfRetries = tenant.getConnection().getMaxRetriesOnDeadlock(); Integer maxIntervalBetweenRetries = tenant.getConnection().getMaxIntervalBetweenRetries(); // List<BatchResponse> responseList = new ArrayList<>(); long start = System.currentTimeMillis(); LOG.info("Thread Execution Started at {}", start); List<Throwable> errors = new ArrayList<>(); int i = 0; if (!savingAccounts.isEmpty()) { for (SavingsAccountData savingsAccountData : savingAccounts) { Integer numberOfRetries = 0; while (numberOfRetries <= maxNumberOfRetries) { try { boolean postInterestAsOn = false; LocalDate transactionDate = null; long startPosting = System.currentTimeMillis(); SavingsAccountData savingsAccountDataRet = savingsAccountWritePlatformService.postInterest(savingsAccountData, postInterestAsOn, transactionDate, backdatedTxnsAllowedTill); long endPosting = System.currentTimeMillis(); savingsAccountDataList.add(savingsAccountDataRet); LOG.info("Posting Completed Within {}", endPosting - startPosting); numberOfRetries = maxNumberOfRetries + 1; } catch (CannotAcquireLockException | ObjectOptimisticLockingFailureException exception) { LOG.info("Interest posting job for savings ID {} has been retried {} time(s)", savingsAccountData.getId(), numberOfRetries); // Fail if the transaction has been retired for // maxNumberOfRetries if (numberOfRetries >= maxNumberOfRetries) { LOG.error( "Interest posting job for savings ID {} has been retried for the max allowed attempts of {} and will be rolled back", savingsAccountData.getId(), numberOfRetries); errors.add(exception); break; } // Else sleep for a random time (between 1 to 10 // seconds) and continue try { int randomNum = random.nextInt(maxIntervalBetweenRetries + 1); Thread.sleep(1000 + (randomNum * 1000)); numberOfRetries = numberOfRetries + 1; } catch (InterruptedException e) { LOG.error("Interest posting job for savings retry failed due to InterruptedException", e); errors.add(e); break; } } catch (Exception e) { LOG.error("Interest posting job for savings failed for account {}", savingsAccountData.getId(), e); numberOfRetries = maxNumberOfRetries + 1; errors.add(e); } } i++; } if (errors.isEmpty()) { try { batchUpdate(savingsAccountDataList); } catch (DataAccessException exception) { LOG.error("Batch update failed due to DataAccessException", exception); errors.add(exception); } catch (NullPointerException exception) { LOG.error("Batch update failed due to NullPointerException", exception); errors.add(exception); } } if (!errors.isEmpty()) { throw new JobExecutionException(errors); } } long end = System.currentTimeMillis(); LOG.info("Time To Finish the batch {} by thread {} for accounts {}", end - start, Thread.currentThread().getId(), savingAccounts.size()); return null; } @Transactional(isolation = Isolation.READ_UNCOMMITTED, rollbackFor = Exception.class) private void batchUpdateJournalEntries(final List<SavingsAccountData> savingsAccountDataList, final HashMap<String, SavingsAccountTransactionData> savingsAccountTransactionDataHashMap) throws DataAccessException, NullPointerException { String queryForJGLUpdate = batchQueryForJournalEntries(); List<Object[]> paramsForGLInsertion = new ArrayList<>(); for (SavingsAccountData savingsAccountData : savingsAccountDataList) { String currencyCode = savingsAccountData.getCurrency().getCode(); List<SavingsAccountTransactionData> savingsAccountTransactionDataList = savingsAccountData.getSavingsAccountTransactionData(); for (SavingsAccountTransactionData savingsAccountTransactionData : savingsAccountTransactionDataList) { if (savingsAccountTransactionData.getId() == null) { final String key = savingsAccountTransactionData.getRefNo(); if (savingsAccountTransactionDataHashMap.containsKey(key)) { LocalDate currentDate = DateUtils.getLocalDateOfTenant(); final SavingsAccountTransactionData dataFromFetch = savingsAccountTransactionDataHashMap.get(key); savingsAccountTransactionData.setId(dataFromFetch.getId()); paramsForGLInsertion.add( new Object[] { savingsAccountData.getGlAccountIdForSavingsControl(), savingsAccountData.getOfficeId(), null, currencyCode, SAVINGS_TRANSACTION_IDENTIFIER + savingsAccountTransactionData.getId().toString(), savingsAccountTransactionData.getId(), null, false, null, false, Date.from(savingsAccountTransactionData.getTransactionDate() .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), JournalEntryType.CREDIT.getValue().longValue(), savingsAccountTransactionData.getAmount(), null, JournalEntryType.CREDIT.getValue().longValue(), savingsAccountData.getId(), Date.from(currentDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), Date.from(currentDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), false, BigDecimal.ZERO, BigDecimal.ZERO, null, Date.from(savingsAccountTransactionData.getTransactionDate() .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), null, Integer.valueOf(1), Integer.valueOf(1) }); paramsForGLInsertion.add(new Object[] { savingsAccountData.getGlAccountIdForInterestOnSavings(), savingsAccountData.getOfficeId(), null, currencyCode, SAVINGS_TRANSACTION_IDENTIFIER + savingsAccountTransactionData.getId().toString(), savingsAccountTransactionData.getId(), null, false, null, false, Date.from(savingsAccountTransactionData.getTransactionDate() .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), JournalEntryType.DEBIT.getValue().longValue(), savingsAccountTransactionData.getAmount(), null, JournalEntryType.DEBIT.getValue().longValue(), savingsAccountData.getId(), Date.from(currentDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), Date.from(currentDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), false, BigDecimal.ZERO, BigDecimal.ZERO, null, Date.from(savingsAccountTransactionData.getTransactionDate() .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()), null, Integer.valueOf(1), Integer.valueOf(1) }); } } } } if (paramsForGLInsertion != null && paramsForGLInsertion.size() > 0) { this.jdbcTemplate.batchUpdate(queryForJGLUpdate, paramsForGLInsertion); } } private String batchQueryForJournalEntries() { StringBuilder query = new StringBuilder(100); query.append("INSERT INTO acc_gl_journal_entry(account_id,office_id,reversal_id,currency_code,transaction_id,"); query.append("savings_transaction_id,client_transaction_id,reversed,ref_num,manual_entry,entry_date,type_enum,"); query.append("amount,description,entity_type_enum,entity_id,created_date,"); query.append("lastmodified_date,is_running_balance_calculated,office_running_balance,organization_running_balance,"); query.append("payment_details_id,transaction_date,share_transaction_id, createdby_id, lastmodifiedby_id) "); query.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); return query.toString(); } private List<SavingsAccountTransactionData> fetchTransactionsFromIds(final List<String> refNo) throws DataAccessException { return this.savingsAccountReadPlatformService.retrieveAllTransactionData(refNo); } @Transactional(isolation = Isolation.READ_UNCOMMITTED) @SuppressWarnings("unused") private void batchUpdate(final List<SavingsAccountData> savingsAccountDataList) throws DataAccessException { String queryForSavingsUpdate = batchQueryForSavingsSummaryUpdate(); String queryForTransactionInsertion = batchQueryForTransactionInsertion(); List<Object[]> paramsForTransactionInsertion = new ArrayList<>(); List<Object[]> paramsForSavingsSummary = new ArrayList<>(); List<String> transRefNo = new ArrayList<>(); for (SavingsAccountData savingsAccountData : savingsAccountDataList) { SavingsAccountSummaryData savingsAccountSummaryData = savingsAccountData.getSummary(); paramsForSavingsSummary.add(new Object[] { savingsAccountSummaryData.getTotalDeposits(), savingsAccountSummaryData.getTotalWithdrawals(), savingsAccountSummaryData.getTotalInterestEarned(), savingsAccountSummaryData.getTotalInterestPosted(), savingsAccountSummaryData.getTotalWithdrawalFees(), savingsAccountSummaryData.getTotalFeeCharge(), savingsAccountSummaryData.getTotalPenaltyCharge(), savingsAccountSummaryData.getTotalAnnualFees(), savingsAccountSummaryData.getAccountBalance(), savingsAccountSummaryData.getTotalOverdraftInterestDerived(), savingsAccountSummaryData.getTotalWithholdTax(), Date.from(savingsAccountSummaryData.getLastInterestCalculationDate().atStartOfDay(DateUtils.getDateTimeZoneOfTenant()) .toInstant()), Date.from(savingsAccountSummaryData.getInterestPostedTillDate().atStartOfDay(DateUtils.getDateTimeZoneOfTenant()) .toInstant()), savingsAccountData.getId() }); List<SavingsAccountTransactionData> savingsAccountTransactionDataList = savingsAccountData.getSavingsAccountTransactionData(); for (SavingsAccountTransactionData savingsAccountTransactionData : savingsAccountTransactionDataList) { if (savingsAccountTransactionData.getId() == null) { UUID uuid = UUID.randomUUID(); savingsAccountTransactionData.setRefNo(uuid.toString()); transRefNo.add(uuid.toString()); java.util.Date balanceEndDate = null; if (savingsAccountTransactionData.getBalanceEndDate() != null) { balanceEndDate = Date.from(savingsAccountTransactionData.getBalanceEndDate() .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); } paramsForTransactionInsertion.add(new Object[] { savingsAccountData.getId(), savingsAccountData.getOfficeId(), savingsAccountTransactionData.getTransactionType().getId(), Date.from(savingsAccountTransactionData.getTransactionDate().atStartOfDay(DateUtils.getDateTimeZoneOfTenant()) .toInstant()), savingsAccountTransactionData.getAmount(), balanceEndDate, savingsAccountTransactionData.getBalanceNumberOfDays(), savingsAccountTransactionData.getRunningBalance(), savingsAccountTransactionData.getCumulativeBalance(), savingsAccountTransactionData.getSubmittedOnDate(), Integer.valueOf(1), savingsAccountTransactionData.isManualTransaction(), savingsAccountTransactionData.getRefNo() }); } } savingsAccountData.setUpdatedTransactions(savingsAccountTransactionDataList); } if (transRefNo.size() > 0) { this.jdbcTemplate.batchUpdate(queryForSavingsUpdate, paramsForSavingsSummary); this.jdbcTemplate.batchUpdate(queryForTransactionInsertion, paramsForTransactionInsertion); List<SavingsAccountTransactionData> savingsAccountTransactionDataList = fetchTransactionsFromIds(transRefNo); if (savingsAccountDataList != null) { LOG.info("Fetched Transactions from DB: {}", savingsAccountTransactionDataList.size()); } HashMap<String, SavingsAccountTransactionData> savingsAccountTransactionMap = new HashMap<>(); for (SavingsAccountTransactionData savingsAccountTransactionData : savingsAccountTransactionDataList) { final String key = savingsAccountTransactionData.getRefNo(); savingsAccountTransactionMap.put(key, savingsAccountTransactionData); } batchUpdateJournalEntries(savingsAccountDataList, savingsAccountTransactionMap); } } private String batchQueryForTransactionInsertion() { StringBuilder query = new StringBuilder(100); query.append("INSERT INTO m_savings_account_transaction (savings_account_id, office_id, is_reversed,"); query.append("transaction_type_enum, transaction_date, amount, balance_end_date_derived,"); query.append("balance_number_of_days_derived, running_balance_derived, cumulative_balance_derived,"); query.append("created_date, appuser_id, is_manual, is_loan_disbursement, ref_no) VALUES "); query.append("(?, ?, false, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, false, ?)"); return query.toString(); } private String batchQueryForSavingsSummaryUpdate() { StringBuilder query = new StringBuilder(100); query.append("update m_savings_account set total_deposits_derived=?, total_withdrawals_derived=?, "); query.append("total_interest_earned_derived=?, total_interest_posted_derived=?, total_withdrawal_fees_derived=?, "); query.append("total_fees_charge_derived=?, total_penalty_charge_derived=?, total_annual_fees_derived=?, "); query.append("account_balance_derived=?, total_overdraft_interest_derived=?, total_withhold_tax_derived=?, "); query.append("last_interest_calculation_date=?, interest_posted_till_date=? where id=?"); return query.toString(); } }
package Utils; import jakarta.faces.view.ViewScoped; import jakarta.inject.Named; import java.io.Serializable; /** * * @author csgn */ @Named("navigation") @ViewScoped public class Navigation implements Serializable { final private String path = "/modules/"; final private String extension = ".xhtml"; private String content = "home"; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String fullPath() { return path + content + extension; } }
package vip.mate.core.file.util; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; /** * Excel导入导出工具类 * @author pangu */ public class ExcelUtil { /** * 导出工具类 * @param list * @param title * @param sheetName * @param pojoClass * @param fileName * @param isCreateHeader * @param response */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response){ ExportParams exportParams = new ExportParams(title, sheetName); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } /** * 导出工具类 * @param list * @param title * @param sheetName * @param pojoClass * @param fileName * @param response */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){ defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){ defaultExport(list, fileName, response); } private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) { Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list); if (workbook != null); downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { //throw new NormalException(e.getMessage()); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){ if (StringUtils.isBlank(filePath)){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); }catch (NoSuchElementException e){ //throw new NormalException("模板不能为空"); } catch (Exception e) { e.printStackTrace(); //throw new NormalException(e.getMessage()); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){ if (file == null){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); }catch (NoSuchElementException e){ // throw new NormalException("excel文件不能为空"); } catch (Exception e) { //throw new NormalException(e.getMessage()); System.out.println(e.getMessage()); } return list; } }
import entity.Person; import entity.Student; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; public class StringFormatterTest { @Test public void format1() { StringFormatter stringFormatter = new StringFormatter(null); Assert.assertNull(stringFormatter.toString()); stringFormatter = new StringFormatter(""); Assert.assertEquals(stringFormatter.toString(), ""); stringFormatter = new StringFormatter("123"); Assert.assertEquals(stringFormatter.toString(), "123"); stringFormatter = new StringFormatter("{}"); Assert.assertEquals(stringFormatter.toString(), "{}"); stringFormatter = new StringFormatter("{}"); Assert.assertEquals(stringFormatter.formatString("123").toString(), "123"); stringFormatter = new StringFormatter("{}"); Assert.assertEquals(stringFormatter.formatString("123", "456").toString(), "123"); stringFormatter = new StringFormatter("{}{}"); Assert.assertEquals(stringFormatter.formatString("123", "456").toString(), "123456"); stringFormatter = new StringFormatter("{}{}{}"); Assert.assertEquals(stringFormatter.formatString("abc", "efg").toString(), "abcefg{}"); stringFormatter = new StringFormatter("{}{}{}"); Assert.assertEquals( "abcefg{}", stringFormatter. formatString("abc"). formatString("efg"). toString()); stringFormatter = new StringFormatter("this is {} and {} and {}"); Assert.assertEquals( "this is abc and efg and hij", stringFormatter. formatString("abc"). formatString("efg"). formatString("hij"). toString()); } @Test public void format2() { StringFormatter stringFormatter = new StringFormatter("my name is {name}"); try { stringFormatter.format(null, ""); Assert.fail(); } catch (Exception ignored) { } try { stringFormatter.format("", ""); Assert.fail(); } catch (Exception ignored) { } String replacement = null; try { stringFormatter.format("name", replacement); Assert.fail(); } catch (Exception ignored) { } Assert.assertEquals( "my name is Levy", stringFormatter.format("name", "Levy").toString()); stringFormatter = new StringFormatter("my name is {name}, and I'm {age} years old."); Assert.assertEquals( "my name is Levy, and I'm 40 years old.", stringFormatter. format("name", "Levy"). format("age", "40").toString()); Assert.assertEquals( "my name is Levy, and I'm 40 years old.", stringFormatter. format("name", "Levy"). format("age", 40).toString()); Assert.assertEquals( "my name is Levy, and I'm 40 years old.", stringFormatter. format("name", "Levy"). format("age", 40L).toString()); stringFormatter = new StringFormatter("my name is {name}, and the number is {number}."); Assert.assertEquals( "my name is Levy, and the number is 40.1.", stringFormatter. format("name", "Levy"). format("number", 40.1).toString()); stringFormatter = new StringFormatter("my name is {name}, and the number is {number}."); BigDecimal bigDecimal = new BigDecimal("50.111111"); Assert.assertEquals( "my name is Levy, and the number is 50.111111.", stringFormatter. format("name", "Levy"). format("number", bigDecimal).toString()); stringFormatter = new StringFormatter("my name is {name}, and the number is {number}."); Integer integer = 15; Assert.assertEquals( "my name is Levy, and the number is 15.", stringFormatter. format("name", "Levy"). format("number", integer).toString()); } @Test public void format3() { StringFormatter stringFormatter = new StringFormatter("my name is {name}, and the number is {number}."); Map<String, Object> replacement = null; Assert.assertEquals( "my name is {name}, and the number is {number}.", stringFormatter. format(replacement).toString()); replacement = new HashMap<>(); replacement.put("aaa", 123); Assert.assertEquals( "my name is {name}, and the number is {number}.", stringFormatter. format(replacement).toString()); replacement = new HashMap<>(); replacement.put("name", "Levy"); replacement.put("number", 15); Assert.assertEquals( "my name is Levy, and the number is 15.", stringFormatter. format(replacement).toString()); } @Test public void format4() { StringFormatter stringFormatter = new StringFormatter("my name is {name}, and I'm {age} years old, and the number is {number}."); Person person = new Person(); Assert.assertEquals( "my name is {name}, and I'm {age} years old, and the number is {number}.", stringFormatter. format(person).toString()); person.setName("Levy"); Assert.assertEquals( "my name is Levy, and I'm {age} years old, and the number is {number}.", stringFormatter. format(person).toString()); person.setName("Levy"); person.setAge(40); Assert.assertEquals( "my name is Levy, and I'm 40 years old, and the number is {number}.", stringFormatter. format(person).toString()); Student student = new Student(); student.setName("Levy"); student.setAge(40); student.setNumber(15L); Assert.assertEquals( "my name is Levy, and I'm 40 years old, and the number is 15.", stringFormatter. format(student).toString()); } }
package nextstep.subway.line.domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @DisplayName("지하철 노선 단위 테스트") public class LineStationsTest { private LineStations lineStations; @BeforeEach void setUp() { // given lineStations = new LineStations(); lineStations.add(new LineStation(1L, null, 10, 10)); lineStations.add(new LineStation(2L, 1L, 10, 10)); lineStations.add(new LineStation(3L, 2L, 10, 10)); } @DisplayName("지하철 노선에 역을 마지막에 등록한다.") @Test void add1() { // when lineStations.add(new LineStation(4L, 3L, 10, 10)); // then 역의_순서가_예상과_일치함(lineStations, Arrays.asList(1L, 2L, 3L, 4L)); } @DisplayName("지하철 노선에 역을 중간에 등록한다.") @Test void add2() { // when lineStations.add(new LineStation(4L, 1L, 10, 10)); // then 역의_순서가_예상과_일치함(lineStations, Arrays.asList(1L, 4L, 2L, 3L)); } @DisplayName("이미 등록되어 있던 역을 등록한다.") @Test void add3() { // when assertThatThrownBy(() -> lineStations.add(new LineStation(2L, 1L, 10, 10))) .isInstanceOf(RuntimeException.class); } @DisplayName("지하철 노선에 등록된 마지막 지하철역을 제외한다.") @Test void removeLineStation1() { // when lineStations.removeByStationId(3L); // then 역의_순서가_예상과_일치함(lineStations, Arrays.asList(1L, 2L)); } @DisplayName("지하철 노선에 등록된 중간 지하철역을 제외한다.") @Test void removeLineStation2() { // when lineStations.removeByStationId(2L); // then 역의_순서가_예상과_일치함(lineStations, Arrays.asList(1L, 3L)); } @DisplayName("지하철 노선의 출발점을 제외한다.") @Test void removeLineStation3() { // when lineStations.removeByStationId(1L); // then 역의_순서가_예상과_일치함(lineStations, Arrays.asList(2L, 3L)); } @DisplayName("지하철 노선에서 등록되지 않는 역을 제외한다.") @Test void removeLineStation4() { // when assertThatThrownBy(() -> lineStations.removeByStationId(4L)) .isInstanceOf(RuntimeException.class); } public void 역의_순서가_예상과_일치함(LineStations lineStations, List<Long> expectedStationIds) { List<Long> stationIds = lineStations.getStationsInOrder().stream() .map(LineStation::getStationId) .collect(Collectors.toList()); assertThat(stationIds).isEqualTo(expectedStationIds); } }
/* * Copyright © 2018 Apple Inc. and the ServiceTalk project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.servicetalk.concurrent.api; import io.servicetalk.concurrent.internal.SignalOffloader; import static io.servicetalk.concurrent.Cancellable.IGNORE_CANCEL; /** * A {@link Single} that does not expect to receive a call to {@link #handleSubscribe(Subscriber)} since it overrides * {@link #handleSubscribe(Subscriber, SignalOffloader)}. * * @param <T> Type of the result of the single. */ abstract class AbstractNoHandleSubscribeSingle<T> extends Single<T> { AbstractNoHandleSubscribeSingle() { } AbstractNoHandleSubscribeSingle(Executor executor) { super(executor); } @Override protected final void handleSubscribe(Subscriber<? super T> subscriber) { subscriber.onSubscribe(IGNORE_CANCEL); subscriber.onError(new UnsupportedOperationException("Subscribe with no executor is not supported for " + getClass())); } }
/* * Copyright 2013-2017 consulo.io * * 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 consulo.csharp.lang.psi.impl.source; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import consulo.annotation.access.RequiredReadAction; import consulo.csharp.lang.psi.CSharpElementVisitor; import consulo.csharp.lang.psi.impl.DotNetTypes2; import consulo.csharp.lang.psi.impl.source.resolve.type.CSharpGenericWrapperTypeRef; import consulo.csharp.lang.psi.impl.source.resolve.type.CSharpTypeRefByQName; import consulo.dotnet.psi.DotNetExpression; import consulo.dotnet.resolve.DotNetTypeRef; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author VISTALL * @since 29.11.14 */ public class CSharpLinqQueryBodyImpl extends CSharpElementImpl { public CSharpLinqQueryBodyImpl(@Nonnull IElementType elementType) { super(elementType); } @Nonnull @RequiredReadAction public DotNetTypeRef calcTypeRef(boolean skipContinuation) { CSharpLinqSelectOrGroupClauseImpl selectOrGroupClause = getSelectOrGroupClause(); if(selectOrGroupClause == null) { return DotNetTypeRef.ERROR_TYPE; } if(!skipContinuation) { CSharpLinqQueryContinuationImpl queryContinuation = getQueryContinuation(); if(queryContinuation != null) { CSharpLinqQueryBodyImpl queryBody = queryContinuation.getQueryBody(); if(queryBody != null) { return queryBody.calcTypeRef(false); } } } DotNetTypeRef innerTypeRef; if(selectOrGroupClause.isGroup()) { DotNetTypeRef[] arguments = new DotNetTypeRef[] {typeRefOrError(selectOrGroupClause.getSecondExpression()), typeRefOrError(selectOrGroupClause.getFirstExpression())}; innerTypeRef = new CSharpGenericWrapperTypeRef(getProject(), getResolveScope(), new CSharpTypeRefByQName(getProject(), getResolveScope(), DotNetTypes2.System.Linq.IGrouping$2), arguments); } else { innerTypeRef = typeRefOrError(selectOrGroupClause.getFirstExpression()); } if(innerTypeRef != DotNetTypeRef.ERROR_TYPE) { CSharpTypeRefByQName enumerableTypeRef = new CSharpTypeRefByQName(getProject(), getResolveScope(), DotNetTypes2.System.Collections.Generic.IEnumerable$1); return new CSharpGenericWrapperTypeRef(getProject(), getResolveScope(), enumerableTypeRef, innerTypeRef); } return DotNetTypeRef.ERROR_TYPE; } @Nonnull private static DotNetTypeRef typeRefOrError(@Nullable DotNetExpression expression) { return expression == null ? DotNetTypeRef.ERROR_TYPE : expression.toTypeRef(true); } @Nullable public CSharpLinqSelectOrGroupClauseImpl getSelectOrGroupClause() { return findChildByClass(CSharpLinqSelectOrGroupClauseImpl.class); } @Nullable public CSharpLinqQueryContinuationImpl getQueryContinuation() { return findChildByClass(CSharpLinqQueryContinuationImpl.class); } @Override public boolean processDeclarations(@Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, PsiElement lastParent, @Nonnull PsiElement place) { if(lastParent == null || !PsiTreeUtil.isAncestor(this, lastParent, false)) { return true; } for(PsiElement psiElement : getChildren()) { if(!psiElement.processDeclarations(processor, state, lastParent, place)) { return false; } } return super.processDeclarations(processor, state, lastParent, place); } @Override public void accept(@Nonnull CSharpElementVisitor visitor) { visitor.visitLinqQueryBody(this); } }
package gms.dataacquisition.seedlink.clientlibrary.data.formats; import gms.dataacquisition.seedlink.clientlibrary.data.Format.Uncompressed; public class Ascii extends Uncompressed { @Override public int code() { return 0; } @Override public int sampleLength() { return 1; } @Override public String name() { return "ASCII"; } @Override public Number[] samples(byte[] data, int numSamp, boolean bigEndian) throws Exception { throw new UnsupportedOperationException(); } }
package Catman2D.Logic; public interface LogicListener { public abstract void onUpdate(); }
/* * The MIT License * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.business.delegate; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests that Business Delegate example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. * * Solution: Inserted assertion to check whether the execution of the main method in {@link App} * throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.error.future; import java.util.concurrent.Future; import org.assertj.core.error.BasicErrorMessageFactory; import org.assertj.core.error.ErrorMessageFactory; public class ShouldNotBeDone extends BasicErrorMessageFactory { private static final String SHOULD_NOT_BE_DONE = "%nExpecting%n <%s>%nnot to be done.%n" + Warning.WARNING; public static ErrorMessageFactory shouldNotBeDone(Future<?> actual) { return new ShouldNotBeDone(actual); } private ShouldNotBeDone(Future<?> actual) { super(SHOULD_NOT_BE_DONE, actual); } }
// SPDX-License-Identifier: MIT package com.mercedesbenz.sechub.owaspzapwrapper.config; import java.io.File; import java.io.IOException; import com.mercedesbenz.sechub.commons.TextFileReader; import com.mercedesbenz.sechub.commons.model.SecHubScanConfiguration; import com.mercedesbenz.sechub.commons.model.SecHubWebScanConfiguration; import com.mercedesbenz.sechub.owaspzapwrapper.cli.MustExitCode; import com.mercedesbenz.sechub.owaspzapwrapper.cli.MustExitRuntimeException; public class SechubWebConfigProvider { public SecHubWebScanConfiguration getSecHubWebConfiguration(File secHubConfigFile) { TextFileReader fileReader = new TextFileReader(); if (secHubConfigFile == null) { // can happen when an unauthenticated scan is started with only the target URL return new SecHubWebScanConfiguration(); } String sechubConfigJson; SecHubScanConfiguration sechubConfig; try { sechubConfigJson = fileReader.loadTextFile(secHubConfigFile); sechubConfig = SecHubScanConfiguration.createFromJSON(sechubConfigJson); } catch (IOException e) { throw new MustExitRuntimeException("Was not able to read sechub config file: " + secHubConfigFile, e, MustExitCode.SECHUB_CONFIGURATION_INVALID); } return getSecHubWebConfiguration(sechubConfig); } private SecHubWebScanConfiguration getSecHubWebConfiguration(SecHubScanConfiguration sechubConfig) { if (sechubConfig == null) { throw new MustExitRuntimeException("SecHub web scan configuration may not be null at this point.", MustExitCode.SECHUB_CONFIGURATION_INVALID); } return sechubConfig.getWebScan().get(); } }
package com.dremio.exec.store.jdbc.dialect.arp; import com.fasterxml.jackson.annotation.*; import com.google.common.collect.*; import java.util.*; public class VariableOperatorDefinition extends OperatorDefinition { VariableOperatorDefinition(@JsonProperty("names") final List<String> names, @JsonProperty("variable_signatures") final List<VarArgsRewritingSignature> signatures) { super(names, (List<Signature>)ImmutableList.copyOf((Collection)signatures)); } }
/* * Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.support.model.transform; import java.util.Map; import java.util.Map.Entry; import java.math.*; import java.nio.ByteBuffer; import com.amazonaws.services.support.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeSeverityLevelsResult JSON Unmarshaller */ public class DescribeSeverityLevelsResultJsonUnmarshaller implements Unmarshaller<DescribeSeverityLevelsResult, JsonUnmarshallerContext> { public DescribeSeverityLevelsResult unmarshall( JsonUnmarshallerContext context) throws Exception { DescribeSeverityLevelsResult describeSeverityLevelsResult = new DescribeSeverityLevelsResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("severityLevels", targetDepth)) { context.nextToken(); describeSeverityLevelsResult .setSeverityLevels(new ListUnmarshaller<SeverityLevel>( SeverityLevelJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeSeverityLevelsResult; } private static DescribeSeverityLevelsResultJsonUnmarshaller instance; public static DescribeSeverityLevelsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeSeverityLevelsResultJsonUnmarshaller(); return instance; } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; import org.springframework.beans.factory.parsing.SourceExtractor; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinitionReader; import org.springframework.beans.factory.support.BeanDefinitionReader; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.MethodMetadata; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Reads a given fully-populated set of ConfigurationClass instances, registering bean * definitions with the given {@link BeanDefinitionRegistry} based on its contents. * * <p>This class was modeled after the {@link BeanDefinitionReader} hierarchy, but does * not implement/extend any of its artifacts as a set of configuration classes is not a * {@link Resource}. * * @author Chris Beams * @author Juergen Hoeller * @author Phillip Webb * @author Sam Brannen * @since 3.0 * @see ConfigurationClassParser */ class ConfigurationClassBeanDefinitionReader { private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class); private static final ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver(); private final BeanDefinitionRegistry registry; private final SourceExtractor sourceExtractor; private final ResourceLoader resourceLoader; private final Environment environment; private final BeanNameGenerator importBeanNameGenerator; private final ImportRegistry importRegistry; private final ConditionEvaluator conditionEvaluator; /** * Create a new {@link ConfigurationClassBeanDefinitionReader} instance * that will be used to populate the given {@link BeanDefinitionRegistry}. */ ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor, ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator, ImportRegistry importRegistry) { this.registry = registry; this.sourceExtractor = sourceExtractor; this.resourceLoader = resourceLoader; this.environment = environment; this.importBeanNameGenerator = importBeanNameGenerator; this.importRegistry = importRegistry; this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader); } /** * Read {@code configurationModel}, registering bean definitions * with the registry based on its contents. */ public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) { TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator(); for (ConfigurationClass configClass : configurationModel) { loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator); } } /** * Read a particular {@link ConfigurationClass}, registering bean definitions * for the class itself and all of its {@link Bean} methods. */ private void loadBeanDefinitionsForConfigurationClass( ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) { if (trackedConditionEvaluator.shouldSkip(configClass)) { String beanName = configClass.getBeanName(); if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) { this.registry.removeBeanDefinition(beanName); } this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName()); return; } if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); } for (BeanMethod beanMethod : configClass.getBeanMethods()) { loadBeanDefinitionsForBeanMethod(beanMethod); } loadBeanDefinitionsFromImportedResources(configClass.getImportedResources()); loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars()); } /** * Register the {@link Configuration} class itself as a bean definition. */ private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) { AnnotationMetadata metadata = configClass.getMetadata(); AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata); ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef); configBeanDef.setScope(scopeMetadata.getScopeName()); String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry); AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition()); configClass.setBeanName(configBeanName); if (logger.isTraceEnabled()) { logger.trace("Registered bean definition for imported class '" + configBeanName + "'"); } } /** * Read the given {@link BeanMethod}, registering bean definitions * with the BeanDefinitionRegistry based on its contents. */ @SuppressWarnings("deprecation") // for RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) { ConfigurationClass configClass = beanMethod.getConfigurationClass(); MethodMetadata metadata = beanMethod.getMetadata(); String methodName = metadata.getMethodName(); // Do we need to mark the bean as skipped by its condition? if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) { configClass.skippedBeanMethods.add(methodName); return; } if (configClass.skippedBeanMethods.contains(methodName)) { return; } AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class); Assert.state(bean != null, "No @Bean annotation attributes"); // Consider name and any aliases List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name"))); String beanName = (!names.isEmpty() ? names.remove(0) : methodName); // Register aliases even when overridden for (String alias : names) { this.registry.registerAlias(beanName, alias); } // Has this effectively been overridden before (e.g. via XML)? if (isOverriddenByExistingDefinition(beanMethod, beanName)) { if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) { throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(), beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() + "' clashes with bean name for containing configuration class; please make those names unique!"); } return; } ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata); beanDef.setResource(configClass.getResource()); beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource())); if (metadata.isStatic()) { // static @Bean method beanDef.setBeanClassName(configClass.getMetadata().getClassName()); beanDef.setFactoryMethodName(methodName); } else { // instance @Bean method beanDef.setFactoryBeanName(configClass.getBeanName()); beanDef.setUniqueFactoryMethodName(methodName); } beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor. SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE); AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata); Autowire autowire = bean.getEnum("autowire"); if (autowire.isAutowire()) { beanDef.setAutowireMode(autowire.value()); } boolean autowireCandidate = bean.getBoolean("autowireCandidate"); if (!autowireCandidate) { beanDef.setAutowireCandidate(false); } String initMethodName = bean.getString("initMethod"); if (StringUtils.hasText(initMethodName)) { beanDef.setInitMethodName(initMethodName); } String destroyMethodName = bean.getString("destroyMethod"); beanDef.setDestroyMethodName(destroyMethodName); // Consider scoping ScopedProxyMode proxyMode = ScopedProxyMode.NO; AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class); if (attributes != null) { beanDef.setScope(attributes.getString("value")); proxyMode = attributes.getEnum("proxyMode"); if (proxyMode == ScopedProxyMode.DEFAULT) { proxyMode = ScopedProxyMode.NO; } } // Replace the original bean definition with the target one, if necessary BeanDefinition beanDefToRegister = beanDef; if (proxyMode != ScopedProxyMode.NO) { BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy( new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS); beanDefToRegister = new ConfigurationClassBeanDefinition( (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata); } if (logger.isTraceEnabled()) { logger.trace(String.format("Registering bean definition for @Bean method %s.%s()", configClass.getMetadata().getClassName(), beanName)); } this.registry.registerBeanDefinition(beanName, beanDefToRegister); } protected boolean isOverriddenByExistingDefinition(BeanMethod beanMethod, String beanName) { if (!this.registry.containsBeanDefinition(beanName)) { return false; } BeanDefinition existingBeanDef = this.registry.getBeanDefinition(beanName); // Is the existing bean definition one that was created from a configuration class? // -> allow the current bean method to override, since both are at second-pass level. // However, if the bean method is an overloaded case on the same configuration class, // preserve the existing bean definition. if (existingBeanDef instanceof ConfigurationClassBeanDefinition) { ConfigurationClassBeanDefinition ccbd = (ConfigurationClassBeanDefinition) existingBeanDef; return ccbd.getMetadata().getClassName().equals( beanMethod.getConfigurationClass().getMetadata().getClassName()); } // A bean definition resulting from a component scan can be silently overridden // by an @Bean method, as of 4.2... if (existingBeanDef instanceof ScannedGenericBeanDefinition) { return false; } // Has the existing bean definition bean marked as a framework-generated bean? // -> allow the current bean method to override it, since it is application-level if (existingBeanDef.getRole() > BeanDefinition.ROLE_APPLICATION) { return false; } // At this point, it's a top-level override (probably XML), just having been parsed // before configuration class processing kicks in... if (this.registry instanceof DefaultListableBeanFactory && !((DefaultListableBeanFactory) this.registry).isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(), beanName, "@Bean definition illegally overridden by existing bean definition: " + existingBeanDef); } if (logger.isDebugEnabled()) { logger.debug(String.format("Skipping bean definition for %s: a definition for bean '%s' " + "already exists. This top-level bean definition is considered as an override.", beanMethod, beanName)); } return true; } private void loadBeanDefinitionsFromImportedResources( Map<String, Class<? extends BeanDefinitionReader>> importedResources) { Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<>(); importedResources.forEach((resource, readerClass) -> { // Default reader selection necessary? if (BeanDefinitionReader.class == readerClass) { if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) { // When clearly asking for Groovy, that's what they'll get... readerClass = GroovyBeanDefinitionReader.class; } else { // Primarily ".xml" files but for any other extension as well readerClass = XmlBeanDefinitionReader.class; } } BeanDefinitionReader reader = readerInstanceCache.get(readerClass); if (reader == null) { try { // Instantiate the specified BeanDefinitionReader reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); // Delegate the current ResourceLoader to it if possible if (reader instanceof AbstractBeanDefinitionReader) { AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader); abdr.setResourceLoader(this.resourceLoader); abdr.setEnvironment(this.environment); } readerInstanceCache.put(readerClass, reader); } catch (Throwable ex) { throw new IllegalStateException( "Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]"); } } // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations reader.loadBeanDefinitions(resource); }); } private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) { registrars.forEach((registrar, metadata) -> registrar.registerBeanDefinitions(metadata, this.registry)); } /** * {@link RootBeanDefinition} marker subclass used to signify that a bean definition * was created from a configuration class as opposed to any other configuration source. * Used in bean overriding cases where it's necessary to determine whether the bean * definition was created externally. */ @SuppressWarnings("serial") private static class ConfigurationClassBeanDefinition extends RootBeanDefinition implements AnnotatedBeanDefinition { private final AnnotationMetadata annotationMetadata; private final MethodMetadata factoryMethodMetadata; public ConfigurationClassBeanDefinition(ConfigurationClass configClass, MethodMetadata beanMethodMetadata) { this.annotationMetadata = configClass.getMetadata(); this.factoryMethodMetadata = beanMethodMetadata; setLenientConstructorResolution(false); } public ConfigurationClassBeanDefinition( RootBeanDefinition original, ConfigurationClass configClass, MethodMetadata beanMethodMetadata) { super(original); this.annotationMetadata = configClass.getMetadata(); this.factoryMethodMetadata = beanMethodMetadata; } private ConfigurationClassBeanDefinition(ConfigurationClassBeanDefinition original) { super(original); this.annotationMetadata = original.annotationMetadata; this.factoryMethodMetadata = original.factoryMethodMetadata; } @Override public AnnotationMetadata getMetadata() { return this.annotationMetadata; } @Override public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; } @Override public boolean isFactoryMethod(Method candidate) { return (super.isFactoryMethod(candidate) && BeanAnnotationHelper.isBeanAnnotated(candidate)); } @Override public ConfigurationClassBeanDefinition cloneBeanDefinition() { return new ConfigurationClassBeanDefinition(this); } } /** * Evaluate {@code @Conditional} annotations, tracking results and taking into * account 'imported by'. */ private class TrackedConditionEvaluator { private final Map<ConfigurationClass, Boolean> skipped = new HashMap<>(); public boolean shouldSkip(ConfigurationClass configClass) { Boolean skip = this.skipped.get(configClass); if (skip == null) { if (configClass.isImported()) { boolean allSkipped = true; for (ConfigurationClass importedBy : configClass.getImportedBy()) { if (!shouldSkip(importedBy)) { allSkipped = false; break; } } if (allSkipped) { // The config classes that imported this one were all skipped, therefore we are skipped... skip = true; } } if (skip == null) { skip = conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN); } this.skipped.put(configClass, skip); } return skip; } } }
/* * Copyright (c) 2020-2021, Antonio Gabriel Muñoz Conejo <antoniogmc at gmail dot com> * Distributed under the terms of the MIT License */ package com.github.tonivade.purejson; import static com.github.tonivade.purefun.data.ImmutableList.toImmutableList; import static com.github.tonivade.purefun.data.ImmutableMap.toImmutableMap; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ElementVisitor; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; import javax.tools.JavaFileObject; import com.github.tonivade.purefun.Tuple; import com.github.tonivade.purefun.Tuple2; import com.github.tonivade.purefun.data.ImmutableList; import com.github.tonivade.purefun.data.ImmutableMap; import com.github.tonivade.purefun.data.Sequence; import com.github.tonivade.purefun.type.Option; import com.github.tonivade.purefun.type.Try; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; @SupportedAnnotationTypes("com.github.tonivade.purejson.Json") public class JsonAnnotationProcessor extends AbstractProcessor { @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { getAdapterFromAnnotation(getAnnotation(annotation, element)) .ifPresentOrElse( adapter -> adapterAlreadyExists(element, adapter), () -> generateAdapter(element)); } } return true; } private AnnotationMirror getAnnotation(TypeElement annotation, Element element) { return element.getAnnotationMirrors().stream() .filter(am -> am.getAnnotationType().equals(annotation.asType())) .findFirst().orElseThrow(); } private Optional<? extends AnnotationValue> getAdapterFromAnnotation(AnnotationMirror json) { return json.getElementValues().entrySet().stream() .filter(entry -> entry.getKey().getSimpleName().toString().equals("adapter")) .map(Map.Entry::getValue).findFirst(); } private void adapterAlreadyExists(Element element, AnnotationValue adapter) { printNote(element.getSimpleName() + " pojo found with adapter: " + adapter.getValue()); } private void generateAdapter(Element element) { if (element.getKind().name().equals("RECORD")) { printNote(element.getSimpleName() + " record found"); saveFile(modelForRecord((TypeElement) element)); } else if (element.getKind().name().equals("CLASS")) { printNote(element.getSimpleName() + " pojo found"); saveFile(modelForPojo((TypeElement) element)); } else { printError(element.getSimpleName() + " is not supported: " + element.getKind()); } } static final class Model { private final String packageName; private final String name; private final TypeMirror type; private final Sequence<Field> fields; public Model(String packageName, String name, TypeMirror type, Sequence<Field> fields) { this.packageName = packageName; this.name = name; this.type = type; this.fields = fields; } String getAdapterName() { return name + "Adapter"; } public JavaFile build() { TypeSpec typeSpec = TypeSpec.enumBuilder(getAdapterName()) .addModifiers(Modifier.PUBLIC) .addSuperinterface(ParameterizedTypeName.get(ClassName.get(JsonAdapter.class), TypeName.get(type))) .addEnumConstant("INSTANCE") .addFields(buildAdapters()) .addMethod(MethodSpec.methodBuilder("encode") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.get(type), "value") .returns(JsonNode.class) .addCode(encodeMethod()) .build()) .addMethod(MethodSpec.methodBuilder("decode") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(JsonNode.class, "node") .returns(TypeName.get(type)) .addCode(decodeMethod()) .build()) .build(); return JavaFile.builder(packageName, typeSpec).build(); } private List<FieldSpec> buildAdapters() { var list = new ArrayList<FieldSpec>(); for (var field : fields) { list.add( FieldSpec.builder( ParameterizedTypeName.get(ClassName.get(JsonAdapter.class), TypeName.get(field.type).box()), field.getAdapterName(), Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer(CodeBlock.builder().add("$T.adapter($L)", JsonAdapter.class, field.getFieldType()).build()) .build()); } return list; } private CodeBlock encodeMethod() { var builder = CodeBlock.builder(); for (var field : fields) { builder.addStatement("var $N = $T.entry($S, $L.encode($N.$N()))", field.name, JsonDSL.class, field.name, field.getAdapterName(), "value", field.accessor.getSimpleName()); } String params = fields.map(f -> f.name).join(", "); return builder.addStatement("return $T.object($L)", JsonDSL.class, params).build(); } private CodeBlock decodeMethod() { var builder = CodeBlock.builder(); builder.addStatement("var $N = $N.asObject()", "object", "node"); for (var field : fields) { builder.addStatement("var $N = $L.decode($N.get($S))", field.name, field.getAdapterName(), "object", field.name); } String params = fields.map(f -> f.name).join(", "); return builder.addStatement("return new $N($L)", name, params).build(); } } static final class Field { private final String name; private final TypeMirror type; private final ExecutableElement accessor; public Field(String name, TypeMirror type, ExecutableElement accessor) { this.name = name; this.type = type; this.accessor = accessor; } String getAdapterName() { return name.toUpperCase() + "_ADAPTER"; } CodeBlock getFieldType() { var typeName = TypeName.get(type); if (typeName.isPrimitive()) { return CodeBlock.builder().add("$T.class", typeName).build(); } if (typeName instanceof ClassName) { return CodeBlock.builder().add("$T.class", typeName).build(); } if (typeName instanceof ParameterizedTypeName) { return CodeBlock.builder().add("new $T<$T>(){}.getType()", TypeToken.class, typeName).build(); } throw new UnsupportedOperationException(typeName.toString()); } } private void saveFile(Model model) { try { JavaFileObject test = createFile(model.packageName, model.getAdapterName()); try (Writer openWriter = test.openWriter()) { model.build().writeTo(openWriter); } } catch (IOException e) { throw new UncheckedIOException(e); } } private JavaFileObject createFile(String packageName, String className) throws IOException { String qualifiedName = packageName != null ? packageName + "." + className : className; return processingEnv.getFiler().createSourceFile(qualifiedName); } private Model modelForPojo(TypeElement element) { ImmutableList<VariableElement> fields = element.getEnclosedElements().stream() .filter(e -> e.getKind() == ElementKind.FIELD) .map(e -> (VariableElement) e) .collect(toImmutableList()); findConstructor(element, fields); ImmutableMap<String, ExecutableElement> methods = element.getEnclosedElements().stream() .filter(e -> e.getKind() == ElementKind.METHOD) .map(e -> (ExecutableElement) e) .map(e -> Tuple.of(e.getSimpleName().toString(), e)) .collect(toImmutableMap(Tuple2::get1, Tuple2::get2)); String qualifiedName = element.getQualifiedName().toString(); String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf('.')); String simpleName = element.getSimpleName().toString(); return new Model(packageName, simpleName, element.asType(), fields.stream().flatMap( f -> { var name = f.getSimpleName().toString(); var key = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); var accessor = methods.get(key).orElse(methods.get(name)) .ifEmpty(() -> printError("not accessor found for field " + name + " of type " + element.getSimpleName())); return accessor.map(a -> new Field(f.getSimpleName().toString(), a.getReturnType(), a)).stream(); }) .collect(toImmutableList())); } private Model modelForRecord(TypeElement element) { ImmutableList<RecordComponentElement> fields = element.getEnclosedElements().stream() .filter(e -> e.getKind().name().equals("RECORD_COMPONENT")) .map(RecordComponentElement::new) .collect(toImmutableList()); findConstructor(element, fields); String qualifiedName = element.getQualifiedName().toString(); String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf('.')); String simpleName = element.getSimpleName().toString(); return new Model(packageName, simpleName, element.asType(), fields.stream().map( f -> new Field( f.getSimpleName().toString(), f.getAccessor().getReturnType(), f.getAccessor())) .collect(toImmutableList())); } private <T extends Element> void findConstructor(TypeElement element, ImmutableList<T> fields) { element.getEnclosedElements().stream() .filter(e -> e.getKind() == ElementKind.CONSTRUCTOR) .map(e -> (ExecutableElement) e) .filter(c -> c.getParameters().size() == fields.size()) .findFirst().map(Option::some).orElseGet(Option::none) .ifEmpty(() -> printError("no proper constructor found: " + element.getSimpleName() + fields.map(Element::asType).join(",", "(", ")"))); } private void printNote(String msg) { processingEnv.getMessager().printMessage(Kind.NOTE, msg); } private void printError(String msg) { processingEnv.getMessager().printMessage(Kind.ERROR, msg); } static final class RecordComponentElement implements Element { private static final Method GET_ACCESSOR; static { Method getAccessor; try { Class<?> clazz = Class.forName("javax.lang.model.element.RecordComponentElement"); getAccessor = clazz.getMethod("getAccessor"); } catch (ClassNotFoundException | NoSuchMethodException e) { getAccessor = null; } GET_ACCESSOR = getAccessor; } private final Element element; public RecordComponentElement(Element element) { this.element = element; } public TypeMirror asType() { return element.asType(); } public ElementKind getKind() { return element.getKind(); } public Set<Modifier> getModifiers() { return element.getModifiers(); } public Name getSimpleName() { return element.getSimpleName(); } public Element getEnclosingElement() { return element.getEnclosingElement(); } public List<? extends Element> getEnclosedElements() { return element.getEnclosedElements(); } public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) { return element.getAnnotationsByType(annotationType); } public boolean equals(Object obj) { return element.equals(obj); } public int hashCode() { return element.hashCode(); } public List<? extends AnnotationMirror> getAnnotationMirrors() { return element.getAnnotationMirrors(); } public <A extends Annotation> A getAnnotation(Class<A> annotationType) { return element.getAnnotation(annotationType); } public <R, P> R accept(ElementVisitor<R, P> visitor, P parameter) { return element.accept(visitor, parameter); } public ExecutableElement getAccessor() { return (ExecutableElement) Try.of(() -> GET_ACCESSOR.invoke(element)).getOrElseThrow(); } } }
package COMSETsystem; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; public class Statistics { public static void agent_statistics(Simulator simulator, AgentEvent ag, ResourceEvent resource, long arriveTime) { long cruiseTime = ag.time - ag.startSearchTime; simulator.totalAgentCruiseTime += cruiseTime; long approachTime = arriveTime - ag.time; long searchTime = cruiseTime + approachTime; simulator.totalAgentSearchTime += searchTime; long waitTime = arriveTime - resource.availableTime; simulator.totalResourceWaitTime += waitTime; simulator.totalAssignments++; System.out.println("\n"); } public static void store_statistics (long assignmentType,long totalAgents,long totalResources,long numberOfHubs,long windowSize,long totalAssignments,long averageResourceWaitTime,long averageAgentSearchTime,long expiredResourcesPercent, long totalSimulationTime){ //Connection connection = null; Connection conn = null; try { String databaseURL = "jdbc:mysql://localhost:3306/av_schema"; Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(databaseURL, "root", "tiger123"); if (conn == null) { System.out.println("Not Connected to the database"); } if (assignmentType == 1) windowSize = windowSize*30; String eachRow = "INSERT INTO fullstatistics (assignmentType,totalAgents,totalResources,numberOfHubs, windowSize,totalAssignments,averageResourceWaitTime,averageAgentSearchTime,expiredResourcesPercent, totalSimulationTime ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(eachRow); statement.setLong(1,assignmentType); statement.setLong(2, totalAgents); statement.setLong(3, totalResources); statement.setLong(4, numberOfHubs); statement.setLong(5, windowSize); statement.setLong(6, totalAssignments); statement.setLong(7, averageResourceWaitTime); statement.setLong(8, averageAgentSearchTime); statement.setLong(9, expiredResourcesPercent); statement.setLong(10, totalSimulationTime); statement.addBatch(); statement.executeBatch(); // conn.commit(); conn.close(); } catch (SQLException | ClassNotFoundException ex) { ex.printStackTrace(); } } }
/* * Swift Parallel Scripting Language (http://swift-lang.org) * Code from Java CoG Kit Project (see notice below) with modifications. * * Copyright 2005-2014 University of Chicago * * 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. */ //---------------------------------------------------------------------- //This code is developed as part of the Java CoG Kit project //The terms of the license can be found at http://www.cogkit.org/license //This message may not be removed or altered. //---------------------------------------------------------------------- /* * Created on May 18, 2009 */ package org.globus.cog.abstraction.coaster.service.job.manager; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.globus.cog.coaster.ProtocolException; import org.globus.cog.coaster.handlers.RequestHandler; public class BQPStatusHandler extends RequestHandler { public static final Logger logger = Logger.getLogger(BQPStatusHandler.class); public static final String NAME = BQPStatusCommand.NAME; private int index; private static SwingBQPMonitor monitor; private static synchronized SwingBQPMonitor getMonitor() { if (monitor == null) { monitor = new SwingBQPMonitor(); } return monitor; } public void requestComplete() throws ProtocolException { index = 0; sendReply("OK"); try { Status status = new Status(); String[] items; items = nextItem("settings"); status.settings.put("lowOverallocation", items[0]); status.settings.put("highOverallocation", items[0]); status.settings.put("overallocationDecayFactor", items[0]); items = nextItem("queuedsize"); int qs = Integer.parseInt(items[0]); for (int i = 0; i < qs; i++) { items = nextItem("job"); Job j = new Job(); j.setMaxWallTime(timeInterval(items[0])); j.setStartTime(time(items[1])); j.setEndTime(time(items[2])); status.queued.add(j); } items = nextItem("jobssize"); int jobssize = Integer.parseInt(items[0]); for (int i = 0; i < jobssize; i++) { items = nextItem("job"); Job j = new Job(); j.setMaxWallTime(timeInterval(items[0])); j.setStartTime(time(items[1])); j.setEndTime(time(items[2])); status.jobs.add(j); } items = nextItem("blockssize"); int blockssize = Integer.parseInt(items[0]); for (int i = 0; i < blockssize; i++) { items = nextItem("block"); Block b = new Block(items[0]); status.blocks.add(b); b.setWorkerCount(Integer.parseInt(items[1])); b.setCreationTime(time(items[2])); b.setStartTime(time(items[3])); b.setEndTime(time(items[4])); b.setDeadline(time(items[5])); b.setWalltime(timeInterval(items[6])); int cpus = Integer.parseInt(items[7]); for (int j = 0; j < cpus; j++) { items = nextItem("cpu"); Cpu cpu = new Cpu(); cpu.setId(Integer.parseInt(items[0])); boolean running = Boolean.valueOf(items[1]).booleanValue(); int donejobssize = Integer.parseInt(items[2]); if (running) { Job r = new Job(); items = nextItem("runningjob"); r.setMaxWallTime(timeInterval(items[0])); r.setStartTime(time(items[1])); cpu.setRunning(r); } for (int k = 0; k < donejobssize; k++) { items = nextItem("donejob"); Job d = new Job(); d.setMaxWallTime(timeInterval(items[0])); d.setStartTime(time(items[1])); d.setEndTime(time(items[2])); cpu.addDoneJob(d); } b.getCpus().add(cpu); } } logger.info("Process BQP status update 1"); getMonitor().update(status.settings, status.jobs, status.queued, status.blocks); logger.info("Process BQP status update 2"); } catch (Exception e) { logger.warn("Failed to process data", e); } } private String nextString() { return getInDataAsString(index++); } private String[] nextItem(String type) { String s = nextString(); if (!s.startsWith(type + ": ")) { throw new IllegalArgumentException("Invalid data line (" + s + "). Expected " + type + "."); } return s.substring(type.length() + 2).split("\\s+"); } private static class Status { public Settings settings; public SortedJobSet queued; public List jobs, blocks; public Status() { settings = new Settings(); queued = new SortedJobSet(); jobs = new ArrayList(); blocks = new ArrayList(); } } private Time time(String s) { long i = Long.parseLong(s); if (i == -1) { return null; } else { return Time.fromMilliseconds(i); } } private TimeInterval timeInterval(String s) { long i = Long.parseLong(s); if (i == -1) { return null; } else { return TimeInterval.fromMilliseconds(i); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sentry.tests.e2e.dbprovider; import org.apache.hadoop.fs.permission.FsAction; import org.apache.sentry.tests.e2e.hdfs.TestHDFSIntegrationBase; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.Statement; public class TestHmsNotificationProcessingWithOutSyncOnDrop extends TestHmsNotificationProcessingBase { @BeforeClass public static void setup() throws Exception { hiveSyncOnDrop = false; hiveSyncOnCreate = true; hdfsSyncEnabled = true; TestHDFSIntegrationBase.setup(); } /* Tests basic sanity of Hms notification processing by verifying below when new Hive objects are created 1. Making sure that HDFS ACL rules for an new Hive objects created. 2. Making sure that stale permissions are deleted for the new Hive object that are created. 3. Making sure that permissions are not deleted when hive objects are deleted */ @Test public void testHmsNotificationProcessingSanity() throws Throwable { dbNames = new String[]{DB1}; roles = new String[]{"admin_role", "read_db1", "select_tbl1"}; admin = "hive"; Connection connection = hiveServer2.createConnection(admin, admin); Statement statement = connection.createStatement(); statement.execute("create role admin_role"); statement.execute("grant role admin_role to group hive"); statement.execute("grant all on server server1 to role admin_role"); // Add privileges for an objects that do not exist yet statement.execute("create role read_db1"); statement.execute("create role select_tbl1"); statement.execute("grant role read_db1 to group hbase"); statement.execute("grant role select_tbl1 to group hbase"); //Add object statement.execute("CREATE DATABASE " + DB1); statement.execute("use " + DB1); statement.execute("create table " + DB1 + "." + tableName1 + " (under_col int comment 'the under column', value string)"); Thread.sleep(WAIT_FOR_NOTIFICATION_PROCESSING); //Make sure that the privileges for that object are removed. verifyPrivilegesCount(statement, 0); //add "select" sentry permission for the object's statement.execute("GRANT select ON DATABASE " + DB1 + " TO ROLE read_db1"); statement.execute("USE " + DB1); statement.execute("GRANT SELECT ON TABLE " + tableName1 + " TO ROLE select_tbl1"); verifyPrivilegesCount(statement, 2); // Make sure that an ACL is added for that verifyOnAllSubDirs("/user/hive/warehouse/db_1.db", FsAction.READ_EXECUTE, "hbase", true); verifyOnAllSubDirs("/user/hive/warehouse/db_1.db/tb_1", FsAction.READ_EXECUTE, "hbase", true); //Drop the object statement.execute("DROP DATABASE " + DB1 + " CASCADE"); Thread.sleep(WAIT_FOR_NOTIFICATION_PROCESSING); //Make sure that the privileges added for that object are removed. verifyPrivilegesCount(statement, 2); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package logica.impresion; /** * * @author Toshiba */ public class Objeto { private int id; private String nombre; private int cantidad; private long precio; public Objeto(String nombre, int cantidad, long precio) { this.nombre = nombre; this.cantidad = cantidad; this.precio = precio; this.id =0; } public Objeto(int id, String nombre, int cantidad, long precio) { this.id = id; this.nombre = nombre; this.cantidad = cantidad; this.precio = precio; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getCantidad() { return cantidad; } public long getPrecio() { return precio; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } public void setPrecio(long precio) { this.precio = precio; } }
package com.github.bael.course.unit2.examples.inheritance; /* * Транспортное средство * */ public abstract class Vehicle { private int velocity; private int weight; protected String destination; protected abstract void move(); public void travel(String destination) { this.destination = destination; move(); } }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.jaxrs.v2_0; import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.namedOneOf; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; import io.opentelemetry.javaagent.instrumentation.api.InstrumentationContext; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.matcher.ElementMatcher; import org.jboss.resteasy.core.ResourceLocatorInvoker; import org.jboss.resteasy.core.ResourceMethodInvoker; public class ResteasyRootNodeTypeInstrumentation implements TypeInstrumentation { @Override public ElementMatcher<TypeDescription> typeMatcher() { return named("org.jboss.resteasy.core.registry.RootNode"); } @Override public void transform(TypeTransformer transformer) { transformer.applyAdviceToMethod( named("addInvoker") .and(takesArgument(0, String.class)) // package of ResourceInvoker was changed in reasteasy 4 .and( takesArgument( 1, namedOneOf( "org.jboss.resteasy.core.ResourceInvoker", "org.jboss.resteasy.spi.ResourceInvoker"))), ResteasyRootNodeTypeInstrumentation.class.getName() + "$AddInvokerAdvice"); } @SuppressWarnings("unused") public static class AddInvokerAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static void addInvoker( @Advice.Argument(0) String path, @Advice.Argument(value = 1, typing = Assigner.Typing.DYNAMIC) Object invoker) { String normalizedPath = JaxRsPathUtil.normalizePath(path); if (invoker instanceof ResourceLocatorInvoker) { ResourceLocatorInvoker resourceLocatorInvoker = (ResourceLocatorInvoker) invoker; InstrumentationContext.get(ResourceLocatorInvoker.class, String.class) .put(resourceLocatorInvoker, normalizedPath); } else if (invoker instanceof ResourceMethodInvoker) { ResourceMethodInvoker resourceMethodInvoker = (ResourceMethodInvoker) invoker; InstrumentationContext.get(ResourceMethodInvoker.class, String.class) .put(resourceMethodInvoker, normalizedPath); } } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.royale.compiler.problems; import org.apache.royale.compiler.tree.as.IASNode; /** * Strict semantics diagnostic emitted when the method body * semantic checker detects loss of precision in a Vector * literal's initializers. */ public final class LossyConversionProblem extends StrictSemanticsProblem { public static final String DESCRIPTION = "Invalid initialization: conversion to type ${targetType} loses data."; public static final int errorCode = 1215; public LossyConversionProblem(IASNode site, String targetType) { super(site); this.targetType = targetType; } public final String targetType; }
package uk.co.epsilontechnologies.primer.domain; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public interface Response { void populate(HttpServletResponse httpServletResponse) throws IOException; }
package com.fourtk.movieflix.resources; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.fourtk.movieflix.dto.GenreDTO; import com.fourtk.movieflix.services.GenreService; @RestController @RequestMapping(value = "/genres") public class GenreResource { @Autowired private GenreService service; @GetMapping(value = "/{id}") public ResponseEntity<GenreDTO> findById(@PathVariable Long id) { GenreDTO dto = service.findById(id); return ResponseEntity.ok().body(dto); } @GetMapping public ResponseEntity<List<GenreDTO>> findAll(){ List<GenreDTO> list = service.findAll(); return ResponseEntity.ok(list); } @GetMapping(value = "/pagination") public ResponseEntity<Page<GenreDTO>> findAll( @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "linesPerPage", defaultValue = "4") Integer linesPerPage, @RequestParam(value = "direction", defaultValue = "ASC") String direction, @RequestParam(value = "orderBy", defaultValue = "name") String orderBy ){ PageRequest pageRequest = PageRequest.of(page, linesPerPage,Direction.valueOf(direction), orderBy ); Page<GenreDTO> list = service.findAllPaged(pageRequest); return ResponseEntity.ok().body(list); } }
/* * ============================================================================ * JGribX * ============================================================================ * Written by Andrew Spiteri <andrew.spiteri@um.edu.mt> * Adapted from JGRIB: http://jgrib.sourceforge.net/ * * Licensed under MIT: https://github.com/spidru/JGribX/blob/master/LICENSE * ============================================================================ */ package mt.edu.um.cf2.jgribx.grib1; import java.io.IOException; import java.util.Arrays; import mt.edu.um.cf2.jgribx.Bytes2Number; import mt.edu.um.cf2.jgribx.GribInputStream; import mt.edu.um.cf2.jgribx.NoValidGribException; /** * A class that represents the bitmap section (BMS) of a GRIB record. It * indicates grid points where no parameter value is defined. * * @author Benjamin Stark * @version 1.0 */ public class Grib1RecordBMS { /** * Length in bytes of this section. */ protected int length; /** * The bit map. */ protected boolean[] bitmap; // *** constructors ******************************************************* /** * Constructs a <tt>GribRecordBMS</tt> object from a bit input stream. * * @param in bit input stream with BMS content * * @throws IOException if stream can not be opened etc. * @throws NoValidGribException if stream contains no valid GRIB file */ public Grib1RecordBMS(GribInputStream in) throws IOException, NoValidGribException { byte[] octets; int[] bitmask = {128, 64, 32, 16, 8, 4, 2, 1}; octets = new byte[3]; in.read(octets); // octets 1-3 (length of section) this.length = Bytes2Number.bytesToUint(Arrays.copyOfRange(octets, 0, 3)); // read rest of section octets = new byte[this.length - 3]; in.read(octets); int nBitsUnused = Bytes2Number.bytesToUint(octets[0]); // octets 5-6 if (octets[1] != 0 || octets[2] != 0) throw new NoValidGribException("GribRecordBMS: No bit map defined here."); // create new bit map, octet 4 contains number of unused bits at the end this.bitmap = new boolean[(this.length - 6) * 8 - nBitsUnused]; // fill bit map for (int i = 0; i < this.bitmap.length; i++) this.bitmap[i] = (octets[i / 8 + 3] & bitmask[i % 8]) != 0; } // *** public methods ********************************************************* /** * Get length in bytes of this section. * * @return length in bytes */ public int getLength() { return this.length; } /** * Get bit map. * * @return bit map as array of boolean values */ public boolean[] getBitmap() { return this.bitmap; } /** * Get a string representation of this BMS. * * @return string representation of this BMS */ @Override public String toString() { return " BMS section:" + '\n' + " bitmap length: " + this.bitmap.length; } }
package com.example.mentalhealthguide; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; /** * A simple {@link Fragment} subclass. */ public class Welcome extends Fragment { public Welcome() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_welcome, container, false); TextView textView = view.findViewById(R.id.textView5); textView.setClickable(true); textView.setMovementMethod(LinkMovementMethod.getInstance()); return view; } }
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ @SuppressWarnings("all") public class VmMacConflictEvent extends VmEvent { public VmEventArgument conflictedVm; public String mac; public VmEventArgument getConflictedVm() { return this.conflictedVm; } public String getMac() { return this.mac; } public void setConflictedVm(VmEventArgument conflictedVm) { this.conflictedVm = conflictedVm; } public void setMac(String mac) { this.mac = mac; } }
/* * Copyright 2014-present Facebook, Inc. * * 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.facebook.buck.apple.toolchain.impl; import com.dd.plist.NSArray; import com.dd.plist.NSDictionary; import com.dd.plist.NSString; import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListParser; import com.facebook.buck.apple.AppleConfig; import com.facebook.buck.apple.toolchain.ApplePlatform; import com.facebook.buck.apple.toolchain.AppleSdk; import com.facebook.buck.apple.toolchain.AppleSdkPaths; import com.facebook.buck.apple.toolchain.AppleToolchain; import com.facebook.buck.log.Logger; import com.facebook.buck.util.VersionStringComparator; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Ordering; import com.google.common.collect.TreeMultimap; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.text.ParseException; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** Utility class to discover the location of SDKs contained inside an Xcode installation. */ public class AppleSdkDiscovery { private static final Logger LOG = Logger.get(AppleSdkDiscovery.class); private static final Ordering<AppleSdk> APPLE_SDK_VERSION_ORDERING = new Ordering<AppleSdk>() { VersionStringComparator versionComparator = new VersionStringComparator(); @Override public int compare(AppleSdk thisSdk, AppleSdk thatSdk) { int result = versionComparator.compare(thisSdk.getVersion(), thatSdk.getVersion()); return result == 0 ? thisSdk.getName().compareTo(thatSdk.getName()) : result; } }; private static final String DEFAULT_TOOLCHAIN_ID = "com.apple.dt.toolchain.XcodeDefault"; // Utility class; do not instantiate. private AppleSdkDiscovery() {} /** * Given a path to an Xcode developer directory and a map of (xctoolchain ID: path) pairs as * returned by {@link AppleToolchainDiscovery}, walks through the platforms and builds a map of * ({@link AppleSdk}: {@link AppleSdkPaths}) objects describing the paths to the SDKs inside. * * <p>The {@link AppleSdk#getName()} strings match the ones displayed by {@code xcodebuild * -showsdks} and look like {@code macosx10.9}, {@code iphoneos8.0}, {@code iphonesimulator8.0}, * etc. */ public static ImmutableMap<AppleSdk, AppleSdkPaths> discoverAppleSdkPaths( Optional<Path> developerDir, ImmutableList<Path> extraDirs, ImmutableMap<String, AppleToolchain> xcodeToolchains, AppleConfig appleConfig) throws IOException { Optional<AppleToolchain> defaultToolchain = Optional.ofNullable(xcodeToolchains.get(DEFAULT_TOOLCHAIN_ID)); ImmutableMap.Builder<AppleSdk, AppleSdkPaths> appleSdkPathsBuilder = ImmutableMap.builder(); HashSet<Path> platformPaths = new HashSet<Path>(extraDirs); if (developerDir.isPresent()) { Path platformsDir = developerDir.get().resolve("Platforms"); LOG.debug("Searching for Xcode platforms under %s", platformsDir); platformPaths.add(platformsDir); } // We need to find the most recent SDK for each platform so we can // make the fall-back SDKs with no version number in their name // ("macosx", "iphonesimulator", "iphoneos"). // // To do this, we store a map of (platform: [sdk1, sdk2, ...]) // pairs where the SDKs for each platform are ordered by version. TreeMultimap<ApplePlatform, AppleSdk> orderedSdksForPlatform = TreeMultimap.create(Ordering.natural(), APPLE_SDK_VERSION_ORDERING); for (Path platforms : platformPaths) { if (!Files.exists(platforms)) { LOG.debug("Skipping platform search path %s that does not exist", platforms); continue; } LOG.debug("Searching for Xcode SDKs in %s", platforms); try (DirectoryStream<Path> platformStream = Files.newDirectoryStream(platforms, "*.platform")) { for (Path platformDir : platformStream) { Path developerSdksPath = platformDir.resolve("Developer/SDKs"); try (DirectoryStream<Path> sdkStream = Files.newDirectoryStream(developerSdksPath, "*.sdk")) { Set<Path> scannedSdkDirs = new HashSet<>(); for (Path sdkDir : sdkStream) { LOG.debug("Fetching SDK name for %s", sdkDir); try { sdkDir = sdkDir.toRealPath(); } catch (NoSuchFileException e) { LOG.warn(e, "SDK at path %s is a dangling link, ignoring", sdkDir); continue; } if (scannedSdkDirs.contains(sdkDir)) { LOG.debug("Skipping already scanned SDK directory %s", sdkDir); continue; } AppleSdk.Builder sdkBuilder = AppleSdk.builder(); if (buildSdkFromPath( sdkDir, sdkBuilder, xcodeToolchains, defaultToolchain, appleConfig)) { AppleSdk sdk = sdkBuilder.build(); LOG.debug("Found SDK %s", sdk); AppleSdkPaths.Builder xcodePathsBuilder = AppleSdkPaths.builder(); for (AppleToolchain toolchain : sdk.getToolchains()) { xcodePathsBuilder.addToolchainPaths(toolchain.getPath()); } AppleSdkPaths xcodePaths = xcodePathsBuilder .setDeveloperPath(developerDir) .setPlatformPath(platformDir) .setSdkPath(sdkDir) .build(); appleSdkPathsBuilder.put(sdk, xcodePaths); orderedSdksForPlatform.put(sdk.getApplePlatform(), sdk); } scannedSdkDirs.add(sdkDir); } } catch (NoSuchFileException e) { LOG.warn( e, "Couldn't discover SDKs at path %s, ignoring platform %s", developerSdksPath, platformDir); } } } } // Get a snapshot of what's in appleSdkPathsBuilder, then for each // ApplePlatform, add to appleSdkPathsBuilder the most recent // SDK with an unversioned name. ImmutableMap<AppleSdk, AppleSdkPaths> discoveredSdkPaths = appleSdkPathsBuilder.build(); for (ApplePlatform platform : orderedSdksForPlatform.keySet()) { Set<AppleSdk> platformSdks = orderedSdksForPlatform.get(platform); boolean shouldCreateUnversionedSdk = true; for (AppleSdk sdk : platformSdks) { shouldCreateUnversionedSdk &= !sdk.getName().equals(platform.getName()); } if (shouldCreateUnversionedSdk) { AppleSdk mostRecentSdkForPlatform = orderedSdksForPlatform.get(platform).last(); appleSdkPathsBuilder.put( mostRecentSdkForPlatform.withName(platform.getName()), discoveredSdkPaths.get(mostRecentSdkForPlatform)); } } // This includes both the discovered SDKs with versions in their names, as well as // the unversioned aliases added just above. return appleSdkPathsBuilder.build(); } private static boolean buildSdkFromPath( Path sdkDir, AppleSdk.Builder sdkBuilder, ImmutableMap<String, AppleToolchain> xcodeToolchains, Optional<AppleToolchain> defaultToolchain, AppleConfig appleConfig) throws IOException { try (InputStream sdkSettingsPlist = Files.newInputStream(sdkDir.resolve("SDKSettings.plist")); BufferedInputStream bufferedSdkSettingsPlist = new BufferedInputStream(sdkSettingsPlist)) { NSDictionary sdkSettings; try { sdkSettings = (NSDictionary) PropertyListParser.parse(bufferedSdkSettingsPlist); } catch (PropertyListFormatException | ParseException | SAXException e) { LOG.error(e, "Malformatted SDKSettings.plist. Skipping SDK path %s.", sdkDir); return false; } catch (ParserConfigurationException e) { throw new IOException(e); } String name = sdkSettings.objectForKey("CanonicalName").toString(); String version = sdkSettings.objectForKey("Version").toString(); NSDictionary defaultProperties = (NSDictionary) sdkSettings.objectForKey("DefaultProperties"); NSString platformName = (NSString) defaultProperties.objectForKey("PLATFORM_NAME"); Optional<ImmutableList<String>> toolchains = appleConfig.getToolchainsOverrideForSDKName(platformName.toString()); boolean foundToolchain = false; if (!toolchains.isPresent()) { NSArray settingsToolchains = (NSArray) sdkSettings.objectForKey("Toolchains"); if (settingsToolchains != null) { toolchains = Optional.of( Arrays.stream(settingsToolchains.getArray()) .map(Object::toString) .collect(ImmutableList.toImmutableList())); } } if (toolchains.isPresent()) { for (String toolchainId : toolchains.get()) { AppleToolchain toolchain = xcodeToolchains.get(toolchainId); if (toolchain != null) { foundToolchain = true; sdkBuilder.addToolchains(toolchain); } else { LOG.debug("Specified toolchain %s not found for SDK path %s", toolchainId, sdkDir); } } } if (!foundToolchain && defaultToolchain.isPresent()) { foundToolchain = true; sdkBuilder.addToolchains(defaultToolchain.get()); } if (!foundToolchain) { LOG.warn("No toolchains found and no default toolchain. Skipping SDK path %s.", sdkDir); return false; } else { ApplePlatform applePlatform = ApplePlatform.of(platformName.toString()); sdkBuilder.setName(name).setVersion(version).setApplePlatform(applePlatform); ImmutableList<String> architectures = validArchitecturesForPlatform(applePlatform, sdkDir); sdkBuilder.addAllArchitectures(architectures); return true; } } catch (NoSuchFileException e) { LOG.warn(e, "Skipping SDK at path %s, no SDKSettings.plist found", sdkDir); return false; } } private static ImmutableList<String> validArchitecturesForPlatform( ApplePlatform platform, Path sdkDir) throws IOException { ImmutableList<String> architectures = platform.getArchitectures(); try (DirectoryStream<Path> sdkFiles = Files.newDirectoryStream(sdkDir)) { ImmutableList.Builder<String> architectureSubdirsBuilder = ImmutableList.builder(); for (Path path : sdkFiles) { if (Files.isDirectory(path)) { String directoryName = path.getFileName().toString(); // Default Apple SDKs contain fat binaries and have no architecture subdirectories, // but custom SDKs might. if (architectures.contains(directoryName)) { architectureSubdirsBuilder.add(directoryName); } } } ImmutableList<String> architectureSubdirs = architectureSubdirsBuilder.build(); if (!architectureSubdirs.isEmpty()) { architectures = architectureSubdirs; } } return architectures; } }
/******************************************************************************* * Copyright (c) 2019 Georgia Tech Research Institute * * 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 edu.gatech.chai.omoponfhir.dstu2.security; import java.util.Map; import javax.servlet.http.HttpServletRequest; import ca.uhn.fhir.model.api.ExtensionDt; import ca.uhn.fhir.model.dstu2.resource.Conformance; import ca.uhn.fhir.model.dstu2.resource.Conformance.Rest; import ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource; import ca.uhn.fhir.model.dstu2.resource.Conformance.RestSecurity; import ca.uhn.fhir.model.dstu2.valueset.RestfulSecurityServiceEnum; import ca.uhn.fhir.model.primitive.DecimalDt; import ca.uhn.fhir.model.primitive.UriDt; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.provider.dstu2.ServerConformanceProvider; import ca.uhn.fhir.util.ExtensionConstants; import edu.gatech.chai.omoponfhir.omopv5.dstu2.utilities.ExtensionUtil; /** * @author mc142local * */ public class SMARTonFHIRConformanceStatement extends ServerConformanceProvider { // static String authorizeURI = // "http://fhir-registry.smarthealthit.org/Profile/oauth-uris#authorize"; // static String tokenURI = // "http://fhir-registry.smarthealthit.org/Profile/oauth-uris#token"; // static String registerURI = // "http://fhir-registry.smarthealthit.org/Profile/oauth-uris#register"; static String oauthURI = "http://DSTU2/fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris"; static String authorizeURI = "authorize"; static String tokenURI = "token"; static String registerURI = "register"; String authorizeURIvalue = "http://localhost:8080/authorize"; String tokenURIvalue = "http://localhost:8080/token"; public SMARTonFHIRConformanceStatement() { super(); super.setCache(false); // try { // InetAddress addr = java.net.InetAddress.getLocalHost(); // System.out.println(addr); // String hostname = addr.getCanonicalHostName(); // System.out.println("Hostname of system = " + hostname); // // // authorizeURIvalue = "http://"+hostname+":9085/authorize"; // // tokenURIvalue = "http://"+hostname+":9085/token"; // // registerURIvalue = "http://"+hostname+":9085/register"; // } catch (UnknownHostException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public SMARTonFHIRConformanceStatement(RestfulServer theRestfulServer) { // super(theRestfulServer); // super.setCache(false); // try { // InetAddress addr = java.net.InetAddress.getLocalHost(); // System.out.println(addr); // String hostname = addr.getCanonicalHostName(); // System.out.println("Hostname of system = " + hostname); // // // authorizeURIvalue = "http://"+hostname+":9085/authorize"; // // tokenURIvalue = "http://"+hostname+":9085/token"; // // registerURIvalue = "http://"+hostname+":9085/register"; // } catch (UnknownHostException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } @Override public Conformance getServerConformance(HttpServletRequest theRequest, RequestDetails theRequestDetails) { Conformance conformanceStatement = super.getServerConformance(theRequest, theRequestDetails); Map<String, Long> counts = ExtensionUtil.getResourceCounts(); for (Rest rest : conformanceStatement.getRest()) { for (RestResource nextResource : rest.getResource()) { Long count = counts.get(nextResource.getTypeElement().getValueAsString()); if (count != null) { nextResource.addUndeclaredExtension(new ExtensionDt(false, ExtensionConstants.CONF_RESOURCE_COUNT, new DecimalDt(count))); } } RestSecurity restSec = rest.getSecurity(); restSec.addService(RestfulSecurityServiceEnum.SMART_ON_FHIR); ExtensionDt extension = new ExtensionDt(); extension.setUrl(oauthURI); ExtensionDt authorizeExtension = new ExtensionDt(); authorizeExtension.setUrl(authorizeURI); authorizeExtension.setValue(new UriDt(authorizeURIvalue)); ExtensionDt tokenExtension = new ExtensionDt(); tokenExtension.setUrl(tokenURI); tokenExtension.setValue(new UriDt(tokenURIvalue)); extension.addUndeclaredExtension(authorizeExtension); extension.addUndeclaredExtension(tokenExtension); restSec.addUndeclaredExtension(extension); } return conformanceStatement; } public void setAuthServerUrl(String url) { authorizeURIvalue = url; } public void setTokenServerUrl(String url) { tokenURIvalue = url; } }
package io.bootique.logback.sentry; import com.google.inject.Binder; import com.google.inject.Module; /** * Loads configuration for {@link io.sentry.Sentry}. * * @author Ibragimov Ruslan * @since 0.16 */ public class LogbackSentryModule implements Module { @Override public void configure(Binder binder) { } }
/******************************************************************************* * Copyright 2017 Bstek * * 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 org.sbybfai.ureport.chart.dataset; /** * @author Jacky.gao * @since 2017年6月8日 */ public class BubbleData { private double x; private double y; private double r; public BubbleData(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getR() { return r; } public void setR(double r) { this.r = r; } }
package com.github.zhenwei.pkix.mime.encoding; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * Reader for Base64 armored objects which converts them into binary data. */ public class Base64InputStream extends InputStream { /* * set up the decoding table. */ private static final byte[] decodingTable; static { decodingTable = new byte[128]; for (int i = 'A'; i <= 'Z'; i++) { decodingTable[i] = (byte) (i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { decodingTable[i] = (byte) (i - 'a' + 26); } for (int i = '0'; i <= '9'; i++) { decodingTable[i] = (byte) (i - '0' + 52); } decodingTable['+'] = 62; decodingTable['/'] = 63; } /** * decode the base 64 encoded input data. * * @return the offset the data starts in out. */ private int decode( int in0, int in1, int in2, int in3, int[] out) throws EOFException { int b1, b2, b3, b4; if (in3 < 0) { throw new EOFException("unexpected end of file in armored stream."); } if (in2 == '=') { b1 = decodingTable[in0] & 0xff; b2 = decodingTable[in1] & 0xff; out[2] = ((b1 << 2) | (b2 >> 4)) & 0xff; return 2; } else if (in3 == '=') { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; out[1] = ((b1 << 2) | (b2 >> 4)) & 0xff; out[2] = ((b2 << 4) | (b3 >> 2)) & 0xff; return 1; } else { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; b4 = decodingTable[in3]; out[0] = ((b1 << 2) | (b2 >> 4)) & 0xff; out[1] = ((b2 << 4) | (b3 >> 2)) & 0xff; out[2] = ((b3 << 6) | b4) & 0xff; return 0; } } InputStream in; int[] outBuf = new int[3]; int bufPtr = 3; // boolean isEndOfStream; public Base64InputStream( InputStream in) { this.in = in; } public int available() throws IOException { // We can't guarantee 'in.available()' bytes aren't all spaces return 0; } public int read() throws IOException { if (bufPtr > 2) { int in0 = readIgnoreSpaceFirst(); if (in0 < 0) { // isEndOfStream = true; return -1; } int in1 = readIgnoreSpace(); int in2 = readIgnoreSpace(); int in3 = readIgnoreSpace(); bufPtr = decode(in0, in1, in2, in3, outBuf); } return outBuf[bufPtr++]; } public void close() throws IOException { in.close(); } private int readIgnoreSpace() throws IOException { for (; ; ) { int c; switch (c = in.read()) { case ' ': case '\t': break; default: return c; } } } private int readIgnoreSpaceFirst() throws IOException { for (; ; ) { int c; switch (c = in.read()) { case ' ': case '\n': case '\r': case '\t': break; default: return c; } } } }
/* * The MIT License * * Copyright (c) 2009-2021 PrimeTek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.primefaces.expression; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.EnumSet; import org.primefaces.mock.FacesContextMock; import org.primefaces.mock.TestVisitContextFactory; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.component.UICommand; import javax.faces.component.UIComponent; import javax.faces.component.UIForm; import javax.faces.component.UINamingContainer; import javax.faces.component.UIOutput; import javax.faces.component.UIPanel; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.primefaces.component.dialog.Dialog; import org.primefaces.component.inputtext.InputText; public class SearchExpressionFacadeTest { @BeforeEach public void setup() { Map<Object, Object> attributes = new HashMap<Object, Object>(); attributes.put(UINamingContainer.SEPARATOR_CHAR_PARAM_NAME, ':'); FacesContext context = new FacesContextMock(attributes); context.setViewRoot(new UIViewRoot()); FactoryFinder.setFactory(FactoryFinder.VISIT_CONTEXT_FACTORY, TestVisitContextFactory.class.getName()); } private UIComponent resolveComponent(UIComponent source, String expression) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveComponent(context, source, expression); } private UIComponent resolveComponent(UIComponent source, String expression, Set<SearchExpressionHint> hints) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveComponent(context, source, expression, hints); } private String resolveClientId(UIComponent source, String expression) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveClientId(context, source, expression); } private String resolveClientId(UIComponent source, String expression, Set<SearchExpressionHint> hints) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveClientId(context, source, expression, hints); } private List<UIComponent> resolveComponents(UIComponent source, String expression) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveComponents(context, source, expression); } private List<UIComponent> resolveComponents(UIComponent source, String expression, Set<SearchExpressionHint> hints) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveComponents(context, source, expression, hints); } private String resolveClientIds(UIComponent source, String expression) { FacesContext context = FacesContext.getCurrentInstance(); return SearchExpressionFacade.resolveClientIds(context, source, expression); } @Test public void resolveComponent_Parent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(innerContainer, resolveComponent(source, "@parent")); } @Test public void resolveComponent_ParentParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(outerContainer, resolveComponent(source, "@parent:@parent"), "Failed"); } @Test public void resolveComponent_Form() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(form, resolveComponent(source, "@form")); } @Test public void resolveComponent_FormParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(root, resolveComponent(source, "@form:@parent")); } @Test public void resolveComponent_All() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(root, resolveComponent(source, "@all")); } @Test public void resolveComponent_This() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(source, resolveComponent(source, "@this")); } @Test public void resolveComponent_ThisParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(innerContainer, resolveComponent(source, "@this:@parent")); } @Test public void resolveComponent_Namingcontainer() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(innerContainer, resolveComponent(source, "@namingcontainer")); } @Test public void resolveComponent_NamingcontainerNamingcontainer() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(outerContainer, resolveComponent(source, "@namingcontainer:@namingcontainer")); } @Test public void resolveComponent_NamingcontainerParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertSame(outerContainer, resolveComponent(source, "@namingcontainer:@parent")); } @Test public void resolveComponent_None() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals(null, resolveComponent(source, "@none")); } @Test public void resolveComponent_Absolute() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertSame(source, resolveComponent(source, " :form:outerContainer:innerContainer:source ")); } @Test public void resolveComponent_Relative() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertSame(component, resolveComponent(source, " other ")); } @Test public void resolveComponent_AbsoluteForm() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertSame(root, resolveComponent(source, " :form:@parent ")); } @Test public void resolveComponent_ParentChild() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertSame(component, resolveComponent(source, " @parent:@child(0) ")); assertSame(source, resolveComponent(source, " @parent:@child(1) ")); } @Test public void resolveClientId_ParentChild() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:other", resolveClientId(source, " @parent:@child(0) ")); assertEquals("form:outerContainer:innerContainer:source", resolveClientId(source, " @parent:@child(1) ")); } @Test public void resolveComponent_AbsoluteNamingcontainer() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertSame(form, resolveComponent(source, " :form:outerContainer:@namingcontainer ")); } @Test public void resolveComponent_AbsoluteNamingcontainerParent() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals(root, resolveComponent(source, " :form:outerContainer:@namingcontainer:@parent ")); } @Test public void resolveClientId_None() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals("@none", resolveClientId(source, " @none", EnumSet.of(SearchExpressionHint.RESOLVE_CLIENT_SIDE))); } @Test public void resolveClientId_PFS() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals("@(.myClass, div)", resolveClientId(source, "@(.myClass, div) ")); } @Test public void resolveClientId_All() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals("@all", resolveClientId(source, "@all", EnumSet.of(SearchExpressionHint.RESOLVE_CLIENT_SIDE))); } @Test public void resolveComponent_NotNestablePasstrough() { UIComponent source = new UICommand(); source.setId("source"); try { resolveComponent(source, " @widgetVar(myForm:myDiv):asd"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } try { resolveComponent(source, " @none:@all:asd"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveClientId_NotNestablePasstrough() { UIComponent source = new UICommand(); source.setId("source"); try { resolveClientId(source, " @none:@all:asd"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveClientId_Parent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer", resolveClientId(source, " @parent ")); } @Test public void resolveClientId_This() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:source", resolveClientId(source, " @this ")); } @Test public void resolveClientId_Namingcontainer() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer", resolveClientId(source, " @namingcontainer ")); } @Test public void resolveClientId_Form() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form", resolveClientId(source, " @form ")); } @Test public void resolveClientId_AbsoluteId() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals("form", resolveClientId(source, " :form ")); } @Test public void resolveClientId_Absolute() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:source", resolveClientId(source, " :form:outerContainer:innerContainer:source ")); } @Test public void resolveClientId_Relative() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:other", resolveClientId(source, " other ")); } @Test public void resolveClientId_AbsoluteForm() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("root", resolveClientId(source, " :form:@parent ")); } @Test public void resolveClientId_AbsoluteNamingcontainer() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form", resolveClientId(source, " :form:outerContainer:@namingcontainer ")); } @Test public void resolveClientId_AbsoluteNamingcontainerParent() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("root", resolveClientId(source, " :form:outerContainer:@namingcontainer:@parent ")); } @Test public void resolveComponent_AbsoluteKeywordStart() { UIComponent source = new UICommand(); source.setId("source"); try { resolveComponent(source, " :@form:asd"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveClientId_AbsoluteKeywordStart() { UIComponent source = new UICommand(); source.setId("source"); try { resolveClientId(source, " :@form:asd"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveClientIds_RelativeAndParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:other form:outerContainer:innerContainer", resolveClientIds(source, " other @parent")); } @Test public void resolveClientIds_RelativeAndParentParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:other form:outerContainer", resolveClientIds(source, " other @parent:@parent")); } @Test public void resolveClientIds_RelativeAndThisParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:other form:outerContainer:innerContainer", resolveClientIds(source, " other @this:@parent")); } @Test public void resolveClientIds_RelativeAndPFSAndWidgetVarAndFormParent() { UIComponent root = new UIPanel(); root.setId("root"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("form:outerContainer:innerContainer:other @(.myClass, .myClass2) @widgetVar(test) root @(.myClass :not:(select))", resolveClientIds(source, " other,@(.myClass, .myClass2) @widgetVar(test),@form:@parent @(.myClass :not:(select))")); } @Test public void resolveComponents_RelativeAndParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); List<UIComponent> resolvedComponents = resolveComponents(source, " other @parent"); assertTrue(resolvedComponents.contains(component)); assertTrue(resolvedComponents.contains(innerContainer)); assertEquals(2, resolvedComponents.size()); } @Test public void resolveComponents_RelativeAndParentParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); List<UIComponent> resolvedComponents = resolveComponents(source, " other @parent:@parent "); assertTrue(resolvedComponents.contains(component)); assertTrue(resolvedComponents.contains(outerContainer)); assertEquals(2, resolvedComponents.size()); } @Test public void resolveComponents_RelativeAndThisParent() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); component.setId("other"); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); List<UIComponent> resolvedComponents = resolveComponents(source, " other,@this:@parent "); assertTrue(resolvedComponents.contains(component)); assertTrue(resolvedComponents.contains(innerContainer)); assertEquals(2, resolvedComponents.size()); } @Test public void resolveClientIds_PFSNestedParenthese() { UIComponent source = new UICommand(); source.setId("source"); assertEquals("@(.ui-panel :input:not(select)) @widgetVar(test)", resolveClientIds(source, " @(.ui-panel :input:not(select)),@widgetVar(test) ")); } @Test public void resolveClientIds_PFSMultipleIds() { UIComponent source = new UICommand(); source.setId("source"); assertEquals("source @(.ui-panel :input:not(select), #myPanel, #myPanel2) @(myId3) source", resolveClientIds(source, " @this,@(.ui-panel :input:not(select), #myPanel, #myPanel2) @(myId3),@this")); } @Test public void resolveClientId_NonCombineableAllAndNone() { UIComponent source = new UICommand(); source.setId("source"); try { resolveClientIds(source, " :@form:asd @none @all "); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveComponentWithParentFallback() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); assertEquals( root, SearchExpressionFacade.resolveComponent( FacesContext.getCurrentInstance(), form, null, EnumSet.of(SearchExpressionHint.PARENT_FALLBACK))); assertEquals( root, SearchExpressionFacade.resolveComponent( FacesContext.getCurrentInstance(), form, " ", EnumSet.of(SearchExpressionHint.PARENT_FALLBACK))); } @Test public void resolveClientIdsWithParentFallback() { UIComponent root = new UIPanel(); root.setId("test"); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); assertEquals( "test", SearchExpressionFacade.resolveClientIds( FacesContext.getCurrentInstance(), form, null, EnumSet.of(SearchExpressionHint.PARENT_FALLBACK))); assertEquals( "test", SearchExpressionFacade.resolveClientIds( FacesContext.getCurrentInstance(), form, " ", EnumSet.of(SearchExpressionHint.PARENT_FALLBACK))); } @Test public void resolveComponent_Next() { UIComponent root = new UIPanel(); root.setId("root"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); UIComponent command3 = new UICommand(); command3.setId("command3"); root.getChildren().add(command3); assertSame(command2, resolveComponent(command1, " @next ")); assertSame(command3, resolveComponent(command2, " @next ")); try { resolveComponent(command3, " @next"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(ComponentNotFoundException.class, e.getClass()); } } @Test public void resolveComponent_NextNext() { UIComponent root = new UIPanel(); root.setId("root"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); UIComponent command3 = new UICommand(); command3.setId("command3"); root.getChildren().add(command3); assertSame(command3, resolveComponent(command1, " @next:@next ")); try { resolveComponent(command2, " @next:@next"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } try { resolveComponent(command3, " @next:@next"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveComponent_Previous() { UIComponent root = new UIPanel(); root.setId("root"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); UIComponent command3 = new UICommand(); command3.setId("command3"); root.getChildren().add(command3); assertSame(command1, resolveComponent(command2, " @previous ")); assertSame(command2, resolveComponent(command3, " @previous ")); try { resolveComponent(command1, " @previous"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(ComponentNotFoundException.class, e.getClass()); } } @Test public void resolveComponent_PreviousPrevious() { UIComponent root = new UIPanel(); root.setId("root"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); UIComponent command3 = new UICommand(); command3.setId("command3"); root.getChildren().add(command3); assertSame(command1, resolveComponent(command3, " @previous:@previous ")); try { resolveComponent(command2, " @previous:@previous"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } try { resolveComponent(command1, " @previous:@previous"); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveComponent_FormChildNextNext() { UIForm root = new UIForm(); root.setId("form"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); UIComponent command3 = new UICommand(); command3.setId("command3"); root.getChildren().add(command3); assertSame(command3, resolveComponent(command1, " @form:@child(0):@next:@next ")); } @Test public void resolveComponent_NoResult() { UIForm root = new UIForm(); root.setId("form"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); try { assertSame(root, resolveComponent(command1, " command1:@parent:command3 ")); Assertions.fail("This should actually raise an exception"); } catch (Exception e) { assertEquals(FacesException.class, e.getClass()); } } @Test public void resolveComponent_IgnoreNoResult() { UIForm root = new UIForm(); root.setId("form"); UIComponent command1 = new UICommand(); command1.setId("command1"); root.getChildren().add(command1); UIComponent command2 = new UICommand(); command2.setId("command2"); root.getChildren().add(command2); assertSame(null, resolveComponent(command1, " command3 ", EnumSet.of(SearchExpressionHint.IGNORE_NO_RESULT))); } @Test public void resolveComponent_WidgetVarNext() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); InputText input = new InputText(); input.setWidgetVar("myInput_Widget"); outerContainer.getChildren().add(input); InputText input2 = new InputText(); input2.setWidgetVar("myInput_Widget2"); outerContainer.getChildren().add(input2); assertEquals(input2, resolveComponent(source, " @widgetVar(myInput_Widget):@next")); } @Test public void resolveClientId_WidgetVarNext() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); InputText input = new InputText(); input.setWidgetVar("myInput_Widget"); outerContainer.getChildren().add(input); InputText input2 = new InputText(); input2.setId("input2"); input2.setWidgetVar("myInput_Widget2"); outerContainer.getChildren().add(input2); assertEquals(input2.getClientId(), resolveClientId(source, " @widgetVar(myInput_Widget):@next")); } @Test public void resolveComponent_WidgetVar() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); InputText input = new InputText(); input.setWidgetVar("myInput_Widget"); outerContainer.getChildren().add(input); assertEquals(input, resolveComponent(source, " @widgetVar(myInput_Widget)")); } @Test public void resolveClientId_AbsoluteWithFormPrependIdFalse() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("outerContainer:innerContainer:source", resolveClientId(source, " :form:outerContainer:innerContainer:source ")); } @Test public void resolveClientId_AbsoluteWithFormPrependIdFalse_InvokeOnComponent() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("outerContainer:innerContainer:source", resolveClientId(source, " outerContainer:innerContainer:source ")); } @Test public void resolveClientId_AbsoluteWithFormPrependIdFalse_InvokeOnComponentSkipUnrendered() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals("outerContainer:innerContainer:source", resolveClientId(source, " outerContainer:innerContainer:source ")); } @Test public void resolveClientId_AbsoluteWithFormPrependIdFalse_InvokeOnComponentUnrendered() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); innerContainer.setRendered(false); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals(source.getClientId(), resolveClientId(source, " outerContainer:innerContainer:source ")); } @Test public void resolveComponent_AbsoluteWithFormPrependIdFalse_InvokeOnComponentUnrendered() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); innerContainer.setRendered(false); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); source.setId("source"); innerContainer.getChildren().add(source); assertEquals(source, resolveComponent(source, " outerContainer:innerContainer:source ")); } @Test public void resolveComponents_SimpleMultiSearchExpressionResolver() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); ArrayList<UIComponent> components = new ArrayList<>(); components.add(outerContainer); components.add(innerContainer); SearchExpressionResolverFactory.registerResolver("@test", new TestMultiSearchExpressionResolver(components)); List<UIComponent> result = resolveComponents(root, " @test "); assertTrue(result.size() == 2); assertTrue(result.contains(outerContainer)); assertTrue(result.contains(innerContainer)); SearchExpressionResolverFactory.removeResolver("@test"); } @Test public void resolveComponents_SimpleMultiSearchExpressionResolver_Parent() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); ArrayList<UIComponent> components = new ArrayList<>(); components.add(outerContainer); components.add(innerContainer); SearchExpressionResolverFactory.registerResolver("@test", new TestMultiSearchExpressionResolver(components)); List<UIComponent> result = resolveComponents(root, " @test:@parent "); assertTrue(result.size() == 2); assertTrue(result.contains(outerContainer)); assertTrue(result.contains(form)); SearchExpressionResolverFactory.removeResolver("@test"); } @Test public void resolveComponents_SimpleMultiSearchExpressionResolver_ParentParent() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("outerContainer"); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("innerContainer"); outerContainer.getChildren().add(innerContainer); ArrayList<UIComponent> components = new ArrayList<>(); components.add(outerContainer); components.add(innerContainer); SearchExpressionResolverFactory.registerResolver("@test", new TestMultiSearchExpressionResolver(components)); List<UIComponent> result = resolveComponents(root, " @test:@parent:@parent "); assertTrue(result.size() == 2); assertTrue(result.contains(root)); assertTrue(result.contains(form)); SearchExpressionResolverFactory.removeResolver("@test"); } @Test public void resolveComponents_SimpleMultiSearchExpressionResolver_ParentParent_IgnoreNoResult() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); ArrayList<UIComponent> components = new ArrayList<>(); components.add(form); components.add(root); SearchExpressionResolverFactory.registerResolver("@test", new TestMultiSearchExpressionResolver(components)); List<UIComponent> result = resolveComponents(root, " @test:@parent:@parent ", EnumSet.of(SearchExpressionHint.IGNORE_NO_RESULT)); assertTrue(result.size() == 1); assertTrue(result.contains(FacesContext.getCurrentInstance().getViewRoot())); SearchExpressionResolverFactory.removeResolver("@test"); } @Test public void resolveClientIds_MultiSearchExpressionResolver_ClientIdSearchExpressionResolver() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UIForm form = new UIForm(); form.setId("form"); form.setPrependId(false); root.getChildren().add(form); ArrayList<UIComponent> components = new ArrayList<>(); components.add(form); components.add(root); SearchExpressionResolverFactory.registerResolver("@test", new TestMultiSearchExpressionResolver(components)); SearchExpressionResolverFactory.registerResolver("@test2", new TestClientIdSearchExpressionResolver("hallo client id")); String result = resolveClientIds(root, " @test:@test2 "); assertEquals("hallo client id hallo client id", result); SearchExpressionResolverFactory.removeResolver("@test"); SearchExpressionResolverFactory.removeResolver("@test2"); } @Test public void resolveComponent_Root() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("myContainer"); root.getChildren().add(outerContainer); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); Assertions.assertEquals(FacesContext.getCurrentInstance().getViewRoot(), resolveComponent(form, " @root ")); } @Test public void resolveComponents_Root() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("myContainer"); root.getChildren().add(outerContainer); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("myContainer"); form.getChildren().add(innerContainer); UINamingContainer innerContainer2 = new UINamingContainer(); innerContainer2.setId("myContainer2"); form.getChildren().add(innerContainer2); List<UIComponent> result = resolveComponents(innerContainer2, " @root "); assertTrue(result.size() == 1); assertTrue(result.contains(FacesContext.getCurrentInstance().getViewRoot())); } @Test public void resolveClientId_Root() { UIComponent root = new UIPanel(); UIForm form = new UIForm(); root.getChildren().add(form); UINamingContainer outerContainer = new UINamingContainer(); form.getChildren().add(outerContainer); UINamingContainer innerContainer = new UINamingContainer(); outerContainer.getChildren().add(innerContainer); UIComponent component = new UIOutput(); innerContainer.getChildren().add(component); UIComponent source = new UICommand(); innerContainer.getChildren().add(source); assertEquals("@all", resolveClientId(source, "@root", EnumSet.of(SearchExpressionHint.RESOLVE_CLIENT_SIDE))); } @Test public void resolveComponents_Id_FromRoot() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("myContainer"); root.getChildren().add(outerContainer); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("myContainer"); form.getChildren().add(innerContainer); UINamingContainer innerContainer2 = new UINamingContainer(); innerContainer2.setId("myContainer2"); form.getChildren().add(innerContainer2); List<UIComponent> result = resolveComponents(innerContainer2, " @root:@id(myContainer) "); assertTrue(result.size() == 2); assertTrue(result.contains(outerContainer)); assertTrue(result.contains(innerContainer)); } public void resolveComponent_Id() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("myContainer"); root.getChildren().add(outerContainer); resolveComponent(root, " @id(myContainer) "); } @Test public void resolveComponents_Id() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); UINamingContainer outerContainer = new UINamingContainer(); outerContainer.setId("myContainer"); root.getChildren().add(outerContainer); UIForm form = new UIForm(); form.setId("form"); root.getChildren().add(form); UINamingContainer innerContainer = new UINamingContainer(); innerContainer.setId("myContainer"); form.getChildren().add(innerContainer); UINamingContainer innerContainer2 = new UINamingContainer(); innerContainer2.setId("myContainer2"); form.getChildren().add(innerContainer2); UINamingContainer innerContainer3 = new UINamingContainer(); innerContainer3.setId("myContainer3-test"); form.getChildren().add(innerContainer3); List<UIComponent> result = resolveComponents(form, " @id(myContainer) "); assertTrue(result.size() == 1); assertTrue(result.contains(innerContainer)); result = resolveComponents(form, " @id(myContainer3-test) "); assertTrue(result.size() == 1); assertTrue(result.contains(innerContainer3)); } @Test public void resolveClientIdClientSide() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); Dialog dialog = new Dialog(); dialog.setId("dlg"); dialog.setWidgetVar("myDlg"); root.getChildren().add(dialog); String clientId = resolveClientId(root, " @widgetVar(myDlg) ", EnumSet.of(SearchExpressionHint.RESOLVE_CLIENT_SIDE)); assertEquals("@widgetVar(myDlg)", clientId); } @Test public void resolveClientId() { UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); Dialog dialog = new Dialog(); dialog.setId("dlg"); dialog.setWidgetVar("myDlg"); root.getChildren().add(dialog); String clientId = resolveClientId(root, " @widgetVar(myDlg) "); assertSame("dlg", clientId); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.devicefarm.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.devicefarm.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetSuiteResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetSuiteResultJsonUnmarshaller implements Unmarshaller<GetSuiteResult, JsonUnmarshallerContext> { public GetSuiteResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetSuiteResult getSuiteResult = new GetSuiteResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getSuiteResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("suite", targetDepth)) { context.nextToken(); getSuiteResult.setSuite(SuiteJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getSuiteResult; } private static GetSuiteResultJsonUnmarshaller instance; public static GetSuiteResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetSuiteResultJsonUnmarshaller(); return instance; } }
package com.felhr.usbserial; import com.felhr.utils.HexData; import android.util.Log; public class UsbSerialDebugger { private static final String CLASS_ID = UsbSerialDebugger.class.getSimpleName(); public static final String ENCODING = "UTF-8"; private UsbSerialDebugger() { } public static void printLogGet(byte[] src, boolean verbose) { if(!verbose) { Log.i(CLASS_ID, "Data obtained from write buffer: " + new String(src)); }else { Log.i(CLASS_ID, "Data obtained from write buffer: " + new String(src)); Log.i(CLASS_ID, "Raw data from write buffer: " + HexData.hexToString(src)); Log.i(CLASS_ID, "Number of bytes obtained from write buffer: " + src.length); } } public static void printLogPut(byte[] src, boolean verbose) { if(!verbose) { Log.i(CLASS_ID, "Data obtained pushed to write buffer: " + new String(src)); }else { Log.i(CLASS_ID, "Data obtained pushed to write buffer: " + new String(src)); Log.i(CLASS_ID, "Raw data pushed to write buffer: " + HexData.hexToString(src)); Log.i(CLASS_ID, "Number of bytes pushed from write buffer: " + src.length); } } public static void printReadLogGet(byte[] src, boolean verbose) { if(!verbose) { Log.i(CLASS_ID, "Data obtained from Read buffer: " + new String(src)); }else { Log.i(CLASS_ID, "Data obtained from Read buffer: " + new String(src)); Log.i(CLASS_ID, "Raw data from Read buffer: " + HexData.hexToString(src)); Log.i(CLASS_ID, "Number of bytes obtained from Read buffer: " + src.length); } } public static void printReadLogPut(byte[] src, boolean verbose) { if(!verbose) { Log.i(CLASS_ID, "Data obtained pushed to read buffer: " + new String(src)); }else { Log.i(CLASS_ID, "Data obtained pushed to read buffer: " + new String(src)); Log.i(CLASS_ID, "Raw data pushed to read buffer: " + HexData.hexToString(src)); Log.i(CLASS_ID, "Number of bytes pushed from read buffer: " + src.length); } } }
package com.oulumo.ngrok.client.dto; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Zsolt Homorodi. */ public enum TunnelCreationTlsType { @JsonProperty("true") HttpsOnly, @JsonProperty("false") HttpOnly, @JsonProperty("both") Both }
package com.mytool.admin.dao; import com.mytool.admin.dto.SmsCouponParam; import org.apache.ibatis.annotations.Param; /** * 自定义优惠券管理Dao * Created by macro on 2018/8/29. */ public interface SmsCouponDao { /** * 获取优惠券详情包括绑定关系 */ SmsCouponParam getItem(@Param("id") Long id); }
/* * 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 org.jsmpp.bean; import static org.testng.Assert.*; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataCodings; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.SimpleDataCoding; import org.testng.annotations.Test; /** * @author uudashr * */ public class SimpleDataCodingTest { @Test public void alphaDefaultClass0() { // 11110000 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS0); byte expected = (byte)0xf0; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alphaDefaultClass1() { // 11110001 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1); byte expected = (byte)0xf1; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alphaDefaultClass2() { // 11110010 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS2); byte expected = (byte)0xf2; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alphaDefaultClass3() { // 11110011 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS3); byte expected = (byte)0xf3; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alpha8BitClass0() { // 11110100 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_8_BIT, MessageClass.CLASS0); byte expected = (byte)0xf4; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alpha8BitClass1() { // 11110101 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_8_BIT, MessageClass.CLASS1); byte expected = (byte)0xf5; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alpha8BitClass2() { // 11110110 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_8_BIT, MessageClass.CLASS2); byte expected = (byte)0xf6; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } @Test public void alpha8BitClass3() { // 11110111 SimpleDataCoding dataCoding = new SimpleDataCoding(Alphabet.ALPHA_8_BIT, MessageClass.CLASS3); byte expected = (byte)0xf7; assertEquals(dataCoding.toByte(), expected); DataCoding buildedInstance = DataCodings.newInstance(dataCoding.toByte()); assertEquals(buildedInstance, dataCoding); } }
package com.auth0.jwt.algorithms; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import org.apache.commons.codec.binary.Base64; class NoneAlgorithm extends Algorithm { NoneAlgorithm() { super("none", "none"); } @Override public void verify(DecodedJWT jwt) throws SignatureVerificationException { byte[] signatureBytes = Base64.decodeBase64(jwt.getSignature()); if (signatureBytes.length > 0) { throw new SignatureVerificationException(this); } } @Override public byte[] sign(byte[] headerBytes, byte[] payloadBytes) throws SignatureGenerationException { return new byte[0]; } @Override @Deprecated public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { return new byte[0]; } }
package jetbrains.mps.core.xml.textGen; /*Generated by MPS */ import jetbrains.mps.text.rt.TextGenDescriptorBase; import jetbrains.mps.text.rt.TextGenContext; import jetbrains.mps.text.impl.TextGenSupport; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class XmlCharRefValue_TextGen extends TextGenDescriptorBase { @Override public void generateText(final TextGenContext ctx) { final TextGenSupport tgs = new TextGenSupport(ctx); tgs.append("&#"); tgs.append(SPropertyOperations.getString(ctx.getPrimaryInput(), PROPS.charCode$OD8V)); tgs.append(";"); } private static final class PROPS { /*package*/ static final SProperty charCode$OD8V = MetaAdapterFactory.getProperty(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x2abf08504ffed7feL, 0x2abf08504ffed806L, "charCode"); } }
package ca.ulaval.glo4003.gates.helpers; import static ca.ulaval.glo4003.gates.helpers.AccessStatusMother.createAccessStatus; import ca.ulaval.glo4003.gates.services.dto.AccessStatusDto; public class AccessStatusDtoBuilder { private String accessStatus = createAccessStatus().toString(); private AccessStatusDtoBuilder() {} public static AccessStatusDtoBuilder anAccessStatusDto() { return new AccessStatusDtoBuilder(); } public AccessStatusDtoBuilder withAccessStatus(String accessStatus) { this.accessStatus = accessStatus; return this; } public AccessStatusDto build() { AccessStatusDto accessStatusDto = new AccessStatusDto(); accessStatusDto.accessStatus = accessStatus; return accessStatusDto; } }
package org.apache.ofbiz.shipment.shipment; import lombok.experimental.FieldNameConstants; import java.io.Serializable; import lombok.Getter; import lombok.Setter; import java.sql.Timestamp; import org.apache.ofbiz.entity.GenericValue; import java.util.List; import java.util.ArrayList; /** * Shipment Status */ @FieldNameConstants public class ShipmentStatus implements Serializable { public static final long serialVersionUID = 8153589021283104768L; public static final String NAME = "ShipmentStatus"; /** * Status Id */ @Getter @Setter private String statusId; /** * Shipment Id */ @Getter @Setter private String shipmentId; /** * Status Date */ @Getter @Setter private Timestamp statusDate; /** * Change By User Login Id */ @Getter @Setter private String changeByUserLoginId; /** * Last Updated Stamp */ @Getter @Setter private Timestamp lastUpdatedStamp; /** * Last Updated Tx Stamp */ @Getter @Setter private Timestamp lastUpdatedTxStamp; /** * Created Stamp */ @Getter @Setter private Timestamp createdStamp; /** * Created Tx Stamp */ @Getter @Setter private Timestamp createdTxStamp; public ShipmentStatus(GenericValue value) { statusId = (String) value.get(FIELD_STATUS_ID); shipmentId = (String) value.get(FIELD_SHIPMENT_ID); statusDate = (Timestamp) value.get(FIELD_STATUS_DATE); changeByUserLoginId = (String) value.get(FIELD_CHANGE_BY_USER_LOGIN_ID); lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP); lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP); createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP); createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP); } public static ShipmentStatus fromValue( org.apache.ofbiz.entity.GenericValue value) { return new ShipmentStatus(value); } public static List<ShipmentStatus> fromValues(List<GenericValue> values) { List<ShipmentStatus> entities = new ArrayList<>(); for (GenericValue value : values) { entities.add(new ShipmentStatus(value)); } return entities; } }
package utilities.swing; import java.awt.Color; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoManager; @SuppressWarnings("serial") public class LinedTextArea extends JScrollPane { private static final Logger LOGGER = Logger.getLogger(LinedTextArea.class.getName()); private static final int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); private final JTextArea lines; public LinedTextArea(final JTextArea textArea) { lines = new JTextArea("1"); lines.setBackground(Color.LIGHT_GRAY); lines.setEditable(false); final UndoManager undoManager = new UndoManager(); Document document = textArea.getDocument(); document.addUndoableEditListener(new UndoableEditListener() { @Override public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); // System.out.println(e); } }); textArea.getActionMap().put("Undo", new AbstractAction("Undo") { @Override public void actionPerformed(ActionEvent evt) { try { if (undoManager.canUndo()) { undoManager.undo(); } } catch (CannotUndoException e) { LOGGER.log(Level.WARNING, "Unable to undo", e); } } }); textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, MASK), "Undo"); textArea.getActionMap().put("Redo", new AbstractAction("Redo") { @Override public void actionPerformed(ActionEvent evt) { try { if (undoManager.canRedo()) { undoManager.redo(); } } catch (CannotRedoException e) { LOGGER.log(Level.WARNING, "Unable to redo", e); } } }); textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Y,MASK), "Redo"); textArea.getDocument().addDocumentListener(new DocumentListener(){ private String getText() { int caretPosition = textArea.getDocument().getLength(); Element root = textArea.getDocument().getDefaultRootElement(); StringBuilder text = new StringBuilder("1" + System.getProperty("line.separator")); for(int i = 2; i < root.getElementIndex(caretPosition) + 2; i++){ text.append(i + System.getProperty("line.separator")); } return text.toString(); } @Override public void changedUpdate(DocumentEvent de) { lines.setText(getText()); } @Override public void insertUpdate(DocumentEvent de) { lines.setText(getText()); } @Override public void removeUpdate(DocumentEvent de) { lines.setText(getText()); } }); getViewport().add(textArea); setRowHeaderView(lines); setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * * Copyright 2018 Nextdoor.com, Inc * */ package com.nextdoor.bender.operation.json.key; import com.nextdoor.bender.config.AbstractConfig; import com.nextdoor.bender.operation.EventOperation; import com.nextdoor.bender.operation.OperationFactory; /** * Create a {@link FlattenOperation}. */ public class FlattenOperationFactory implements OperationFactory { private FlattenOperationConfig config; public FlattenOperationFactory() { } @Override public EventOperation newInstance() { return new FlattenOperation(this.config.getSeparator()); } @Override public Class getChildClass() { return FlattenOperation.class; } @Override public void setConf(AbstractConfig config) { this.config = (FlattenOperationConfig) config; } }
package com.ocadotechnology.newrelic.apiclient.internal; import com.ocadotechnology.newrelic.apiclient.ServersApi; import com.ocadotechnology.newrelic.apiclient.internal.client.NewRelicClient; import com.ocadotechnology.newrelic.apiclient.internal.model.ServerList; import com.ocadotechnology.newrelic.apiclient.model.servers.Server; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import java.util.Collections; import java.util.Optional; import static java.util.Arrays.asList; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultServersApiTest { @Rule public final MockitoRule mockito = MockitoJUnit.rule(); @Mock private Response responseMock; private ServersApi testee; @Before public void setUp() { NewRelicClient clientMock = mock(NewRelicClient.class); WebTarget webTargetMock = mock(WebTarget.class); Invocation.Builder builderMock = mock(Invocation.Builder.class); when(clientMock.target("/v2/servers.json")).thenReturn(webTargetMock); when(webTargetMock.queryParam("filter[name]", "server")).thenReturn(webTargetMock); when(webTargetMock.request(APPLICATION_JSON_TYPE)).thenReturn(builderMock); when(builderMock.get()).thenReturn(responseMock); testee = new DefaultServersApi(clientMock); } @Test public void getByName_shouldReturnServer_whenClientReturnsNotUniqueResult() throws Exception { // given when(responseMock.readEntity(ServerList.class)).thenReturn(new ServerList(asList( Server.builder().name("server").build(), Server.builder().name("server1").build() ))); // when Optional<Server> serverOptional = testee.getByName("server"); // then assertThat(serverOptional).isNotEmpty(); } @Test public void getByName_shouldNotReturnServer_whenClientReturnsNotMatchingResult() throws Exception { // given when(responseMock.readEntity(ServerList.class)).thenReturn(new ServerList(Collections.singletonList( Server.builder().name("server1").build() ))); // when Optional<Server> serverOptional = testee.getByName("server"); // then assertThat(serverOptional).isEmpty(); } @Test public void getByName_shouldNotReturnServer_whenClientReturnsEmptyList() throws Exception { // given when(responseMock.readEntity(ServerList.class)).thenReturn(new ServerList(Collections.emptyList())); // when Optional<Server> serverOptional = testee.getByName("server"); // then assertThat(serverOptional).isEmpty(); } }
package org.batfish.representation.cumulus; import java.io.Serializable; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** An access-list for IPv4 prefixes */ public final class IpPrefixList implements Serializable { private @Nullable String _description; private final @Nonnull SortedMap<Long, IpPrefixListLine> _lines; private final @Nonnull String _name; public IpPrefixList(String name) { _name = name; _lines = new TreeMap<>(); } public @Nullable String getDescription() { return _description; } public @Nonnull SortedMap<Long, IpPrefixListLine> getLines() { return _lines; } public void addLine(IpPrefixListLine line) { _lines.put(line.getLine(), line); } public @Nonnull String getName() { return _name; } public void setDescription(String description) { _description = description; } }
/* * Copyright 2012 GitHub Inc. * * 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.github.pockethub.ui.issue; import static com.github.pockethub.RequestCodes.ISSUE_CLOSE; import static com.github.pockethub.RequestCodes.ISSUE_REOPEN; import static org.eclipse.egit.github.core.service.IssueService.STATE_CLOSED; import static org.eclipse.egit.github.core.service.IssueService.STATE_OPEN; import android.accounts.Account; import com.alorma.github.sdk.bean.dto.response.IssueState; import com.github.pockethub.R; import com.github.pockethub.core.issue.IssueStore; import com.github.pockethub.ui.ConfirmDialogFragment; import com.github.pockethub.ui.DialogFragmentActivity; import com.github.pockethub.ui.ProgressDialogTask; import com.google.inject.Inject; import com.alorma.github.sdk.bean.dto.response.Repo; import com.alorma.github.sdk.bean.dto.response.Issue; /** * Task to close or reopen an issue */ public class EditStateTask extends ProgressDialogTask<Issue> { @Inject private IssueStore store; private final Repo repositoryId; private final int issueNumber; private boolean close; /** * Create task to edit issue state * * @param activity * @param repositoryId * @param issueNumber */ public EditStateTask(final DialogFragmentActivity activity, final Repo repositoryId, final int issueNumber) { super(activity); this.repositoryId = repositoryId; this.issueNumber = issueNumber; } /** * Confirm action * * @param close * @return this task */ public EditStateTask confirm(boolean close) { if (close) ConfirmDialogFragment.show((DialogFragmentActivity) getContext(), ISSUE_CLOSE, getString(R.string.issue_confirm_close_title), getString(R.string.issue_confirm_close_message)); else ConfirmDialogFragment.show((DialogFragmentActivity) getContext(), ISSUE_REOPEN, getString(R.string.issue_confirm_reopen_title), getString(R.string.issue_confirm_reopen_message)); return this; } @Override protected Issue run(Account account) throws Exception { IssueState state; if (close) state = IssueState.closed; else state = IssueState.open; return store.changeState(repositoryId, issueNumber, state); } /** * Edit state of issue * * @param close * @return this task */ public EditStateTask edit(boolean close) { if (close) showIndeterminate(R.string.closing_issue); else showIndeterminate(R.string.reopening_issue); this.close = close; execute(); return this; } }
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 ~ 2010 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package handling.world; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class MapleParty implements Serializable { private static final long serialVersionUID = 9179541993413738569L; private MaplePartyCharacter leader; private List<MaplePartyCharacter> members = new LinkedList<MaplePartyCharacter>(); private int id; public MapleParty(int id, MaplePartyCharacter chrfor) { this.leader = chrfor; this.members.add(this.leader); this.id = id; } public boolean containsMembers(MaplePartyCharacter member) { return members.contains(member); } public void addMember(MaplePartyCharacter member) { members.add(member); } public void removeMember(MaplePartyCharacter member) { members.remove(member); } public void updateMember(MaplePartyCharacter member) { for (int i = 0; i < members.size(); i++) { MaplePartyCharacter chr = members.get(i); if (chr.equals(member)) { members.set(i, member); } } } public MaplePartyCharacter getMemberById(int id) { for (MaplePartyCharacter chr : members) { if (chr.getId() == id) { return chr; } } return null; } public MaplePartyCharacter getMemberByIndex(int index) { return members.get(index); } public Collection<MaplePartyCharacter> getMembers() { return new LinkedList<MaplePartyCharacter>(members); } public int getId() { return id; } public void setId(int id) { this.id = id; } public MaplePartyCharacter getLeader() { return leader; } public void setLeader(MaplePartyCharacter nLeader) { leader = nLeader; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MapleParty other = (MapleParty) obj; if (id != other.id) { return false; } return true; } }
package com.mcmu.juanjesus.mcmuasteroids; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
package xyz.tdt4240.breakin.game.sprites.bricks; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import java.util.Timer; import java.util.TimerTask; import xyz.tdt4240.breakin.application.Constants; import xyz.tdt4240.breakin.game.movement_patterns.CircularMovementPattern; import xyz.tdt4240.breakin.game.sprites.Ball; import xyz.tdt4240.breakin.game.states.GameState; /** * Increases ball velocity when hit */ public class SpeedBrick extends Brick { //Should not really be static since the speed can be applied to different players and different balls private static volatile boolean isSpeedChanged; private Timer timer; private Ball ball; public SpeedBrick(GameState gameState){ super(gameState); brickScore = Constants.BRICK_SCORE_SPEED; brickTexture = new Texture(Constants.TEXTURE_BRICK_SPEED); } @Override public void onBreak(Ball ball) { super.onBreak(ball); if(!isSpeedChanged){ isSpeedChanged = true; this.ball = ball; Vector2 velocity = ball.getVelocity(); velocity.scl(2f); ball.setVelocity(velocity); timer = new Timer(); timer.schedule(new ResetSpeedTask(), Constants.SPEED_BRICK_TIME); } } private class ResetSpeedTask extends TimerTask { public void run(){ isSpeedChanged = false; Vector2 velocity = ball.getVelocity(); velocity.scl(0.5f); ball.setVelocity(velocity); } } }
package com.skymanlab.weighttraining.management.project.ApiManager; import android.app.Activity; import android.app.NotificationChannel; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.skymanlab.weighttraining.MainActivity; import com.skymanlab.weighttraining.R; import com.squareup.picasso.Picasso; public class NotificationManager { // constant public static final int NOTIFICATION_FITNESS_CENTER = 40000; // constant private static final String CHANNEL_ID_FITNESS_CENTER = "FitnessCenterNotification"; // instance private Activity activity; // constructor public NotificationManager(Activity activity) { this.activity = activity; } public void init() { // 앱의 알림 채널을 시스템에 등록록 createNotificationChannel(); } public void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Fitness Center channel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // 이름, 설명, 중요도 CharSequence name = activity.getString(R.string.etc_notification_manager_channel_id_fitness_center_notification_name); String description = activity.getString(R.string.etc_notification_manager_channel_id_fitness_center_notification_description); int importance = android.app.NotificationManager.IMPORTANCE_DEFAULT; // 채널 생성 NotificationChannel channelFitnessCenterGeofencingNotification = new NotificationChannel(CHANNEL_ID_FITNESS_CENTER, name, importance); channelFitnessCenterGeofencingNotification.setDescription(description); // 채널 등록 android.app.NotificationManager notificationManager = activity.getSystemService(android.app.NotificationManager.class); notificationManager.createNotificationChannel(channelFitnessCenterGeofencingNotification); } } public static void sendFitnessCenterNotification(Context context, int notificationId, String title, String message) { Intent home = new Intent(context, MainActivity.class); home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent homePendingIntent = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID_FITNESS_CENTER) .setSmallIcon(R.mipmap.icon) .setContentTitle(title) .setContentText(message) .setStyle(new NotificationCompat.BigTextStyle().bigText(message)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(homePendingIntent) .setAutoCancel(true); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(notificationId, builder.build()); } public void sendFitnessCenterNotification(int notificationId, String title, String message) { NotificationCompat.Builder builder = new NotificationCompat.Builder(activity.getApplicationContext(), CHANNEL_ID_FITNESS_CENTER) .setSmallIcon(R.mipmap.icon) .setContentTitle(title) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_DEFAULT); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(activity.getApplicationContext()); notificationManager.notify(notificationId, builder.build()); } }
package me.tomassetti.turin.typesystem; import me.tomassetti.jvm.JvmType; import me.tomassetti.turin.parser.ast.virtual.ArrayLength; import me.tomassetti.turin.symbols.Symbol; import java.util.Map; import java.util.Optional; public class ArrayTypeUsage implements TypeUsage { private static String LENGTH_FIELD_NAME = "length"; private TypeUsage componentType; public ArrayTypeUsage(TypeUsage componentType) { this.componentType = componentType; } public TypeUsage getComponentType() { return componentType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArrayTypeUsage that = (ArrayTypeUsage) o; if (!componentType.equals(that.componentType)) return false; return true; } @Override public int hashCode() { return componentType.hashCode(); } /// /// Relation with other types /// @Override public boolean isArray() { return true; } @Override public boolean isReference() { return true; } @Override public ArrayTypeUsage asArrayTypeUsage() { return this; } /// /// JVM /// @Override public JvmType jvmType() { return new JvmType("[" + componentType.jvmType().getSignature()); } /// /// Fields /// @Override public boolean hasInstanceField(String fieldName, Symbol instance) { return fieldName.equals(LENGTH_FIELD_NAME); } @Override public Symbol getInstanceField(String fieldName, Symbol instance) { if (fieldName.equals(LENGTH_FIELD_NAME)) { return new ArrayLength(instance); } else { throw new IllegalArgumentException("An array has no field named " + fieldName); } } /// /// Methods /// @Override public Optional<Invokable> getMethod(String method, boolean staticContext) { return Optional.empty(); } /// /// Misc /// @Override public boolean canBeAssignedTo(TypeUsage type) { if (type.isArray()) { return componentType.equals(type.asArrayTypeUsage().getComponentType()); } else { return type.isReferenceTypeUsage() && type.asReferenceTypeUsage().getQualifiedName().equals(Object.class.getCanonicalName()); } } @Override public String toString() { return "ArrayTypeUsage{" + "componentType=" + componentType + '}'; } @Override public <T extends TypeUsage> TypeUsage replaceTypeVariables(Map<String, T> typeParams) { return this; } @Override public boolean sameType(TypeUsage other) { if (!other.isArray()) { return false; } return this.getComponentType().sameType(other.asArrayTypeUsage().getComponentType()); } @Override public String describe() { return "array of " + getComponentType().describe(); } }
/* * Copyright © 2015-2021 I.N.F.N. * Copyright © 2015-2020 Santer Reply S.p.A. * * 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 it.reply.orchestrator.service.deployment.providers; import it.reply.orchestrator.dto.security.ServiceCredential; public interface CredentialProviderService { public <T extends ServiceCredential> T credentialProvider(String serviceId, String accessToken, Class<T> clazz); }
package smartthings.dw.cassandra.loadbalancing; import com.datastax.driver.core.policies.LoadBalancingPolicy; import com.datastax.driver.core.policies.TokenAwarePolicy; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; @JsonTypeName("tokenAware") public class TokenAwarePolicyFactory implements LoadBalancingPolicyFactory { private final static Logger LOG = LoggerFactory.getLogger(TokenAwarePolicyFactory.class); @Valid @NotNull private LoadBalancingPolicyFactory subPolicy; private Boolean shuffleReplicas; @JsonProperty public LoadBalancingPolicyFactory getSubPolicy() { return subPolicy; } @JsonProperty public void setSubPolicy(LoadBalancingPolicyFactory subPolicy) { this.subPolicy = subPolicy; } @JsonProperty public Boolean getShuffleReplicas() { return shuffleReplicas; } @JsonProperty public void setShuffleReplicas(Boolean shuffleReplicas) { this.shuffleReplicas = shuffleReplicas; } @Override public LoadBalancingPolicy build() { if (shuffleReplicas == null) { LOG.info("TokenAwarePolicyFactory - subPolicy {}", subPolicy.getClass().getCanonicalName()); return new TokenAwarePolicy(subPolicy.build()); } else { LOG.info("TokenAwarePolicyFactory - subPolicy {}", subPolicy.getClass().getCanonicalName()); LOG.info("TokenAwarePolicyFactory - shuffleReplicas {}", shuffleReplicas); return new TokenAwarePolicy(subPolicy.build(), shuffleReplicas); } } }
package com.example.gulimall.ware.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.example.gulimall.ware.entity.PurchaseEntity; import com.example.gulimall.ware.service.PurchaseService; import com.example.gulimall.common.utils.PageUtils; import com.example.gulimall.common.utils.R; /** * 采购信息 * * @author TechRice * @email trice12345@aliyun.com * @date 2021-09-11 00:26:11 */ @RestController @RequestMapping("ware/purchase") public class PurchaseController { @Autowired private PurchaseService purchaseService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("ware:purchase:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = purchaseService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("ware:purchase:info") public R info(@PathVariable("id") Long id){ PurchaseEntity purchase = purchaseService.getById(id); return R.ok().put("purchase", purchase); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("ware:purchase:save") public R save(@RequestBody PurchaseEntity purchase){ purchaseService.save(purchase); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("ware:purchase:update") public R update(@RequestBody PurchaseEntity purchase){ purchaseService.updateById(purchase); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("ware:purchase:delete") public R delete(@RequestBody Long[] ids){ purchaseService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package com.myrunning.leaderboard.model; /** * File: Admin.java * Author: Joshua Forester * Date: 9/10/2009 * Description: Bean class for Admin object. **/ import java.util.List; import java.io.Serializable; import java.sql.Timestamp; public class Admin extends Person implements Serializable { private String username; private String password; private String confirmPassword; private String isDisabled; private String isDeleted; /** * Creates a new instance of Admin */ public Admin() { } /** * Gets the current value of username * @return Current value of username */ public String getUsername() { return username; } /** * Sets the value of username * @param username New value for username */ public void setUsername(String username) { this.username=username; } /** * Gets the current value of password * @return Current value of password */ public String getPassword() { return password; } /** * Sets the value of password * @param password New value for password */ public void setPassword(String password) { this.password=password; } /** * Gets the current value of confirmPassword * @return Current value of confirmPassword */ public String getConfirmPassword() { return confirmPassword; } /** * Sets the value of confirmPassword * @param confirmPassword New value for confirmPassword */ public void setConfirmPassword(String confirmPassword) { this.confirmPassword=confirmPassword; } /** * Gets the current value of isDisabled * @return Current value of isDisabled */ public String getIsDisabled() { return isDisabled; } /** * Sets the value of isDisabled * @param isDisabled New value for isDisabled */ public void setIsDisabled(String isDisabled) { this.isDisabled=isDisabled; } /** * Gets the current value of isDeleted * @return Current value of isDeleted */ public String getIsDeleted() { return isDeleted; } /** * Sets the value of isDeleted * @param isDeleted New value for isDeleted */ public void setIsDeleted(String isDeleted) { this.isDeleted=isDeleted; } public String toString() { String r = new String(); r += "Admin ["; r += "id=" + getId() + ","; r += "username=" + username + ","; r += "password=" + password + ","; r += "confirmPassword=" + confirmPassword + ","; r += "isDisabled=" + isDisabled + ","; r += "isDeleted=" + isDeleted + "]"; r += super.toString(); return r; } }
package hundeklemmen.legacy.extra; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.logging.Level; public class ActionBar { // These are the Class instances. Needed to get fields or methods for classes. private static Class<?> CRAFTPLAYERCLASS, PACKET_PLAYER_CHAT_CLASS, ICHATCOMP, CHATMESSAGE, PACKET_CLASS, CHAT_MESSAGE_TYPE_CLASS; private static Field PLAYERCONNECTION; private static Method GETHANDLE, SENDPACKET; // These are the constructors for those classes. Need to create new objects. private static Constructor<?> PACKET_PLAYER_CHAT_CONSTRUCTOR, CHATMESSAGE_CONSTRUCTOR; // Used in 1.12+. Bytes are replaced with this enum private static Object CHAT_MESSAGE_TYPE_ENUM_OBJECT; // This is the server version. This is how we know the server version. private static final String SERVER_VERSION; private static boolean useByte = false; static { // This gets the server version. String name = Bukkit.getServer().getClass().getName(); name = name.substring(name.indexOf("craftbukkit.") + "craftbukkit.".length()); name = name.substring(0, name.indexOf(".")); SERVER_VERSION = name; try { // This here sets the class fields. CRAFTPLAYERCLASS = Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + ".entity.CraftPlayer"); PACKET_PLAYER_CHAT_CLASS = Class.forName("net.minecraft.server." + SERVER_VERSION + ".PacketPlayOutChat"); PACKET_CLASS = Class.forName("net.minecraft.server." + SERVER_VERSION + ".Packet"); ICHATCOMP = Class.forName("net.minecraft.server." + SERVER_VERSION + ".IChatBaseComponent"); GETHANDLE = CRAFTPLAYERCLASS.getMethod("getHandle"); PLAYERCONNECTION = GETHANDLE.getReturnType().getField("playerConnection"); SENDPACKET = PLAYERCONNECTION.getType().getMethod("sendPacket", PACKET_CLASS); try { CHAT_MESSAGE_TYPE_CLASS = Class.forName("net.minecraft.server." + SERVER_VERSION + ".ChatMessageType"); CHAT_MESSAGE_TYPE_ENUM_OBJECT = CHAT_MESSAGE_TYPE_CLASS.getEnumConstants()[2]; PACKET_PLAYER_CHAT_CONSTRUCTOR = PACKET_PLAYER_CHAT_CLASS.getConstructor(ICHATCOMP, CHAT_MESSAGE_TYPE_CLASS); } catch (NoSuchMethodException e) { PACKET_PLAYER_CHAT_CONSTRUCTOR = PACKET_PLAYER_CHAT_CLASS.getConstructor(ICHATCOMP, byte.class); useByte = true; } CHATMESSAGE = Class.forName("net.minecraft.server." + SERVER_VERSION + ".ChatMessage"); CHATMESSAGE_CONSTRUCTOR = CHATMESSAGE.getConstructor(String.class, Object[].class); } catch (Exception e) { e.printStackTrace(); } } /** * Sends the hotbar message 'message' to the player 'player' * * @param player * @param message * @throws Exception */ public static void sendHotBarMessage(Player player, String message) throws Exception { try { // This creates the IChatComponentBase instance Object icb = CHATMESSAGE_CONSTRUCTOR.newInstance(message, new Object[0]); // This creates the packet Object packet; if (useByte) packet = PACKET_PLAYER_CHAT_CONSTRUCTOR.newInstance(icb, (byte) 2); else packet = PACKET_PLAYER_CHAT_CONSTRUCTOR.newInstance(icb, CHAT_MESSAGE_TYPE_ENUM_OBJECT); // This casts the player to a craftplayer Object craftplayerInst = CRAFTPLAYERCLASS.cast(player); // This invokes the method above. Object methodhHandle = GETHANDLE.invoke(craftplayerInst); // This gets the player's connection Object playerConnection = PLAYERCONNECTION.get(methodhHandle); // This sends the packet. SENDPACKET.invoke(playerConnection, packet); } catch (Exception e) { failsafe("sendHotBarMessage"); throw e; } } private static void failsafe(String message) { Bukkit.getLogger().log(Level.WARNING, "[PluginConstructorAPI] HotBarMessager disabled! Something went wrong with: " + message); Bukkit.getLogger().log(Level.WARNING, "[PluginConstructorAPI] Report this to Zombie_Striker"); Bukkit.getLogger().log(Level.WARNING, "[PluginConstructorAPI] Needed Information: " + Bukkit.getName() + ", " + Bukkit.getVersion() + ", " + Bukkit.getBukkitVersion()); Bukkit.getLogger().log(Level.WARNING, "[PluginConstructorAPI] [URL]https://github.com/ZombieStriker/PluginConstructorAPI[/URL]"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.index.sai; import java.lang.invoke.MethodHandles; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.concurrent.ThreadSafe; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.index.sai.disk.format.IndexDescriptor; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.utils.Pair; /** * Manage per-sstable {@link SSTableContext} for {@link StorageAttachedIndexGroup} */ @ThreadSafe public class SSTableContextManager { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final ConcurrentHashMap<SSTableReader, SSTableContext> sstableContexts = new ConcurrentHashMap<>(); /** * Initialize {@link SSTableContext}s if they are not already initialized. * * @param removed SSTables being removed * @param added SSTables being added * @param validate if true, header and footer will be validated. * * @return a set of contexts for SSTables with valid per-SSTable components, and a set of * SSTables with invalid or missing components */ @SuppressWarnings("resource") public Pair<Set<SSTableContext>, Set<SSTableReader>> update(Collection<SSTableReader> removed, Iterable<SSTableReader> added, boolean validate) { release(removed); Set<SSTableContext> contexts = new HashSet<>(); Set<SSTableReader> invalid = new HashSet<>(); for (SSTableReader sstable : added) { if (sstable.isMarkedCompacted()) { continue; } IndexDescriptor indexDescriptor = IndexDescriptor.create(sstable); if (!indexDescriptor.isPerSSTableBuildComplete()) { // Don't even try to validate or add the context if the completion marker is missing. continue; } try { // Only validate on restart or newly refreshed SSTable. Newly built files are unlikely to be corrupted. if (validate && !sstableContexts.containsKey(sstable) && !indexDescriptor.validatePerSSTableComponents()) { logger.warn(indexDescriptor.logMessage("Invalid per-SSTable component for SSTable {}"), sstable.descriptor); invalid.add(sstable); removeInvalidSSTableContext(sstable); continue; } // ConcurrentHashMap#computeIfAbsent guarantees atomicity, so {@link SSTableContext#create(SSTableReader)}} // is called at most once per key. contexts.add(sstableContexts.computeIfAbsent(sstable, SSTableContext::create)); } catch (Throwable t) { logger.warn(indexDescriptor.logMessage("Failed to update per-SSTable components for SSTable {}"), sstable.descriptor, t); invalid.add(sstable); removeInvalidSSTableContext(sstable); } } return Pair.create(contexts, invalid); } public void release(Collection<SSTableReader> toRelease) { toRelease.stream().map(sstableContexts::remove).filter(Objects::nonNull).forEach(SSTableContext::close); } /** * @return total number of per-sstable open files for live sstables */ int openFiles() { return sstableContexts.values().stream().mapToInt(SSTableContext::openFilesPerSSTable).sum(); } /** * @return total disk usage of all per-sstable index files */ long diskUsage() { return sstableContexts.values().stream().mapToLong(SSTableContext::diskUsage).sum(); } Set<SSTableReader> sstables() { return sstableContexts.keySet(); } @VisibleForTesting public int size() { return sstableContexts.size(); } @VisibleForTesting public void clear() { sstableContexts.values().forEach(SSTableContext::close); sstableContexts.clear(); } @SuppressWarnings("resource") private void removeInvalidSSTableContext(SSTableReader sstable) { SSTableContext invalidContext = sstableContexts.remove(sstable); if (invalidContext != null) invalidContext.close(); } }
/*=========================================================================== Copyright (C) 2008 by the Okapi Framework contributors ----------------------------------------------------------------------------- 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 net.sf.okapi.steps.bomconversion; import net.sf.okapi.common.StringParameters; public class Parameters extends StringParameters { private static final String REMOVEBOM = "removeBOM"; private static final String ALSONONUTF8 = "alsoNonUTF8"; public Parameters () { super(); } public boolean getRemoveBOM() { return getBoolean(REMOVEBOM); } public void setRemoveBOM(boolean removeBOM) { setBoolean(REMOVEBOM, removeBOM); } public boolean getAlsoNonUTF8() { return getBoolean(ALSONONUTF8); } public void setAlsoNonUTF8(boolean alsoNonUTF8) { setBoolean(ALSONONUTF8, alsoNonUTF8); } public void reset() { super.reset(); setRemoveBOM(false);; setAlsoNonUTF8(false); } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.compute.v2019_07_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Describes the properties of a run command parameter. */ public class RunCommandInputParameter { /** * The run command parameter name. */ @JsonProperty(value = "name", required = true) private String name; /** * The run command parameter value. */ @JsonProperty(value = "value", required = true) private String value; /** * Get the run command parameter name. * * @return the name value */ public String name() { return this.name; } /** * Set the run command parameter name. * * @param name the name value to set * @return the RunCommandInputParameter object itself. */ public RunCommandInputParameter withName(String name) { this.name = name; return this; } /** * Get the run command parameter value. * * @return the value value */ public String value() { return this.value; } /** * Set the run command parameter value. * * @param value the value value to set * @return the RunCommandInputParameter object itself. */ public RunCommandInputParameter withValue(String value) { this.value = value; return this; } }
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; /** * Created by Роман on 13.03.2020. */ public class NavigationHelper extends HelperBase { public NavigationHelper(FirefoxDriver wd) { super(wd); } public void gotoGroupPage() { click(By.linkText("group page")); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * 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 org.pentaho.di.job.entries.mysqlbulkload; import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import java.io.File; import java.util.List; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.provider.local.LocalFile; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.job.entry.validator.ValidatorContext; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.resource.ResourceReference; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; /** * This defines a MySQL job entry. * * @author Samatar Hassan * @since Jan-2007 */ public class JobEntryMysqlBulkLoad extends JobEntryBase implements Cloneable, JobEntryInterface { private static Class<?> PKG = JobEntryMysqlBulkLoad.class; // for i18n purposes, needed by Translator2!! private String schemaname; private String tablename; private String filename; private String separator; private String enclosed; private String escaped; private String linestarted; private String lineterminated; private String ignorelines; private boolean replacedata; private String listattribut; private boolean localinfile; public int prorityvalue; private boolean addfiletoresult; private DatabaseMeta connection; public JobEntryMysqlBulkLoad( String n ) { super( n, "" ); tablename = null; schemaname = null; filename = null; separator = null; enclosed = null; escaped = null; lineterminated = null; linestarted = null; replacedata = true; ignorelines = "0"; listattribut = null; localinfile = true; connection = null; addfiletoresult = false; } public JobEntryMysqlBulkLoad() { this( "" ); } public Object clone() { JobEntryMysqlBulkLoad je = (JobEntryMysqlBulkLoad) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer( 200 ); retval.append( super.getXML() ); retval.append( " " ).append( XMLHandler.addTagValue( "schemaname", schemaname ) ); retval.append( " " ).append( XMLHandler.addTagValue( "tablename", tablename ) ); retval.append( " " ).append( XMLHandler.addTagValue( "filename", filename ) ); retval.append( " " ).append( XMLHandler.addTagValue( "separator", separator ) ); retval.append( " " ).append( XMLHandler.addTagValue( "enclosed", enclosed ) ); retval.append( " " ).append( XMLHandler.addTagValue( "escaped", escaped ) ); retval.append( " " ).append( XMLHandler.addTagValue( "linestarted", linestarted ) ); retval.append( " " ).append( XMLHandler.addTagValue( "lineterminated", lineterminated ) ); retval.append( " " ).append( XMLHandler.addTagValue( "replacedata", replacedata ) ); retval.append( " " ).append( XMLHandler.addTagValue( "ignorelines", ignorelines ) ); retval.append( " " ).append( XMLHandler.addTagValue( "listattribut", listattribut ) ); retval.append( " " ).append( XMLHandler.addTagValue( "localinfile", localinfile ) ); retval.append( " " ).append( XMLHandler.addTagValue( "prorityvalue", prorityvalue ) ); retval.append( " " ).append( XMLHandler.addTagValue( "addfiletoresult", addfiletoresult ) ); retval.append( " " ).append( XMLHandler.addTagValue( "connection", connection == null ? null : connection.getName() ) ); return retval.toString(); } public void loadXML( Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep, IMetaStore metaStore ) throws KettleXMLException { try { super.loadXML( entrynode, databases, slaveServers ); schemaname = XMLHandler.getTagValue( entrynode, "schemaname" ); tablename = XMLHandler.getTagValue( entrynode, "tablename" ); filename = XMLHandler.getTagValue( entrynode, "filename" ); separator = XMLHandler.getTagValue( entrynode, "separator" ); enclosed = XMLHandler.getTagValue( entrynode, "enclosed" ); escaped = XMLHandler.getTagValue( entrynode, "escaped" ); linestarted = XMLHandler.getTagValue( entrynode, "linestarted" ); lineterminated = XMLHandler.getTagValue( entrynode, "lineterminated" ); replacedata = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "replacedata" ) ); ignorelines = XMLHandler.getTagValue( entrynode, "ignorelines" ); listattribut = XMLHandler.getTagValue( entrynode, "listattribut" ); localinfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "localinfile" ) ); prorityvalue = Const.toInt( XMLHandler.getTagValue( entrynode, "prorityvalue" ), -1 ); String dbname = XMLHandler.getTagValue( entrynode, "connection" ); addfiletoresult = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "addfiletoresult" ) ); connection = DatabaseMeta.findDatabase( databases, dbname ); } catch ( KettleException e ) { throw new KettleXMLException( "Unable to load job entry of type 'Mysql bulk load' from XML node", e ); } } public void loadRep( Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers ) throws KettleException { try { schemaname = rep.getJobEntryAttributeString( id_jobentry, "schemaname" ); tablename = rep.getJobEntryAttributeString( id_jobentry, "tablename" ); filename = rep.getJobEntryAttributeString( id_jobentry, "filename" ); separator = rep.getJobEntryAttributeString( id_jobentry, "separator" ); enclosed = rep.getJobEntryAttributeString( id_jobentry, "enclosed" ); escaped = rep.getJobEntryAttributeString( id_jobentry, "escaped" ); linestarted = rep.getJobEntryAttributeString( id_jobentry, "linestarted" ); lineterminated = rep.getJobEntryAttributeString( id_jobentry, "lineterminated" ); replacedata = rep.getJobEntryAttributeBoolean( id_jobentry, "replacedata" ); ignorelines = rep.getJobEntryAttributeString( id_jobentry, "ignorelines" ); listattribut = rep.getJobEntryAttributeString( id_jobentry, "listattribut" ); localinfile = rep.getJobEntryAttributeBoolean( id_jobentry, "localinfile" ); prorityvalue = (int) rep.getJobEntryAttributeInteger( id_jobentry, "prorityvalue" ); addfiletoresult = rep.getJobEntryAttributeBoolean( id_jobentry, "addfiletoresult" ); connection = rep.loadDatabaseMetaFromJobEntryAttribute( id_jobentry, "connection", "id_database", databases ); } catch ( KettleDatabaseException dbe ) { throw new KettleException( "Unable to load job entry of type 'Mysql bulk load' from the repository for id_jobentry=" + id_jobentry, dbe ); } } public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_job ) throws KettleException { try { rep.saveJobEntryAttribute( id_job, getObjectId(), "schemaname", schemaname ); rep.saveJobEntryAttribute( id_job, getObjectId(), "tablename", tablename ); rep.saveJobEntryAttribute( id_job, getObjectId(), "filename", filename ); rep.saveJobEntryAttribute( id_job, getObjectId(), "separator", separator ); rep.saveJobEntryAttribute( id_job, getObjectId(), "enclosed", enclosed ); rep.saveJobEntryAttribute( id_job, getObjectId(), "escaped", escaped ); rep.saveJobEntryAttribute( id_job, getObjectId(), "linestarted", linestarted ); rep.saveJobEntryAttribute( id_job, getObjectId(), "lineterminated", lineterminated ); rep.saveJobEntryAttribute( id_job, getObjectId(), "replacedata", replacedata ); rep.saveJobEntryAttribute( id_job, getObjectId(), "ignorelines", ignorelines ); rep.saveJobEntryAttribute( id_job, getObjectId(), "listattribut", listattribut ); rep.saveJobEntryAttribute( id_job, getObjectId(), "localinfile", localinfile ); rep.saveJobEntryAttribute( id_job, getObjectId(), "prorityvalue", prorityvalue ); rep.saveJobEntryAttribute( id_job, getObjectId(), "addfiletoresult", addfiletoresult ); rep.saveDatabaseMetaJobEntryAttribute( id_job, getObjectId(), "connection", "id_database", connection ); } catch ( KettleDatabaseException dbe ) { throw new KettleException( "Unable to load job entry of type 'Mysql Bulk Load' to the repository for id_job=" + id_job, dbe ); } } public void setTablename( String tablename ) { this.tablename = tablename; } public void setSchemaname( String schemaname ) { this.schemaname = schemaname; } public String getSchemaname() { return schemaname; } public String getTablename() { return tablename; } public void setDatabase( DatabaseMeta database ) { this.connection = database; } public DatabaseMeta getDatabase() { return connection; } public boolean evaluates() { return true; } public boolean isUnconditional() { return true; } public Result execute( Result previousResult, int nr ) { String ReplaceIgnore; String IgnoreNbrLignes = ""; String ListOfColumn = ""; String LocalExec = ""; String PriorityText = ""; String LineTerminatedby = ""; String FieldTerminatedby = ""; Result result = previousResult; result.setResult( false ); String vfsFilename = environmentSubstitute( filename ); // Let's check the filename ... if ( !Const.isEmpty( vfsFilename ) ) { try { // User has specified a file, We can continue ... // // This is running over VFS but we need a normal file. // As such, we're going to verify that it's a local file... // We're also going to convert VFS FileObject to File // FileObject fileObject = KettleVFS.getFileObject( vfsFilename, this ); if ( !( fileObject instanceof LocalFile ) ) { // MySQL LOAD DATA can only use local files, so that's what we limit ourselves to. // throw new KettleException( "Only local files are supported at this time, file [" + vfsFilename + "] is not a local file." ); } // Convert it to a regular platform specific file name // String realFilename = KettleVFS.getFilename( fileObject ); // Here we go... back to the regular scheduled program... // File file = new File( realFilename ); if ( ( file.exists() && file.canRead() ) || isLocalInfile() == false ) { // User has specified an existing file, We can continue ... if ( log.isDetailed() ) { logDetailed( "File [" + realFilename + "] exists." ); } if ( connection != null ) { // User has specified a connection, We can continue ... Database db = new Database( this, connection ); db.shareVariablesWith( this ); try { db.connect( parentJob.getTransactionId(), null ); // Get schemaname String realSchemaname = environmentSubstitute( schemaname ); // Get tablename String realTablename = environmentSubstitute( tablename ); if ( db.checkTableExists( realTablename ) ) { // The table existe, We can continue ... if ( log.isDetailed() ) { logDetailed( "Table [" + realTablename + "] exists." ); } // Add schemaname (Most the time Schemaname.Tablename) if ( schemaname != null ) { realTablename = realSchemaname + "." + realTablename; } // Set the REPLACE or IGNORE if ( isReplacedata() ) { ReplaceIgnore = "REPLACE"; } else { ReplaceIgnore = "IGNORE"; } // Set the IGNORE LINES if ( Const.toInt( getRealIgnorelines(), 0 ) > 0 ) { IgnoreNbrLignes = "IGNORE " + getRealIgnorelines() + " LINES"; } // Set list of Column if ( getRealListattribut() != null ) { ListOfColumn = "(" + MysqlString( getRealListattribut() ) + ")"; } // Local File execution if ( isLocalInfile() ) { LocalExec = "LOCAL"; } // Prority if ( prorityvalue == 1 ) { // LOW PriorityText = "LOW_PRIORITY"; } else if ( prorityvalue == 2 ) { // CONCURRENT PriorityText = "CONCURRENT"; } // Fields .... if ( getRealSeparator() != null || getRealEnclosed() != null || getRealEscaped() != null ) { FieldTerminatedby = "FIELDS "; if ( getRealSeparator() != null ) { FieldTerminatedby = FieldTerminatedby + "TERMINATED BY '" + Const.replace( getRealSeparator(), "'", "''" ) + "'"; } if ( getRealEnclosed() != null ) { FieldTerminatedby = FieldTerminatedby + " ENCLOSED BY '" + Const.replace( getRealEnclosed(), "'", "''" ) + "'"; } if ( getRealEscaped() != null ) { FieldTerminatedby = FieldTerminatedby + " ESCAPED BY '" + Const.replace( getRealEscaped(), "'", "''" ) + "'"; } } // LINES ... if ( getRealLinestarted() != null || getRealLineterminated() != null ) { LineTerminatedby = "LINES "; // Line starting By if ( getRealLinestarted() != null ) { LineTerminatedby = LineTerminatedby + "STARTING BY '" + Const.replace( getRealLinestarted(), "'", "''" ) + "'"; } // Line terminating By if ( getRealLineterminated() != null ) { LineTerminatedby = LineTerminatedby + " TERMINATED BY '" + Const.replace( getRealLineterminated(), "'", "''" ) + "'"; } } String SQLBULKLOAD = "LOAD DATA " + PriorityText + " " + LocalExec + " INFILE '" + realFilename.replace( '\\', '/' ) + "' " + ReplaceIgnore + " INTO TABLE " + realTablename + " " + FieldTerminatedby + " " + LineTerminatedby + " " + IgnoreNbrLignes + " " + ListOfColumn + ";"; try { // Run the SQL db.execStatement( SQLBULKLOAD ); // Everything is OK...we can deconnect now db.disconnect(); if ( isAddFileToResult() ) { // Add zip filename to output files ResultFile resultFile = new ResultFile( ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject( realFilename, this ), parentJob .getJobname(), toString() ); result.getResultFiles().put( resultFile.getFile().toString(), resultFile ); } result.setResult( true ); } catch ( KettleDatabaseException je ) { db.disconnect(); result.setNrErrors( 1 ); logError( "An error occurred executing this job entry : " + je.getMessage() ); } catch ( KettleFileException e ) { logError( "An error occurred executing this job entry : " + e.getMessage() ); result.setNrErrors( 1 ); } } else { // Of course, the table should have been created already before the bulk load operation db.disconnect(); result.setNrErrors( 1 ); if ( log.isDetailed() ) { logDetailed( "Table [" + realTablename + "] doesn't exist!" ); } } } catch ( KettleDatabaseException dbe ) { db.disconnect(); result.setNrErrors( 1 ); logError( "An error occurred executing this entry: " + dbe.getMessage() ); } } else { // No database connection is defined result.setNrErrors( 1 ); logError( BaseMessages.getString( PKG, "JobMysqlBulkLoad.Nodatabase.Label" ) ); } } else { // the file doesn't exist result.setNrErrors( 1 ); logError( "File [" + realFilename + "] doesn't exist!" ); } } catch ( Exception e ) { // An unexpected error occurred result.setNrErrors( 1 ); logError( BaseMessages.getString( PKG, "JobMysqlBulkLoad.UnexpectedError.Label" ), e ); } } else { // No file was specified result.setNrErrors( 1 ); logError( BaseMessages.getString( PKG, "JobMysqlBulkLoad.Nofilename.Label" ) ); } return result; } public DatabaseMeta[] getUsedDatabaseConnections() { return new DatabaseMeta[] { connection, }; } public boolean isReplacedata() { return replacedata; } public void setReplacedata( boolean replacedata ) { this.replacedata = replacedata; } public void setLocalInfile( boolean localinfile ) { this.localinfile = localinfile; } public boolean isLocalInfile() { return localinfile; } public void setFilename( String filename ) { this.filename = filename; } public String getFilename() { return filename; } public void setSeparator( String separator ) { this.separator = separator; } public void setLineterminated( String lineterminated ) { this.lineterminated = lineterminated; } public void setLinestarted( String linestarted ) { this.linestarted = linestarted; } public String getEnclosed() { return enclosed; } public String getRealEnclosed() { return environmentSubstitute( getEnclosed() ); } public void setEnclosed( String enclosed ) { this.enclosed = enclosed; } public String getEscaped() { return escaped; } public String getRealEscaped() { return environmentSubstitute( getEscaped() ); } public void setEscaped( String escaped ) { this.escaped = escaped; } public String getSeparator() { return separator; } public String getLineterminated() { return lineterminated; } public String getLinestarted() { return linestarted; } public String getRealLinestarted() { return environmentSubstitute( getLinestarted() ); } public String getRealLineterminated() { return environmentSubstitute( getLineterminated() ); } public String getRealSeparator() { return environmentSubstitute( getSeparator() ); } public void setIgnorelines( String ignorelines ) { this.ignorelines = ignorelines; } public String getIgnorelines() { return ignorelines; } public String getRealIgnorelines() { return environmentSubstitute( getIgnorelines() ); } public void setListattribut( String listattribut ) { this.listattribut = listattribut; } public String getListattribut() { return listattribut; } public String getRealListattribut() { return environmentSubstitute( getListattribut() ); } public void setAddFileToResult( boolean addfiletoresultin ) { this.addfiletoresult = addfiletoresultin; } public boolean isAddFileToResult() { return addfiletoresult; } private String MysqlString( String listcolumns ) { /* * Handle forbiden char like ' */ String returnString = ""; String[] split = listcolumns.split( "," ); for ( int i = 0; i < split.length; i++ ) { if ( returnString.equals( "" ) ) { returnString = "`" + Const.trim( split[i] ) + "`"; } else { returnString = returnString + ", `" + Const.trim( split[i] ) + "`"; } } return returnString; } public List<ResourceReference> getResourceDependencies( JobMeta jobMeta ) { List<ResourceReference> references = super.getResourceDependencies( jobMeta ); ResourceReference reference = null; if ( connection != null ) { reference = new ResourceReference( this ); references.add( reference ); reference.getEntries().add( new ResourceEntry( connection.getHostname(), ResourceType.SERVER ) ); reference.getEntries().add( new ResourceEntry( connection.getDatabaseName(), ResourceType.DATABASENAME ) ); } if ( filename != null ) { String realFilename = getRealFilename(); if ( reference == null ) { reference = new ResourceReference( this ); references.add( reference ); } reference.getEntries().add( new ResourceEntry( realFilename, ResourceType.FILE ) ); } return references; } @Override public void check( List<CheckResultInterface> remarks, JobMeta jobMeta, VariableSpace space, Repository repository, IMetaStore metaStore ) { ValidatorContext ctx = new ValidatorContext(); putVariableSpace( ctx, getVariables() ); putValidators( ctx, notBlankValidator(), fileExistsValidator() ); andValidator().validate( this, "filename", remarks, ctx ); andValidator().validate( this, "tablename", remarks, putValidators( notBlankValidator() ) ); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.websvc.manager.model; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.modules.websvc.manager.WebServiceManager; import org.netbeans.modules.websvc.manager.WebServicePersistenceManager; import org.netbeans.modules.websvc.saas.util.WsdlUtil; import org.openide.filesystems.FileAttributeEvent; import org.openide.filesystems.FileChangeListener; import org.openide.filesystems.FileEvent; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileRenameEvent; import org.openide.filesystems.FileUtil; import org.openide.util.RequestProcessor; import org.openide.util.RequestProcessor.Task; import org.openide.util.WeakListeners; /** * A model to keep track of web service data and their group * Nodes are created using this model * @author Winston Prakash */ public class WebServiceListModel { public static final String DEFAULT_GROUP = "default"; // NOI18N private static Random serviceRandom = new Random(System.currentTimeMillis()); private static Random serviceGroupRandom = new Random(System.currentTimeMillis()); public boolean isDirty = false; Set<WebServiceListModelListener> listeners = new HashSet<>(); /** * Fix for Bug#: 5039378 * Netbeans can potentially use multiple threads to maintain a Node's data model. *- David Botterill 5/6/2004 */ private List<WebServiceData> webServices = Collections.synchronizedList(new ArrayList<WebServiceData>()); private List<WebServiceGroup> webServiceGroups = Collections.synchronizedList(new ArrayList<WebServiceGroup>()); // To maintain the display names for the webservice/port private Set<String> uniqueDisplayNames = Collections.synchronizedSet(new HashSet<String>()); private List<String> partnerServices = new ArrayList<String>(); private static WebServiceListModel websvcNodeModel = new WebServiceListModel(); private boolean initialized = false; private RestFolderListener partnerServiceListener; private WebServiceListModel() { } public static WebServiceListModel getInstance() { return websvcNodeModel; } /** * For unit test use */ public static void resetInstance() { websvcNodeModel = new WebServiceListModel(); } public void addWebServiceListModelListener(WebServiceListModelListener listener) { listeners.add(listener); } public void removeWebServiceListModelListener(WebServiceListModelListener listener) { listeners.remove(listener); } public List<String> getPartnerServices() { return partnerServices; } private static boolean containsKey(List list, String key) { synchronized (list) { for (Object o : list) { if (o instanceof WebServiceData) { WebServiceData wsData = (WebServiceData) o; if (wsData.getId().equals(key)) { return true; } } else if (o instanceof WebServiceGroup) { WebServiceGroup wsGroup = (WebServiceGroup) o; if (wsGroup.getId().equals(key)) { return true; } } } return false; } } /** Get a unique Id for the webservice data * Unique Id is "webservice" + a random number. */ public String getUniqueWebServiceId() { initialize(); String uniqueId = "webservice" + serviceRandom.nextLong(); while (containsKey(webServices, uniqueId)) { uniqueId = "webservice" + serviceRandom.nextLong(); } return uniqueId; } /** Get a unique Id for the webservice data group * Unique Id is "webserviceGroup" + a random number. */ public String getUniqueWebServiceGroupId() { initialize(); String uniqueId = "webserviceGroup" + serviceGroupRandom.nextLong(); while (containsKey(webServiceGroups, uniqueId)) { uniqueId = "webserviceGroup" + serviceGroupRandom.nextLong(); } return uniqueId; } /** Add the webservice data with a unique Id */ public void addWebService(WebServiceData webService) { initialize(); if (!webServices.contains(webService)) { WebServiceListModel.getInstance().setDirty(true); webServices.add(webService); } } /** Get the webservice data based on unique Id */ public WebServiceData getWebService(String webServiceId) { synchronized (webServices) { initialize(); for (WebServiceData wsData : webServices) { if (wsData.getId().equals(webServiceId)) { return wsData; } } } return null; } /** Get the webservice data from the model */ public void removeWebService(String webServiceId) { initialize(); WebServiceData wsData = getWebService(webServiceId); if (wsData == null) { return; } WebServiceGroup group = getWebServiceGroup(wsData.getGroupId()); WebServiceListModel.getInstance().setDirty(true); if (group != null) { group.remove(webServiceId); } webServices.remove(wsData); } /** Check if the model contains the webservice data*/ public boolean webServiceExists(WebServiceData webService) { initialize(); return containsKey(webServices, webService.getId()); } /** Get a unique display name */ public String getUniqueDisplayName(String name) { initialize(); String displayName = name; for (int i = 1; uniqueDisplayNames.contains(displayName); i++) { displayName = name + Integer.toString(i); } return displayName; } public boolean isDisplayNameUnique(String name) { return !uniqueDisplayNames.contains(name); } /** Get all the webservice data added to this model*/ public List<WebServiceData> getWebServiceSet() { initialize(); return webServices; } /** Add a webservice group to the model*/ public void addWebServiceGroup(WebServiceGroup group) { initialize(); if (!webServiceGroups.contains(group)) { WebServiceListModel.getInstance().setDirty(true); webServiceGroups.add(group); for (WebServiceListModelListener listener : listeners) { WebServiceListModelEvent evt = new WebServiceListModelEvent(group.getId()); listener.webServiceGroupAdded(evt); } } } /** Remove the webservice group from the model*/ public void removeWebServiceGroup(String groupId) { initialize(); WebServiceGroup group = getWebServiceGroup(groupId); if (group != null) { WebServiceListModel.getInstance().setDirty(true); /** * Fix bug: * We need to get an array of the web services instead of using the Iterator because a * Set iterator is fail-safe and will throw a ConcurrentModificationException if you're using * it and the set is modified. * - David Botterill 5/6/2004. */ String[] webserviceIds = getWebServiceGroup(groupId).getWebServiceIds().toArray(new String[0]); for (int ii = 0; null != webserviceIds && ii < webserviceIds.length; ii++) { WebServiceManager.getInstance().removeWebService(getWebService(webserviceIds[ii])); } webServiceGroups.remove(group); Iterator<WebServiceListModelListener> iter = listeners.iterator(); while (iter.hasNext()) { WebServiceListModelEvent evt = new WebServiceListModelEvent(groupId); iter.next().webServiceGroupRemoved(evt); } } } /** Get a webservice group by its Id*/ public WebServiceGroup getWebServiceGroup(String groupId) { synchronized (webServiceGroups) { initialize(); for (WebServiceGroup wsGroup : webServiceGroups) { if (wsGroup.getId().equals(groupId)) { return wsGroup; } } } return null; } public WebServiceData findWebServiceData(String wsdlUrl, String serviceName) { return findWebServiceData(wsdlUrl, serviceName, true); } public WebServiceData findWebServiceData(String wsdlUrl, String serviceName, boolean strict) { // RESOLVE: Look up only by wsdlUrl since we don't know the serviceName // until the data is loaded. In the future, we should implement // look up by wsdlUrl and the group name. For now, we will assume that // each service is uniquely identitied by its url. for (WebServiceData wsd : getWebServiceSet()) { if (wsdlUrl.equals(wsd.getOriginalWsdl())) { return wsd; } } // WebServiceData target = null; // for (WebServiceData wsd : getWebServiceSet()) { // if (wsdlUrl.equals(wsd.getOriginalWsdl())) { // target = wsd; // } // if (serviceName.equals(wsd.getName())) { // return wsd; // } // } // // if (! strict && target != null) { // WebServiceData clone = new WebServiceData(target); // clone.setName(serviceName); // return clone; // } return null; } public WebServiceData getWebServiceData(String wsdlUrl, String serviceName) { return getWebServiceData(wsdlUrl, serviceName, true); } public WebServiceData getWebServiceData(String wsdlUrl, String serviceName, boolean synchronous) { final WebServiceData target = findWebServiceData(wsdlUrl, serviceName, false); if (target != null && !target.isReady()) { Runnable run = new Runnable() { public void run() { try { WebServiceManager.getInstance().addWebService(target, true); } catch (IOException ex) { Logger.getGlobal().log(Level.INFO, ex.getLocalizedMessage(), ex); } } }; Task t = RequestProcessor.getDefault().post(run); if (synchronous) { t.waitFinished(); } } return target; } public List<WebServiceGroup> getWebServiceGroupSet() { initialize(); return webServiceGroups; } public void setDirty(boolean isDirty) { this.isDirty = isDirty; } public boolean isDirty() { return isDirty; } private synchronized void initialize() { if (!initialized) { initialized = true; WebServicePersistenceManager manager = new WebServicePersistenceManager(); if (!WsdlUtil.hasProcessedImport()) { manager.setImported(false); manager.load(); WsdlUtil.markImportProcessed(); } else { manager.load(); } // TODO doesn't do anything useful yet partnerServiceListener = new RestFolderListener(); FileObject restFolder = FileUtil.getConfigFile("RestComponents"); // NOI18N if (restFolder != null) { restFolder.addFileChangeListener(WeakListeners.create(FileChangeListener.class, partnerServiceListener, restFolder)); } for (WebServiceGroup wsGroup : webServiceGroups) { if (wsGroup.getId().equals(DEFAULT_GROUP)) { for (WebServiceGroupListener defaultGroupListener : defaultGroupListeners) { wsGroup.addWebServiceGroupListener(defaultGroupListener); } defaultGroupListeners = null; return; } } // Generate the default group on initialization if it doesn't exist WebServiceGroup defaultGroup = new WebServiceGroup(WebServiceListModel.DEFAULT_GROUP); webServiceGroups.add(defaultGroup); for (WebServiceGroupListener defaultGroupListener : defaultGroupListeners) { defaultGroup.addWebServiceGroupListener(defaultGroupListener); } defaultGroupListeners = null; } } private List<WebServiceGroupListener> defaultGroupListeners = new ArrayList<WebServiceGroupListener>(); public void addDefaultGroupListener(WebServiceGroupListener listener) { synchronized (webServiceGroups) { for (WebServiceGroup wsGroup : webServiceGroups) { if (wsGroup.getId().equals(DEFAULT_GROUP)) { wsGroup.addWebServiceGroupListener(listener); return; } } if (!defaultGroupListeners.contains(listener)) { defaultGroupListeners.add(listener); } } } public boolean isInitialized() { return initialized; } private static final class RestFolderListener implements FileChangeListener { public void fileFolderCreated(FileEvent fe) { //new WebServicePersistenceManager().loadPartnerServices(); } public void fileDataCreated(FileEvent fe) { } public void fileChanged(FileEvent fe) { } public void fileDeleted(FileEvent fe) { } public void fileRenamed(FileRenameEvent fe) { } public void fileAttributeChanged(FileAttributeEvent fe) { } } }
package edu.neu.ccs.prl.meringue; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; public final class FileUtil { private FileUtil() { throw new AssertionError(getClass().getSimpleName() + " is a static utility class and should " + "not be instantiated"); } /** * Creates a Java Archive (JAR) file containing only a manifest that specifies a value for the Class-Path attribute. * * @param classPathElements elements to be included on the class path * @param jar the JAR file that should be created * @throws IOException if an I/O error occurs * @throws NullPointerException if {@code classPathElements} is null, * an element of {@code classPathElements} is null, or {@code jar} is null. */ public static void buildManifestJar(Collection<File> classPathElements, File jar) throws IOException { Set<File> classPathFilesCopy = new HashSet<>(classPathElements); String[] paths = classPathFilesCopy.stream() .map(f -> f.isFile() ? f.getAbsolutePath() : f.getAbsolutePath() + "/") .toArray(String[]::new); ensureDirectory(jar.getParentFile()); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); manifest.getMainAttributes().putValue("Class-Path", String.join(" ", paths)); JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), manifest); jos.close(); } public static File getClassPathElement(Class<?> clazz) { return new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); } public static File javaHomeToJavaExec(File javaHome) { return new File(javaHome, "bin" + File.separator + "java"); } /** * Returns the home directory of the Java installation for the specified Java executable. * pre-java 9 HOME/jre/bin/java or HOME/bin/java * * @param javaExec a Java executable * @return the home directory of the Java installation for the specified Java executable * @throws NullPointerException if {@code javaExec} is null * @throws IllegalArgumentException if {@code javaExec} does not point to a Java executable */ public static File javaExecToJavaHome(File javaExec) { if ("java".equals(javaExec.getName())) { File parent = javaExec.getParentFile(); if ("bin".equals(parent.getName())) { File grandparent = parent.getParentFile(); return "jre".equals(grandparent.getName()) ? grandparent.getParentFile() : grandparent; } } throw new IllegalArgumentException("Invalid Java executable " + javaExec); } /** * Creates the specified directory if it does not already exist. * * @param dir the directory to create * @throws IOException if the specified directory did not already exist and was not successfully created */ public static void ensureDirectory(File dir) throws IOException { if (!dir.isDirectory() && !dir.mkdirs()) { throw new IOException("Failed to create directory: " + dir); } } /** * Ensures that the specified directory exists and is empty. * * @param dir the directory to be created or emptied * @throws IOException if the specified directory could not be created or emptied */ public static void createOrCleanDirectory(File dir) throws IOException { if (dir.isDirectory()) { Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw e; } } }); } else if (dir.isFile() && !dir.delete()) { throw new IOException("Failed to delete: " + dir); } if (!dir.mkdirs()) { throw new IOException("Failed to create directory: " + dir); } } }
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.media.v1; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.Twilio; import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.TwilioException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import mockit.Mocked; import mockit.NonStrictExpectations; import org.junit.Before; import org.junit.Test; import java.net.URI; import static com.twilio.TwilioTest.serialize; import static org.junit.Assert.*; public class MediaProcessorTest { @Mocked private TwilioRestClient twilioRestClient; @Before public void setUp() throws Exception { Twilio.init("AC123", "AUTH TOKEN"); } @Test public void testCreateRequest() { new NonStrictExpectations() {{ Request request = new Request(HttpMethod.POST, Domains.MEDIA.toString(), "/v1/MediaProcessors"); request.addPostParam("Extension", serialize("extension")); request.addPostParam("ExtensionContext", serialize("extension_context")); twilioRestClient.request(request); times = 1; result = new Response("", 500); twilioRestClient.getAccountSid(); result = "AC123"; }}; try { MediaProcessor.creator("extension", "extension_context").create(); fail("Expected TwilioException to be thrown for 500"); } catch (TwilioException e) {} } @Test public void testCreateResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"extension\": \"video-composer-v1\",\"extension_context\": \"{}\",\"sid\": \"ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"status\": \"started\",\"status_callback\": \"http://www.example.com\",\"status_callback_method\": \"POST\",\"ended_reason\": null,\"url\": \"https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"max_duration\": 300}", TwilioRestClient.HTTP_STATUS_CODE_CREATED); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; MediaProcessor.creator("extension", "extension_context").create(); } @Test public void testFetchRequest() { new NonStrictExpectations() {{ Request request = new Request(HttpMethod.GET, Domains.MEDIA.toString(), "/v1/MediaProcessors/ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.request(request); times = 1; result = new Response("", 500); twilioRestClient.getAccountSid(); result = "AC123"; }}; try { MediaProcessor.fetcher("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(); fail("Expected TwilioException to be thrown for 500"); } catch (TwilioException e) {} } @Test public void testFetchResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"extension\": \"video-composer-v1\",\"extension_context\": \"{}\",\"sid\": \"ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"status\": \"started\",\"status_callback\": \"http://www.example.com\",\"status_callback_method\": \"POST\",\"ended_reason\": null,\"url\": \"https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"max_duration\": 300}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; assertNotNull(MediaProcessor.fetcher("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()); } @Test public void testUpdateRequest() { new NonStrictExpectations() {{ Request request = new Request(HttpMethod.POST, Domains.MEDIA.toString(), "/v1/MediaProcessors/ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); request.addPostParam("Status", serialize(MediaProcessor.UpdateStatus.ENDED)); twilioRestClient.request(request); times = 1; result = new Response("", 500); twilioRestClient.getAccountSid(); result = "AC123"; }}; try { MediaProcessor.updater("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", MediaProcessor.UpdateStatus.ENDED).update(); fail("Expected TwilioException to be thrown for 500"); } catch (TwilioException e) {} } @Test public void testUpdateEndedResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:01:00Z\",\"extension\": \"video-composer-v1\",\"extension_context\": \"{}\",\"sid\": \"ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"status\": \"ended\",\"status_callback\": \"http://www.example.com\",\"status_callback_method\": \"POST\",\"ended_reason\": \"ended-via-api\",\"url\": \"https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"max_duration\": 300}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; MediaProcessor.updater("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", MediaProcessor.UpdateStatus.ENDED).update(); } @Test public void testReadRequest() { new NonStrictExpectations() {{ Request request = new Request(HttpMethod.GET, Domains.MEDIA.toString(), "/v1/MediaProcessors"); twilioRestClient.request(request); times = 1; result = new Response("", 500); twilioRestClient.getAccountSid(); result = "AC123"; }}; try { MediaProcessor.reader().read(); fail("Expected TwilioException to be thrown for 500"); } catch (TwilioException e) {} } @Test public void testReadEmptyResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"meta\": {\"page\": 0,\"page_size\": 10,\"first_page_url\": \"https://media.twilio.com/v1/MediaProcessors?Status=started&Order=asc&PageSize=10&Page=0\",\"previous_page_url\": null,\"url\": \"https://media.twilio.com/v1/MediaProcessors?Status=started&Order=asc&PageSize=10&Page=0\",\"next_page_url\": null,\"key\": \"media_processors\"},\"media_processors\": []}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; assertNotNull(MediaProcessor.reader().read()); } @Test public void testReadItemsResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"meta\": {\"page\": 0,\"page_size\": 10,\"first_page_url\": \"https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0\",\"previous_page_url\": null,\"url\": \"https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0\",\"next_page_url\": null,\"key\": \"media_processors\"},\"media_processors\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:01:00Z\",\"extension\": \"video-composer-v1\",\"extension_context\": \"{}\",\"sid\": \"ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"status\": \"ended\",\"status_callback\": \"http://www.example.com\",\"status_callback_method\": \"POST\",\"ended_reason\": \"ended-via-api\",\"url\": \"https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"max_duration\": 300}]}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; assertNotNull(MediaProcessor.reader().read()); } @Test public void testReadItemsUsingPageTokenResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"meta\": {\"page\": 0,\"page_size\": 10,\"first_page_url\": \"https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0\",\"previous_page_url\": null,\"url\": \"https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0&PageToken=PTTUszYTgyOGFhNDIzZWExNzA0OTkwODNlMDlkZTg3M2NiNDoxOjI%253D\",\"next_page_url\": null,\"key\": \"media_processors\"},\"media_processors\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:01:00Z\",\"extension\": \"video-composer-v1\",\"extension_context\": \"{}\",\"sid\": \"ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"status\": \"ended\",\"status_callback\": \"http://www.example.com\",\"status_callback_method\": \"POST\",\"ended_reason\": \"ended-via-api\",\"url\": \"https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"max_duration\": 300}]}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; assertNotNull(MediaProcessor.reader().read()); } @Test public void testReadItemsPageLargerThanMaxResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"meta\": {\"page\": 0,\"page_size\": 100,\"first_page_url\": \"https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=100&Page=0\",\"previous_page_url\": null,\"url\": \"https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=100&Page=0\",\"next_page_url\": null,\"key\": \"media_processors\"},\"media_processors\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:01:00Z\",\"extension\": \"video-composer-v1\",\"extension_context\": \"{}\",\"sid\": \"ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"status\": \"ended\",\"status_callback\": \"http://www.example.com\",\"status_callback_method\": \"POST\",\"ended_reason\": \"ended-via-api\",\"url\": \"https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef\",\"max_duration\": 300}]}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; assertNotNull(MediaProcessor.reader().read()); } }
package com.qfedu.test; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.qfedu.domain.Account; import com.qfedu.mapper.AccountMapper; public class Test07 { public static void main(String[] args) throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sessionFactory.openSession(); AccountMapper accountMapper = session.getMapper(AccountMapper.class); Account account = accountMapper.findById(2); System.out.println(account.getNumber()); System.out.println(account.getUser().getUsername()); System.out.println(account.getUser().getPassword()); System.out.println(account.getUser().getEmail()); session.commit(); session.close(); } }