code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/** * <copyright> * </copyright> * * */ package eu.hyvar.dataValues.resource.hydatavalue.ui; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; /** * A provider class for all images that are required by the generated UI plug-in. * The default implementation load images from the bundle and caches them to make * sure each image is loaded at most once. */ public class HydatavalueImageProvider { public final static HydatavalueImageProvider INSTANCE = new HydatavalueImageProvider(); private Map<String, Image> imageCache = new LinkedHashMap<String, Image>(); /** * Returns the image associated with the given key. The key can be either a path * to an image file in the resource bundle or a shared image from * org.eclipse.ui.ISharedImages. */ public Image getImage(String key) { if (key == null) { return null; } Image image = null; // try shared images try { Field declaredField = ISharedImages.class.getDeclaredField(key); Object valueObject = declaredField.get(null); if (valueObject instanceof String) { String value = (String) valueObject; image = PlatformUI.getWorkbench().getSharedImages().getImage(value); } } catch (SecurityException e) { } catch (NoSuchFieldException e) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } if (image != null) { return image; } // try cache if (imageCache.containsKey(key)) { return imageCache.get(key); } // try loading image from UI bundle ImageDescriptor descriptor = getImageDescriptor(key); if (descriptor == null) { return null; } image = descriptor.createImage(); if (image == null) { return null; } imageCache.put(key, image); return image; } /** * <p> * Returns the image for the given key. Possible keys are: * </p> * <p> * <ul> * </p> * <p> * <li>platform:/plugin/your.plugin/icons/yourIcon.png</li> * </p> * <p> * <li>bundleentry://557.fwk3560063/icons/yourIcon.png</li> * </p> * <p> * </ul> * </p> */ public ImageDescriptor getImageDescriptor(String key) { IPath path = new Path(key); eu.hyvar.dataValues.resource.hydatavalue.ui.HydatavalueUIPlugin plugin = eu.hyvar.dataValues.resource.hydatavalue.ui.HydatavalueUIPlugin.getDefault(); if (plugin == null) { return null; } ImageDescriptor descriptor = ImageDescriptor.createFromURL(FileLocator.find(plugin.getBundle(), path, null)); if (ImageDescriptor.getMissingImageDescriptor().equals(descriptor) || descriptor == null) { // try loading image from any bundle try { URL pluginUrl = new URL(key); descriptor = ImageDescriptor.createFromURL(pluginUrl); if (ImageDescriptor.getMissingImageDescriptor().equals(descriptor) || descriptor == null) { return null; } } catch (MalformedURLException mue) { eu.hyvar.dataValues.resource.hydatavalue.ui.HydatavalueUIPlugin.logError("IconProvider can't load image (URL is malformed).", mue); } } return descriptor; } }
DarwinSPL/DarwinSPL
plugins/eu.hyvar.dataValues.resource.hydatavalue.ui/src-gen/eu/hyvar/dataValues/resource/hydatavalue/ui/HydatavalueImageProvider.java
Java
apache-2.0
3,386
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.showcase.demos.redis.job.consumer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.springside.examples.showcase.demos.redis.JedisPoolFactory; import org.springside.modules.nosql.redis.JedisUtils; import org.springside.modules.nosql.redis.scheduler.SimpleJobConsumer; import org.springside.modules.test.benchmark.ConcurrentBenchmark; import redis.clients.jedis.JedisPool; import com.google.common.util.concurrent.RateLimiter; /** * 多线程运行JobConsumer,从"ss.job:ready" list中popup job进行处理。 * * 可用系统参数-Dthread.count 改变线程数 * * @author calvin */ public class SimpleJobConsumerDemo implements Runnable { protected static final int THREAD_COUNT = 10; protected static final int PRINT_BETWEEN_SECONDS = 10; protected static JedisPool pool; protected static int threadCount; protected static AtomicLong golbalCounter = new AtomicLong(0); protected static AtomicLong golbalPreviousCount = new AtomicLong(0); protected static RateLimiter golbalPrintRate = RateLimiter.create(1d / PRINT_BETWEEN_SECONDS); protected long localCounter = 0L; protected long localPreviousCount = 0L; protected RateLimiter localPrintRate = RateLimiter.create(1d / PRINT_BETWEEN_SECONDS); private SimpleJobConsumer consumer; public static void main(String[] args) throws Exception { threadCount = Integer.parseInt(System.getProperty(ConcurrentBenchmark.THREAD_COUNT_NAME, String.valueOf(THREAD_COUNT))); pool = JedisPoolFactory.createJedisPool(JedisUtils.DEFAULT_HOST, JedisUtils.DEFAULT_PORT, JedisUtils.DEFAULT_TIMEOUT, threadCount); ExecutorService threadPool = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { SimpleJobConsumerDemo demo = new SimpleJobConsumerDemo(); threadPool.execute(demo); } System.out.println("Hit enter to stop"); try { while (true) { char c = (char) System.in.read(); if (c == '\n') { System.out.println("Shutting down"); threadPool.shutdownNow(); boolean shutdownSucess = threadPool.awaitTermination( SimpleJobConsumer.DEFAULT_POPUP_TIMEOUT_SECONDS + 1, TimeUnit.SECONDS); if (!shutdownSucess) { System.out.println("Forcing exiting."); System.exit(-1); } return; } } } finally { pool.destroy(); } } public SimpleJobConsumerDemo() { consumer = new SimpleJobConsumer("ss", pool); } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { String job = consumer.popupJob(); if (job != null) { handleJob(job); } } catch (Throwable e) { e.printStackTrace(); } } } /** * 处理Job的回调函数. */ public void handleJob(String job) { long globalCount = golbalCounter.incrementAndGet(); localCounter++; // print global progress, 所有線程裡只有一個会在10秒內打印一次。 if (golbalPrintRate.tryAcquire()) { System.out.printf("Total pop %,d jobs, tps is %,d%n", globalCount, (globalCount - golbalPreviousCount.get()) / PRINT_BETWEEN_SECONDS); golbalPreviousCount.set(globalCount); } // print current thread progress,10秒內打印一次。 if (localPrintRate.tryAcquire()) { System.out.printf("Local thread pop %,d jobs, tps is %,d%n", localCounter, (localCounter - localPreviousCount) / PRINT_BETWEEN_SECONDS); localPreviousCount = localCounter; } } }
lenzl/springside4
examples/showcase/src/main/java/org/springside/examples/showcase/demos/redis/job/consumer/SimpleJobConsumerDemo.java
Java
apache-2.0
3,843
/** * 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.jms; import java.util.Map; import java.util.concurrent.ExecutorService; import javax.jms.ConnectionFactory; import javax.jms.ExceptionListener; import javax.jms.Message; import javax.jms.Session; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.LoggingLevel; import org.apache.camel.impl.HeaderFilterStrategyComponent; import org.apache.camel.spi.Metadata; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.task.TaskExecutor; import org.springframework.jms.connection.JmsTransactionManager; import org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter; import org.springframework.jms.core.JmsOperations; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.jms.support.destination.DestinationResolver; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.util.ErrorHandler; import static org.apache.camel.util.ObjectHelper.removeStartingCharacters; /** * A <a href="http://activemq.apache.org/jms.html">JMS Component</a> * * @version */ public class JmsComponent extends HeaderFilterStrategyComponent implements ApplicationContextAware { private static final Logger LOG = LoggerFactory.getLogger(JmsComponent.class); private static final String KEY_FORMAT_STRATEGY_PARAM = "jmsKeyFormatStrategy"; private ExecutorService asyncStartStopExecutorService; private ApplicationContext applicationContext; @Metadata(label = "advanced", description = "To use a shared JMS configuration") private JmsConfiguration configuration; @Metadata(label = "advanced", description = "To use a custom QueueBrowseStrategy when browsing queues") private QueueBrowseStrategy queueBrowseStrategy; @Metadata(label = "advanced", description = "To use the given MessageCreatedStrategy which are invoked when Camel creates new instances" + " of javax.jms.Message objects when Camel is sending a JMS message.") private MessageCreatedStrategy messageCreatedStrategy; public JmsComponent() { super(JmsEndpoint.class); } public JmsComponent(Class<? extends Endpoint> endpointClass) { super(endpointClass); } public JmsComponent(CamelContext context) { super(context, JmsEndpoint.class); } public JmsComponent(CamelContext context, Class<? extends Endpoint> endpointClass) { super(context, endpointClass); } public JmsComponent(JmsConfiguration configuration) { this(); this.configuration = configuration; } /** * Static builder method */ public static JmsComponent jmsComponent() { return new JmsComponent(); } /** * Static builder method */ public static JmsComponent jmsComponent(JmsConfiguration configuration) { return new JmsComponent(configuration); } /** * Static builder method */ public static JmsComponent jmsComponent(ConnectionFactory connectionFactory) { return jmsComponent(new JmsConfiguration(connectionFactory)); } /** * Static builder method */ public static JmsComponent jmsComponentClientAcknowledge(ConnectionFactory connectionFactory) { JmsConfiguration template = new JmsConfiguration(connectionFactory); template.setAcknowledgementMode(Session.CLIENT_ACKNOWLEDGE); return jmsComponent(template); } /** * Static builder method */ public static JmsComponent jmsComponentAutoAcknowledge(ConnectionFactory connectionFactory) { JmsConfiguration template = new JmsConfiguration(connectionFactory); template.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE); return jmsComponent(template); } public static JmsComponent jmsComponentTransacted(ConnectionFactory connectionFactory) { JmsTransactionManager transactionManager = new JmsTransactionManager(); transactionManager.setConnectionFactory(connectionFactory); return jmsComponentTransacted(connectionFactory, transactionManager); } @SuppressWarnings("deprecation") public static JmsComponent jmsComponentTransacted(ConnectionFactory connectionFactory, PlatformTransactionManager transactionManager) { JmsConfiguration template = new JmsConfiguration(connectionFactory); template.setTransactionManager(transactionManager); template.setTransacted(true); template.setTransactedInOut(true); return jmsComponent(template); } // Properties // ------------------------------------------------------------------------- public JmsConfiguration getConfiguration() { if (configuration == null) { configuration = createConfiguration(); // If we are being configured with spring... if (applicationContext != null) { if (isAllowAutoWiredConnectionFactory()) { Map<String, ConnectionFactory> beansOfTypeConnectionFactory = applicationContext.getBeansOfType(ConnectionFactory.class); if (!beansOfTypeConnectionFactory.isEmpty()) { ConnectionFactory cf = beansOfTypeConnectionFactory.values().iterator().next(); configuration.setConnectionFactory(cf); } } if (isAllowAutoWiredDestinationResolver()) { Map<String, DestinationResolver> beansOfTypeDestinationResolver = applicationContext.getBeansOfType(DestinationResolver.class); if (!beansOfTypeDestinationResolver.isEmpty()) { DestinationResolver destinationResolver = beansOfTypeDestinationResolver.values().iterator().next(); configuration.setDestinationResolver(destinationResolver); } } } } return configuration; } /** * Subclasses can override to prevent the jms configuration from being * setup to use an auto-wired the connection factory that's found in the spring * application context. * * @return true by default */ public boolean isAllowAutoWiredConnectionFactory() { return true; } /** * Subclasses can override to prevent the jms configuration from being * setup to use an auto-wired the destination resolved that's found in the spring * application context. * * @return true by default */ public boolean isAllowAutoWiredDestinationResolver() { return true; } /** * To use a shared JMS configuration */ public void setConfiguration(JmsConfiguration configuration) { this.configuration = configuration; } /** * Specifies whether the consumer accept messages while it is stopping. * You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages * enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, * and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message * may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. */ @Metadata(label = "consumer,advanced", description = "Specifies whether the consumer accept messages while it is stopping." + " You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages" + " enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected," + " and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message" + " may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option.") public void setAcceptMessagesWhileStopping(boolean acceptMessagesWhileStopping) { getConfiguration().setAcceptMessagesWhileStopping(acceptMessagesWhileStopping); } /** * Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow * the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping * is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by * default in the regular JMS consumers but to enable for reply managers you must enable this flag. */ @Metadata(label = "consumer,advanced", description = "Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow " + " the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping" + " is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by" + " default in the regular JMS consumers but to enable for reply managers you must enable this flag.") public void setAllowReplyManagerQuickStop(boolean allowReplyManagerQuickStop) { getConfiguration().setAllowReplyManagerQuickStop(allowReplyManagerQuickStop); } /** * The JMS acknowledgement mode defined as an Integer. * Allows you to set vendor-specific extensions to the acknowledgment mode. * For the regular modes, it is preferable to use the acknowledgementModeName instead. */ @Metadata(label = "consumer", description = "The JMS acknowledgement mode defined as an Integer. Allows you to set vendor-specific extensions to the acknowledgment mode." + "For the regular modes, it is preferable to use the acknowledgementModeName instead.") public void setAcknowledgementMode(int consumerAcknowledgementMode) { getConfiguration().setAcknowledgementMode(consumerAcknowledgementMode); } /** * Enables eager loading of JMS properties as soon as a message is loaded * which generally is inefficient as the JMS properties may not be required * but sometimes can catch early any issues with the underlying JMS provider * and the use of JMS properties */ @Metadata(label = "consumer,advanced", description = "Enables eager loading of JMS properties as soon as a message is loaded" + " which generally is inefficient as the JMS properties may not be required" + " but sometimes can catch early any issues with the underlying JMS provider" + " and the use of JMS properties") public void setEagerLoadingOfProperties(boolean eagerLoadingOfProperties) { getConfiguration().setEagerLoadingOfProperties(eagerLoadingOfProperties); } /** * The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE */ @Metadata(defaultValue = "AUTO_ACKNOWLEDGE", label = "consumer", enums = "SESSION_TRANSACTED,CLIENT_ACKNOWLEDGE,AUTO_ACKNOWLEDGE,DUPS_OK_ACKNOWLEDGE", description = "The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE") public void setAcknowledgementModeName(String consumerAcknowledgementMode) { getConfiguration().setAcknowledgementModeName(consumerAcknowledgementMode); } /** * Specifies whether the consumer container should auto-startup. */ @Metadata(label = "consumer", defaultValue = "true", description = "Specifies whether the consumer container should auto-startup.") public void setAutoStartup(boolean autoStartup) { getConfiguration().setAutoStartup(autoStartup); } /** * Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. */ @Metadata(label = "consumer", description = "Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details.") public void setCacheLevel(int cacheLevel) { getConfiguration().setCacheLevel(cacheLevel); } /** * Sets the cache level by name for the underlying JMS resources. * Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. * The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. */ @Metadata(defaultValue = "CACHE_AUTO", label = "consumer", enums = "CACHE_AUTO,CACHE_CONNECTION,CACHE_CONSUMER,CACHE_NONE,CACHE_SESSION", description = "Sets the cache level by name for the underlying JMS resources." + " Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION." + " The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information.") public void setCacheLevelName(String cacheName) { getConfiguration().setCacheLevelName(cacheName); } /** * Sets the cache level by name for the reply consumer when doing request/reply over JMS. * This option only applies when using fixed reply queues (not temporary). * Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. * And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere * may require to set the replyToCacheLevelName=CACHE_NONE to work. * Note: If using temporary queues then CACHE_NONE is not allowed, * and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. */ @Metadata(label = "producer,advanced", enums = "CACHE_AUTO,CACHE_CONNECTION,CACHE_CONSUMER,CACHE_NONE,CACHE_SESSION", description = "Sets the cache level by name for the reply consumer when doing request/reply over JMS." + " This option only applies when using fixed reply queues (not temporary)." + " Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName." + " And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere" + " may require to set the replyToCacheLevelName=CACHE_NONE to work." + " Note: If using temporary queues then CACHE_NONE is not allowed," + " and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION.") public void setReplyToCacheLevelName(String cacheName) { getConfiguration().setReplyToCacheLevelName(cacheName); } /** * Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. * It is typically only required for durable topic subscriptions. * <p/> * If using Apache ActiveMQ you may prefer to use Virtual Topics instead. */ @Metadata(description = "Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance." + " It is typically only required for durable topic subscriptions." + " If using Apache ActiveMQ you may prefer to use Virtual Topics instead.") public void setClientId(String consumerClientId) { getConfiguration().setClientId(consumerClientId); } /** * Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). * See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. * <p/> * When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number * of concurrent consumers on the reply message listener. */ @Metadata(defaultValue = "1", label = "consumer", description = "Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS)." + " See also the maxMessagesPerTask option to control dynamic scaling up/down of threads." + " When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number" + " of concurrent consumers on the reply message listener.") public void setConcurrentConsumers(int concurrentConsumers) { getConfiguration().setConcurrentConsumers(concurrentConsumers); } /** * Specifies the default number of concurrent consumers when doing request/reply over JMS. * See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. */ @Metadata(defaultValue = "1", label = "producer", description = "Specifies the default number of concurrent consumers when doing request/reply over JMS." + " See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.") public void setReplyToConcurrentConsumers(int concurrentConsumers) { getConfiguration().setReplyToConcurrentConsumers(concurrentConsumers); } /** * The connection factory to be use. A connection factory must be configured either on the component or endpoint. */ @Metadata(description = "The connection factory to be use. A connection factory must be configured either on the component or endpoint.") public void setConnectionFactory(ConnectionFactory connectionFactory) { getConfiguration().setConnectionFactory(connectionFactory); } /** * Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. */ @Metadata(label = "security", secret = true, description = "Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.") public void setUsername(String username) { getConfiguration().setUsername(username); } /** * Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. */ @Metadata(label = "security", secret = true, description = "Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.") public void setPassword(String password) { getConfiguration().setPassword(password); } /** * Specifies whether persistent delivery is used by default. */ @Metadata(defaultValue = "true", label = "producer", description = "Specifies whether persistent delivery is used by default.") public void setDeliveryPersistent(boolean deliveryPersistent) { getConfiguration().setDeliveryPersistent(deliveryPersistent); } /** * Specifies the delivery mode to be used. Possible values are * Possibles values are those defined by javax.jms.DeliveryMode. * NON_PERSISTENT = 1 and PERSISTENT = 2. */ @Metadata(label = "producer", enums = "1,2", description = "Specifies the delivery mode to be used." + " Possibles values are those defined by javax.jms.DeliveryMode." + " NON_PERSISTENT = 1 and PERSISTENT = 2.") public void setDeliveryMode(Integer deliveryMode) { getConfiguration().setDeliveryMode(deliveryMode); } /** * The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well. */ @Metadata(description = "The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well.") public void setDurableSubscriptionName(String durableSubscriptionName) { getConfiguration().setDurableSubscriptionName(durableSubscriptionName); } /** * Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. */ @Metadata(label = "advanced", description = "Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.") public void setExceptionListener(ExceptionListener exceptionListener) { getConfiguration().setExceptionListener(exceptionListener); } /** * Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. * By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. * You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. * This makes it much easier to configure, than having to code a custom errorHandler. */ @Metadata(label = "advanced", description = "Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message." + " By default these exceptions will be logged at the WARN level, if no errorHandler has been configured." + " You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options." + " This makes it much easier to configure, than having to code a custom errorHandler.") public void setErrorHandler(ErrorHandler errorHandler) { getConfiguration().setErrorHandler(errorHandler); } /** * Allows to configure the default errorHandler logging level for logging uncaught exceptions. */ @Metadata(defaultValue = "WARN", label = "consumer,logging", description = "Allows to configure the default errorHandler logging level for logging uncaught exceptions.") public void setErrorHandlerLoggingLevel(LoggingLevel errorHandlerLoggingLevel) { getConfiguration().setErrorHandlerLoggingLevel(errorHandlerLoggingLevel); } /** * Allows to control whether stacktraces should be logged or not, by the default errorHandler. */ @Metadata(defaultValue = "true", label = "consumer,logging", description = "Allows to control whether stacktraces should be logged or not, by the default errorHandler.") public void setErrorHandlerLogStackTrace(boolean errorHandlerLogStackTrace) { getConfiguration().setErrorHandlerLogStackTrace(errorHandlerLogStackTrace); } /** * Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. * This option is based on Spring's JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. * This contrasts with the preserveMessageQos option, which operates at message granularity, * reading QoS properties exclusively from the Camel In message headers. */ @Metadata(label = "producer", defaultValue = "false", description = "Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages." + " This option is based on Spring's JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint." + " This contrasts with the preserveMessageQos option, which operates at message granularity," + " reading QoS properties exclusively from the Camel In message headers.") public void setExplicitQosEnabled(boolean explicitQosEnabled) { getConfiguration().setExplicitQosEnabled(explicitQosEnabled); } /** * Specifies whether the listener session should be exposed when consuming messages. */ @Metadata(label = "consumer,advanced", description = "Specifies whether the listener session should be exposed when consuming messages.") public void setExposeListenerSession(boolean exposeListenerSession) { getConfiguration().setExposeListenerSession(exposeListenerSession); } /** * Specifies the limit for idle executions of a receive task, not having received any message within its execution. * If this limit is reached, the task will shut down and leave receiving to other executing tasks * (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). * There is additional doc available from Spring. */ @Metadata(defaultValue = "1", label = "advanced", description = "Specifies the limit for idle executions of a receive task, not having received any message within its execution." + " If this limit is reached, the task will shut down and leave receiving to other executing tasks" + " (in the case of dynamic scheduling; see the maxConcurrentConsumers setting)." + " There is additional doc available from Spring.") public void setIdleTaskExecutionLimit(int idleTaskExecutionLimit) { getConfiguration().setIdleTaskExecutionLimit(idleTaskExecutionLimit); } /** * Specify the limit for the number of consumers that are allowed to be idle at any given time. */ @Metadata(defaultValue = "1", label = "advanced", description = "Specify the limit for the number of consumers that are allowed to be idle at any given time.") public void setIdleConsumerLimit(int idleConsumerLimit) { getConfiguration().setIdleConsumerLimit(idleConsumerLimit); } /** * Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). * See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. * <p/> * When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number * of concurrent consumers on the reply message listener. */ @Metadata(label = "consumer", description = "Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS)." + " See also the maxMessagesPerTask option to control dynamic scaling up/down of threads." + " When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number" + " of concurrent consumers on the reply message listener.") public void setMaxConcurrentConsumers(int maxConcurrentConsumers) { getConfiguration().setMaxConcurrentConsumers(maxConcurrentConsumers); } /** * Specifies the maximum number of concurrent consumers when using request/reply over JMS. * See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. */ @Metadata(label = "producer", description = "Specifies the maximum number of concurrent consumers when using request/reply over JMS." + " See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.") public void setReplyToMaxConcurrentConsumers(int maxConcurrentConsumers) { getConfiguration().setReplyToMaxConcurrentConsumers(maxConcurrentConsumers); } /** * Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. */ @Metadata(label = "producer", defaultValue = "1", description = "Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS.") public void setReplyOnTimeoutToMaxConcurrentConsumers(int maxConcurrentConsumers) { getConfiguration().setReplyToOnTimeoutMaxConcurrentConsumers(maxConcurrentConsumers); } /** * The number of messages per task. -1 is unlimited. * If you use a range for concurrent consumers (eg min < max), then this option can be used to set * a value to eg 100 to control how fast the consumers will shrink when less work is required. */ @Metadata(defaultValue = "-1", label = "advanced", description = "The number of messages per task. -1 is unlimited." + " If you use a range for concurrent consumers (eg min < max), then this option can be used to set" + " a value to eg 100 to control how fast the consumers will shrink when less work is required.") public void setMaxMessagesPerTask(int maxMessagesPerTask) { getConfiguration().setMaxMessagesPerTask(maxMessagesPerTask); } /** * To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control * how to map to/from a javax.jms.Message. */ @Metadata(label = "advanced", description = "To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message.") public void setMessageConverter(MessageConverter messageConverter) { getConfiguration().setMessageConverter(messageConverter); } /** * Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc. * See section about how mapping works below for more details. */ @Metadata(defaultValue = "true", label = "advanced", description = "Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc.") public void setMapJmsMessage(boolean mapJmsMessage) { getConfiguration().setMapJmsMessage(mapJmsMessage); } /** * When sending, specifies whether message IDs should be added. This is just an hint to the JMS Broker. * If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value */ @Metadata(defaultValue = "true", label = "advanced", description = "When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker." + "If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, " + "the message ID must be set to its normal unique value") public void setMessageIdEnabled(boolean messageIdEnabled) { getConfiguration().setMessageIdEnabled(messageIdEnabled); } /** * Specifies whether timestamps should be enabled by default on sending messages. */ @Metadata(defaultValue = "true", label = "advanced", description = "Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker." + "If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint " + "the timestamp must be set to its normal value") public void setMessageTimestampEnabled(boolean messageTimestampEnabled) { getConfiguration().setMessageTimestampEnabled(messageTimestampEnabled); } /** * If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. * Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set * (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set) */ @Metadata(label = "producer,advanced", description = "If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending." + " Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set" + " (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set)") public void setAlwaysCopyMessage(boolean alwaysCopyMessage) { getConfiguration().setAlwaysCopyMessage(alwaysCopyMessage); } /** * Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. */ @Metadata(label = "advanced", description = "Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages.") public void setUseMessageIDAsCorrelationID(boolean useMessageIDAsCorrelationID) { getConfiguration().setUseMessageIDAsCorrelationID(useMessageIDAsCorrelationID); } /** * Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). * The explicitQosEnabled option must also be enabled in order for this option to have any effect. */ @Metadata(defaultValue = "" + Message.DEFAULT_PRIORITY, enums = "1,2,3,4,5,6,7,8,9", label = "producer", description = "Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest)." + " The explicitQosEnabled option must also be enabled in order for this option to have any effect.") public void setPriority(int priority) { getConfiguration().setPriority(priority); } /** * Specifies whether to inhibit the delivery of messages published by its own connection. */ @Metadata(label = "advanced", description = "Specifies whether to inhibit the delivery of messages published by its own connection.") public void setPubSubNoLocal(boolean pubSubNoLocal) { getConfiguration().setPubSubNoLocal(pubSubNoLocal); } /** * The timeout for receiving messages (in milliseconds). */ @Metadata(defaultValue = "1000", label = "advanced", description = "The timeout for receiving messages (in milliseconds).") public void setReceiveTimeout(long receiveTimeout) { getConfiguration().setReceiveTimeout(receiveTimeout); } /** * Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. * The default is 5000 ms, that is, 5 seconds. */ @Metadata(defaultValue = "5000", label = "advanced", description = "Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds." + " The default is 5000 ms, that is, 5 seconds.") public void setRecoveryInterval(long recoveryInterval) { getConfiguration().setRecoveryInterval(recoveryInterval); } /** * Deprecated: Enabled by default, if you specify a durableSubscriptionName and a clientId. */ @Deprecated public void setSubscriptionDurable(boolean subscriptionDurable) { getConfiguration().setSubscriptionDurable(subscriptionDurable); } /** * Allows you to specify a custom task executor for consuming messages. */ @Metadata(label = "consumer,advanced", description = "Allows you to specify a custom task executor for consuming messages.") public void setTaskExecutor(TaskExecutor taskExecutor) { getConfiguration().setTaskExecutor(taskExecutor); } /** * When sending messages, specifies the time-to-live of the message (in milliseconds). */ @Metadata(defaultValue = "-1", label = "producer", description = "When sending messages, specifies the time-to-live of the message (in milliseconds).") public void setTimeToLive(long timeToLive) { getConfiguration().setTimeToLive(timeToLive); } /** * Specifies whether to use transacted mode */ @Metadata(label = "transaction", description = "Specifies whether to use transacted mode") public void setTransacted(boolean consumerTransacted) { getConfiguration().setTransacted(consumerTransacted); } /** * If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true. */ @Metadata(defaultValue = "true", label = "transaction,advanced", description = "If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true.") public void setLazyCreateTransactionManager(boolean lazyCreating) { getConfiguration().setLazyCreateTransactionManager(lazyCreating); } /** * The Spring transaction manager to use. */ @Metadata(label = "transaction,advanced", description = "The Spring transaction manager to use.") public void setTransactionManager(PlatformTransactionManager transactionManager) { getConfiguration().setTransactionManager(transactionManager); } /** * The name of the transaction to use. */ @Metadata(label = "transaction,advanced", description = "The name of the transaction to use.") public void setTransactionName(String transactionName) { getConfiguration().setTransactionName(transactionName); } /** * The timeout value of the transaction (in seconds), if using transacted mode. */ @Metadata(defaultValue = "-1", label = "transaction,advanced", description = "The timeout value of the transaction (in seconds), if using transacted mode.") public void setTransactionTimeout(int transactionTimeout) { getConfiguration().setTransactionTimeout(transactionTimeout); } /** * Specifies whether to test the connection on startup. * This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. * If a connection cannot be granted then Camel throws an exception on startup. * This ensures that Camel is not started with failed connections. * The JMS producers is tested as well. */ @Metadata(description = "Specifies whether to test the connection on startup." + " This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker." + " If a connection cannot be granted then Camel throws an exception on startup." + " This ensures that Camel is not started with failed connections." + " The JMS producers is tested as well.") public void setTestConnectionOnStartup(boolean testConnectionOnStartup) { getConfiguration().setTestConnectionOnStartup(testConnectionOnStartup); } /** * Whether to startup the JmsConsumer message listener asynchronously, when starting a route. * For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying * and/or failover. This will cause Camel to block while starting routes. By setting this option to true, * you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread * in asynchronous mode. If this option is used, then beware that if the connection could not be established, * then an exception is logged at WARN level, and the consumer will not be able to receive messages; * You can then restart the route to retry. */ @Metadata(label = "advanced", description = "Whether to startup the JmsConsumer message listener asynchronously, when starting a route." + " For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying" + " and/or failover. This will cause Camel to block while starting routes. By setting this option to true," + " you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread" + " in asynchronous mode. If this option is used, then beware that if the connection could not be established," + " then an exception is logged at WARN level, and the consumer will not be able to receive messages;" + " You can then restart the route to retry.") public void setAsyncStartListener(boolean asyncStartListener) { getConfiguration().setAsyncStartListener(asyncStartListener); } /** * Whether to stop the JmsConsumer message listener asynchronously, when stopping a route. */ @Metadata(label = "advanced", description = "Whether to stop the JmsConsumer message listener asynchronously, when stopping a route.") public void setAsyncStopListener(boolean asyncStopListener) { getConfiguration().setAsyncStopListener(asyncStopListener); } /** * When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination * if you touch the headers (get or set) during the route. Set this option to true to force Camel to send * the original JMS message that was received. */ @Metadata(label = "producer,advanced", description = "When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination" + " if you touch the headers (get or set) during the route. Set this option to true to force Camel to send" + " the original JMS message that was received.") public void setForceSendOriginalMessage(boolean forceSendOriginalMessage) { getConfiguration().setForceSendOriginalMessage(forceSendOriginalMessage); } /** * The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). * The default is 20 seconds. You can include the header "CamelJmsRequestTimeout" to override this endpoint configured * timeout value, and thus have per message individual timeout values. * See also the requestTimeoutCheckerInterval option. */ @Metadata(defaultValue = "20000", label = "producer", description = "The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds)." + " The default is 20 seconds. You can include the header \"CamelJmsRequestTimeout\" to override this endpoint configured" + " timeout value, and thus have per message individual timeout values." + " See also the requestTimeoutCheckerInterval option.") public void setRequestTimeout(long requestTimeout) { getConfiguration().setRequestTimeout(requestTimeout); } /** * Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. * By default Camel checks once per second. But if you must react faster when a timeout occurs, * then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout. */ @Metadata(defaultValue = "1000", label = "advanced", description = "Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS." + " By default Camel checks once per second. But if you must react faster when a timeout occurs," + " then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout.") public void setRequestTimeoutCheckerInterval(long requestTimeoutCheckerInterval) { getConfiguration().setRequestTimeoutCheckerInterval(requestTimeoutCheckerInterval); } /** * You can transfer the exchange over the wire instead of just the body and headers. * The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, * exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. * You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload. */ @Metadata(label = "advanced", description = "You can transfer the exchange over the wire instead of just the body and headers." + " The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers," + " exchange properties, exchange exception." + " This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level." + " You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload.") public void setTransferExchange(boolean transferExchange) { getConfiguration().setTransferExchange(transferExchange); } /** * If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, * then the caused Exception will be send back in response as a javax.jms.ObjectMessage. * If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge * in your routing - for example, using persistent queues to enable robust routing. * Notice that if you also have transferExchange enabled, this option takes precedence. * The caught exception is required to be serializable. * The original Exception on the consumer side can be wrapped in an outer exception * such as org.apache.camel.RuntimeCamelException when returned to the producer. */ @Metadata(label = "advanced", description = "If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side," + " then the caused Exception will be send back in response as a javax.jms.ObjectMessage." + " If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge" + " in your routing - for example, using persistent queues to enable robust routing." + " Notice that if you also have transferExchange enabled, this option takes precedence." + " The caught exception is required to be serializable." + " The original Exception on the consumer side can be wrapped in an outer exception" + " such as org.apache.camel.RuntimeCamelException when returned to the producer.") public void setTransferException(boolean transferException) { getConfiguration().setTransferException(transferException); } /** * If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side, * then the fault flag on {@link org.apache.camel.Message#isFault()} will be send back in the response as a JMS header with the key * {@link JmsConstants#JMS_TRANSFER_FAULT}. * If the client is Camel, the returned fault flag will be set on the {@link org.apache.camel.Message#setFault(boolean)}. * <p/> * You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws. */ @Metadata(label = "advanced", description = "If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side," + " then the fault flag on Message#isFault() will be send back in the response as a JMS header with the key" + " org.apache.camel.component.jms.JmsConstants#JMS_TRANSFER_FAULT#JMS_TRANSFER_FAULT." + " If the client is Camel, the returned fault flag will be set on the {@link org.apache.camel.Message#setFault(boolean)}." + " You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws.") public void setTransferFault(boolean transferFault) { getConfiguration().setTransferFault(transferFault); } /** * Allows you to use your own implementation of the org.springframework.jms.core.JmsOperations interface. * Camel uses JmsTemplate as default. Can be used for testing purpose, but not used much as stated in the spring API docs. */ @Metadata(label = "advanced", description = "Allows you to use your own implementation of the org.springframework.jms.core.JmsOperations interface." + " Camel uses JmsTemplate as default. Can be used for testing purpose, but not used much as stated in the spring API docs.") public void setJmsOperations(JmsOperations jmsOperations) { getConfiguration().setJmsOperations(jmsOperations); } /** * A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver * (for example, to lookup the real destination in a JNDI registry). */ @Metadata(label = "advanced", description = "A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver" + " (for example, to lookup the real destination in a JNDI registry).") public void setDestinationResolver(DestinationResolver destinationResolver) { getConfiguration().setDestinationResolver(destinationResolver); } /** * Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. * Possible values are: Temporary, Shared, or Exclusive. * By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. * This option allows you to use exclusive queues instead of shared ones. * See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, * and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. */ @Metadata(label = "producer", description = "Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS." + " Possible values are: Temporary, Shared, or Exclusive." + " By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default." + " This option allows you to use exclusive queues instead of shared ones." + " See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment," + " and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive.") public void setReplyToType(ReplyToType replyToType) { getConfiguration().setReplyToType(replyToType); } /** * Set to true, if you want to send message using the QoS settings specified on the message, * instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, * and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the * values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. * The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header. */ @Metadata(label = "producer", description = "Set to true, if you want to send message using the QoS settings specified on the message," + " instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode," + " and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the" + " values from the endpoint instead. So, when using this option, the headers override the values from the endpoint." + " The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header.") public void setPreserveMessageQos(boolean preserveMessageQos) { getConfiguration().setPreserveMessageQos(preserveMessageQos); } /** * Whether the JmsConsumer processes the Exchange asynchronously. * If enabled then the JmsConsumer may pickup the next message from the JMS queue, * while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). * This means that messages may be processed not 100% strictly in order. If disabled (as default) * then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. * Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction * must be executed synchronously (Camel 3.0 may support async transactions). */ @Metadata(label = "consumer", description = "Whether the JmsConsumer processes the Exchange asynchronously." + " If enabled then the JmsConsumer may pickup the next message from the JMS queue," + " while the previous message is being processed asynchronously (by the Asynchronous Routing Engine)." + " This means that messages may be processed not 100% strictly in order. If disabled (as default)" + " then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue." + " Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction" + " must be executed synchronously (Camel 3.0 may support async transactions).") public void setAsyncConsumer(boolean asyncConsumer) { getConfiguration().setAsyncConsumer(asyncConsumer); } /** * Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown. */ @Metadata(defaultValue = "true", label = "producer,advanced", description = "Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown.") public void setAllowNullBody(boolean allowNullBody) { getConfiguration().setAllowNullBody(allowNullBody); } /** * Only applicable when sending to JMS destination using InOnly (eg fire and forget). * Enabling this option will enrich the Camel Exchange with the actual JMSMessageID * that was used by the JMS client when the message was sent to the JMS destination. */ @Metadata(label = "producer,advanced", description = "Only applicable when sending to JMS destination using InOnly (eg fire and forget)." + " Enabling this option will enrich the Camel Exchange with the actual JMSMessageID" + " that was used by the JMS client when the message was sent to the JMS destination.") public void setIncludeSentJMSMessageID(boolean includeSentJMSMessageID) { getConfiguration().setIncludeSentJMSMessageID(includeSentJMSMessageID); } /** * Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. * Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. * Note: If you are using a custom headerFilterStrategy then this option does not apply. */ @Metadata(label = "advanced", description = "Whether to include all JMSXxxx properties when mapping from JMS to Camel Message." + " Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc." + " Note: If you are using a custom headerFilterStrategy then this option does not apply.") public void setIncludeAllJMSXProperties(boolean includeAllJMSXProperties) { getConfiguration().setIncludeAllJMSXProperties(includeAllJMSXProperties); } /** * Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, * for both consumer endpoints and the ReplyTo consumer of producer endpoints. * Possible values: SimpleAsync (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool * (uses Spring's ThreadPoolTaskExecutor with optimal values - cached threadpool-like). * If not set, it defaults to the previous behaviour, which uses a cached thread pool * for consumer endpoints and SimpleAsync for reply consumers. * The use of ThreadPool is recommended to reduce "thread trash" in elastic configurations * with dynamically increasing and decreasing concurrent consumers. */ @Metadata(label = "consumer,advanced", description = "Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer," + " for both consumer endpoints and the ReplyTo consumer of producer endpoints." + " Possible values: SimpleAsync (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool" + " (uses Spring's ThreadPoolTaskExecutor with optimal values - cached threadpool-like)." + " If not set, it defaults to the previous behaviour, which uses a cached thread pool" + " for consumer endpoints and SimpleAsync for reply consumers." + " The use of ThreadPool is recommended to reduce thread trash in elastic configurations" + " with dynamically increasing and decreasing concurrent consumers.") public void setDefaultTaskExecutorType(DefaultTaskExecutorType type) { getConfiguration().setDefaultTaskExecutorType(type); } /** * Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. * Camel provides two implementations out of the box: default and passthrough. * The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. * Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. * You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy * and refer to it using the # notation. */ @Metadata(label = "advanced", description = "Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification." + " Camel provides two implementations out of the box: default and passthrough." + " The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is." + " Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters." + " You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy" + " and refer to it using the # notation.") public void setJmsKeyFormatStrategy(JmsKeyFormatStrategy jmsKeyFormatStrategy) { getConfiguration().setJmsKeyFormatStrategy(jmsKeyFormatStrategy); } /** * Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. * Camel provides two implementations out of the box: default and passthrough. * The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. * Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. * You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy * and refer to it using the # notation. */ public void setJmsKeyFormatStrategy(String jmsKeyFormatStrategyName) { // allow to configure a standard by its name, which is simpler JmsKeyFormatStrategy strategy = resolveStandardJmsKeyFormatStrategy(jmsKeyFormatStrategyName); if (strategy == null) { throw new IllegalArgumentException("JmsKeyFormatStrategy with name " + jmsKeyFormatStrategyName + " is not a standard supported name"); } else { getConfiguration().setJmsKeyFormatStrategy(strategy); } } /** * Sets the Spring ApplicationContext to use */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public QueueBrowseStrategy getQueueBrowseStrategy() { if (queueBrowseStrategy == null) { queueBrowseStrategy = new DefaultQueueBrowseStrategy(); } return queueBrowseStrategy; } /** * To use a custom QueueBrowseStrategy when browsing queues */ public void setQueueBrowseStrategy(QueueBrowseStrategy queueBrowseStrategy) { this.queueBrowseStrategy = queueBrowseStrategy; } public MessageCreatedStrategy getMessageCreatedStrategy() { return messageCreatedStrategy; } /** * To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of <tt>javax.jms.Message</tt> * objects when Camel is sending a JMS message. */ public void setMessageCreatedStrategy(MessageCreatedStrategy messageCreatedStrategy) { this.messageCreatedStrategy = messageCreatedStrategy; } public int getWaitForProvisionCorrelationToBeUpdatedCounter() { return getConfiguration().getWaitForProvisionCorrelationToBeUpdatedCounter(); } /** * Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS * and when the option useMessageIDAsCorrelationID is enabled. */ @Metadata(defaultValue = "50", label = "advanced", description = "Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS" + " and when the option useMessageIDAsCorrelationID is enabled.") public void setWaitForProvisionCorrelationToBeUpdatedCounter(int counter) { getConfiguration().setWaitForProvisionCorrelationToBeUpdatedCounter(counter); } public long getWaitForProvisionCorrelationToBeUpdatedThreadSleepingTime() { return getConfiguration().getWaitForProvisionCorrelationToBeUpdatedThreadSleepingTime(); } /** * Interval in millis to sleep each time while waiting for provisional correlation id to be updated. */ @Metadata(defaultValue = "100", label = "advanced", description = "Interval in millis to sleep each time while waiting for provisional correlation id to be updated.") public void setWaitForProvisionCorrelationToBeUpdatedThreadSleepingTime(long sleepingTime) { getConfiguration().setWaitForProvisionCorrelationToBeUpdatedThreadSleepingTime(sleepingTime); } /** * Use this JMS property to correlate messages in InOut exchange pattern (request-reply) * instead of JMSCorrelationID property. This allows you to exchange messages with * systems that do not correlate messages using JMSCorrelationID JMS property. If used * JMSCorrelationID will not be used or set by Camel. The value of here named property * will be generated if not supplied in the header of the message under the same name. */ @Metadata(label = "producer,advanced", description = "Use this JMS property to correlate messages in InOut exchange pattern (request-reply)" + " instead of JMSCorrelationID property. This allows you to exchange messages with" + " systems that do not correlate messages using JMSCorrelationID JMS property. If used" + " JMSCorrelationID will not be used or set by Camel. The value of here named property" + " will be generated if not supplied in the header of the message under the same name.") public void setCorrelationProperty(final String correlationProperty) { getConfiguration().setCorrelationProperty(correlationProperty); } // Implementation methods // ------------------------------------------------------------------------- @Override protected void doStart() throws Exception { if (getHeaderFilterStrategy() == null) { setHeaderFilterStrategy(new JmsHeaderFilterStrategy(getConfiguration().isIncludeAllJMSXProperties())); } } @Override protected void doShutdown() throws Exception { if (asyncStartStopExecutorService != null) { getCamelContext().getExecutorServiceManager().shutdownNow(asyncStartStopExecutorService); asyncStartStopExecutorService = null; } super.doShutdown(); } protected synchronized ExecutorService getAsyncStartStopExecutorService() { if (asyncStartStopExecutorService == null) { // use a cached thread pool for async start tasks as they can run for a while, and we need a dedicated thread // for each task, and the thread pool will shrink when no more tasks running asyncStartStopExecutorService = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "AsyncStartStopListener"); } return asyncStartStopExecutorService; } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { boolean pubSubDomain = false; boolean tempDestination = false; if (remaining.startsWith(JmsConfiguration.QUEUE_PREFIX)) { pubSubDomain = false; remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.QUEUE_PREFIX.length()), '/'); } else if (remaining.startsWith(JmsConfiguration.TOPIC_PREFIX)) { pubSubDomain = true; remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.TOPIC_PREFIX.length()), '/'); } else if (remaining.startsWith(JmsConfiguration.TEMP_QUEUE_PREFIX)) { pubSubDomain = false; tempDestination = true; remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.TEMP_QUEUE_PREFIX.length()), '/'); } else if (remaining.startsWith(JmsConfiguration.TEMP_TOPIC_PREFIX)) { pubSubDomain = true; tempDestination = true; remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.TEMP_TOPIC_PREFIX.length()), '/'); } final String subject = convertPathToActualDestination(remaining, parameters); // lets make sure we copy the configuration as each endpoint can // customize its own version JmsConfiguration newConfiguration = getConfiguration().copy(); JmsEndpoint endpoint; if (pubSubDomain) { if (tempDestination) { endpoint = createTemporaryTopicEndpoint(uri, this, subject, newConfiguration); } else { endpoint = createTopicEndpoint(uri, this, subject, newConfiguration); } } else { QueueBrowseStrategy strategy = getQueueBrowseStrategy(); if (tempDestination) { endpoint = createTemporaryQueueEndpoint(uri, this, subject, newConfiguration, strategy); } else { endpoint = createQueueEndpoint(uri, this, subject, newConfiguration, strategy); } } // resolve any custom connection factory first ConnectionFactory cf = resolveAndRemoveReferenceParameter(parameters, "connectionFactory", ConnectionFactory.class); if (cf != null) { endpoint.getConfiguration().setConnectionFactory(cf); } // if username or password provided then wrap the connection factory String cfUsername = getAndRemoveParameter(parameters, "username", String.class, getConfiguration().getUsername()); String cfPassword = getAndRemoveParameter(parameters, "password", String.class, getConfiguration().getPassword()); if (cfUsername != null && cfPassword != null) { cf = endpoint.getConfiguration().getConnectionFactory(); ObjectHelper.notNull(cf, "ConnectionFactory"); LOG.debug("Wrapping existing ConnectionFactory with UserCredentialsConnectionFactoryAdapter using username: {} and password: ******", cfUsername); UserCredentialsConnectionFactoryAdapter ucfa = new UserCredentialsConnectionFactoryAdapter(); ucfa.setTargetConnectionFactory(cf); ucfa.setPassword(cfPassword); ucfa.setUsername(cfUsername); endpoint.getConfiguration().setConnectionFactory(ucfa); } else { // if only username or password was provided then fail if (cfUsername != null || cfPassword != null) { if (cfUsername == null) { throw new IllegalArgumentException("Username must also be provided when using username/password as credentials."); } else { throw new IllegalArgumentException("Password must also be provided when using username/password as credentials."); } } } // jms header strategy String strategyVal = getAndRemoveParameter(parameters, KEY_FORMAT_STRATEGY_PARAM, String.class); JmsKeyFormatStrategy strategy = resolveStandardJmsKeyFormatStrategy(strategyVal); if (strategy != null) { endpoint.setJmsKeyFormatStrategy(strategy); } else { // its not a standard, but a reference parameters.put(KEY_FORMAT_STRATEGY_PARAM, strategyVal); endpoint.setJmsKeyFormatStrategy(resolveAndRemoveReferenceParameter( parameters, KEY_FORMAT_STRATEGY_PARAM, JmsKeyFormatStrategy.class)); } MessageListenerContainerFactory messageListenerContainerFactory = resolveAndRemoveReferenceParameter(parameters, "messageListenerContainerFactoryRef", MessageListenerContainerFactory.class); if (messageListenerContainerFactory == null) { messageListenerContainerFactory = resolveAndRemoveReferenceParameter(parameters, "messageListenerContainerFactory", MessageListenerContainerFactory.class); } if (messageListenerContainerFactory != null) { endpoint.setMessageListenerContainerFactory(messageListenerContainerFactory); } setProperties(endpoint.getConfiguration(), parameters); endpoint.setHeaderFilterStrategy(getHeaderFilterStrategy()); return endpoint; } protected JmsEndpoint createTemporaryTopicEndpoint(String uri, JmsComponent component, String subject, JmsConfiguration configuration) { return new JmsTemporaryTopicEndpoint(uri, component, subject, configuration); } protected JmsEndpoint createTopicEndpoint(String uri, JmsComponent component, String subject, JmsConfiguration configuration) { return new JmsEndpoint(uri, component, subject, true, configuration); } protected JmsEndpoint createTemporaryQueueEndpoint(String uri, JmsComponent component, String subject, JmsConfiguration configuration, QueueBrowseStrategy queueBrowseStrategy) { return new JmsTemporaryQueueEndpoint(uri, component, subject, configuration, queueBrowseStrategy); } protected JmsEndpoint createQueueEndpoint(String uri, JmsComponent component, String subject, JmsConfiguration configuration, QueueBrowseStrategy queueBrowseStrategy) { return new JmsQueueEndpoint(uri, component, subject, configuration, queueBrowseStrategy); } /** * Resolves the standard supported {@link JmsKeyFormatStrategy} by a name which can be: * <ul> * <li>default - to use the default strategy</li> * <li>passthrough - to use the passthrough strategy</li> * </ul> * * @param name the name * @return the strategy, or <tt>null</tt> if not a standard name. */ private static JmsKeyFormatStrategy resolveStandardJmsKeyFormatStrategy(String name) { if ("default".equalsIgnoreCase(name)) { return new DefaultJmsKeyFormatStrategy(); } else if ("passthrough".equalsIgnoreCase(name)) { return new PassThroughJmsKeyFormatStrategy(); } else { return null; } } /** * A strategy method allowing the URI destination to be translated into the * actual JMS destination name (say by looking up in JNDI or something) */ protected String convertPathToActualDestination(String path, Map<String, Object> parameters) { return path; } /** * Factory method to create the default configuration instance * * @return a newly created configuration object which can then be further * customized */ protected JmsConfiguration createConfiguration() { return new JmsConfiguration(); } }
veithen/camel
components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsComponent.java
Java
apache-2.0
74,797
/* * 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.omg.CORBA; // // IDL:omg.org/CORBA/PolicyError:1.0 // final public class PolicyErrorHolder implements org.omg.CORBA.portable.Streamable { public PolicyError value; public PolicyErrorHolder() { } public PolicyErrorHolder(PolicyError initial) { value = initial; } public void _read(org.omg.CORBA.portable.InputStream in) { value = PolicyErrorHelper.read(in); } public void _write(org.omg.CORBA.portable.OutputStream out) { PolicyErrorHelper.write(out, value); } public org.omg.CORBA.TypeCode _type() { return PolicyErrorHelper.type(); } }
apache/geronimo-yoko
yoko-spec-corba/src/main/java/org/omg/CORBA/PolicyErrorHolder.java
Java
apache-2.0
1,480
package com.ztiany.ndk.importlibs; /** * @author Ztiany * Email: [email protected] * Date : 2017-11-04 23:07 */ class JniUtils { public native String stringFromJNI(); static { System.loadLibrary("hello-libs"); } }
Ztiany/CodeRepository
Android/NDK/Sample-NdkBuild-ThirdLib/project-import-libs/src/main/java/com/ztiany/ndk/importlibs/JniUtils.java
Java
apache-2.0
257
/* * 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.ignite.testsuites; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.ignite.internal.processors.cache.CacheNoAffinityExchangeTest; import org.apache.ignite.internal.processors.cache.PartitionedAtomicCacheGetsDistributionTest; import org.apache.ignite.internal.processors.cache.PartitionedTransactionalOptimisticCacheGetsDistributionTest; import org.apache.ignite.internal.processors.cache.PartitionedTransactionalPessimisticCacheGetsDistributionTest; import org.apache.ignite.internal.processors.cache.PartitionsExchangeCoordinatorFailoverTest; import org.apache.ignite.internal.processors.cache.ReplicatedAtomicCacheGetsDistributionTest; import org.apache.ignite.internal.processors.cache.ReplicatedTransactionalOptimisticCacheGetsDistributionTest; import org.apache.ignite.internal.processors.cache.ReplicatedTransactionalPessimisticCacheGetsDistributionTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteExchangeLatchManagerCoordinatorFailTest; import org.apache.ignite.internal.processors.cache.distributed.CacheExchangeMergeTest; import org.apache.ignite.internal.processors.cache.distributed.CacheParallelStartTest; import org.apache.ignite.internal.processors.cache.distributed.CacheTryLockMultithreadedTest; import org.apache.ignite.internal.processors.cache.distributed.ExchangeMergeStaleServerNodesTest; import org.apache.ignite.internal.processors.cache.distributed.GridCachePartitionEvictionDuringReadThroughSelfTest; import org.apache.ignite.internal.processors.cache.distributed.IgniteCache150ClientsTest; import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheThreadLocalTxTest; import org.apache.ignite.internal.processors.cache.distributed.IgniteOptimisticTxSuspendResumeTest; import org.apache.ignite.internal.processors.cache.distributed.IgnitePessimisticTxSuspendResumeTest; import org.apache.ignite.internal.processors.cache.transactions.TxLabelTest; import org.apache.ignite.internal.processors.cache.transactions.TxMultiCacheAsyncOpsTest; import org.apache.ignite.internal.processors.cache.transactions.TxOnCachesStartTest; import org.apache.ignite.internal.processors.cache.transactions.TxOptimisticOnPartitionExchangeTest; import org.apache.ignite.internal.processors.cache.transactions.TxOptimisticPrepareOnUnstableTopologyTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackAsyncNearCacheTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackAsyncTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnIncorrectParamsTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutNearCacheTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutNoDeadlockDetectionTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutOnePhaseCommitTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutTest; import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTopologyChangeTest; import org.apache.ignite.internal.processors.cache.transactions.TxStateChangeEventTest; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.DynamicSuite; import org.junit.runner.RunWith; /** * Test suite. */ @RunWith(DynamicSuite.class) public class IgniteCacheTestSuite6 { /** * @return IgniteCache test suite. */ public static List<Class<?>> suite() { return suite(null); } /** * @param ignoredTests Tests to ignore. * @return Test suite. */ public static List<Class<?>> suite(Collection<Class> ignoredTests) { List<Class<?>> suite = new ArrayList<>(); GridTestUtils.addTestIfNeeded(suite, GridCachePartitionEvictionDuringReadThroughSelfTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, IgniteOptimisticTxSuspendResumeTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, IgnitePessimisticTxSuspendResumeTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, CacheExchangeMergeTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, ExchangeMergeStaleServerNodesTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackOnTimeoutTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackOnTimeoutNoDeadlockDetectionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackOnTimeoutNearCacheTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, IgniteCacheThreadLocalTxTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackAsyncTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackAsyncNearCacheTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackOnTopologyChangeTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackOnTimeoutOnePhaseCommitTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxOptimisticPrepareOnUnstableTopologyTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxLabelTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxRollbackOnIncorrectParamsTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxStateChangeEventTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxMultiCacheAsyncOpsTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxOnCachesStartTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, IgniteCache150ClientsTest.class, ignoredTests); // TODO enable this test after IGNITE-6753, now it takes too long // GridTestUtils.addTestIfNeeded(suite, IgniteOutOfMemoryPropagationTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, ReplicatedAtomicCacheGetsDistributionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, ReplicatedTransactionalOptimisticCacheGetsDistributionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, ReplicatedTransactionalPessimisticCacheGetsDistributionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, PartitionedAtomicCacheGetsDistributionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, PartitionedTransactionalOptimisticCacheGetsDistributionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, PartitionedTransactionalPessimisticCacheGetsDistributionTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, TxOptimisticOnPartitionExchangeTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, IgniteExchangeLatchManagerCoordinatorFailTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, PartitionsExchangeCoordinatorFailoverTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, CacheTryLockMultithreadedTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, CacheParallelStartTest.class, ignoredTests); GridTestUtils.addTestIfNeeded(suite, CacheNoAffinityExchangeTest.class, ignoredTests); //GridTestUtils.addTestIfNeeded(suite, CacheClientsConcurrentStartTest.class, ignoredTests); //GridTestUtils.addTestIfNeeded(suite, GridCacheRebalancingOrderingTest.class, ignoredTests); //GridTestUtils.addTestIfNeeded(suite, IgniteCacheClientMultiNodeUpdateTopologyLockTest.class, ignoredTests); return suite; } }
ptupitsyn/ignite
modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite6.java
Java
apache-2.0
8,438
// 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 cn.ucloud.sdk.vo.uhost.out; /** * * @author Jack shen<[email protected]> * */ public class Price { private String chargeType; private Float price; public String getChargeType() { return chargeType; } public void setChargeType(String chargeType) { this.chargeType = chargeType; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } }
shenyefeng21/ucloud-java-sdk
src/main/java/cn/ucloud/sdk/vo/uhost/out/Price.java
Java
apache-2.0
1,272
/** * 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.oozie.client.rest; import java.util.Properties; import org.apache.oozie.client.JMSConnectionInfoWrapper; import org.apache.oozie.client.rest.JsonTags; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * JMS connection info bean representing the JMS related information for a job * */ public class JMSConnectionInfoBean implements JsonBean, JMSConnectionInfoWrapper { private Properties JNDIProperties; private String topicPrefix; private Properties topicProperties; @Override public JSONObject toJSONObject() { return toJSONObject("GMT"); } /** * Set the JNDI properties for jms connection * @param JNDIProperties the properties */ public void setJNDIProperties(Properties JNDIProperties) { this.JNDIProperties = JNDIProperties; } public Properties getJNDIProperties() { return JNDIProperties; } @SuppressWarnings("unchecked") @Override public JSONObject toJSONObject(String timeZoneId) { JSONObject json = new JSONObject(); json.put(JsonTags.JMS_JNDI_PROPERTIES, JSONValue.toJSONString(JNDIProperties)); json.put(JsonTags.JMS_TOPIC_PATTERN, JSONValue.toJSONString(topicProperties)); json.put(JsonTags.JMS_TOPIC_PREFIX, topicPrefix); return json; } @Override public String getTopicPrefix() { return topicPrefix; } /** * Sets the topic prefix * @param topicPrefix the prefix */ public void setTopicPrefix(String topicPrefix) { this.topicPrefix = topicPrefix; } /** * Set the topic pattern properties * @param topicProperties the properties */ public void setTopicPatternProperties(Properties topicProperties) { this.topicProperties = topicProperties; } @Override public Properties getTopicPatternProperties() { return topicProperties; } }
cbaenziger/oozie
core/src/main/java/org/apache/oozie/client/rest/JMSConnectionInfoBean.java
Java
apache-2.0
2,753
/* * 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.jclouds.providers.internal; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.Constants.PROPERTY_API; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.Constants.PROPERTY_BUILD_VERSION; import static org.jclouds.Constants.PROPERTY_ENDPOINT; import static org.jclouds.Constants.PROPERTY_ISO3166_CODES; import static org.jclouds.Constants.PROPERTY_PROVIDER; import java.util.Properties; import org.jclouds.apis.ApiMetadata; import org.jclouds.providers.AnonymousProviderMetadata; import org.jclouds.providers.ProviderMetadata; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Splitter; /** * Updates {@link ProviderMetadata} carrying over the input {@code Properties}, filtering out those which are typed fields in {@link ProviderMetadata} or {@link ApiMetadata} */ public class UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { private final ApiMetadata apiMetadata; private final Optional<ProviderMetadata> providerMetadata; public UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata) { this(checkNotNull(providerMetadata, "providerMetadata").getApiMetadata(), Optional.of(providerMetadata)); } public UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata) { this(checkNotNull(apiMetadata, "apiMetadata"), Optional.<ProviderMetadata> absent()); } public UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata) { this.apiMetadata = checkNotNull(apiMetadata, "apiMetadata"); this.providerMetadata = checkNotNull(providerMetadata, "providerMetadata"); } @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } private static String getAndRemove(Properties expanded, String key, String defaultVal) { try { return expanded.getProperty(key, defaultVal); } finally { expanded.remove(key); } } }
yanzhijun/jclouds-aliyun
core/src/main/java/org/jclouds/providers/internal/UpdateProviderMetadataFromProperties.java
Java
apache-2.0
4,429
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES 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.google.security.zynamics.zylib.gui.zygraph.realizers; import com.google.common.base.Preconditions; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.realizers.IZyNodeRealizer; public class ZyRegenerateableNodeRealizer implements IZyRegenerateableRealizer { private final IZyNodeRealizer realizer; public ZyRegenerateableNodeRealizer(final IZyNodeRealizer realizer) { this.realizer = Preconditions.checkNotNull(realizer, "Error: Node realizer can't be null."); } @Override public void regenerate() { realizer.regenerate(); } @Override public void repaint() { realizer.repaint(); } }
mayl8822/binnavi
src/main/java/com/google/security/zynamics/zylib/gui/zygraph/realizers/ZyRegenerateableNodeRealizer.java
Java
apache-2.0
1,233
package com.gigamole.sample.utils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.gigamole.sample.R; /** * Created by GIGAMOLE on 8/18/16. */ public class Utils { public static void setupItem(final View view, final LibraryObject libraryObject) { final TextView txt = (TextView) view.findViewById(R.id.txt_item); txt.setText(libraryObject.getTitle()); final ImageView img = (ImageView) view.findViewById(R.id.img_item); img.setImageResource(libraryObject.getRes()); } public static class LibraryObject { private String mTitle; private int mRes; public LibraryObject(final int res, final String title) { mRes = res; mTitle = title; } public String getTitle() { return mTitle; } public void setTitle(final String title) { mTitle = title; } public int getRes() { return mRes; } public void setRes(final int res) { mRes = res; } } }
DevLight-Mobile-Agency/InfiniteCycleViewPager
app/src/main/java/com/gigamole/sample/utils/Utils.java
Java
apache-2.0
1,113
/* * 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.skywalking.apm.testcase.spring.async; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class CaseServlet extends HttpServlet { private static final long serialVersionUID = -5173829093752900411L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AsyncConfig.class); AsyncBean async = applicationContext.getBean(AsyncBean.class); async.sendVisitBySystem(); async.sendVisitByCustomize(); PrintWriter writer = resp.getWriter(); writer.write("Success"); writer.flush(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
wu-sheng/sky-walking
test/plugin/scenarios/spring-async-scenario/src/main/java/org/apache/skywalking/apm/testcase/spring/async/CaseServlet.java
Java
apache-2.0
1,992
/* Copyright 2020 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.openkilda.server42.control.stormstub.swagger; import org.openkilda.server42.control.messaging.flowrtt.AddFlow; import org.openkilda.server42.control.messaging.flowrtt.Message; import com.fasterxml.classmate.TypeResolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 @Configuration public class SwaggerApiDocumentationConfig { private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Server42 storm stub REST CRUD") .description( "HTTP control on server42") .termsOfServiceUrl("").version("0.0.1-SNAPSHOT").build(); } @Autowired private TypeResolver typeResolver; @Bean public Docket configureControllerPackageAndConvertors() { return new Docket(DocumentationType.SWAGGER_2) .additionalModels(typeResolver.resolve(AddFlow.class), typeResolver.resolve(Message.class)) .select() .apis(RequestHandlerSelectors.basePackage("org.openkilda.server42.control.stormstub")).build() .apiInfo(apiInfo()); } }
jonvestal/open-kilda
src-java/server42/server42-control-storm-stub/src/main/java/org/openkilda/server42/control/stormstub/swagger/SwaggerApiDocumentationConfig.java
Java
apache-2.0
2,225
// 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 cn.ucloud.sdk.vo.ulb.out; import cn.ucloud.sdk.vo.UcloudOutVo; /** * * @author Jack shen<[email protected]> * */ public class ReleaseBackendOutVo extends UcloudOutVo { }
shenyefeng21/ucloud-java-sdk
src/main/java/cn/ucloud/sdk/vo/ulb/out/ReleaseBackendOutVo.java
Java
apache-2.0
985
/* * 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.jena.datatypes; import java.net.URI; import java.net.URL; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import org.apache.jena.datatypes.xsd.XSDDatatype ; import org.apache.jena.datatypes.xsd.impl.RDFLangString ; import org.apache.jena.datatypes.xsd.impl.XMLLiteralType ; import org.apache.jena.shared.impl.JenaParameters ; /** * The TypeMapper provides a global registry of known datatypes. * The datatypes can be retrieved by their URI or from the java class * that is used to represent them. */ // Added extended set of class mappings and getTypeByClass // as suggested by Thorsten Moeller. der 8/5/09 public class TypeMapper { //======================================================================= // Statics /** * Return the single global instance of the TypeMapper. * Done this way rather than simply making the static * field directly accessible to allow us to dynamically * replace the entire mapper table if needed. */ public static TypeMapper getInstance() { return theTypeMap; } public static void setInstance(TypeMapper typeMapper) { theTypeMap = typeMapper ; } /** * The single global instance of the TypeMapper */ private static TypeMapper theTypeMap; /** * Static initializer. Adds builtin datatypes to the mapper. */ static { reset() ; } public static void reset() { theTypeMap = new TypeMapper(); theTypeMap.registerDatatype(XMLLiteralType.theXMLLiteralType); theTypeMap.registerDatatype(RDFLangString.rdfLangString) ; XSDDatatype.loadXSDSimpleTypes(theTypeMap); // add primitive types theTypeMap.classToDT.put(float.class, theTypeMap.classToDT.get(Float.class)); theTypeMap.classToDT.put(double.class, theTypeMap.classToDT.get(Double.class)); theTypeMap.classToDT.put(int.class, theTypeMap.classToDT.get(Integer.class)); theTypeMap.classToDT.put(long.class, theTypeMap.classToDT.get(Long.class)); theTypeMap.classToDT.put(short.class, theTypeMap.classToDT.get(Short.class)); theTypeMap.classToDT.put(byte.class, theTypeMap.classToDT.get(Byte.class)); theTypeMap.classToDT.put(boolean.class, theTypeMap.classToDT.get(Boolean.class)); // add missing character types theTypeMap.classToDT.put(char.class, theTypeMap.classToDT.get(String.class)); theTypeMap.classToDT.put(Character.class, theTypeMap.classToDT.get(String.class)); // add mapping for URL class theTypeMap.classToDT.put(URL.class, theTypeMap.classToDT.get(URI.class)); } public TypeMapper() { super(); } //======================================================================= // Variables /** Map from uri to datatype */ private final ConcurrentHashMap<String, RDFDatatype> uriToDT = new ConcurrentHashMap<>(); /** Map from java class to datatype */ private final ConcurrentHashMap<Class<?>, RDFDatatype> classToDT = new ConcurrentHashMap<>(); //======================================================================= // Methods /** * Version of getTypeByName which will treat unknown URIs as typed literals but with * just the default implementation * <p> * RDF 1.1: null for {@code uri} returns null and it will mean {@code xsd:string} * because plain literals (no lang tag) and xsd:strings are now the same. * * @param uri * the URI of the desired datatype * @return Datatype the datatype definition registered at uri, if there is no such * registered type it returns a new instance of the default datatype * implementation, if the uri is null it returns null (indicating a plain RDF * literal). */ public RDFDatatype getSafeTypeByName(final String uri) { if (uri == null) { // Plain literal return null; } RDFDatatype dtype = uriToDT.get(uri); if (dtype == null) { // Unknown datatype if (JenaParameters.enableSilentAcceptanceOfUnknownDatatypes) { dtype = new BaseDatatype(uri); registerDatatype(dtype); } else { throw new DatatypeFormatException( "Attempted to created typed literal using an unknown datatype - " + uri); } } return dtype; } /** * Lookup a known datatype. An unknown datatype or a datatype with uri null * will return null will mean that the value will be treated as a old-style plain literal. * * @param uri the URI of the desired datatype * @return Datatype the datatype definition of null if not known. */ public RDFDatatype getTypeByName(final String uri) { return uri == null ? null : uriToDT.get(uri); } /** * Method getTypeByValue. Look up a datatype suitable for representing * the given java value object. * * @param value a value instance to be represented * @return Datatype a datatype whose value space matches the java class * of <code>value</code> */ public RDFDatatype getTypeByValue(final Object value) { return classToDT.get(value.getClass()); } /** * List all the known datatypes */ public Iterator<RDFDatatype> listTypes() { return uriToDT.values().iterator(); } /** * Look up a datatype suitable for representing instances of the * given Java class. * * @param clazz a Java class to be represented * @return a datatype whose value space matches the given java class */ public RDFDatatype getTypeByClass(final Class<?> clazz) { return clazz == null ? null : classToDT.get(clazz); } /** * Register a new datatype */ public void registerDatatype(final RDFDatatype type) { uriToDT.put(type.getURI(), type); final Class<?> jc = type.getJavaClass(); if (jc != null) { classToDT.put(jc, type); } } /** * Remove a datatype registration. */ public void unregisterDatatype(final RDFDatatype type) { uriToDT.remove(type.getURI()); final Class<?> jc = type.getJavaClass(); if (jc != null) { classToDT.remove(jc); } } }
apache/jena
jena-core/src/main/java/org/apache/jena/datatypes/TypeMapper.java
Java
apache-2.0
7,205
/* Derby - Class org.apache.derby.iapi.sql.compile.CostEstimate 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.derby.iapi.sql.compile; import org.apache.derby.iapi.store.access.StoreCostResult; /** * A CostEstimate represents the cost of getting a ResultSet, along with the * ordering of rows in the ResultSet, and the estimated number of rows in * this ResultSet. * */ public interface CostEstimate extends StoreCostResult { /** * Set the cost for this cost estimate. */ void setCost(double cost, double rowCount, double singleScanRowCount); /** * Copy the values from the given cost estimate into this one. */ void setCost(CostEstimate other); /** * Set the single scan row count. */ void setSingleScanRowCount(double singleRowScanCount); /** * Compare this cost estimate with the given cost estimate. * * @param other The cost estimate to compare this one with * * @return &lt; 0 if this &lt; other, 0 if this == other, &gt; 0 if this &gt; other */ double compare(CostEstimate other); /** * Add this cost estimate to another one. This presumes that any row * ordering is destroyed. * * @param addend This cost estimate to add this one to. * @param retval If non-null, put the result here. * * @return this + other. */ CostEstimate add(CostEstimate addend, CostEstimate retval); /** * Multiply this cost estimate by a scalar, non-dimensional number. This * presumes that any row ordering is destroyed. * * @param multiplicand The value to multiply this CostEstimate by. * @param retval If non-null, put the result here. * * @return this * multiplicand */ CostEstimate multiply(double multiplicand, CostEstimate retval); /** * Divide this cost estimate by a scalar, non-dimensional number. * * @param divisor The value to divide this CostEstimate by. * @param retval If non-null, put the result here. * * @return this / divisor */ CostEstimate divide(double divisor, CostEstimate retval); /** * Get the estimated number of rows returned by the ResultSet that this * CostEstimate models. */ double rowCount(); /** * Get the estimated number of rows returned by a single scan of * the ResultSet that this CostEstimate models. */ double singleScanRowCount(); /** Get a copy of this CostEstimate */ CostEstimate cloneMe(); /** * Return whether or not this CostEstimate is uninitialized. * * @return Whether or not this CostEstimate is uninitialized. */ public boolean isUninitialized(); }
apache/derby
java/org.apache.derby.engine/org/apache/derby/iapi/sql/compile/CostEstimate.java
Java
apache-2.0
3,295
/* * 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.jclouds.s3.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; import org.jclouds.s3.domain.Payer; @Singleton public class BindPayerToXmlPayload implements Binder { @Override public <R extends HttpRequest> R bindToRequest(R request, Object toBind) { checkArgument(checkNotNull(toBind, "toBind") instanceof Payer, "this binder is only valid for Payer!"); String text = String .format( "<RequestPaymentConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Payer>%s</Payer></RequestPaymentConfiguration>", ((Payer) toBind).value()); request.setPayload(text); request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML); return request; } }
yanzhijun/jclouds-aliyun
apis/s3/src/main/java/org/jclouds/s3/binders/BindPayerToXmlPayload.java
Java
apache-2.0
1,793
/* * Sun Public License Notice * * The contents of this file are subject to the Sun Public License * Version 1.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is available at * http://www.sun.com/ * * The Original Code is NetBeans. The Initial Developer of the Original * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.lib.cvsclient.command.log; import java.util.Date; /** * @author Thomas Singer */ public final class Revision { // Fields ================================================================= private String number; private Date date; private String author; private String state; private String lines; private String message; private String branches; // Setup ================================================================== public Revision(String number) { this.number = number; } // Accessing ============================================================== public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getLines() { return lines; } public void setLines(String lines) { this.lines = lines; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getBranches() { return branches; } public void setBranches(String branches) { this.branches = branches; } }
jexp/idea2
plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/command/log/Revision.java
Java
apache-2.0
1,891
/** * Copyright (c) 2011 RedEngine Ltd, http://www.RedEngine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.bootstrap.guice4; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.MembersInjector; import com.google.inject.Scope; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.binder.ScopedBindingBuilder; import com.google.inject.matcher.Matchers; import com.google.inject.spi.TypeListener; import de.devsurf.injection.guice.install.InstallationContext.BindingStage; import de.devsurf.injection.guice.install.bindjob.BindingJob; import de.devsurf.injection.guice.scanner.features.BindingScannerFeature; import net.stickycode.metadata.MetadataResolverRegistry; import net.stickycode.reflector.Methods; import net.stickycode.stereotype.StickyComponent; import net.stickycode.stereotype.StickyDomain; import net.stickycode.stereotype.StickyFramework; import net.stickycode.stereotype.component.StickyRepository; @Singleton public class StickyStereotypeScannerFeature extends BindingScannerFeature { private Logger log = LoggerFactory.getLogger(getClass()); @Inject MetadataResolverRegistry metadataResolver; @Override public BindingStage accept(Class<Object> annotatedClass, Map<String, Annotation> annotations) { if (isFrameworkComponent(annotatedClass)) return BindingStage.IGNORE; for (Class<? extends Annotation> componentAnnotation : getComponentAnnotations()) if (metadataResolver.is(annotatedClass).metaAnnotatedWith(componentAnnotation)) return deriveStage(annotatedClass); return BindingStage.IGNORE; } protected boolean isFrameworkComponent(Class<Object> annotatedClass) { return metadataResolver.is(annotatedClass).metaAnnotatedWith(StickyFramework.class); } protected Class<? extends Annotation>[] getComponentAnnotations() { return new Class[] { StickyComponent.class, StickyDomain.class }; } protected BindingStage deriveStage(Class<Object> annotatedClass) { BindingStage calculateStage = calculateStage(annotatedClass); log.debug("adding {} at {}", annotatedClass.getName(), calculateStage); return calculateStage; } private BindingStage calculateStage(Class<Object> annotatedClass) { for (Class<?> contract : annotatedClass.getInterfaces()) { if (contract.isAnnotationPresent(StickyRepository.class)) return BindingStage.BOOT_BEFORE; } return BindingStage.BOOT; } @Override @SuppressWarnings("unchecked") public void process(Class<Object> annotatedClass, Map<String, Annotation> annotations) { List<Class<?>> interfaces = collectInterfaces(annotatedClass); Scope scope = deriveScope(annotatedClass, interfaces); bind(annotatedClass, null, scope); for (Class<?> interf : interfaces) { if (interf.isAssignableFrom(TypeListener.class)) bindListener(annotatedClass); else if (!interf.isAssignableFrom(MembersInjector.class)) if (Provider.class.isAssignableFrom(interf)) bindProviderWorkaround((Class<Object>) annotatedClass, Scopes.NO_SCOPE); else bind(annotatedClass, (Class<Object>) interf, (Annotation) null, scope); } if (!Provider.class.isAssignableFrom(annotatedClass) && !MembersInjector.class.isAssignableFrom(annotatedClass)) for (Class<?> blah = annotatedClass; blah != null; blah = blah.getSuperclass()) for (Type type : blah.getGenericInterfaces()) { if (type instanceof ParameterizedType) { bindParameterizedType(annotatedClass, type); } } } protected void bindParameterizedType(Class<?> annotatedClass, Type type) { // if the type is parameterised and not multibound then there will only be one instance, // so there is no need to bind to the generic interface } private Scope deriveScope(Class<Object> annotatedClass, List<Class<?>> interfaces) { if (metadataResolver.is(annotatedClass).metaAnnotatedWith(StickyDomain.class)) return Scopes.NO_SCOPE; return Scopes.SINGLETON; } /** * This nasty code is to workaround the bug fixed by (NOTE its says closed but its not fixed yet) in javac. Without these casts * javac will fail while ecj will be fine. */ @SuppressWarnings("unchecked") private void bindProviderWorkaround(Class<Object> annotatedClass, Object object) { Class<Object> annotatedClass2 = annotatedClass; if (annotatedClass2 instanceof Class) bindProvider((Class<? extends Provider<Object>>) (Object) annotatedClass2, null); } private List<Class<?>> collectInterfaces(Class<Object> annotatedClass) { List<Class<?>> interfaces = new ArrayList<Class<?>>(); for (Class<?> base = annotatedClass; base != null; base = base.getSuperclass()) for (Class<?> class1 : base.getInterfaces()) { interfaces.add(class1); processInterface(class1, interfaces); } log.debug("found {} with {}", annotatedClass, interfaces); return interfaces; } private <Y, T extends Provider<Y>> void bindProvider(Class<T> providerClass, Scope scope) { BindingJob job = new ProviderClassBindingJob(scope, providerClass.getName()); if (!tracer.contains(job)) { synchronized (_binder) { Method m = Methods.find(providerClass, "get"); // ParameterizedType t = Types.providerOf(); TypeLiteral<T> tl = (TypeLiteral<T>) TypeLiteral.get(providerClass); @SuppressWarnings("unchecked") ScopedBindingBuilder scopedBuilder = _binder.bind((Class<Y>) m.getReturnType()) .toProvider(tl); if (scope != null) { scopedBuilder.in(scope); } } tracer.add(job); } else { log.info("ignoring {}", job); } } private void processInterface(Class<?> target, List<Class<?>> interfaces) { for (Class<?> class1 : target.getInterfaces()) { interfaces.add(class1); processInterface(class1, interfaces); } } private void bindListener(Class<Object> annotatedClass) { TypeListener typeListener = typeListener(annotatedClass); _binder.requestInjection(typeListener); _binder.bindListener(Matchers.any(), typeListener); } private TypeListener typeListener(Class<Object> annotatedClass) { try { return (TypeListener) annotatedClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
tectronics/stickycode
net.stickycode.bootstrap/sticky-bootstrap-guice4-1/src/main/java/net/stickycode/bootstrap/guice4/StickyStereotypeScannerFeature.java
Java
apache-2.0
7,497
package org.apache.fineract.ui.online.customers.customerdetails; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.apache.fineract.R; import org.apache.fineract.ui.base.FineractBaseActivity; import org.apache.fineract.utils.ConstantKeys; /** * @author Rajan Maurya * On 26/06/17. */ public class CustomerDetailsActivity extends FineractBaseActivity { public static final String LOG_TAG = CustomerDetailsActivity.class.getSimpleName(); private CustomerDetailsFragment customerDetailsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_global_container); String identifier = getIntent().getExtras().getString(ConstantKeys.CUSTOMER_IDENTIFIER); customerDetailsFragment = CustomerDetailsFragment.newInstance(identifier); replaceFragment(customerDetailsFragment, false, R.id.global_container); showBackButton(); } @Override public void onBackPressed() { try { Intent intent = new Intent(); intent.putExtra(ConstantKeys.CUSTOMER_STATUS, customerDetailsFragment.getCustomerStatus()); setResult(RESULT_OK, intent); finish(); } catch (NullPointerException e) { Log.d(LOG_TAG, e.getLocalizedMessage()); } super.onBackPressed(); } }
therajanmaurya/android-client-2.0
app/src/main/java/org/apache/fineract/ui/online/customers/customerdetails/CustomerDetailsActivity.java
Java
apache-2.0
1,484
/* * Copyright (C) 2012-2015 DataStax 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.datastax.driver.core; import org.testng.annotations.Test; import java.util.Calendar; import java.util.concurrent.TimeUnit; import static com.datastax.driver.core.Assertions.assertThat; import static com.datastax.driver.core.LocalDate.*; public class LocalDateTest { @Test(groups = "unit") public void should_build_from_days_since_epoch() { assertThat(fromDaysSinceEpoch(0)) .hasMillisSinceEpoch(0) .hasDaysSinceEpoch(0) .hasYearMonthDay(1970, 1, 1) .hasToString("1970-01-01"); assertThat(fromDaysSinceEpoch(10)) .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(10)) .hasDaysSinceEpoch(10) .hasYearMonthDay(1970, 1, 11) .hasToString("1970-01-11"); assertThat(fromDaysSinceEpoch(-10)) .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(-10)) .hasDaysSinceEpoch(-10) .hasYearMonthDay(1969, 12, 22) .hasToString("1969-12-22"); assertThat(fromDaysSinceEpoch(Integer.MAX_VALUE)) .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(Integer.MAX_VALUE)) .hasDaysSinceEpoch(Integer.MAX_VALUE) .hasYearMonthDay(5881580, 7, 11) .hasToString("5881580-07-11"); assertThat(fromDaysSinceEpoch(Integer.MIN_VALUE)) .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(Integer.MIN_VALUE)) .hasDaysSinceEpoch(Integer.MIN_VALUE) .hasYearMonthDay(-5877641, 6, 23) .hasToString("-5877641-06-23"); } @Test(groups = "unit") public void should_build_from_millis_since_epoch() { assertThat(fromMillisSinceEpoch(0)) .hasMillisSinceEpoch(0) .hasDaysSinceEpoch(0) .hasYearMonthDay(1970, 1, 1) .hasToString("1970-01-01"); // Rounding assertThat(fromMillisSinceEpoch(3600)) .hasMillisSinceEpoch(0) .hasDaysSinceEpoch(0) .hasYearMonthDay(1970, 1, 1) .hasToString("1970-01-01"); assertThat(fromMillisSinceEpoch(-3600)) .hasMillisSinceEpoch(0) .hasDaysSinceEpoch(0) .hasYearMonthDay(1970, 1, 1) .hasToString("1970-01-01"); // Bound checks try { fromMillisSinceEpoch(TimeUnit.DAYS.toMillis((long) Integer.MIN_VALUE - 1)); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } try { fromMillisSinceEpoch(TimeUnit.DAYS.toMillis((long) Integer.MAX_VALUE + 1)); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } } @Test(groups = "unit") public void should_build_from_year_month_day() { assertThat(fromYearMonthDay(1970, 1, 1)) .hasMillisSinceEpoch(0) .hasDaysSinceEpoch(0) .hasYearMonthDay(1970, 1, 1) .hasToString("1970-01-01"); // Handling of 0 / negative years assertThat(fromYearMonthDay(1, 1, 1)) .hasDaysSinceEpoch(-719162) .hasYearMonthDay(1, 1, 1) .hasToString("1-01-01"); assertThat(fromYearMonthDay(0, 1, 1)) .hasDaysSinceEpoch(-719162 - 366) .hasYearMonthDay(0, 1, 1) .hasToString("0-01-01"); assertThat(fromYearMonthDay(-1, 1, 1)) .hasDaysSinceEpoch(-719162 - 366 - 365) .hasYearMonthDay(-1, 1, 1) .hasToString("-1-01-01"); // Month/day out of bounds try { fromYearMonthDay(1970, 0, 1); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } try { fromYearMonthDay(1970, 13, 1); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } try { fromYearMonthDay(1970, 1, 0); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } try { fromYearMonthDay(1970, 1, 32); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } // Resulting date out of bounds try { fromYearMonthDay(6000000, 1, 1); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } try { fromYearMonthDay(-6000000, 1, 1); Assertions.fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { /*expected*/ } } @Test(groups = "unit") public void should_add_and_subtract_years() { assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, 1)) .hasYearMonthDay(1971, 1, 1); assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, -1)) .hasYearMonthDay(1969, 1, 1); assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, -1970)) .hasYearMonthDay(0, 1, 1); assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, -1971)) .hasYearMonthDay(-1, 1, 1); assertThat(fromYearMonthDay(0, 5, 12).add(Calendar.YEAR, 1)) .hasYearMonthDay(1, 5, 12); assertThat(fromYearMonthDay(-1, 5, 12).add(Calendar.YEAR, 1)) .hasYearMonthDay(0, 5, 12); assertThat(fromYearMonthDay(-1, 5, 12).add(Calendar.YEAR, 2)) .hasYearMonthDay(1, 5, 12); } @Test(groups = "unit") public void should_add_and_subtract_months() { assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.MONTH, 2)) .hasYearMonthDay(1970, 3, 1); assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.MONTH, 24)) .hasYearMonthDay(1972, 1, 1); assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.MONTH, -5)) .hasYearMonthDay(1969, 8, 1); assertThat(fromYearMonthDay(1, 1, 1).add(Calendar.MONTH, -1)) .hasYearMonthDay(0, 12, 1); assertThat(fromYearMonthDay(0, 1, 1).add(Calendar.MONTH, -1)) .hasYearMonthDay(-1, 12, 1); assertThat(fromYearMonthDay(-1, 12, 1).add(Calendar.MONTH, 1)) .hasYearMonthDay(0, 1, 1); assertThat(fromYearMonthDay(0, 12, 1).add(Calendar.MONTH, 1)) .hasYearMonthDay(1, 1, 1); } @Test(groups = "unit") public void should_add_and_subtract_days() { assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.DAY_OF_MONTH, 12)) .hasYearMonthDay(1970, 1, 13); assertThat(fromYearMonthDay(1970, 3, 28).add(Calendar.DAY_OF_MONTH, -40)) .hasYearMonthDay(1970, 2, 16); assertThat(fromYearMonthDay(1, 1, 1).add(Calendar.DAY_OF_MONTH, -2)) .hasYearMonthDay(0, 12, 30); assertThat(fromYearMonthDay(0, 1, 1).add(Calendar.DAY_OF_MONTH, -2)) .hasYearMonthDay(-1, 12, 30); assertThat(fromYearMonthDay(-1, 12, 31).add(Calendar.DAY_OF_MONTH, 4)) .hasYearMonthDay(0, 1, 4); assertThat(fromYearMonthDay(0, 12, 25).add(Calendar.DAY_OF_MONTH, 14)) .hasYearMonthDay(1, 1, 8); } }
mebigfatguy/java-driver
driver-core/src/test/java/com/datastax/driver/core/LocalDateTest.java
Java
apache-2.0
8,229
/* * 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.geode.internal.cache.partitioned; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Set; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializer; import org.apache.geode.cache.CacheException; import org.apache.geode.cache.InterestRegistrationEvent; import org.apache.geode.distributed.internal.ClusterDistributionManager; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.DistributionStats; import org.apache.geode.distributed.internal.HighPriorityDistributionMessage; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.ReplyException; import org.apache.geode.distributed.internal.ReplyProcessor21; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.cache.ForceReattemptException; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.PartitionedRegionDataStore; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LogMarker; /** * This message is used as the notification that a client interest registration or unregistration * event occurred. * * @since GemFire 5.8BetaSUISSE */ public class InterestEventMessage extends PartitionMessage { private static final Logger logger = LogService.getLogger(); /** The <code>InterestRegistrationEvent</code> */ private InterestRegistrationEvent event; /** * Empty constructor to satisfy {@link DataSerializer} requirements */ public InterestEventMessage() {} private InterestEventMessage(Set recipients, int regionId, int processorId, final InterestRegistrationEvent event, ReplyProcessor21 processor) { super(recipients, regionId, processor); this.event = event; } @Override public int getProcessorType() { return ClusterDistributionManager.STANDARD_EXECUTOR; } @Override protected boolean operateOnPartitionedRegion(final ClusterDistributionManager dm, PartitionedRegion r, long startTime) throws ForceReattemptException { if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "InterestEventMessage operateOnPartitionedRegion: {}", r.getFullPath()); } PartitionedRegionDataStore ds = r.getDataStore(); if (ds != null) { try { ds.handleInterestEvent(this.event); r.getPrStats().endPartitionMessagesProcessing(startTime); InterestEventReplyMessage.send(getSender(), getProcessorId(), dm); } catch (Exception e) { sendReply(getSender(), getProcessorId(), dm, new ReplyException(new ForceReattemptException( "Caught exception during interest registration processing:", e)), r, startTime); return false; } } else { throw new InternalError("InterestEvent message was sent to a member with no storage."); } // Unless there was an exception thrown, this message handles sending the // response return false; } @Override protected void appendFields(StringBuilder buff) { super.appendFields(buff); buff.append("; event=").append(this.event); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.event = (InterestRegistrationEvent) DataSerializer.readObject(in); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); DataSerializer.writeObject(this.event, out); } /** * Sends an InterestEventMessage message * * @param recipients the Set of members that the get message is being sent to * @param region the PartitionedRegion for which interest event was received * @param event the InterestRegistrationEvent to send * @return the InterestEventResponse * @throws ForceReattemptException if the peer is no longer available */ public static InterestEventResponse send(Set recipients, PartitionedRegion region, final InterestRegistrationEvent event) throws ForceReattemptException { InterestEventResponse response = new InterestEventResponse(region.getSystem(), recipients); InterestEventMessage m = new InterestEventMessage(recipients, region.getPRId(), response.getProcessorId(), event, response); m.setTransactionDistributed(region.getCache().getTxManager().isDistributed()); Set failures = region.getDistributionManager().putOutgoing(m); if (failures != null && failures.size() > 0) { throw new ForceReattemptException("Failed sending <" + m + "> to " + failures); } return response; } /** * This message is used for the reply to a {@link InterestEventMessage}. * * @since GemFire 5.8BetaSUISSE */ public static class InterestEventReplyMessage extends HighPriorityDistributionMessage { /** The shared obj id of the ReplyProcessor */ private int processorId; /** * Empty constructor to conform to DataSerializable interface */ public InterestEventReplyMessage() {} private InterestEventReplyMessage(int processorId) { this.processorId = processorId; } /** Send an ack */ public static void send(InternalDistributedMember recipient, int processorId, DistributionManager dm) throws ForceReattemptException { InterestEventReplyMessage m = new InterestEventReplyMessage(processorId); m.setRecipient(recipient); dm.putOutgoing(m); } /** * Processes this message. This method is invoked by the receiver of the message. * * @param dm the distribution manager that is processing the message. */ @Override protected void process(final ClusterDistributionManager dm) { final long startTime = getTimestamp(); if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "InterestEventReplyMessage process invoking reply processor with processorId: {}", this.processorId); } try { ReplyProcessor21 processor = ReplyProcessor21.getProcessor(this.processorId); if (processor == null) { if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "InterestEventReplyMessage processor not found"); } return; } processor.process(this); if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace("{} processed {}", processor, this); } } finally { dm.getStats().incReplyMessageTime(DistributionStats.getStatTime() - startTime); } } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeInt(processorId); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.processorId = in.readInt(); } @Override public String toString() { StringBuffer sb = new StringBuffer().append("InterestEventReplyMessage ").append("processorid=") .append(this.processorId).append(" reply to sender ").append(this.getSender()); return sb.toString(); } public int getDSFID() { return INTEREST_EVENT_REPLY_MESSAGE; } } /** * A processor to capture the value returned by * {@link org.apache.geode.internal.cache.partitioned.InterestEventMessage.InterestEventReplyMessage} * * @since GemFire 5.1 */ public static class InterestEventResponse extends PartitionResponse { public InterestEventResponse(InternalDistributedSystem ds, Set recipients) { super(ds, recipients); } /** * @throws ForceReattemptException if the peer is no longer available */ public void waitForResponse() throws ForceReattemptException { try { waitForCacheException(); } catch (ForceReattemptException e) { logger.debug("InterestEventResponse got ForceReattemptException; rethrowing {}", e.getMessage(), e); throw e; } catch (CacheException e) { final String msg = "InterestEventResponse got remote CacheException, throwing ForceReattemptException"; logger.debug(msg, e); throw new ForceReattemptException(msg, e); } } } public int getDSFID() { return INTEREST_EVENT_MESSAGE; } }
pdxrunner/geode
geode-core/src/main/java/org/apache/geode/internal/cache/partitioned/InterestEventMessage.java
Java
apache-2.0
9,308
package org.insightech.er.editor.model.dbexport.excel.sheet_generator; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFHyperlink; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Font; import org.insightech.er.ResourceString; import org.insightech.er.editor.model.ERDiagram; import org.insightech.er.editor.model.ObjectModel; import org.insightech.er.editor.model.dbexport.excel.ExportToExcelManager.LoopDefinition; import org.insightech.er.editor.model.progress_monitor.ProgressMonitor; import org.insightech.er.util.POIUtils; import org.insightech.er.util.POIUtils.CellLocation; public class SheetIndexSheetGenerator extends AbstractSheetGenerator { private static final String KEYWORD_SHEET_TYPE = "$SHTT"; private static final String KEYWORD_NAME = "$NAM"; private static final String KEYWORD_DESCRIPTION = "$DSC"; private static final String KEYWORD_SHEET_NAME = "$SHTN"; private static final String[] FIND_KEYWORDS_LIST = {KEYWORD_SHEET_TYPE, KEYWORD_NAME, KEYWORD_DESCRIPTION}; /** * {@inheritDoc} */ @Override public void generate(final ProgressMonitor monitor, final HSSFWorkbook workbook, final int sheetNo, final boolean useLogicalNameAsSheetName, final Map<String, Integer> sheetNameMap, final Map<String, ObjectModel> sheetObjectMap, final ERDiagram diagram, final Map<String, LoopDefinition> loopDefinitionMap) throws InterruptedException { final HSSFSheet sheet = workbook.getSheetAt(sheetNo); setSheetListData(workbook, sheet, sheetObjectMap, diagram); } public void setSheetListData(final HSSFWorkbook workbook, final HSSFSheet sheet, final Map<String, ObjectModel> sheetObjectMap, final ERDiagram diagram) { final CellLocation cellLocation = POIUtils.findCell(sheet, FIND_KEYWORDS_LIST); if (cellLocation != null) { int rowNum = cellLocation.r; final HSSFRow templateRow = sheet.getRow(rowNum); final ColumnTemplate columnTemplate = loadColumnTemplate(workbook, sheet, cellLocation); int order = 1; HSSFFont linkCellFont = null; int linkCol = -1; for (final Map.Entry<String, ObjectModel> entry : sheetObjectMap.entrySet()) { final String sheetName = entry.getKey(); final ObjectModel objectModel = entry.getValue(); final HSSFRow row = POIUtils.insertRow(sheet, rowNum++); for (final int columnNum : columnTemplate.columnTemplateMap.keySet()) { final HSSFCell cell = row.createCell(columnNum); final String template = columnTemplate.columnTemplateMap.get(columnNum); String value = null; if (KEYWORD_ORDER.equals(template)) { value = String.valueOf(order); } else { if (KEYWORD_SHEET_TYPE.equals(template)) { value = ResourceString.getResourceString("label.object.type." + objectModel.getObjectType()); } else if (KEYWORD_NAME.equals(template)) { value = sheetName; final HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT); link.setAddress("'" + sheetName + "'!A1"); cell.setHyperlink(link); if (linkCellFont == null) { linkCol = columnNum; linkCellFont = POIUtils.copyFont(workbook, cell.getCellStyle().getFont(workbook)); linkCellFont.setColor(HSSFColor.BLUE.index); linkCellFont.setUnderline(Font.U_SINGLE); } } else if (KEYWORD_DESCRIPTION.equals(template)) { value = objectModel.getDescription(); } final HSSFRichTextString text = new HSSFRichTextString(value); cell.setCellValue(text); } order++; } } setCellStyle(columnTemplate, sheet, cellLocation.r, rowNum - cellLocation.r, templateRow.getFirstCellNum()); if (linkCol != -1) { for (int row = cellLocation.r; row < rowNum; row++) { final HSSFCell cell = sheet.getRow(row).getCell(linkCol); cell.getCellStyle().setFont(linkCellFont); } } } } public String getSheetName() { String name = keywordsValueMap.get(KEYWORD_SHEET_NAME); if (name == null) { name = "List of sheets"; } return name; } /** * {@inheritDoc} */ @Override public String getTemplateSheetName() { return "sheet_index_template"; } @Override public String[] getKeywords() { return new String[] {KEYWORD_SHEET_TYPE, KEYWORD_NAME, KEYWORD_DESCRIPTION, KEYWORD_ORDER, KEYWORD_SHEET_NAME}; } @Override public int getKeywordsColumnNo() { return 24; } @Override public int count(final ERDiagram diagram) { return 1; } }
roundrop/ermasterr
src/org/insightech/er/editor/model/dbexport/excel/sheet_generator/SheetIndexSheetGenerator.java
Java
apache-2.0
5,778
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT 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-2019 the original author or authors. */ package org.assertj.core.description; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.description.Description.mostRelevantDescription; import org.junit.jupiter.api.Test; public class Description_mostRelevantDescription_Test { @Test public void should_return_exsiting_description_if_not_empty() { // GIVEN String existing = "bar"; Description description = new TextDescription(existing); // WHEN String mostRelevantDescription = mostRelevantDescription(description, "foo"); // THEN assertThat(mostRelevantDescription).isEqualTo(existing); } @Test public void should_return_the_other_value_if_description_value_is_empty() { // GIVEN Description description = new TextDescription(""); String other = "foo"; // WHEN String mostRelevantDescription = mostRelevantDescription(description, other); // THEN assertThat(mostRelevantDescription).isEqualTo(other); } @Test public void should_return_the_other_value_if_description_value_is_null() { // GIVEN Description description = new TextDescription(null); String other = "foo"; // WHEN String mostRelevantDescription = mostRelevantDescription(description, other); // THEN assertThat(mostRelevantDescription).isEqualTo(other); } @Test public void should_return_the_other_value_if_null() { // GIVEN Description description = null; String other = "foo"; // WHEN String mostRelevantDescription = mostRelevantDescription(description, other); // THEN assertThat(mostRelevantDescription).isEqualTo(other); } }
xasx/assertj-core
src/test/java/org/assertj/core/description/Description_mostRelevantDescription_Test.java
Java
apache-2.0
2,243
/* * Copyright 2012 JBoss 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 org.artificer.demos.simpleclient; import org.artificer.client.ArtificerAtomApiClient; import org.artificer.common.query.ArtifactSummary; import org.artificer.client.query.QueryResultSet; import org.artificer.common.ArtifactType; import org.artificer.common.ArtificerModelUtils; import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType; import java.io.InputStream; /** * A simple S-RAMP client demo. This class strives to demonstrate how to use the S-RAMP client. * * @author [email protected] */ public class SimpleClientDemo { private static final String DEFAULT_ENDPOINT = "http://localhost:8080/artificer-server"; private static final String DEFAULT_USER = "admin"; private static final String DEFAULT_PASSWORD = "artificer1!"; private static final String[] FILES = { "ws-humantask.xsd", "ws-humantask-context.xsd", "ws-humantask-policy.xsd", "ws-humantask-types.xsd", "ws-humantask-leantask-api.wsdl", "ws-humantask-protocol.wsdl" }; /** * Main. * * @param args */ public static void main(String[] args) throws Exception { System.out.println("\n*** Running Artificer Simple Client Demo ***\n"); String endpoint = System.getProperty("artificer.endpoint"); String username = System.getProperty("artificer.auth.username"); String password = System.getProperty("artificer.auth.password"); if (endpoint == null || endpoint.trim().length() == 0) { endpoint = DEFAULT_ENDPOINT; } if (username == null || username.trim().length() == 0) { username = DEFAULT_USER; } if (password == null || password.trim().length() == 0) { password = DEFAULT_PASSWORD; } System.out.println("Artificer Endpoint: " + endpoint); System.out.println("Artificer User: " + username); ArtificerAtomApiClient client = new ArtificerAtomApiClient(endpoint, username, password, true); // Have we already run this demo? QueryResultSet rs = client.buildQuery("/s-ramp[@from-demo = ?]") .parameter(SimpleClientDemo.class.getSimpleName()).count(1).query(); if (rs.size() > 0) { System.out.println("It looks like you already ran this demo!"); System.out.println("I'm going to quit, because I don't want to clutter up"); System.out.println("your repository with duplicate stuff."); System.exit(1); } // Upload some artifacts to the Artificer repository System.out.println("Uploading some XML schemas..."); for (String file : FILES) { // Get an InputStream over the file content InputStream is = SimpleClientDemo.class.getResourceAsStream(file); try { // We need to know the artifact type ArtifactType type = ArtifactType.XsdDocument(); if (file.endsWith(".wsdl")) { type = ArtifactType.WsdlDocument(); } // Upload that content to Artificer System.out.print("\tUploading artifact " + file + "..."); BaseArtifactType artifact = client.uploadArtifact(type, is, file); System.out.println("done."); // Update the artifact meta-data (set the version and add a custom property) artifact.setVersion("1.1"); ArtificerModelUtils.setCustomProperty(artifact, "from-demo", SimpleClientDemo.class.getSimpleName()); // Tell the server about the updated meta-data System.out.print("\tUpdating meta-data for artifact " + file + "..."); client.updateArtifactMetaData(artifact); System.out.println("done."); } finally { is.close(); } } // Now query the Artificer repository (for the Schemas only) System.out.print("Querying the Artificer repository for Schemas..."); QueryResultSet rset = client.query("/s-ramp/xsd/XsdDocument"); System.out.println("success: " + rset.size() + " Schemas found:"); for (ArtifactSummary entry : rset) { System.out.println("\t * " + entry.getName() + " (" + entry.getUuid() + ")"); } System.out.println("\n*** Demo Completed Successfully ***\n\n"); Thread.sleep(3000); } }
brmeyer/s-ramp
demos/simple-client/src/main/java/org/artificer/demos/simpleclient/SimpleClientDemo.java
Java
apache-2.0
4,667
package ch.fhnw.ima.bimgur.activiti.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import javaslang.Tuple2; import javaslang.collection.HashMap; import javaslang.collection.List; import javaslang.collection.Map; public final class TaskFormData { private final String taskId; private final List<Map<String, String>> properties; @JsonCreator public TaskFormData(@JsonProperty("taskId") TaskId taskId, @JsonProperty("properties") List<Tuple2<FormPropertyId, String>> properties) { this.taskId = taskId.getRaw(); this.properties = properties.map(t -> HashMap.of("id", t._1.getRaw(), "value", t._2)); } public String getTaskId() { return taskId; } public List<Map<String, String>> getProperties() { return properties; } }
bimgur/bimgur
bimgur-activiti-rest-client/src/main/java/ch/fhnw/ima/bimgur/activiti/model/TaskFormData.java
Java
apache-2.0
859
/** * Copyright 2009-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 net.javacrumbs.jsonunit.core; import net.javacrumbs.jsonunit.core.internal.Options; import java.math.BigDecimal; /** * Comparison configuration. Immutable. */ public class Configuration { private static final Configuration EMPTY_CONFIGURATION = new Configuration(null, Options.empty(), "${json-unit.ignore}"); private final BigDecimal tolerance; private final Options options; private final String ignorePlaceholder; public Configuration(BigDecimal tolerance, Options options, String ignorePlaceholder) { this.tolerance = tolerance; this.options = options; this.ignorePlaceholder = ignorePlaceholder; } /** * Returns an empty configuration. * * @return */ public static Configuration empty() { return EMPTY_CONFIGURATION; } /** * Sets numerical comparison tolerance. * * @param tolerance * @return */ public Configuration withTolerance(BigDecimal tolerance) { return new Configuration(tolerance, options, ignorePlaceholder); } /** * Sets numerical comparison tolerance. * * @param tolerance * @return */ public Configuration withTolerance(double tolerance) { return withTolerance(BigDecimal.valueOf(tolerance)); } /** * Adds comparison options. * * @param first * @param next * @return */ public Configuration when(Option first, Option... next) { return withOptions(first, next); } /** * Adds comparison options. * * @param first * @param next * @return */ public Configuration withOptions(Option first, Option... next) { return new Configuration(tolerance, options.with(first, next), ignorePlaceholder); } /** * Sets comparison options. * * @param options * @return */ public Configuration withOptions(Options options) { return new Configuration(tolerance, options, ignorePlaceholder); } /** * Sets ignore placeholder. * * @param ignorePlaceholder * @return */ public Configuration withIgnorePlaceholder(String ignorePlaceholder) { return new Configuration(tolerance, options, ignorePlaceholder); } public BigDecimal getTolerance() { return tolerance; } public Options getOptions() { return options; } public String getIgnorePlaceholder() { return ignorePlaceholder; } }
liry/JsonUnit
json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java
Java
apache-2.0
3,134
package info.iconmaster.typhon.model; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.junit.Assert; import org.junit.runners.Parameterized; import info.iconmaster.typhon.TyphonInput; import info.iconmaster.typhon.TyphonTest; import info.iconmaster.typhon.antlr.TyphonLexer; import info.iconmaster.typhon.antlr.TyphonParser; import info.iconmaster.typhon.antlr.TyphonParser.AnnotationContext; import info.iconmaster.typhon.model.Annotation; import info.iconmaster.typhon.model.TyphonModelReader; /** * Tests <tt>{@link TyphonModelReader}.readAnnotations()</tt>. * * @author iconmaster * */ public class TestAnnotationReader extends TyphonTest { @Parameterized.Parameters public static Collection<Object[]> data() { // The 'x's are to avoid the bug with ANTLR 4.5. return TyphonTest.makeData(new CaseValid("@a", (a)->{ Assert.assertEquals("a", a.getRawDefinition().getText()); }),new CaseValid("@a() x", (a)->{ Assert.assertEquals("a", a.getRawDefinition().getText()); }),new CaseValid("@a(b,c) x", (a)->{ Assert.assertEquals("a", a.getRawDefinition().getText()); Assert.assertEquals(2, a.getArgs().size()); }),new CaseValid("@a(@x b,@y c) x", (a)->{ Assert.assertEquals("a", a.getRawDefinition().getText()); Assert.assertEquals(2, a.getArgs().size()); })); } private static class CaseValid implements Runnable { String input; Consumer<Annotation> test; public CaseValid(String input, Consumer<Annotation> test) { this.input = input; this.test = test; } @Override public void run() { TyphonInput tni = new TyphonInput(); TyphonLexer lexer = new TyphonLexer(new ANTLRInputStream(input)); TyphonParser parser = new TyphonParser(new CommonTokenStream(lexer)); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { Assert.fail("parse of '"+input+"' failed: "+msg); } }); AnnotationContext root = parser.annotation(); List<Annotation> annots = TyphonModelReader.readAnnots(tni, Arrays.asList(root)); Assert.assertEquals(1, annots.size()); test.accept(annots.get(0)); } } }
TyphonLang/Typhon
src/test/java/info/iconmaster/typhon/model/TestAnnotationReader.java
Java
apache-2.0
2,703
/* * 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.flink.cep.nfa; import org.apache.flink.cep.Event; import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy; import org.apache.flink.cep.nfa.aftermatch.SkipPastLastStrategy; import org.apache.flink.cep.nfa.sharedbuffer.SharedBuffer; import org.apache.flink.cep.nfa.sharedbuffer.SharedBufferAccessor; import org.apache.flink.cep.pattern.Pattern; import org.apache.flink.cep.pattern.conditions.IterativeCondition; import org.apache.flink.cep.pattern.conditions.SimpleCondition; import org.apache.flink.cep.utils.TestSharedBuffer; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.util.TestLogger; import org.apache.flink.shaded.guava18.com.google.common.collect.Lists; import org.hamcrest.Matchers; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.apache.flink.cep.nfa.NFATestUtilities.compareMaps; import static org.apache.flink.cep.nfa.NFATestUtilities.feedNFA; import static org.apache.flink.cep.utils.NFAUtils.compile; import static org.junit.Assert.assertThat; /** * IT tests covering {@link AfterMatchSkipStrategy}. */ public class AfterMatchSkipITCase extends TestLogger{ @Test public void testNoSkip() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a", 0.0); Event a2 = new Event(2, "a", 0.0); Event a3 = new Event(3, "a", 0.0); Event a4 = new Event(4, "a", 0.0); Event a5 = new Event(5, "a", 0.0); Event a6 = new Event(6, "a", 0.0); streamEvents.add(new StreamRecord<Event>(a1)); streamEvents.add(new StreamRecord<Event>(a2)); streamEvents.add(new StreamRecord<Event>(a3)); streamEvents.add(new StreamRecord<Event>(a4)); streamEvents.add(new StreamRecord<Event>(a5)); streamEvents.add(new StreamRecord<Event>(a6)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start", AfterMatchSkipStrategy.noSkip()) .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().equals("a"); } }).times(3); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, a2, a3), Lists.newArrayList(a2, a3, a4), Lists.newArrayList(a3, a4, a5), Lists.newArrayList(a4, a5, a6) )); } @Test public void testNoSkipWithFollowedByAny() throws Exception { List<List<Event>> resultingPatterns = TwoVariablesFollowedByAny.compute(AfterMatchSkipStrategy.noSkip()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(TwoVariablesFollowedByAny.a1, TwoVariablesFollowedByAny.b1), Lists.newArrayList(TwoVariablesFollowedByAny.a1, TwoVariablesFollowedByAny.b2), Lists.newArrayList(TwoVariablesFollowedByAny.a2, TwoVariablesFollowedByAny.b2) )); } @Test public void testSkipToNextWithFollowedByAny() throws Exception { List<List<Event>> resultingPatterns = TwoVariablesFollowedByAny.compute(AfterMatchSkipStrategy.skipToNext()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(TwoVariablesFollowedByAny.a1, TwoVariablesFollowedByAny.b1), Lists.newArrayList(TwoVariablesFollowedByAny.a2, TwoVariablesFollowedByAny.b2) )); } static class TwoVariablesFollowedByAny { static Event a1 = new Event(1, "a", 0.0); static Event b1 = new Event(2, "b", 0.0); static Event a2 = new Event(4, "a", 0.0); static Event b2 = new Event(5, "b", 0.0); private static List<List<Event>> compute(AfterMatchSkipStrategy skipStrategy) throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(b1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(b2)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().equals("a"); } }).followedByAny("end") .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().equals("b"); } }); NFA<Event> nfa = compile(pattern, false); return feedNFA(streamEvents, nfa, skipStrategy); } } @Test public void testNoSkipWithQuantifierAtTheEnd() throws Exception { List<List<Event>> resultingPatterns = QuantifierAtEndOfPattern.compute(AfterMatchSkipStrategy.noSkip()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(QuantifierAtEndOfPattern.a1, QuantifierAtEndOfPattern.b1, QuantifierAtEndOfPattern.b2, QuantifierAtEndOfPattern.b3), Lists.newArrayList(QuantifierAtEndOfPattern.a1, QuantifierAtEndOfPattern.b1, QuantifierAtEndOfPattern.b2), Lists.newArrayList(QuantifierAtEndOfPattern.a1, QuantifierAtEndOfPattern.b1) )); } @Test public void testSkipToNextWithQuantifierAtTheEnd() throws Exception { List<List<Event>> resultingPatterns = QuantifierAtEndOfPattern.compute(AfterMatchSkipStrategy.skipToNext()); compareMaps(resultingPatterns, Lists.<List<Event>>newArrayList( Lists.newArrayList(QuantifierAtEndOfPattern.a1, QuantifierAtEndOfPattern.b1) )); } static class QuantifierAtEndOfPattern { static Event a1 = new Event(1, "a", 0.0); static Event b1 = new Event(2, "b", 0.0); static Event b2 = new Event(4, "b", 0.0); static Event b3 = new Event(5, "b", 0.0); private static List<List<Event>> compute(AfterMatchSkipStrategy skipStrategy) throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(b1)); streamEvents.add(new StreamRecord<>(b2)); streamEvents.add(new StreamRecord<>(b3)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().equals("a"); } }).next("end") .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().equals("b"); } }).oneOrMore(); NFA<Event> nfa = compile(pattern, false); return feedNFA(streamEvents, nfa, skipStrategy); } } @Test public void testSkipPastLast() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a", 0.0); Event a2 = new Event(2, "a", 0.0); Event a3 = new Event(3, "a", 0.0); Event a4 = new Event(4, "a", 0.0); Event a5 = new Event(5, "a", 0.0); Event a6 = new Event(6, "a", 0.0); streamEvents.add(new StreamRecord<Event>(a1)); streamEvents.add(new StreamRecord<Event>(a2)); streamEvents.add(new StreamRecord<Event>(a3)); streamEvents.add(new StreamRecord<Event>(a4)); streamEvents.add(new StreamRecord<Event>(a5)); streamEvents.add(new StreamRecord<Event>(a6)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start", AfterMatchSkipStrategy.skipPastLastEvent()) .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().equals("a"); } }).times(3); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, a2, a3), Lists.newArrayList(a4, a5, a6) )); } @Test public void testSkipToFirst() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event ab1 = new Event(1, "ab", 0.0); Event ab2 = new Event(2, "ab", 0.0); Event ab3 = new Event(3, "ab", 0.0); Event ab4 = new Event(4, "ab", 0.0); Event ab5 = new Event(5, "ab", 0.0); Event ab6 = new Event(6, "ab", 0.0); streamEvents.add(new StreamRecord<Event>(ab1)); streamEvents.add(new StreamRecord<Event>(ab2)); streamEvents.add(new StreamRecord<Event>(ab3)); streamEvents.add(new StreamRecord<Event>(ab4)); streamEvents.add(new StreamRecord<Event>(ab5)); streamEvents.add(new StreamRecord<Event>(ab6)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start", AfterMatchSkipStrategy.skipToFirst("end")) .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } }).times(2).next("end").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }).times(2); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(ab1, ab2, ab3, ab4), Lists.newArrayList(ab3, ab4, ab5, ab6) )); } @Test public void testSkipToLast() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event ab1 = new Event(1, "ab", 0.0); Event ab2 = new Event(2, "ab", 0.0); Event ab3 = new Event(3, "ab", 0.0); Event ab4 = new Event(4, "ab", 0.0); Event ab5 = new Event(5, "ab", 0.0); Event ab6 = new Event(6, "ab", 0.0); Event ab7 = new Event(7, "ab", 0.0); streamEvents.add(new StreamRecord<Event>(ab1)); streamEvents.add(new StreamRecord<Event>(ab2)); streamEvents.add(new StreamRecord<Event>(ab3)); streamEvents.add(new StreamRecord<Event>(ab4)); streamEvents.add(new StreamRecord<Event>(ab5)); streamEvents.add(new StreamRecord<Event>(ab6)); streamEvents.add(new StreamRecord<Event>(ab7)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start", AfterMatchSkipStrategy.skipToLast("end")).where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } }).times(2).next("end").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }).times(2); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(ab1, ab2, ab3, ab4), Lists.newArrayList(ab4, ab5, ab6, ab7) )); } @Test public void testSkipPastLast2() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event a2 = new Event(2, "a2", 0.0); Event b1 = new Event(3, "b1", 0.0); Event b2 = new Event(4, "b2", 0.0); Event c1 = new Event(5, "c1", 0.0); Event c2 = new Event(6, "c2", 0.0); Event d1 = new Event(7, "d1", 0.0); Event d2 = new Event(7, "d2", 0.0); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(b1)); streamEvents.add(new StreamRecord<>(b2)); streamEvents.add(new StreamRecord<>(c1)); streamEvents.add(new StreamRecord<>(c2)); streamEvents.add(new StreamRecord<>(d1)); streamEvents.add(new StreamRecord<>(d2)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipPastLastEvent()).where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } }).followedByAny("b").where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } } ).followedByAny("c").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("c"); } }).followedBy("d").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("d"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Collections.singletonList( Lists.newArrayList(a1, b1, c1, d1) )); } @Test public void testSkipPastLast3() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event c = new Event(2, "c", 0.0); Event a2 = new Event(3, "a2", 0.0); Event b2 = new Event(4, "b2", 0.0); streamEvents.add(new StreamRecord<Event>(a1)); streamEvents.add(new StreamRecord<Event>(c)); streamEvents.add(new StreamRecord<Event>(a2)); streamEvents.add(new StreamRecord<Event>(b2)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipPastLastEvent() ).where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } }).next("b").where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } } ); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.<List<Event>>newArrayList( Lists.newArrayList(a2, b2) )); } @Test public void testSkipToFirstWithOptionalMatch() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event ab1 = new Event(1, "ab1", 0.0); Event c1 = new Event(2, "c1", 0.0); Event ab2 = new Event(3, "ab2", 0.0); Event c2 = new Event(4, "c2", 0.0); streamEvents.add(new StreamRecord<Event>(ab1)); streamEvents.add(new StreamRecord<Event>(c1)); streamEvents.add(new StreamRecord<Event>(ab2)); streamEvents.add(new StreamRecord<Event>(c2)); Pattern<Event, ?> pattern = Pattern.<Event>begin("x", AfterMatchSkipStrategy.skipToFirst("b") ).where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("x"); } }).oneOrMore().optional().next("b").where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } } ).next("c").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("c"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(ab1, c1), Lists.newArrayList(ab2, c2) )); } @Test public void testSkipToFirstAtStartPosition() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event ab1 = new Event(1, "ab1", 0.0); Event c1 = new Event(2, "c1", 0.0); Event ab2 = new Event(3, "ab2", 0.0); Event c2 = new Event(4, "c2", 0.0); streamEvents.add(new StreamRecord<Event>(ab1)); streamEvents.add(new StreamRecord<Event>(c1)); streamEvents.add(new StreamRecord<Event>(ab2)); streamEvents.add(new StreamRecord<Event>(c2)); Pattern<Event, ?> pattern = Pattern.<Event>begin("b", AfterMatchSkipStrategy.skipToFirst("b") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } } ).next("c").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("c"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(ab1, c1), Lists.newArrayList(ab2, c2) )); } @Test public void testSkipToFirstWithOneOrMore() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event b1 = new Event(2, "b1", 0.0); Event a2 = new Event(3, "a2", 0.0); Event b2 = new Event(4, "b2", 0.0); Event b3 = new Event(5, "b3", 0.0); Event a3 = new Event(3, "a3", 0.0); Event b4 = new Event(4, "b4", 0.0); streamEvents.add(new StreamRecord<Event>(a1)); streamEvents.add(new StreamRecord<Event>(b1)); streamEvents.add(new StreamRecord<Event>(a2)); streamEvents.add(new StreamRecord<Event>(b2)); streamEvents.add(new StreamRecord<Event>(b3)); streamEvents.add(new StreamRecord<Event>(a3)); streamEvents.add(new StreamRecord<Event>(b4)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipToFirst("b") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }).oneOrMore().consecutive(); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, b1), Lists.newArrayList(a2, b2), Lists.newArrayList(a3, b4) )); } @Test(expected = FlinkRuntimeException.class) public void testSkipToFirstElementOfMatch() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); streamEvents.add(new StreamRecord<Event>(a1)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipToFirst("a").throwExceptionOnMiss() ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ); NFA<Event> nfa = compile(pattern, false); feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); //skip to first element of a match should throw exception if they are enabled, //this mode is used in MATCH RECOGNIZE which assumes that skipping to first element //would result in infinite loop. In CEP by default(with exceptions disabled), we use no skip //strategy in this case. } @Test(expected = FlinkRuntimeException.class) public void testSkipToFirstNonExistentPosition() throws Exception { MissedSkipTo.compute(AfterMatchSkipStrategy.skipToFirst("b").throwExceptionOnMiss()); //exception should be thrown } @Test public void testSkipToFirstNonExistentPositionWithoutException() throws Exception { List<List<Event>> resultingPatterns = MissedSkipTo.compute(AfterMatchSkipStrategy.skipToFirst("b")); compareMaps(resultingPatterns, Collections.singletonList( Lists.newArrayList(MissedSkipTo.a, MissedSkipTo.c) )); } @Test(expected = FlinkRuntimeException.class) public void testSkipToLastNonExistentPosition() throws Exception { MissedSkipTo.compute(AfterMatchSkipStrategy.skipToLast("b").throwExceptionOnMiss()); //exception should be thrown } @Test public void testSkipToLastNonExistentPositionWithoutException() throws Exception { List<List<Event>> resultingPatterns = MissedSkipTo.compute(AfterMatchSkipStrategy.skipToFirst("b")); compareMaps(resultingPatterns, Collections.singletonList( Lists.newArrayList(MissedSkipTo.a, MissedSkipTo.c) )); } static class MissedSkipTo { static Event a = new Event(1, "a", 0.0); static Event c = new Event(4, "c", 0.0); static List<List<Event>> compute(AfterMatchSkipStrategy skipStrategy) throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); streamEvents.add(new StreamRecord<>(a)); streamEvents.add(new StreamRecord<>(c)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a").where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }).oneOrMore().optional().consecutive() .next("c").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("c"); } }); NFA<Event> nfa = compile(pattern, false); return feedNFA(streamEvents, nfa, skipStrategy); } } @Test public void testSkipToLastWithOneOrMore() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event b1 = new Event(2, "b1", 0.0); Event a2 = new Event(3, "a2", 0.0); Event b2 = new Event(4, "b2", 0.0); Event b3 = new Event(5, "b3", 0.0); Event a3 = new Event(3, "a3", 0.0); Event b4 = new Event(4, "b4", 0.0); streamEvents.add(new StreamRecord<Event>(a1)); streamEvents.add(new StreamRecord<Event>(b1)); streamEvents.add(new StreamRecord<Event>(a2)); streamEvents.add(new StreamRecord<Event>(b2)); streamEvents.add(new StreamRecord<Event>(b3)); streamEvents.add(new StreamRecord<Event>(a3)); streamEvents.add(new StreamRecord<Event>(b4)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipToLast("b") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }).oneOrMore().consecutive(); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, b1), Lists.newArrayList(a2, b2), Lists.newArrayList(a3, b4) )); } /** Example from docs. */ @Test public void testSkipPastLastWithOneOrMoreAtBeginning() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event a2 = new Event(2, "a2", 0.0); Event a3 = new Event(3, "a3", 0.0); Event b1 = new Event(4, "b1", 0.0); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(a3)); streamEvents.add(new StreamRecord<>(b1)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipPastLastEvent() ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).oneOrMore().consecutive().greedy() .next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Collections.singletonList( Lists.newArrayList(a1, a2, a3, b1) )); } /** Example from docs. */ @Test public void testSkipToLastWithOneOrMoreAtBeginning() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event a2 = new Event(2, "a2", 0.0); Event a3 = new Event(3, "a3", 0.0); Event b1 = new Event(4, "b1", 0.0); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(a3)); streamEvents.add(new StreamRecord<>(b1)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipToLast("a") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).oneOrMore().consecutive().greedy() .next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, a2, a3, b1), Lists.newArrayList(a3, b1) )); } /** Example from docs. */ @Test public void testSkipToFirstWithOneOrMoreAtBeginning() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event a2 = new Event(2, "a2", 0.0); Event a3 = new Event(3, "a3", 0.0); Event b1 = new Event(4, "b1", 0.0); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(a3)); streamEvents.add(new StreamRecord<>(b1)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipToFirst("a") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).oneOrMore().consecutive().greedy() .next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, a2, a3, b1), Lists.newArrayList(a2, a3, b1), Lists.newArrayList(a3, b1) )); } /** Example from docs. */ @Test public void testNoSkipWithOneOrMoreAtBeginning() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event a2 = new Event(2, "a2", 0.0); Event a3 = new Event(3, "a3", 0.0); Event b1 = new Event(4, "b1", 0.0); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(a3)); streamEvents.add(new StreamRecord<>(b1)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.noSkip() ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).oneOrMore().consecutive().greedy() .next("b").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, a2, a3, b1), Lists.newArrayList(a2, a3, b1), Lists.newArrayList(a3, b1) )); } /** Example from docs. */ @Test public void testSkipToFirstDiscarding() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a = new Event(1, "a", 0.0); Event b = new Event(2, "b", 0.0); Event c1 = new Event(3, "c1", 0.0); Event c2 = new Event(4, "c2", 0.0); Event c3 = new Event(5, "c3", 0.0); Event d = new Event(6, "d", 0.0); streamEvents.add(new StreamRecord<>(a)); streamEvents.add(new StreamRecord<>(b)); streamEvents.add(new StreamRecord<>(c1)); streamEvents.add(new StreamRecord<>(c2)); streamEvents.add(new StreamRecord<>(c3)); streamEvents.add(new StreamRecord<>(d)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a or c", AfterMatchSkipStrategy.skipToFirst("c*") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a") || value.getName().contains("c"); } } ).followedBy("b or c").where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("b") || value.getName().contains("c"); } } ).followedBy("c*").where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("c"); } } ).oneOrMore().greedy() .followedBy("d").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("d"); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a, b, c1, c2, c3, d), Lists.newArrayList(c1, c2, c3, d) )); } @Test public void testSkipBeforeOtherAlreadyCompleted() throws Exception { List<StreamRecord<Event>> streamEvents = new ArrayList<>(); Event a1 = new Event(1, "a1", 0.0); Event c1 = new Event(2, "c1", 0.0); Event a2 = new Event(3, "a2", 1.0); Event c2 = new Event(4, "c2", 0.0); Event b1 = new Event(5, "b1", 1.0); Event b2 = new Event(6, "b2", 0.0); streamEvents.add(new StreamRecord<>(a1)); streamEvents.add(new StreamRecord<>(c1)); streamEvents.add(new StreamRecord<>(a2)); streamEvents.add(new StreamRecord<>(c2)); streamEvents.add(new StreamRecord<>(b1)); streamEvents.add(new StreamRecord<>(b2)); Pattern<Event, ?> pattern = Pattern.<Event>begin("a", AfterMatchSkipStrategy.skipToFirst("c") ).where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("a"); } } ).followedBy("c").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getName().contains("c"); } }).followedBy("b").where(new IterativeCondition<Event>() { @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().contains("b") && ctx.getEventsForPattern("a").iterator().next().getPrice() == value.getPrice(); } }); NFA<Event> nfa = compile(pattern, false); List<List<Event>> resultingPatterns = feedNFA(streamEvents, nfa, pattern.getAfterMatchSkipStrategy()); compareMaps(resultingPatterns, Lists.newArrayList( Lists.newArrayList(a1, c1, b2), Lists.newArrayList(a2, c2, b1) )); } @Test public void testSharedBufferIsProperlyCleared() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); for (int i = 0; i < 4; i++) { inputEvents.add(new StreamRecord<>(new Event(1, "a", 1.0), i)); } SkipPastLastStrategy matchSkipStrategy = AfterMatchSkipStrategy.skipPastLastEvent(); Pattern<Event, ?> pattern = Pattern.<Event>begin("start", matchSkipStrategy) .where(new SimpleCondition<Event>() { private static final long serialVersionUID = 5726188262756267490L; @Override public boolean filter(Event value) throws Exception { return true; } }).times(2); NFA<Event> nfa = compile(pattern, false); SharedBuffer<Event> sharedBuffer = TestSharedBuffer.createTestBuffer(Event.createTypeSerializer()); NFAState nfaState = nfa.createInitialNFAState(); for (StreamRecord<Event> inputEvent : inputEvents) { try (SharedBufferAccessor<Event> sharedBufferAccessor = sharedBuffer.getAccessor()) { nfa.advanceTime(sharedBufferAccessor, nfaState, inputEvent.getTimestamp()); nfa.process( sharedBufferAccessor, nfaState, inputEvent.getValue(), inputEvent.getTimestamp(), matchSkipStrategy); } } assertThat(sharedBuffer.isEmpty(), Matchers.is(true)); } }
mylog00/flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/nfa/AfterMatchSkipITCase.java
Java
apache-2.0
33,258
package org.apereo.cas.oidc.web; import org.apereo.cas.oidc.OidcConstants; import org.apereo.cas.support.oauth.web.OAuth20HandlerInterceptorAdapter; import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenGrantRequestExtractor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Collection; /** * This is {@link OidcHandlerInterceptorAdapter}. * * @author Misagh Moayyed * @since 5.1.0 */ @Slf4j public class OidcHandlerInterceptorAdapter extends OAuth20HandlerInterceptorAdapter { private final HandlerInterceptorAdapter requiresAuthenticationDynamicRegistrationInterceptor; private final HandlerInterceptorAdapter requiresAuthenticationClientConfigurationInterceptor; private final OidcConstants.DynamicClientRegistrationMode dynamicClientRegistrationMode; private final Collection<AccessTokenGrantRequestExtractor> accessTokenGrantRequestExtractors; public OidcHandlerInterceptorAdapter(final HandlerInterceptorAdapter requiresAuthenticationAccessTokenInterceptor, final HandlerInterceptorAdapter requiresAuthenticationAuthorizeInterceptor, final HandlerInterceptorAdapter requiresAuthenticationDynamicRegistrationInterceptor, final HandlerInterceptorAdapter requiresAuthenticationClientConfigurationInterceptor, final OidcConstants.DynamicClientRegistrationMode dynamicClientRegistrationMode, final Collection<AccessTokenGrantRequestExtractor> accessTokenGrantRequestExtractors) { super(requiresAuthenticationAccessTokenInterceptor, requiresAuthenticationAuthorizeInterceptor, accessTokenGrantRequestExtractors); this.requiresAuthenticationDynamicRegistrationInterceptor = requiresAuthenticationDynamicRegistrationInterceptor; this.dynamicClientRegistrationMode = dynamicClientRegistrationMode; this.accessTokenGrantRequestExtractors = accessTokenGrantRequestExtractors; this.requiresAuthenticationClientConfigurationInterceptor = requiresAuthenticationClientConfigurationInterceptor; } @Override public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { LOGGER.trace("Attempting to pre-handle OIDC request at [{}]", request.getRequestURI()); if (!super.preHandle(request, response, handler)) { LOGGER.trace("Unable to pre-handle OIDC request at [{}]", request.getRequestURI()); return false; } if (isClientConfigurationRequest(request.getRequestURI())) { LOGGER.trace("OIDC client configuration is protected at [{}]", request.getRequestURI()); return requiresAuthenticationClientConfigurationInterceptor.preHandle(request, response, handler); } if (isDynamicClientRegistrationRequest(request.getRequestURI())) { LOGGER.trace("OIDC request at [{}] is one of dynamic client registration", request.getRequestURI()); if (isDynamicClientRegistrationRequestProtected()) { LOGGER.trace("OIDC dynamic client registration is protected at [{}]", request.getRequestURI()); return requiresAuthenticationDynamicRegistrationInterceptor.preHandle(request, response, handler); } } return true; } /** * Is dynamic client registration request protected boolean. * * @return the boolean */ private boolean isDynamicClientRegistrationRequestProtected() { return this.dynamicClientRegistrationMode == OidcConstants.DynamicClientRegistrationMode.PROTECTED; } /** * Is dynamic client registration request. * * @param requestPath the request path * @return the boolean */ protected boolean isDynamicClientRegistrationRequest(final String requestPath) { return doesUriMatchPattern(requestPath, OidcConstants.REGISTRATION_URL); } /** * Is client configuration request. * * @param requestPath the request path * @return the boolean */ protected boolean isClientConfigurationRequest(final String requestPath) { return doesUriMatchPattern(requestPath, OidcConstants.CLIENT_CONFIGURATION_URL); } }
rrenomeron/cas
support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/web/OidcHandlerInterceptorAdapter.java
Java
apache-2.0
4,545
/* * 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.drill.exec.physical.impl.scan.convert; import org.apache.drill.exec.vector.accessor.InvalidConversionError; import org.apache.drill.exec.vector.accessor.ScalarWriter; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class ConvertDateToString extends DirectConverter { private final DateTimeFormatter dateTimeFormatter; public ConvertDateToString(ScalarWriter baseWriter) { super(baseWriter); final String formatValue = baseWriter.schema().format(); dateTimeFormatter = formatValue == null ? ISODateTimeFormat.date() : DateTimeFormat.forPattern(formatValue); } @Override public void setDate(final LocalDate value) { if (value == null) { baseWriter.setNull(); } else { try { baseWriter.setString(dateTimeFormatter.print(value)); } catch (final IllegalStateException e) { throw InvalidConversionError.writeError(schema(), value, e); } } } @Override public void setValue(Object value) { if (value == null) { setNull(); } else { setDate((LocalDate) value); } } }
arina-ielchiieva/drill
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/scan/convert/ConvertDateToString.java
Java
apache-2.0
2,031
/* * Copyright 2010-2015 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.waf.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.waf.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetSampledRequestsResult JSON Unmarshaller */ public class GetSampledRequestsResultJsonUnmarshaller implements Unmarshaller<GetSampledRequestsResult, JsonUnmarshallerContext> { public GetSampledRequestsResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetSampledRequestsResult getSampledRequestsResult = new GetSampledRequestsResult(); 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("SampledRequests", targetDepth)) { context.nextToken(); getSampledRequestsResult .setSampledRequests(new ListUnmarshaller<SampledHTTPRequest>( SampledHTTPRequestJsonUnmarshaller .getInstance()).unmarshall(context)); } if (context.testExpression("PopulationSize", targetDepth)) { context.nextToken(); getSampledRequestsResult .setPopulationSize(LongJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("TimeWindow", targetDepth)) { context.nextToken(); getSampledRequestsResult .setTimeWindow(TimeWindowJsonUnmarshaller .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 getSampledRequestsResult; } private static GetSampledRequestsResultJsonUnmarshaller instance; public static GetSampledRequestsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetSampledRequestsResultJsonUnmarshaller(); return instance; } }
sdole/aws-sdk-java
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/transform/GetSampledRequestsResultJsonUnmarshaller.java
Java
apache-2.0
3,664
/** * Copyright 2014-2015 Google 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 br.edu.ifpi.novaescola; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.googlecode.objectify.ObjectifyService; /** * OfyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This is * required to let JSP's access Ofy. **/ public class OfyHelper implements ServletContextListener { public static void register() { // ObjectifyService.register(Guestbook.class); } public void contextInitialized(ServletContextEvent event) { // This will be invoked as part of a warmup request, or the first user // request if no warmup request was invoked. register(); } public void contextDestroyed(ServletContextEvent event) { // App Engine does not currently invoke this method. } }
novageracao/projeto-nova-escola
oficina-urbana/src/main/java/br/edu/ifpi/novaescola/OfyHelper.java
Java
apache-2.0
1,412
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2013 Dirk Beyer * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cfa.ast; import org.sosy_lab.cpachecker.cfa.types.Type; /** * This interface represents the core components that occur in each declaration: * a type and an (optional) name. * * It is part of the declaration of types and variables (see {@link IADeclaration}) * and functions (see {@link AFunctionDeclaration}). * It is also used stand-alone for the declaration of members of composite types * (e.g. structs) and for the declaration of function parameters. */ public interface IASimpleDeclaration extends IAstNode { public String getName(); public String getOrigName(); Type getType(); }
TommesDee/cpachecker
src/org/sosy_lab/cpachecker/cfa/ast/IASimpleDeclaration.java
Java
apache-2.0
1,453
/* * Copyright 2018 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.jbpm.workbench.common.client.filters.basic; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.dashbuilder.dataset.DataSetLookup; import org.jboss.errai.common.client.api.IsElement; import org.jbpm.workbench.common.client.filters.active.ActiveFilterItem; import org.jbpm.workbench.common.client.util.DateRange; public interface BasicFiltersView extends IsElement { void addTextFilter(String label, String placeholder, Consumer<ActiveFilterItem<String>> callback); void addNumericFilter(String label, String placeholder, Consumer<ActiveFilterItem<Integer>> callback); void addDateRangeFilter(String label, String placeholder, Boolean useMaxDate, Consumer<ActiveFilterItem<DateRange>> callback); void clearSelectFilter(String label); void checkSelectFilter(String label, String value); void clearAllSelectFilter(); void addMultiSelectFilter(String label, Map<String, String> options, Consumer<ActiveFilterItem<List<String>>> callback); void addSelectFilter(String label, Map<String, String> options, Consumer<ActiveFilterItem<String>> callback); void addDataSetSelectFilter(String label, DataSetLookup lookup, String textColumnId, String valueColumnId, Consumer<ActiveFilterItem<String>> callback); void hideFilterBySection(); }
nmirasch/jbpm-console-ng
jbpm-wb-common/jbpm-wb-common-client/src/main/java/org/jbpm/workbench/common/client/filters/basic/BasicFiltersView.java
Java
apache-2.0
2,403
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2014 Eric Lafortune ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * 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 General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.visitor; import proguard.classfile.*; import proguard.util.*; /** * This <code>MemberVisitor</code> delegates its visits to another given * <code>MemberVisitor</code>, but only when the visited member * has a descriptor that matches a given regular expression. * * @author Eric Lafortune */ public class MemberDescriptorFilter implements MemberVisitor { private final StringMatcher regularExpressionMatcher; private final MemberVisitor memberVisitor; /** * Creates a new MemberDescriptorFilter. * @param regularExpression the regular expression against which member * descriptors will be matched. * @param memberVisitor the <code>MemberVisitor</code> to which visits * will be delegated. */ public MemberDescriptorFilter(String regularExpression, MemberVisitor memberVisitor) { this(new ClassNameParser().parse(regularExpression), memberVisitor); } /** * Creates a new MemberDescriptorFilter. * @param regularExpressionMatcher the regular expression against which * member descriptors will be matched. * @param memberVisitor the <code>MemberVisitor</code> to which * visits will be delegated. */ public MemberDescriptorFilter(StringMatcher regularExpressionMatcher, MemberVisitor memberVisitor) { this.regularExpressionMatcher = regularExpressionMatcher; this.memberVisitor = memberVisitor; } // Implementations for MemberVisitor. public void visitProgramField(ProgramClass programClass, ProgramField programField) { if (accepted(programField.getDescriptor(programClass))) { memberVisitor.visitProgramField(programClass, programField); } } public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod) { if (accepted(programMethod.getDescriptor(programClass))) { memberVisitor.visitProgramMethod(programClass, programMethod); } } public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField) { if (accepted(libraryField.getDescriptor(libraryClass))) { memberVisitor.visitLibraryField(libraryClass, libraryField); } } public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod) { if (accepted(libraryMethod.getDescriptor(libraryClass))) { memberVisitor.visitLibraryMethod(libraryClass, libraryMethod); } } // Small utility methods. private boolean accepted(String name) { return regularExpressionMatcher.matches(name); } }
oneliang/third-party-lib
proguard/proguard/classfile/visitor/MemberDescriptorFilter.java
Java
apache-2.0
3,806
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2016 Groupon, Inc * Copyright 2014-2016 The Billing Project, LLC * * The Billing Project 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.killbill.billing.entitlement.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; import org.joda.time.DateTime; import org.killbill.billing.callcontext.InternalCallContext; import org.killbill.billing.callcontext.InternalTenantContext; import org.killbill.billing.entitlement.api.BlockingState; import org.killbill.billing.entitlement.api.BlockingStateType; import org.killbill.billing.entitlement.api.EntitlementApiException; import org.killbill.billing.util.entity.dao.MockEntityDaoBase; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; public class MockBlockingStateDao extends MockEntityDaoBase<BlockingStateModelDao, BlockingState, EntitlementApiException> implements BlockingStateDao { private final Map<UUID, List<BlockingState>> blockingStates = new HashMap<UUID, List<BlockingState>>(); private final Map<Long, List<BlockingState>> blockingStatesPerAccountRecordId = new HashMap<Long, List<BlockingState>>(); // TODO This mock class should also check that events are past or present @Override public BlockingState getBlockingStateForService(final UUID blockableId, final BlockingStateType blockingStateType, final String serviceName, final InternalTenantContext context) { final List<BlockingState> states = blockingStates.get(blockableId); if (states == null) { return null; } final ImmutableList<BlockingState> filtered = ImmutableList.<BlockingState>copyOf(Collections2.filter(states, new Predicate<BlockingState>() { @Override public boolean apply(@Nullable final BlockingState input) { return input.getService().equals(serviceName); } })); return filtered.size() == 0 ? null : filtered.get(filtered.size() - 1); } @Override public List<BlockingState> getBlockingState(final UUID blockableId, final BlockingStateType blockingStateType, final DateTime upToDate, final InternalTenantContext context) { final List<BlockingState> blockingStatesForId = blockingStates.get(blockableId); if (blockingStatesForId == null) { return new ArrayList<BlockingState>(); } final Map<String, BlockingState> tmp = new HashMap<String, BlockingState>(); for (BlockingState cur : blockingStatesForId) { final BlockingState curStateForService = tmp.get(cur.getService()); if (curStateForService == null || curStateForService.getEffectiveDate().compareTo(cur.getEffectiveDate()) < 0) { tmp.put(cur.getService(), cur); } } return new ArrayList<BlockingState>(tmp.values()); } @Override public List<BlockingState> getBlockingAllForAccountRecordId(final InternalTenantContext context) { return MoreObjects.firstNonNull(blockingStatesPerAccountRecordId.get(context.getAccountRecordId()), ImmutableList.<BlockingState>of()); } @Override public synchronized void setBlockingStatesAndPostBlockingTransitionEvent(final Map<BlockingState, Optional<UUID>> states, final InternalCallContext context) { for (final BlockingState state : states.keySet()) { if (blockingStates.get(state.getBlockedId()) == null) { blockingStates.put(state.getBlockedId(), new ArrayList<BlockingState>()); } blockingStates.get(state.getBlockedId()).add(state); if (blockingStatesPerAccountRecordId.get(context.getAccountRecordId()) == null) { blockingStatesPerAccountRecordId.put(context.getAccountRecordId(), new ArrayList<BlockingState>()); } blockingStatesPerAccountRecordId.get(context.getAccountRecordId()).add(state); } } @Override public void unactiveBlockingState(final UUID blockableId, final InternalCallContext context) { throw new UnsupportedOperationException(); } public synchronized void clear() { blockingStates.clear(); blockingStatesPerAccountRecordId.clear(); } }
andrenpaes/killbill
entitlement/src/test/java/org/killbill/billing/entitlement/dao/MockBlockingStateDao.java
Java
apache-2.0
5,033
/* * 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.kylin.engine.mr.steps; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import org.apache.hadoop.util.ReflectionUtils; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.persistence.ResourceStore; import org.apache.kylin.common.util.ByteArray; import org.apache.kylin.common.util.Bytes; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.common.util.StringUtil; import org.apache.kylin.cube.CubeDescManager; import org.apache.kylin.cube.CubeInstance; import org.apache.kylin.cube.CubeManager; import org.apache.kylin.cube.CubeSegment; import org.apache.kylin.cube.model.CubeDesc; import org.apache.kylin.dict.DictionaryInfo; import org.apache.kylin.dict.DictionaryManager; import org.apache.kylin.engine.mr.KylinMapper; import org.apache.kylin.engine.mr.common.AbstractHadoopJob; import org.apache.kylin.engine.mr.common.BatchConstants; import org.apache.kylin.engine.mr.common.CubeStatsWriter; import org.apache.kylin.engine.mr.common.SerializableConfiguration; import org.apache.kylin.measure.hllc.HLLCounter; import org.apache.kylin.metadata.model.TblColRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.kylin.shaded.com.google.common.collect.Lists; import org.apache.kylin.shaded.com.google.common.collect.Maps; public class MergeDictionaryMapper extends KylinMapper<IntWritable, NullWritable, IntWritable, Text> { private static final Logger logger = LoggerFactory.getLogger(MergeDictionaryMapper.class); List<CubeSegment> mergingSegments; TblColRef[] tblColRefs; DictionaryManager dictMgr; @Override protected void doSetup(Context context) throws IOException, InterruptedException { super.doSetup(context); final SerializableConfiguration sConf = new SerializableConfiguration(context.getConfiguration()); final String metaUrl = context.getConfiguration().get(BatchConstants.ARG_META_URL); final String cubeName = context.getConfiguration().get(BatchConstants.ARG_CUBE_NAME); final String segmentIds = context.getConfiguration().get(MergeDictionaryJob.OPTION_MERGE_SEGMENT_IDS.getOpt()); final KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeInstance.getDescName()); mergingSegments = getMergingSegments(cubeInstance, StringUtil.splitByComma(segmentIds)); tblColRefs = cubeDesc.getAllColumnsNeedDictionaryBuilt().toArray(new TblColRef[0]); dictMgr = DictionaryManager.getInstance(kylinConfig); } @Override protected void doMap(IntWritable key, NullWritable value, Context context) throws IOException, InterruptedException { int index = key.get(); if (index < tblColRefs.length) { // merge dictionary TblColRef col = tblColRefs[index]; List<DictionaryInfo> dictInfos = Lists.newArrayList(); for (CubeSegment segment : mergingSegments) { if (segment.getDictResPath(col) != null) { DictionaryInfo dictInfo = dictMgr.getDictionaryInfo(segment.getDictResPath(col)); if (dictInfo != null && !dictInfos.contains(dictInfo)) { dictInfos.add(dictInfo); } } } DictionaryInfo mergedDictInfo = dictMgr.mergeDictionary(dictInfos); String tblCol = col.getTableAlias() + ":" + col.getName(); String dictInfoPath = mergedDictInfo == null ? "" : mergedDictInfo.getResourcePath(); context.write(new IntWritable(-1), new Text(tblCol + "=" + dictInfoPath)); } else { // merge statistics KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs( new SerializableConfiguration(context.getConfiguration()), context.getConfiguration().get(BatchConstants.ARG_META_URL)); final String cubeName = context.getConfiguration().get(BatchConstants.ARG_CUBE_NAME); final String segmentId = context.getConfiguration().get(BatchConstants.ARG_SEGMENT_ID); final String statOutputPath = context.getConfiguration() .get(MergeDictionaryJob.OPTION_OUTPUT_PATH_STAT.getOpt()); CubeInstance cubeInstance = CubeManager.getInstance(kylinConfig).getCube(cubeName); logger.info("Statistics output path: {}", statOutputPath); CubeSegment newSegment = cubeInstance.getSegmentById(segmentId); ResourceStore rs = ResourceStore.getStore(kylinConfig); Map<Long, HLLCounter> cuboidHLLMap = Maps.newHashMap(); Configuration conf = null; int averageSamplingPercentage = 0; long sourceRecordCount = 0; long effectiveTimeRange = 0; for (CubeSegment cubeSegment : mergingSegments) { String filePath = cubeSegment.getStatisticsResourcePath(); InputStream is = rs.getResource(filePath).content(); File tempFile; FileOutputStream tempFileStream = null; try { tempFile = File.createTempFile(segmentId, ".seq"); tempFileStream = new FileOutputStream(tempFile); org.apache.commons.io.IOUtils.copy(is, tempFileStream); } finally { IOUtils.closeStream(is); IOUtils.closeStream(tempFileStream); } FileSystem fs = HadoopUtil.getFileSystem("file:///" + tempFile.getAbsolutePath()); SequenceFile.Reader reader = null; try { conf = HadoopUtil.getCurrentConfiguration(); //noinspection deprecation reader = new SequenceFile.Reader(fs, new Path(tempFile.getAbsolutePath()), conf); LongWritable keyW = (LongWritable) ReflectionUtils.newInstance(reader.getKeyClass(), conf); BytesWritable valueW = (BytesWritable) ReflectionUtils.newInstance(reader.getValueClass(), conf); while (reader.next(keyW, valueW)) { if (keyW.get() == 0L) { // sampling percentage; averageSamplingPercentage += Bytes.toInt(valueW.getBytes()); } else if (keyW.get() == -3) { long perSourceRecordCount = Bytes.toLong(valueW.getBytes()); if (perSourceRecordCount > 0) { sourceRecordCount += perSourceRecordCount; CubeSegment iSegment = cubeInstance.getSegmentById(segmentId); effectiveTimeRange += iSegment.getTSRange().duration(); } } else if (keyW.get() > 0) { HLLCounter hll = new HLLCounter(kylinConfig.getCubeStatsHLLPrecision()); ByteArray byteArray = new ByteArray(valueW.getBytes()); hll.readRegisters(byteArray.asBuffer()); if (cuboidHLLMap.get(keyW.get()) != null) { cuboidHLLMap.get(keyW.get()).merge(hll); } else { cuboidHLLMap.put(keyW.get(), hll); } } } } catch (Exception e) { e.printStackTrace(); throw e; } finally { IOUtils.closeStream(reader); } } sourceRecordCount *= effectiveTimeRange == 0 ? 0 : (double) newSegment.getTSRange().duration() / effectiveTimeRange; Path statisticsFilePath = new Path(statOutputPath, BatchConstants.CFG_STATISTICS_CUBOID_ESTIMATION_FILENAME); averageSamplingPercentage = averageSamplingPercentage / mergingSegments.size(); CubeStatsWriter.writeCuboidStatistics(conf, new Path(statOutputPath), cuboidHLLMap, averageSamplingPercentage, sourceRecordCount); FileSystem fs = HadoopUtil.getFileSystem(statisticsFilePath, conf); FSDataInputStream fis = fs.open(statisticsFilePath); try { // put the statistics to metadata store String statisticsFileName = newSegment.getStatisticsResourcePath(); rs.putResource(statisticsFileName, fis, System.currentTimeMillis()); } finally { IOUtils.closeStream(fis); } context.write(new IntWritable(-1), new Text("")); } } private List<CubeSegment> getMergingSegments(CubeInstance cube, String[] segmentIds) { List<CubeSegment> result = Lists.newArrayListWithCapacity(segmentIds.length); for (String id : segmentIds) { result.add(cube.getSegmentById(id)); } return result; } }
apache/kylin
engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/MergeDictionaryMapper.java
Java
apache-2.0
10,679
package com.novachevskyi.datepicker.base.animators; import android.content.Context; import android.text.format.DateUtils; import android.util.AttributeSet; import android.view.accessibility.AccessibilityEvent; import android.widget.ViewAnimator; public class AccessibleDateAnimator extends ViewAnimator { private long mDateMillis; public AccessibleDateAnimator(Context context, AttributeSet attrs) { super(context, attrs); } public void setDateMillis(long dateMillis) { mDateMillis = dateMillis; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { event.getText().clear(); int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY; String dateString = DateUtils.formatDateTime(getContext(), mDateMillis, flags); event.getText().add(dateString); return true; } return super.dispatchPopulateAccessibilityEvent(event); } }
novachevskyi/material-calendar-datepicker
library/src/main/java/com/novachevskyi/datepicker/base/animators/AccessibleDateAnimator.java
Java
apache-2.0
1,058
/* * 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.ambari.server.orm.entities; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import org.apache.ambari.server.controller.internal.ProvisionAction; @Entity @Table(name = "topology_request") @TableGenerator(name = "topology_request_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value", pkColumnValue = "topology_request_id_seq", initialValue = 0) @NamedQueries({ @NamedQuery(name = "TopologyRequestEntity.findByClusterId", query = "SELECT req FROM TopologyRequestEntity req WHERE req.clusterId = :clusterId"), @NamedQuery(name = "TopologyRequestEntity.findProvisionRequests", query = "SELECT req FROM TopologyRequestEntity req WHERE req.action = 'PROVISION'"), }) public class TopologyRequestEntity { @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "topology_request_id_generator") @Column(name = "id", nullable = false, updatable = false) private Long id; @Column(name = "action", length = 255, nullable = false) private String action; @Column(name = "cluster_id", nullable = true) private Long clusterId; @Column(name = "bp_name", length = 100, nullable = false) private String blueprintName; @Column(name = "cluster_properties") @Basic(fetch = FetchType.LAZY) @Lob private String clusterProperties; @Column(name = "cluster_attributes") @Basic(fetch = FetchType.LAZY) @Lob private String clusterAttributes; @Column(name = "description", length = 1024, nullable = false) private String description; @OneToMany(mappedBy = "topologyRequestEntity", cascade = CascadeType.ALL) private Collection<TopologyHostGroupEntity> topologyHostGroupEntities; @OneToOne(mappedBy = "topologyRequestEntity", cascade = CascadeType.ALL) private TopologyLogicalRequestEntity topologyLogicalRequestEntity; @Column(name = "provision_action", length = 255, nullable = true) @Enumerated(EnumType.STRING) private ProvisionAction provisionAction; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getBlueprintName() { return blueprintName; } public void setBlueprintName(String blueprintName) { this.blueprintName = blueprintName; } public String getClusterProperties() { return clusterProperties; } public void setClusterProperties(String clusterProperties) { this.clusterProperties = clusterProperties; } public String getClusterAttributes() { return clusterAttributes; } public void setClusterAttributes(String clusterAttributes) { this.clusterAttributes = clusterAttributes; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Collection<TopologyHostGroupEntity> getTopologyHostGroupEntities() { return topologyHostGroupEntities; } public void setTopologyHostGroupEntities(Collection<TopologyHostGroupEntity> topologyHostGroupEntities) { this.topologyHostGroupEntities = topologyHostGroupEntities; } public TopologyLogicalRequestEntity getTopologyLogicalRequestEntity() { return topologyLogicalRequestEntity; } public void setTopologyLogicalRequestEntity(TopologyLogicalRequestEntity topologyLogicalRequestEntity) { this.topologyLogicalRequestEntity = topologyLogicalRequestEntity; } public ProvisionAction getProvisionAction() { return provisionAction; } public void setProvisionAction(ProvisionAction provisionAction) { this.provisionAction = provisionAction; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TopologyRequestEntity that = (TopologyRequestEntity) o; if (!id.equals(that.id)) return false; return true; } @Override public int hashCode() { return id.hashCode(); } }
sekikn/ambari
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/TopologyRequestEntity.java
Java
apache-2.0
5,617
/* * 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.olingo.server.api.uri.queryoption.search; public interface SearchExpression { //No additional methods needed for now. }
mtaal/olingo-odata4-jpa
lib/server-api/src/main/java/org/apache/olingo/server/api/uri/queryoption/search/SearchExpression.java
Java
apache-2.0
944
/* * * 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.flex.compiler.internal.fxg.sax; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.flex.compiler.fxg.FXGVersion; import org.apache.flex.compiler.fxg.dom.IFXGNode; /** * An abstract implementation of IFXGVersionHandler interface. It implements * interfaces to encapsulate FXG version specific information. It forms the base * class for the different FXGVersionHandlers. This allows the scanner to handle * different versions of fxg files by swapping different FXGVersionHandlers at * runtime depending on the fxg version of the input file. */ public abstract class AbstractFXGVersionHandler implements IFXGVersionHandler { /** * A Map of URIs to a List of local element names. */ protected Map<String, Set<String>> skippedElementsByURI = null; /** * A Map of URIs to a Map of local element names to an IFXGNode Class. */ protected Map<String, Map<String, Class<? extends IFXGNode>>> elementNodesByURI = null; // version of the IFXGVersionHandler protected FXGVersion handlerVersion; /** * @return the FXGVersion of the handler */ @Override public FXGVersion getVersion() { return handlerVersion; } protected void init() { } /** * @param URI - namespace for the elements * @return a Set<String> of the elements that are registered to be skipped * by the scanner */ @Override public Set<String> getSkippedElements(String URI) { init(); if (skippedElementsByURI == null) return null; return skippedElementsByURI.get(URI); } /** * @param URI - namespace for the elements * @return a Map<String, Class<? extends IFXGNode>> that maps element names * to Class that handles the element. */ @Override public Map<String, Class<? extends IFXGNode>> getElementNodes(String URI) { init(); if (elementNodesByURI == null) return null; return elementNodesByURI.get(URI); } /** * Registers names of elements that are to be skipped by the scanner * * @param URI - namespace for the elements * @param skippedElements - Set of Strings that specify elements names that * are to be scanned by scanner */ @Override public void registerSkippedElements(String URI, Set<String> skippedElements) { init(); if (skippedElementsByURI == null) { skippedElementsByURI = new HashMap<String, Set<String>>(1); skippedElementsByURI.put(URI, skippedElements); } else { if (skippedElementsByURI.containsKey(URI)) { Set<String> value = skippedElementsByURI.get(URI); value.addAll(skippedElements); skippedElementsByURI.put(URI, value); } else { skippedElementsByURI.put(URI, skippedElements); } } } /** * Registers mapping for the scanner to process elements and Classes that * handle the elements * * @param URI - namespace for the elements * @param elementNodes - a Map containing mapping from elements names to * Classes that handle the elements. */ @Override public void registerElementNodes(String URI, Map<String, Class<? extends IFXGNode>> elementNodes) { init(); if (elementNodesByURI == null) { elementNodesByURI = new HashMap<String, Map<String, Class<? extends IFXGNode>>>(1); elementNodesByURI.put(URI, elementNodes); } else { if (elementNodesByURI.containsKey(URI)) { Map<String, Class<? extends IFXGNode>> value = elementNodesByURI.get(URI); value.putAll(elementNodes); elementNodesByURI.put(URI, value); } else { elementNodesByURI.put(URI, elementNodes); } } } }
adufilie/flex-falcon
compiler/src/org/apache/flex/compiler/internal/fxg/sax/AbstractFXGVersionHandler.java
Java
apache-2.0
4,962
/** * Copyright © 2010-2014 Nokia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.jsonschema2pojo; import java.io.File; import java.io.FileFilter; import java.net.URL; import java.util.Iterator; import org.jsonschema2pojo.rules.RuleFactory; /** * A generation config that returns default values for all behavioural options. */ public class DefaultGenerationConfig implements GenerationConfig { /** * @return <code>false</code> */ @Override public boolean isGenerateBuilders() { return false; } /** * @return <code>false</code> */ @Override public boolean isUsePrimitives() { return false; } /** * Unsupported since no default source is possible. */ @Override public Iterator<URL> getSource() { throw new UnsupportedOperationException("No default source available"); } /** * @return the current working directory */ @Override public File getTargetDirectory() { return new File("."); } /** * @return the 'default' package (i.e. an empty string) */ @Override public String getTargetPackage() { return ""; } /** * @return an empty array (i.e. no word delimiters) */ @Override public char[] getPropertyWordDelimiters() { return new char[] { '-', ' ', '_' }; } /** * @return <code>false</code> */ @Override public boolean isUseLongIntegers() { return false; } @Override public boolean isUseDoubleNumbers() { return true; } /** * @return <code>true</code> */ @Override public boolean isIncludeHashcodeAndEquals() { return true; } /** * @return <code>true</code> */ @Override public boolean isIncludeToString() { return true; } /** * @return {@link AnnotationStyle#JACKSON2} */ @Override public AnnotationStyle getAnnotationStyle() { return AnnotationStyle.JACKSON; } /** * {@link NoopAnnotator} */ @Override public Class<? extends Annotator> getCustomAnnotator() { return NoopAnnotator.class; } @Override public Class<? extends RuleFactory> getCustomRuleFactory() { return RuleFactory.class; } /** * @return <code>false</code> */ @Override public boolean isIncludeJsr303Annotations() { return false; } /** * @return {@link SourceType#JSONSCHEMA} */ @Override public SourceType getSourceType() { return SourceType.JSONSCHEMA; } /** * @return UTF-8 */ @Override public String getOutputEncoding() { return "UTF-8"; } /** * @return false */ @Override public boolean isRemoveOldOutput() { return false; } /** * @return false */ @Override public boolean isUseJodaDates() { return false; } /** * @return false */ @Override public boolean isUseJodaLocalDates() { return false; } /** * @return false */ @Override public boolean isUseJodaLocalTimes() { return false; } @Override public boolean isUseCommonsLang3() { return false; } @Override public boolean isParcelable() { return false; } @Override public FileFilter getFileFilter() { return new AllFileFilter(); } /** * @return <code>true</code> */ @Override public boolean isInitializeCollections() { return true; } @Override public String getClassNamePrefix() { return ""; } @Override public String getClassNameSuffix() { return ""; } @Override public boolean isIncludeConstructors() { return false; } @Override public boolean isConstructorsRequiredPropertiesOnly() { return false; } @Override public boolean isIncludeAdditionalProperties() { return false; } }
hgl888/jsonschema2pojo
jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/DefaultGenerationConfig.java
Java
apache-2.0
4,607
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn; import com.intellij.ide.FrameStateListener; import com.intellij.idea.RareLogger; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.annotate.AnnotationProvider; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.checkin.CheckinEnvironment; import com.intellij.openapi.vcs.diff.DiffProvider; import com.intellij.openapi.vcs.history.VcsAnnotationCachedProxy; import com.intellij.openapi.vcs.history.VcsHistoryProvider; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vcs.merge.MergeProvider; import com.intellij.openapi.vcs.rollback.RollbackEnvironment; import com.intellij.openapi.vcs.update.UpdateEnvironment; import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.Consumer; import com.intellij.util.ThreeState; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.messages.Topic; import one.util.streamex.EntryStream; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.idea.svn.actions.CleanupWorker; import org.jetbrains.idea.svn.actions.SvnMergeProvider; import org.jetbrains.idea.svn.annotate.SvnAnnotationProvider; import org.jetbrains.idea.svn.api.*; import org.jetbrains.idea.svn.auth.SvnAuthenticationNotifier; import org.jetbrains.idea.svn.branchConfig.SvnLoadedBranchesStorage; import org.jetbrains.idea.svn.checkin.SvnCheckinEnvironment; import org.jetbrains.idea.svn.checkout.SvnCheckoutProvider; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.jetbrains.idea.svn.commandLine.SvnExecutableChecker; import org.jetbrains.idea.svn.dialogs.WCInfo; import org.jetbrains.idea.svn.history.LoadedRevisionsCache; import org.jetbrains.idea.svn.history.SvnChangeList; import org.jetbrains.idea.svn.history.SvnCommittedChangesProvider; import org.jetbrains.idea.svn.history.SvnHistoryProvider; import org.jetbrains.idea.svn.info.Info; import org.jetbrains.idea.svn.info.InfoConsumer; import org.jetbrains.idea.svn.integrate.SvnBranchPointsCalculator; import org.jetbrains.idea.svn.properties.PropertyClient; import org.jetbrains.idea.svn.properties.PropertyValue; import org.jetbrains.idea.svn.rollback.SvnRollbackEnvironment; import org.jetbrains.idea.svn.status.Status; import org.jetbrains.idea.svn.status.StatusType; import org.jetbrains.idea.svn.update.SvnIntegrateEnvironment; import org.jetbrains.idea.svn.update.SvnUpdateEnvironment; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile; import static com.intellij.util.containers.ContainerUtil.*; import static com.intellij.vcsUtil.VcsUtil.getFilePath; import static java.util.Collections.emptyList; import static java.util.function.Function.identity; public class SvnVcs extends AbstractVcs<CommittedChangeList> { private static final String DO_NOT_LISTEN_TO_WC_DB = "svn.do.not.listen.to.wc.db"; private static final Logger REFRESH_LOG = Logger.getInstance("#svn_refresh"); public static boolean ourListenToWcDb = !Boolean.getBoolean(DO_NOT_LISTEN_TO_WC_DB); private static final Logger LOG = wrapLogger(Logger.getInstance("org.jetbrains.idea.svn.SvnVcs")); @NonNls public static final String VCS_NAME = "svn"; public static final String VCS_DISPLAY_NAME = "Subversion"; private static final VcsKey ourKey = createKey(VCS_NAME); public static final Topic<Runnable> WC_CONVERTED = new Topic<>("WC_CONVERTED", Runnable.class); @NotNull private final SvnConfiguration myConfiguration; private final SvnEntriesFileListener myEntriesFileListener; private CheckinEnvironment myCheckinEnvironment; private RollbackEnvironment myRollbackEnvironment; private UpdateEnvironment mySvnUpdateEnvironment; private UpdateEnvironment mySvnIntegrateEnvironment; private AnnotationProvider myAnnotationProvider; private DiffProvider mySvnDiffProvider; private final VcsShowConfirmationOption myAddConfirmation; private final VcsShowConfirmationOption myDeleteConfirmation; private EditFileProvider myEditFilesProvider; private SvnCommittedChangesProvider myCommittedChangesProvider; private final VcsShowSettingOption myCheckoutOptions; private ChangeProvider myChangeProvider; private MergeProvider myMergeProvider; private final SvnChangelistListener myChangeListListener; private SvnCopiesRefreshManager myCopiesRefreshManager; private SvnFileUrlMappingImpl myMapping; private Disposable myFrameStateListenerDisposable; //Consumer<Boolean> public static final Topic<Consumer> ROOTS_RELOADED = new Topic<>("ROOTS_RELOADED", Consumer.class); private VcsListener myVcsListener; private SvnBranchPointsCalculator mySvnBranchPointsCalculator; private final RootsToWorkingCopies myRootsToWorkingCopies; private final SvnAuthenticationNotifier myAuthNotifier; private final SvnLoadedBranchesStorage myLoadedBranchesStorage; private final SvnExecutableChecker myChecker; private SvnCheckoutProvider myCheckoutProvider; @NotNull private final ClientFactory cmdClientFactory; private final boolean myLogExceptions; public SvnVcs(@NotNull Project project, MessageBus bus, SvnConfiguration svnConfiguration, final SvnLoadedBranchesStorage storage) { super(project, VCS_NAME); myLoadedBranchesStorage = storage; myRootsToWorkingCopies = new RootsToWorkingCopies(this); myConfiguration = svnConfiguration; myAuthNotifier = new SvnAuthenticationNotifier(this); cmdClientFactory = new CmdClientFactory(this); final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project); myAddConfirmation = vcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.ADD, this); myDeleteConfirmation = vcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.REMOVE, this); myCheckoutOptions = vcsManager.getStandardOption(VcsConfiguration.StandardOption.CHECKOUT, this); if (myProject.isDefault()) { myChangeListListener = null; myEntriesFileListener = null; } else { myEntriesFileListener = new SvnEntriesFileListener(project); upgradeIfNeeded(bus); myChangeListListener = new SvnChangelistListener(this); myVcsListener = () -> invokeRefreshSvnRoots(); } myChecker = new SvnExecutableChecker(this); Application app = ApplicationManager.getApplication(); myLogExceptions = app != null && (app.isInternal() || app.isUnitTestMode()); } public void postStartup() { if (myProject.isDefault()) return; myCopiesRefreshManager = new SvnCopiesRefreshManager((SvnFileUrlMappingImpl)getSvnFileUrlMapping()); if (!myConfiguration.isCleanupRun()) { ApplicationManager.getApplication().invokeLater(() -> { cleanup17copies(); myConfiguration.setCleanupRun(true); }, ModalityState.NON_MODAL, myProject.getDisposed()); } else { invokeRefreshSvnRoots(); } } /** * TODO: This seems to be related to some issues when upgrading from 1.6 to 1.7. So it is not currently required for 1.8 and later * TODO: formats. And should be removed when 1.6 working copies are no longer supported by IDEA. */ private void cleanup17copies() { Runnable callCleanupWorker = () -> { if (myProject.isDisposed()) return; new CleanupWorker(this, emptyList()) { @Override protected void fillRoots() { for (WCInfo info : getAllWcInfos()) { if (WorkingCopyFormat.ONE_DOT_SEVEN.equals(info.getFormat())) { VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(info.getRootInfo().getIoFile()); if (file == null) { LOG.info("Wasn't able to find virtual file for wc root: " + info.getPath()); } else { myRoots.add(file); } } } } }.execute(); }; myCopiesRefreshManager.waitRefresh(() -> ApplicationManager.getApplication().invokeLater(callCleanupWorker)); } public boolean checkCommandLineVersion() { return getFactory() != cmdClientFactory || myChecker.checkExecutableAndNotifyIfNeeded(); } public void invokeRefreshSvnRoots() { if (REFRESH_LOG.isDebugEnabled()) { REFRESH_LOG.debug("refresh: ", new Throwable()); } if (myCopiesRefreshManager != null) { myCopiesRefreshManager.asynchRequest(); } } @TestOnly SvnCopiesRefreshManager getCopiesRefreshManager() { return myCopiesRefreshManager; } private void upgradeIfNeeded(final MessageBus bus) { final MessageBusConnection connection = bus.connect(); connection.subscribe(ChangeListManagerImpl.LISTS_LOADED, lists -> { if (lists.isEmpty()) return; try { ChangeListManager.getInstance(myProject).setReadOnly(LocalChangeList.DEFAULT_NAME, true); if (!myConfiguration.changeListsSynchronized()) { processChangeLists(lists); } } catch (ProcessCanceledException e) { // } finally { myConfiguration.upgrade(); } connection.disconnect(); }); } public void processChangeLists(final List<LocalChangeList> lists) { final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstanceChecked(myProject); plVcsManager.startBackgroundVcsOperation(); try { for (LocalChangeList list : lists) { if (!list.isDefault()) { final Collection<Change> changes = list.getChanges(); for (Change change : changes) { correctListForRevision(plVcsManager, change.getBeforeRevision(), list.getName()); correctListForRevision(plVcsManager, change.getAfterRevision(), list.getName()); } } } } finally { final Application appManager = ApplicationManager.getApplication(); if (appManager.isDispatchThread()) { appManager.executeOnPooledThread(() -> plVcsManager.stopBackgroundVcsOperation()); } else { plVcsManager.stopBackgroundVcsOperation(); } } } private void correctListForRevision(@NotNull final ProjectLevelVcsManager plVcsManager, @Nullable final ContentRevision revision, @NotNull final String name) { if (revision != null) { final FilePath path = revision.getFile(); final AbstractVcs vcs = plVcsManager.getVcsFor(path); if (vcs != null && VCS_NAME.equals(vcs.getName())) { try { getFactory(path.getIOFile()).createChangeListClient().add(name, path.getIOFile(), null); } catch (VcsException e) { // left in default list } } } } @Override public void activate() { MessageBusConnection busConnection = myProject.getMessageBus().connect(); if (!myProject.isDefault()) { ChangeListManager.getInstance(myProject).addChangeListListener(myChangeListListener); busConnection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, new VcsListener() { @Override public void directoryMappingChanged() { myVcsListener.directoryMappingChanged(); myRootsToWorkingCopies.directoryMappingChanged(); } }); } SvnApplicationSettings.getInstance().svnActivated(); if (myEntriesFileListener != null) { VirtualFileManager.getInstance().addVirtualFileListener(myEntriesFileListener); } // this will initialize its inner listener for committed changes upload LoadedRevisionsCache.getInstance(myProject); if (myFrameStateListenerDisposable == null && !myProject.isDefault()) { myFrameStateListenerDisposable = Disposer.newDisposable(); busConnection.subscribe(FrameStateListener.TOPIC, new MyFrameStateListener(ChangeListManager.getInstance(myProject), VcsDirtyScopeManager.getInstance(myProject))); } myAuthNotifier.init(); mySvnBranchPointsCalculator = new SvnBranchPointsCalculator(this); if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { checkCommandLineVersion(); } // do one time after project loaded StartupManager.getInstance(myProject).runWhenProjectIsInitialized((DumbAwareRunnable)() -> { postStartup(); // for IDEA, it takes 2 minutes - and anyway this can be done in background, no sense... // once it could be mistaken about copies for 2 minutes on start... /*if (! myMapping.getAllWcInfos().isEmpty()) { invokeRefreshSvnRoots(); return; } ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { myCopiesRefreshManager.getCopiesRefresh().ensureInit(); } }, SvnBundle.message("refreshing.working.copies.roots.progress.text"), true, myProject);*/ }); // not allowed to subscribe to the same topic several times, see subscribing above if (myProject.isDefault()) { busConnection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, myRootsToWorkingCopies); } myLoadedBranchesStorage.activate(); } public static Logger wrapLogger(final Logger logger) { return RareLogger.wrap(logger, Boolean.getBoolean("svn.logger.fairsynch"), new SvnExceptionLogFilter()); } public RootsToWorkingCopies getRootsToWorkingCopies() { return myRootsToWorkingCopies; } public SvnAuthenticationNotifier getAuthNotifier() { return myAuthNotifier; } @Override public void deactivate() { Disposable frameStateListenerDisposable = myFrameStateListenerDisposable; if (frameStateListenerDisposable != null) { myFrameStateListenerDisposable = null; Disposer.dispose(frameStateListenerDisposable); } if (myEntriesFileListener != null) { VirtualFileManager.getInstance().removeVirtualFileListener(myEntriesFileListener); } SvnApplicationSettings.getInstance().svnDeactivated(); if (myCommittedChangesProvider != null) { myCommittedChangesProvider.deactivate(); } if (myChangeListListener != null && !myProject.isDefault()) { ChangeListManager.getInstance(myProject).removeChangeListListener(myChangeListListener); } myRootsToWorkingCopies.clear(); myAuthNotifier.stop(); myAuthNotifier.clear(); mySvnBranchPointsCalculator.deactivate(); mySvnBranchPointsCalculator = null; myLoadedBranchesStorage.deactivate(); } public VcsShowConfirmationOption getAddConfirmation() { return myAddConfirmation; } public VcsShowConfirmationOption getDeleteConfirmation() { return myDeleteConfirmation; } public VcsShowSettingOption getCheckoutOptions() { return myCheckoutOptions; } @Override public EditFileProvider getEditFileProvider() { if (myEditFilesProvider == null) { myEditFilesProvider = new SvnEditFileProvider(this); } return myEditFilesProvider; } @Override @NotNull public ChangeProvider getChangeProvider() { if (myChangeProvider == null) { myChangeProvider = new SvnChangeProvider(this); } return myChangeProvider; } @Override public UpdateEnvironment getIntegrateEnvironment() { if (mySvnIntegrateEnvironment == null) { mySvnIntegrateEnvironment = new SvnIntegrateEnvironment(this); } return mySvnIntegrateEnvironment; } @Override public UpdateEnvironment createUpdateEnvironment() { if (mySvnUpdateEnvironment == null) { mySvnUpdateEnvironment = new SvnUpdateEnvironment(this); } return mySvnUpdateEnvironment; } @NotNull @Override public String getDisplayName() { return VCS_DISPLAY_NAME; } @NotNull @Override public String getShortName() { return "SVN"; } @Override public Configurable getConfigurable() { return null; } @NotNull public SvnConfiguration getSvnConfiguration() { return myConfiguration; } public static SvnVcs getInstance(@NotNull Project project) { return (SvnVcs)ProjectLevelVcsManager.getInstance(project).findVcsByName(VCS_NAME); } @Override @NotNull public CheckinEnvironment createCheckinEnvironment() { if (myCheckinEnvironment == null) { myCheckinEnvironment = new SvnCheckinEnvironment(this); } return myCheckinEnvironment; } @Override @NotNull public RollbackEnvironment createRollbackEnvironment() { if (myRollbackEnvironment == null) { myRollbackEnvironment = new SvnRollbackEnvironment(this); } return myRollbackEnvironment; } @Override public VcsHistoryProvider getVcsHistoryProvider() { // no heavy state, but it would be useful to have place to keep state in -> do not reuse instance return new SvnHistoryProvider(this); } @Override public VcsHistoryProvider getVcsBlockHistoryProvider() { return getVcsHistoryProvider(); } @Override public AnnotationProvider getAnnotationProvider() { if (myAnnotationProvider == null) { myAnnotationProvider = new SvnAnnotationProvider(this); } return new VcsAnnotationCachedProxy(this, myAnnotationProvider); } @Override public DiffProvider getDiffProvider() { if (mySvnDiffProvider == null) { mySvnDiffProvider = new SvnDiffProvider(this); } return mySvnDiffProvider; } @Nullable public PropertyValue getPropertyWithCaching(@NotNull VirtualFile file, @NotNull String propName) throws VcsException { // TODO Method is called in EDT - fix File ioFile = virtualToIoFile(file); PropertyClient client = getFactory(ioFile).createPropertyClient(); return client.getProperty(Target.on(ioFile, Revision.WORKING), propName, false, Revision.WORKING); } @Override public boolean fileExistsInVcs(FilePath path) { File file = path.getIOFile(); try { Status status = getFactory(file).createStatusClient().doStatus(file, false); if (status != null) { return status.is(StatusType.STATUS_ADDED) ? status.isCopied() : !status.is(StatusType.STATUS_UNVERSIONED, StatusType.STATUS_IGNORED, StatusType.STATUS_OBSTRUCTED); } } catch (SvnBindException e) { LOG.info(e); } return false; } @Override public boolean fileIsUnderVcs(@NotNull FilePath path) { VirtualFile file = path.getVirtualFile(); return file != null && SvnStatusUtil.isUnderControl(this, file); } @Nullable public Info getInfo(@NotNull Url url, Revision pegRevision, Revision revision) throws SvnBindException { return getFactory().createInfoClient().doInfo(Target.on(url, pegRevision), revision); } @Nullable public Info getInfo(@NotNull Url url, Revision revision) throws SvnBindException { return getInfo(url, Revision.UNDEFINED, revision); } @Nullable public Info getInfo(@NotNull final VirtualFile file) { return getInfo(virtualToIoFile(file)); } @Nullable public Info getInfo(@NotNull String path) { return getInfo(new File(path)); } @Nullable public Info getInfo(@NotNull File ioFile) { return getInfo(ioFile, Revision.UNDEFINED); } public void collectInfo(@NotNull Collection<File> files, @Nullable InfoConsumer handler) { File first = getFirstItem(files); if (first != null) { try { getFactory(first).createInfoClient().doInfo(files, handler); } catch (SvnBindException e) { handleInfoException(e); } } } @Nullable public Info getInfo(@NotNull File ioFile, @NotNull Revision revision) { Info result = null; try { result = getFactory(ioFile).createInfoClient().doInfo(ioFile, revision); } catch (SvnBindException e) { handleInfoException(e); } return result; } private void handleInfoException(@NotNull SvnBindException e) { if (!myLogExceptions || SvnUtil.isUnversionedOrNotFound(e) || // do not log working copy format vs client version inconsistencies as errors e.contains(ErrorCode.WC_UNSUPPORTED_FORMAT) || e.contains(ErrorCode.WC_UPGRADE_REQUIRED)) { LOG.debug(e); } else { LOG.error(e); } } @NotNull public WorkingCopyFormat getWorkingCopyFormat(@NotNull File ioFile) { return getWorkingCopyFormat(ioFile, true); } @NotNull public WorkingCopyFormat getWorkingCopyFormat(@NotNull File ioFile, boolean useMapping) { WorkingCopyFormat format = WorkingCopyFormat.UNKNOWN; if (useMapping) { RootUrlInfo rootInfo = getSvnFileUrlMapping().getWcRootForFilePath(getFilePath(ioFile)); format = rootInfo != null ? rootInfo.getFormat() : WorkingCopyFormat.UNKNOWN; } return WorkingCopyFormat.UNKNOWN.equals(format) ? SvnFormatSelector.findRootAndGetFormat(ioFile) : format; } public boolean isWcRoot(@NotNull FilePath filePath) { boolean isWcRoot = false; VirtualFile file = filePath.getVirtualFile(); WorkingCopy wcRoot = file != null ? myRootsToWorkingCopies.getWcRoot(file) : null; if (wcRoot != null) { isWcRoot = wcRoot.getFile().getAbsolutePath().equals(filePath.getPath()); } return isWcRoot; } @Override public FileStatus[] getProvidedStatuses() { return new FileStatus[]{SvnFileStatus.EXTERNAL, SvnFileStatus.OBSTRUCTED, SvnFileStatus.REPLACED}; } @Override @NotNull public CommittedChangesProvider<SvnChangeList, ChangeBrowserSettings> getCommittedChangesProvider() { if (myCommittedChangesProvider == null) { myCommittedChangesProvider = new SvnCommittedChangesProvider(this); } return myCommittedChangesProvider; } @Nullable @Override public VcsRevisionNumber parseRevisionNumber(final String revisionNumberString) { final Revision revision = Revision.parse(revisionNumberString); if (revision.equals(Revision.UNDEFINED)) { return null; } return new SvnRevisionNumber(revision); } @Override public String getRevisionPattern() { return ourIntegerPattern; } @Override public boolean isVersionedDirectory(final VirtualFile dir) { return SvnUtil.seemsLikeVersionedDir(dir); } @NotNull public SvnFileUrlMapping getSvnFileUrlMapping() { if (myMapping == null) { myMapping = SvnFileUrlMappingImpl.getInstance(myProject); } return myMapping; } /** * Returns real working copies roots - if there is <Project Root> -> Subversion setting, * and there is one working copy, will return one root */ public List<WCInfo> getAllWcInfos() { final SvnFileUrlMapping urlMapping = getSvnFileUrlMapping(); final List<RootUrlInfo> infoList = urlMapping.getAllWcInfos(); final List<WCInfo> infos = new ArrayList<>(); for (RootUrlInfo info : infoList) { final File file = info.getIoFile(); infos.add(new WCInfo(info, SvnUtil.isWorkingCopyRoot(file), SvnUtil.getDepth(this, file))); } return infos; } public List<WCInfo> getWcInfosWithErrors() { List<WCInfo> result = new ArrayList<>(getAllWcInfos()); for (RootUrlInfo info : getSvnFileUrlMapping().getErrorRoots()) { result.add(new WCInfo(info, SvnUtil.isWorkingCopyRoot(info.getIoFile()), Depth.UNKNOWN)); } return result; } @Override public RootsConvertor getCustomConvertor() { if (myProject.isDefault()) return null; return getSvnFileUrlMapping(); } @Override public MergeProvider getMergeProvider() { if (myMergeProvider == null) { myMergeProvider = new SvnMergeProvider(myProject); } return myMergeProvider; } @Override public boolean allowsNestedRoots() { return true; } @NotNull @Override public <S> List<S> filterUniqueRoots(@NotNull List<S> in, @NotNull Function<S, VirtualFile> convertor) { if (in.size() <= 1) return in; return Registry.is("svn.filter.unique.roots.by.url") ? filterUniqueByUrl(in, convertor) : filterUniqueByWorkingCopy(in, convertor); } @NotNull private <S> List<S> filterUniqueByUrl(@NotNull List<S> in, @NotNull Function<S, VirtualFile> convertor) { List<MyPair<S>> infos = newArrayList(); List<S> notMatched = newArrayList(); for (S s : in) { VirtualFile vf = convertor.apply(s); if (vf == null) continue; File ioFile = virtualToIoFile(vf); Url url = getSvnFileUrlMapping().getUrlForFile(ioFile); if (url == null) { url = SvnUtil.getUrl(this, ioFile); if (url == null) { notMatched.add(s); continue; } } infos.add(new MyPair<>(vf, url, s)); } List<MyPair<S>> filtered = new UniqueRootsFilter().filter(infos); List<S> converted = map(filtered, MyPair::getSrc); // potential bug is here: order is not kept. but seems it only occurs for cases where result is sorted after filtering so ok return concat(converted, notMatched); } @NotNull private <S> List<S> filterUniqueByWorkingCopy(@NotNull List<S> in, @NotNull Function<S, VirtualFile> convertor) { Map<VirtualFile, S> filesMap = StreamEx.of(in).mapToEntry(convertor, identity()).distinctKeys().toMap(); Map<VirtualFile, List<VirtualFile>> byWorkingCopy = StreamEx.of(filesMap.keySet()) .mapToEntry( file -> { RootUrlInfo wcRoot = getSvnFileUrlMapping().getWcRootForFilePath(getFilePath(file)); return wcRoot != null ? wcRoot.getVirtualFile() : SvnUtil.getWorkingCopyRoot(file); }, identity()) .nonNullKeys() .grouping(); return EntryStream.of(byWorkingCopy) .flatMapToValue((workingCopy, files) -> { FilterDescendantVirtualFiles.filter(files); return files.stream(); }) .values() .map(filesMap::get) .toList(); } private static class MyPair<T> implements RootUrlPair { @NotNull private final VirtualFile myFile; @NotNull private final Url myUrl; private final T mySrc; private MyPair(@NotNull VirtualFile file, @NotNull Url url, T src) { myFile = file; myUrl = url; mySrc = src; } public T getSrc() { return mySrc; } @NotNull @Override public VirtualFile getVirtualFile() { return myFile; } @NotNull @Override public Url getUrl() { return myUrl; } } private static class MyFrameStateListener implements FrameStateListener { private final ChangeListManager myClManager; private final VcsDirtyScopeManager myDirtyScopeManager; private MyFrameStateListener(ChangeListManager clManager, VcsDirtyScopeManager dirtyScopeManager) { myClManager = clManager; myDirtyScopeManager = dirtyScopeManager; } @Override public void onFrameActivated() { final List<VirtualFile> folders = ((ChangeListManagerImpl)myClManager).getLockedFolders(); if (!folders.isEmpty()) { myDirtyScopeManager.filesDirty(null, folders); } } } public static VcsKey getKey() { return ourKey; } @Override public boolean isVcsBackgroundOperationsAllowed(@NotNull VirtualFile root) { ClientFactory factory = getFactory(virtualToIoFile(root)); return ThreeState.YES.equals(myAuthNotifier.isAuthenticatedFor(root, factory == cmdClientFactory ? factory : null)); } public SvnBranchPointsCalculator getSvnBranchPointsCalculator() { return mySvnBranchPointsCalculator; } @Override public boolean areDirectoriesVersionedItems() { return true; } @Override public CheckoutProvider getCheckoutProvider() { if (myCheckoutProvider == null) { myCheckoutProvider = new SvnCheckoutProvider(); } return myCheckoutProvider; } /** * Detects appropriate client factory based on project root directory working copy format. * <p> * Try to avoid usages of this method (for now) as it could not correctly for all cases * detect svn 1.8 working copy format to guarantee command line client. * <p> * For instance, when working copies of several formats are presented in project * (though it seems to be rather unlikely case). * * @return */ @NotNull public ClientFactory getFactory() { return cmdClientFactory; } @SuppressWarnings("unused") @NotNull public ClientFactory getFactory(@NotNull WorkingCopyFormat format) { return cmdClientFactory; } @SuppressWarnings("unused") @NotNull public ClientFactory getFactory(@NotNull File file) { return cmdClientFactory; } @SuppressWarnings("unused") @NotNull public ClientFactory getFactory(@NotNull File file, boolean useMapping) { return cmdClientFactory; } @NotNull public ClientFactory getFactory(@NotNull Target target) { return target.isFile() ? getFactory(target.getFile()) : getFactory(); } @NotNull public ClientFactory getFactoryFromSettings() { return cmdClientFactory; } @NotNull public ClientFactory getCommandLineFactory() { return cmdClientFactory; } @NotNull public WorkingCopyFormat getLowestSupportedFormatForCommandLine() { WorkingCopyFormat result; try { result = WorkingCopyFormat.from(CmdVersionClient.parseVersion(Registry.stringValue("svn.lowest.supported.format.for.command.line"))); } catch (SvnBindException ignore) { result = WorkingCopyFormat.ONE_DOT_SEVEN; } return result; } public boolean isSupportedByCommandLine(@NotNull WorkingCopyFormat format) { return format.isOrGreater(getLowestSupportedFormatForCommandLine()); } public boolean is16SupportedByCommandLine() { return isSupportedByCommandLine(WorkingCopyFormat.ONE_DOT_SIX); } }
msebire/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java
Java
apache-2.0
31,125
/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.aeron.driver; import org.agrona.DirectBuffer; import java.io.File; /** * Validate if the driver should terminate based on the provided token. */ @FunctionalInterface public interface TerminationValidator { /** * Should the given termination request be considered valid or not. * * @param aeronDir of the driver. * @param tokenBuffer of the token in the request. * @param tokenOffset of the token within the buffer. * @param tokenLength of the token within the buffer. * @return true if request is to be considered valid and the driver termination hook should be run or false if not. */ boolean allowTermination(File aeronDir, DirectBuffer tokenBuffer, int tokenOffset, int tokenLength); }
EvilMcJerkface/Aeron
aeron-driver/src/main/java/io/aeron/driver/TerminationValidator.java
Java
apache-2.0
1,361
/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.cglib.transform; import net.sf.cglib.core.Constants; import org.objectweb.asm.*; public class MethodVisitorTee extends MethodVisitor { private final MethodVisitor mv1; private final MethodVisitor mv2; public MethodVisitorTee(MethodVisitor mv1, MethodVisitor mv2) { super(Constants.ASM_API); this.mv1 = mv1; this.mv2 = mv2; } public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { mv1.visitFrame(type, nLocal, local, nStack, stack); mv2.visitFrame(type, nLocal, local, nStack, stack); } public AnnotationVisitor visitAnnotationDefault() { return AnnotationVisitorTee.getInstance(mv1.visitAnnotationDefault(), mv2.visitAnnotationDefault()); } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitAnnotation(desc, visible), mv2.visitAnnotation(desc, visible)); } public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitParameterAnnotation(parameter, desc, visible), mv2.visitParameterAnnotation(parameter, desc, visible)); } public void visitAttribute(Attribute attr) { mv1.visitAttribute(attr); mv2.visitAttribute(attr); } public void visitCode() { mv1.visitCode(); mv2.visitCode(); } public void visitInsn(int opcode) { mv1.visitInsn(opcode); mv2.visitInsn(opcode); } public void visitIntInsn(int opcode, int operand) { mv1.visitIntInsn(opcode, operand); mv2.visitIntInsn(opcode, operand); } public void visitVarInsn(int opcode, int var) { mv1.visitVarInsn(opcode, var); mv2.visitVarInsn(opcode, var); } public void visitTypeInsn(int opcode, String desc) { mv1.visitTypeInsn(opcode, desc); mv2.visitTypeInsn(opcode, desc); } public void visitFieldInsn(int opcode, String owner, String name, String desc) { mv1.visitFieldInsn(opcode, owner, name, desc); mv2.visitFieldInsn(opcode, owner, name, desc); } public void visitMethodInsn(int opcode, String owner, String name, String desc) { mv1.visitMethodInsn(opcode, owner, name, desc); mv2.visitMethodInsn(opcode, owner, name, desc); } public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { mv1.visitMethodInsn(opcode, owner, name, desc, itf); mv2.visitMethodInsn(opcode, owner, name, desc, itf); } public void visitJumpInsn(int opcode, Label label) { mv1.visitJumpInsn(opcode, label); mv2.visitJumpInsn(opcode, label); } public void visitLabel(Label label) { mv1.visitLabel(label); mv2.visitLabel(label); } public void visitLdcInsn(Object cst) { mv1.visitLdcInsn(cst); mv2.visitLdcInsn(cst); } public void visitIincInsn(int var, int increment) { mv1.visitIincInsn(var, increment); mv2.visitIincInsn(var, increment); } public void visitTableSwitchInsn(int min, int max, Label dflt, Label labels[]) { mv1.visitTableSwitchInsn(min, max, dflt, labels); mv2.visitTableSwitchInsn(min, max, dflt, labels); } public void visitLookupSwitchInsn(Label dflt, int keys[], Label labels[]) { mv1.visitLookupSwitchInsn(dflt, keys, labels); mv2.visitLookupSwitchInsn(dflt, keys, labels); } public void visitMultiANewArrayInsn(String desc, int dims) { mv1.visitMultiANewArrayInsn(desc, dims); mv2.visitMultiANewArrayInsn(desc, dims); } public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { mv1.visitTryCatchBlock(start, end, handler, type); mv2.visitTryCatchBlock(start, end, handler, type); } public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { mv1.visitLocalVariable(name, desc, signature, start, end, index); mv2.visitLocalVariable(name, desc, signature, start, end, index); } public void visitLineNumber(int line, Label start) { mv1.visitLineNumber(line, start); mv2.visitLineNumber(line, start); } public void visitMaxs(int maxStack, int maxLocals) { mv1.visitMaxs(maxStack, maxLocals); mv2.visitMaxs(maxStack, maxLocals); } public void visitEnd() { mv1.visitEnd(); mv2.visitEnd(); } public void visitParameter(String name, int access) { mv1.visitParameter(name, access); mv2.visitParameter(name, access); } public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitTypeAnnotation(typeRef, typePath, desc, visible), mv2.visitTypeAnnotation(typeRef, typePath, desc, visible)); } public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { mv1.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); mv2.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); } public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitInsnAnnotation(typeRef, typePath, desc, visible), mv2.visitInsnAnnotation(typeRef, typePath, desc, visible)); } public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitTryCatchAnnotation(typeRef, typePath, desc, visible), mv2.visitTryCatchAnnotation(typeRef, typePath, desc, visible)); } public AnnotationVisitor visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitLocalVariableAnnotation(typeRef, typePath, start, end, index, desc, visible), mv2.visitLocalVariableAnnotation(typeRef, typePath, start, end, index, desc, visible)); } }
mcculls/cglib
cglib/src/main/java/net/sf/cglib/transform/MethodVisitorTee.java
Java
apache-2.0
7,380
package org.quicktheories.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.List; import java.util.function.BiPredicate; import org.mockito.ArgumentCaptor; import org.quicktheories.QuickTheory; import org.quicktheories.api.AsString; import org.quicktheories.api.Pair; import org.quicktheories.api.Predicate3; import org.quicktheories.api.Predicate4; import org.quicktheories.api.Tuple3; import org.quicktheories.api.Tuple4; import org.quicktheories.core.Configuration; import org.quicktheories.core.NoGuidance; import org.quicktheories.core.Reporter; import org.quicktheories.core.Strategy; public class QTTester { private Reporter r = mock(Reporter.class); public QuickTheory qt(long seed) { Strategy s = new Strategy(Configuration.defaultPRNG(seed), 100, 0, 10000, 10, r, prng -> new NoGuidance()); return org.quicktheories.QuickTheory.qt(() -> s); } public QuickTheory qt() { return qt(0); } public void notFalsified() { verify(r, never()).falsification(anyLong(), anyInt(), any(Object.class), any(List.class), any()); } public void isFalsified() { verify(r, times(1)).falsification(anyLong(), anyInt(), any(Object.class), any(List.class), any()); } public void isFalsifiedByException() { verify(r, times(1)).falsification(anyLong(), anyInt(), any(Object.class), any(Throwable.class), any(List.class), any()); } public void reportedSeedIs(long seed) { verify(r, times(1)).falsification(eq(seed), anyInt(), any(Object.class), any(List.class), any()); } @SuppressWarnings("unchecked") public <T> T smallestFalsifiedValue() { ArgumentCaptor<T> value = (ArgumentCaptor<T>) ArgumentCaptor .forClass(Object.class); verify(r, times(1)).falsification(anyLong(), anyInt(), value.capture(), any(List.class), any()); return value.getValue(); } public void isExahusted() { verify(r, times(1)).valuesExhausted(anyInt()); } @SuppressWarnings({ "rawtypes", "unchecked" }) public <A, B> void smallestValueMatches(BiPredicate<A, B> p) { ArgumentCaptor value = ArgumentCaptor.forClass(Object.class); verify(r, times(1)).falsification(anyLong(), anyInt(), value.capture(), any(List.class), any()); Pair<A, B> v = (Pair<A, B>) value.getValue(); if (!p.test(v._1, v._2)) { throw new AssertionError(v.toString() + " does not satisfy expectations"); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public <A, B, C> void smallestValueMatches(Predicate3<A, B, C> p) { ArgumentCaptor value = ArgumentCaptor.forClass(Object.class); verify(r, times(1)).falsification(anyLong(), anyInt(), value.capture(), any(List.class), any()); Tuple3<A, B, C> v = (Tuple3<A, B, C>) value.getValue(); if (!p.test(v._1, v._2, v._3)) { throw new AssertionError(v.toString() + " does not satisfy expectations"); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public <A, B, C, D> void smallestValueMatches(Predicate4<A, B, C, D> p) { ArgumentCaptor value = ArgumentCaptor.forClass(Object.class); verify(r, times(1)).falsification(anyLong(), anyInt(), value.capture(), any(List.class), any()); Tuple4<A, B, C, D> v = (Tuple4<A, B, C, D>) value.getValue(); if (!p.test(v._1, v._2, v._3, v._4)) { throw new AssertionError(v.toString() + " does not satisfy expectations"); } } @SuppressWarnings({ "rawtypes"}) public void falsificationContainsText(String string) { ArgumentCaptor value = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<AsString> asString = ArgumentCaptor.forClass(AsString.class); verify(r, times(1)).falsification(anyLong(), anyInt(), value.capture(), any(List.class), asString.capture()); assertThat(asString.getValue().asString(value.getValue())).contains(string); } }
NCR-CoDE/QuickTheories
core/src/test/java/org/quicktheories/impl/QTTester.java
Java
apache-2.0
4,247
/* * Copyright 2010 JBoss 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 org.kie.conf; /** * An Enum for EqualityBehavior option. * * drools.equalityBehavior = &lt;identity|equality&gt; * * DEFAULT = identity */ public enum EqualityBehaviorOption implements SingleValueKieBaseOption { IDENTITY, EQUALITY; /** * The property name for the sequential mode option */ public static final String PROPERTY_NAME = "drools.equalityBehavior"; /** * {@inheritDoc} */ public String getPropertyName() { return PROPERTY_NAME; } }
psiroky/droolsjbpm-knowledge
kie-api/src/main/java/org/kie/conf/EqualityBehaviorOption.java
Java
apache-2.0
1,128
/* * Copyright 2013 Websquared, 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 org.fastcatsearch.ir.field; import org.fastcatsearch.ir.io.IOUtil; import org.fastcatsearch.ir.settings.FieldSetting; import org.fastcatsearch.ir.settings.FieldSetting.Type; /** * 하위 묶음문서갯수를 나타낸다. * @author swsong * */ public class BundleSizeField { public static final String fieldName = Type._BUNDLESIZE.toString(); public static final int fieldNumber = -4; public static final int fieldSize = IOUtil.SIZE_OF_INT; public static final FieldSetting field = new FieldSetting(fieldName, null, Type._BUNDLESIZE); }
fastcat-co/fastcatsearch
core/src/main/java/org/fastcatsearch/ir/field/BundleSizeField.java
Java
apache-2.0
1,158
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.01.16 at 12:57:08 PM IST // package org.akomantoso.schema.v3.csd13; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.namespace.QName; /** * * <pre> * &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;type xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;Complex&lt;/type&gt; * </pre> * * <pre> * &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;name xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;debateBodyType&lt;/name&gt; * </pre> * * <pre> * &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;comment xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; * the type debateBodyType specifies a content model of the main hierarchy of a debate&lt;/comment&gt; * </pre> * * * <p>Java class for debateBodyType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="debateBodyType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence maxOccurs="unbounded"> * &lt;group ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13}speechSection"/> * &lt;/sequence> * &lt;attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13}coreopt"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "debateBodyType", propOrder = { "administrationOfOathOrRollCallOrPrayers" }) public class DebateBodyType { @XmlElementRefs({ @XmlElementRef(name = "debateSection", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = DebateSection.class, required = false), @XmlElementRef(name = "personalStatements", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "petitions", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "pointOfOrder", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "rollCall", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "nationalInterest", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "adjournment", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "prayers", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "questions", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "address", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "writtenStatements", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "papers", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "noticesOfMotion", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "oralStatements", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "communication", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "resolutions", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "proceduralMotions", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "administrationOfOath", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "ministerialStatements", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false), @XmlElementRef(name = "declarationOfVote", namespace = "http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13", type = JAXBElement.class, required = false) }) protected List<Object> administrationOfOathOrRollCallOrPrayers; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "space", namespace = "http://www.w3.org/XML/1998/namespace") protected String space; @XmlAttribute(name = "class") protected String clazz; @XmlAttribute(name = "style") protected String style; @XmlAttribute(name = "title") protected String titleAttr; @XmlAttribute(name = "alternativeTo") @XmlSchemaType(name = "anyURI") protected String alternativeTo; @XmlAttribute(name = "eId") protected String eId; @XmlAttribute(name = "wId") protected String wId; @XmlAttribute(name = "GUID") protected String guid; @XmlAttribute(name = "refersTo") protected List<String> refersTo; @XmlAttribute(name = "status") protected StatusType status; @XmlAttribute(name = "period") @XmlSchemaType(name = "anyURI") protected String period; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the administrationOfOathOrRollCallOrPrayers property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the administrationOfOathOrRollCallOrPrayers property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdministrationOfOathOrRollCallOrPrayers().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DebateSection } * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * {@link JAXBElement }{@code <}{@link Althierarchy }{@code >} * * */ public List<Object> getAdministrationOfOathOrRollCallOrPrayers() { if (administrationOfOathOrRollCallOrPrayers == null) { administrationOfOathOrRollCallOrPrayers = new ArrayList<Object>(); } return this.administrationOfOathOrRollCallOrPrayers; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the space property. * * @return * possible object is * {@link String } * */ public String getSpace() { return space; } /** * Sets the value of the space property. * * @param value * allowed object is * {@link String } * */ public void setSpace(String value) { this.space = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the style property. * * @return * possible object is * {@link String } * */ public String getStyle() { return style; } /** * Sets the value of the style property. * * @param value * allowed object is * {@link String } * */ public void setStyle(String value) { this.style = value; } /** * Gets the value of the titleAttr property. * * @return * possible object is * {@link String } * */ public String getTitleAttr() { return titleAttr; } /** * Sets the value of the titleAttr property. * * @param value * allowed object is * {@link String } * */ public void setTitleAttr(String value) { this.titleAttr = value; } /** * Gets the value of the alternativeTo property. * * @return * possible object is * {@link String } * */ public String getAlternativeTo() { return alternativeTo; } /** * Sets the value of the alternativeTo property. * * @param value * allowed object is * {@link String } * */ public void setAlternativeTo(String value) { this.alternativeTo = value; } /** * Gets the value of the eId property. * * @return * possible object is * {@link String } * */ public String getEId() { return eId; } /** * Sets the value of the eId property. * * @param value * allowed object is * {@link String } * */ public void setEId(String value) { this.eId = value; } /** * Gets the value of the wId property. * * @return * possible object is * {@link String } * */ public String getWId() { return wId; } /** * Sets the value of the wId property. * * @param value * allowed object is * {@link String } * */ public void setWId(String value) { this.wId = value; } /** * Gets the value of the guid property. * * @return * possible object is * {@link String } * */ public String getGUID() { return guid; } /** * Sets the value of the guid property. * * @param value * allowed object is * {@link String } * */ public void setGUID(String value) { this.guid = value; } /** * Gets the value of the refersTo property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the refersTo property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRefersTo().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getRefersTo() { if (refersTo == null) { refersTo = new ArrayList<String>(); } return this.refersTo; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusType } * */ public StatusType getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusType } * */ public void setStatus(StatusType value) { this.status = value; } /** * Gets the value of the period property. * * @return * possible object is * {@link String } * */ public String getPeriod() { return period; } /** * Sets the value of the period property. * * @param value * allowed object is * {@link String } * */ public void setPeriod(String value) { this.period = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
kohsah/akomantoso-lib
src/main/java/org/akomantoso/schema/v3/csd13/DebateBodyType.java
Java
apache-2.0
15,515
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.coverage; import com.intellij.openapi.options.CompositeConfigurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.util.List; public class CoverageOptionsConfigurable extends CompositeConfigurable<CoverageOptions> implements SearchableConfigurable { private CoverageOptionsPanel myPanel; private final CoverageOptionsProvider myManager; private final Project myProject; public CoverageOptionsConfigurable(CoverageOptionsProvider manager, Project project) { myManager = manager; myProject = project; } @NotNull @Override public String getId() { return "coverage"; } @Nls @Override public String getDisplayName() { return "Coverage"; } @Override public String getHelpTopic() { return "reference.project.settings.coverage"; } @Override public JComponent createComponent() { myPanel = new CoverageOptionsPanel(); List<JComponent> extensionPanels = collectExtensionOptionsComponents(); if (extensionPanels.size() > 0) { return createCompositePanel(extensionPanels); } else { return myPanel.myWholePanel; } } private List<JComponent> collectExtensionOptionsComponents() { List<JComponent> additionalPanels = ContainerUtil.newArrayList(); for (CoverageOptions coverageOptions : getConfigurables()) { additionalPanels.add(coverageOptions.createComponent()); } return additionalPanels; } private JComponent createCompositePanel(List<JComponent> additionalPanels) { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.NORTHWEST; c.gridx = 0; c.gridy = GridBagConstraints.RELATIVE; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; panel.add(myPanel.myWholePanel, c); for (JComponent p : additionalPanels) { panel.add(p, c); } c.fill = GridBagConstraints.BOTH; c.weightx = 1; c.weighty = 1; panel.add(Box.createVerticalBox(), c); return panel; } @NotNull @Override protected List<CoverageOptions> createConfigurables() { return CoverageOptions.EP_NAME.getExtensionList(myProject); } @Override public boolean isModified() { if (myManager.getOptionToReplace() != getSelectedValue()) { return true; } if (myManager.activateViewOnRun() != myPanel.myActivateCoverageViewCB.isSelected()) { return true; } return super.isModified(); } @Override public void apply() throws ConfigurationException { myManager.setOptionsToReplace(getSelectedValue()); myManager.setActivateViewOnRun(myPanel.myActivateCoverageViewCB.isSelected()); super.apply(); } private int getSelectedValue() { if (myPanel.myReplaceRB.isSelected()) { return 0; } else if (myPanel.myAddRB.isSelected()) { return 1; } else if (myPanel.myDoNotApplyRB.isSelected()) { return 2; } return 3; } @Override public void reset() { final int addOrReplace = myManager.getOptionToReplace(); switch (addOrReplace) { case 0: myPanel.myReplaceRB.setSelected(true); break; case 1: myPanel.myAddRB.setSelected(true); break; case 2: myPanel.myDoNotApplyRB.setSelected(true); break; default: myPanel.myShowOptionsRB.setSelected(true); } myPanel.myActivateCoverageViewCB.setSelected(myManager.activateViewOnRun()); super.reset(); } @Override public void disposeUIResources() { myPanel = null; super.disposeUIResources(); } private static class CoverageOptionsPanel { private JRadioButton myShowOptionsRB; private JRadioButton myReplaceRB; private JRadioButton myAddRB; private JRadioButton myDoNotApplyRB; private JPanel myWholePanel; private JCheckBox myActivateCoverageViewCB; } }
msebire/intellij-community
plugins/coverage-common/src/com/intellij/coverage/CoverageOptionsConfigurable.java
Java
apache-2.0
4,345
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.flowable.rest.service.api.runtime.task; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.flowable.common.rest.util.DateToStringSerializer; import org.flowable.rest.service.api.engine.variable.RestVariable; import org.flowable.task.api.DelegationState; import org.flowable.task.api.Task; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.swagger.annotations.ApiModelProperty; /** * @author Frederik Heremans */ public class TaskResponse { protected String id; protected String url; protected String owner; protected String assignee; protected String delegationState; protected String name; protected String description; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date createTime; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date dueDate; protected int priority; protected boolean suspended; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date claimTime; protected String taskDefinitionKey; protected String scopeDefinitionId; protected String scopeId; protected String scopeType; protected String tenantId; protected String category; protected String formKey; // References to other resources protected String parentTaskId; protected String parentTaskUrl; protected String executionId; protected String executionUrl; protected String processInstanceId; protected String processInstanceUrl; protected String processDefinitionId; protected String processDefinitionUrl; protected List<RestVariable> variables = new ArrayList<>(); public TaskResponse() { } public TaskResponse(Task task) { setId(task.getId()); setOwner(task.getOwner()); setAssignee(task.getAssignee()); setDelegationState(getDelegationStateString(task.getDelegationState())); setName(task.getName()); setDescription(task.getDescription()); setCreateTime(task.getCreateTime()); setDueDate(task.getDueDate()); setPriority(task.getPriority()); setSuspended(task.isSuspended()); setClaimTime(task.getClaimTime()); setTaskDefinitionKey(task.getTaskDefinitionKey()); setParentTaskId(task.getParentTaskId()); setExecutionId(task.getExecutionId()); setCategory(task.getCategory()); setProcessInstanceId(task.getProcessInstanceId()); setProcessDefinitionId(task.getProcessDefinitionId()); setScopeDefinitionId(task.getScopeDefinitionId()); setScopeId(task.getScopeId()); setScopeType(task.getScopeType()); setTenantId(task.getTenantId()); setFormKey(task.getFormKey()); } protected String getDelegationStateString(DelegationState state) { String result = null; if (state != null) { result = state.toString().toLowerCase(); } return result; } @ApiModelProperty(example = "8") public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "http://localhost:8182/runtime/tasks/8") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "owner") public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } @ApiModelProperty(example = "kermit") public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } @ApiModelProperty(example = "pending", value = "Delegation-state of the task, can be null, \"pending\" or \"resolved\".") public String getDelegationState() { return delegationState; } public void setDelegationState(String delegationState) { this.delegationState = delegationState; } @ApiModelProperty(example = "My task") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "Task description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ApiModelProperty(example = "2018-04-17T10:17:43.902+0000") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "2018-04-17T10:17:43.902+0000") public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @ApiModelProperty(example = "50") public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public boolean isSuspended() { return suspended; } public void setSuspended(boolean suspended) { this.suspended = suspended; } @ApiModelProperty(example = "2018-04-17T10:17:43.902+0000", dataType = "string") public Date getClaimTime() { return claimTime; } public void setClaimTime(Date claimTime) { this.claimTime = claimTime; } @ApiModelProperty(example = "theTask") public String getTaskDefinitionKey() { return taskDefinitionKey; } public void setTaskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; } @ApiModelProperty(example = "null") public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } @ApiModelProperty(example = "null") public String getParentTaskUrl() { return parentTaskUrl; } public void setParentTaskUrl(String parentTaskUrl) { this.parentTaskUrl = parentTaskUrl; } @ApiModelProperty(example = "5") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "http://localhost:8182/runtime/executions/5") public String getExecutionUrl() { return executionUrl; } public void setCategory(String category) { this.category = category; } @ApiModelProperty(example = "ExampleCategory") public String getCategory() { return category; } public void setExecutionUrl(String executionUrl) { this.executionUrl = executionUrl; } @ApiModelProperty(example = "5") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "http://localhost:8182/runtime/process-instances/5") public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(example = "oneTaskProcess%3A1%3A4") public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @ApiModelProperty(example = "http://localhost:8182/runtime/process-definitions/oneTaskProcess%3A1%3A4") public String getProcessDefinitionUrl() { return processDefinitionUrl; } public void setProcessDefinitionUrl(String processDefinitionUrl) { this.processDefinitionUrl = processDefinitionUrl; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "12") public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @ApiModelProperty(example = "14") public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } @ApiModelProperty(example = "cmmn") public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @ApiModelProperty(example = "someTenantId") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } }
lsmall/flowable-engine
modules/flowable-rest/src/main/java/org/flowable/rest/service/api/runtime/task/TaskResponse.java
Java
apache-2.0
9,866
/* * Copyright (C) 2015-2017 NS Solutions Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.htmlhifive.pitalium.it.assertion_old.scroll; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.htmlhifive.pitalium.core.PtlTestBase; import com.htmlhifive.pitalium.core.config.ExecMode; import com.htmlhifive.pitalium.core.config.PtlTestConfig; import com.htmlhifive.pitalium.core.model.CompareTarget; import com.htmlhifive.pitalium.core.model.DomSelector; import com.htmlhifive.pitalium.core.model.ScreenArea; import com.htmlhifive.pitalium.core.model.SelectorType; import com.htmlhifive.pitalium.core.selenium.PtlWebDriverWait; /** * 部分スクロール内Excludeありのスクリーンショットが正しくとれているかのテスト */ public class CompareScrollPartWithExcludeTest extends PtlTestBase { private static final PtlTestConfig config = PtlTestConfig.getInstance(); private static final String BASE_URL = config.getTestAppConfig().getBaseUrl(); @Rule public ExpectedException expectedException = ExpectedException.none(); /** * excludeを指定しないとdiffが出ることの確認のテスト<br> * 前提条件:なし<br> * 実行環境:IE7~11/FireFox/Chrome/Android 2.3, 4.0, 4.4, 5.1/iOS 8.1, 8.3<br> * 期待結果:assertViewでテストが失敗する */ @Test public void checkFailure() { driver.get(BASE_URL); PtlWebDriverWait wait = new PtlWebDriverWait(driver, 30); wait.untilLoad(); if (PtlTestConfig.getInstance().getEnvironment().getExecMode() == ExecMode.RUN_TEST) { driver.executeJavaScript("document.getElementById('banana').innerHTML='バナ'"); expectedException.expect(AssertionError.class); } DomSelector tbodySelector = new DomSelector(SelectorType.CSS_SELECTOR, "#table-scroll tbody"); ScreenArea tbodyScreenArea = ScreenArea.of(tbodySelector.getType(), tbodySelector.getValue()); CompareTarget[] targets = { new CompareTarget(tbodyScreenArea, null, true, true) }; assertionView.assertView("DiffTbody", targets); } /** * 1つのExclude要素を指定してスクリーンショットがとれるかのテスト<br> * 実行環境:IE7~11/FireFox/Chrome/Android 2.3, 4.0, 4.4/iOS 8.1<br> * 期待結果:テストに成功する。 */ @Test public void takeSinglePartExcludeTest() { driver.get(BASE_URL); PtlWebDriverWait wait = new PtlWebDriverWait(driver, 30); wait.untilLoad(); if (PtlTestConfig.getInstance().getEnvironment().getExecMode() == ExecMode.RUN_TEST) { driver.executeJavaScript("document.getElementById('banana').innerHTML='バナ'"); } DomSelector tbodySelector = new DomSelector(SelectorType.CSS_SELECTOR, "#table-scroll tbody"); ScreenArea tbodyScreenArea = ScreenArea.of(tbodySelector.getType(), tbodySelector.getValue()); ScreenArea excludeArea = ScreenArea.of(SelectorType.ID, "banana"); CompareTarget[] targets = { new CompareTarget(tbodyScreenArea, new ScreenArea[] { excludeArea }, true, true) }; assertionView.assertView("SingleExcludeScreenshot", targets); } /** * スクロールしないと見えない要素をExclude指定してスクリーンショットがとれるかのテスト<br> * 実行環境:IE7~11/FireFox/Chrome/Android 2.3, 4.0, 4.4/iOS 8.1<br> * 期待結果:テストに成功する。 */ @Test public void takeInvisiblePartExcludeTest() { driver.get(BASE_URL); PtlWebDriverWait wait = new PtlWebDriverWait(driver, 30); wait.untilLoad(); if (PtlTestConfig.getInstance().getEnvironment().getExecMode() == ExecMode.RUN_TEST) { driver.executeJavaScript("document.getElementById('banana').innerHTML='バナ'"); driver.executeJavaScript("document.getElementById('grape').innerHTML='ぶど'"); driver.executeJavaScript("document.getElementById('pineapple').innerHTML='パイナップ'"); } DomSelector tbodySelector = new DomSelector(SelectorType.CSS_SELECTOR, "#table-scroll tbody"); ScreenArea tbodyScreenArea = ScreenArea.of(tbodySelector.getType(), tbodySelector.getValue()); ScreenArea excludeArea1 = ScreenArea.of(SelectorType.ID, "banana"); ScreenArea excludeArea2 = ScreenArea.of(SelectorType.ID, "grape"); ScreenArea excludeArea3 = ScreenArea.of(SelectorType.ID, "pineapple"); CompareTarget[] targets = { new CompareTarget(tbodyScreenArea, new ScreenArea[] { excludeArea1, excludeArea2, excludeArea3 }, true, true) }; assertionView.assertView("SingleExcludeScreenshot", targets); } }
hifive/hifive-pitalium
pitalium/src/test/java/com/htmlhifive/pitalium/it/assertion_old/scroll/CompareScrollPartWithExcludeTest.java
Java
apache-2.0
5,022
/** * 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.netty4.http; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.ssl.SslHandler; import org.apache.camel.CamelContext; import org.apache.camel.RuntimeCamelException; import org.apache.camel.component.netty4.NettyConsumer; import org.apache.camel.component.netty4.ServerInitializerFactory; import org.apache.camel.component.netty4.ssl.SSLEngineFactory; import org.apache.camel.impl.DefaultClassResolver; import org.apache.camel.spi.ClassResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A shared {@link HttpServerInitializerFactory} for a shared Netty HTTP server. * * @see NettySharedHttpServer */ public class HttpServerSharedInitializerFactory extends HttpServerInitializerFactory { private static final Logger LOG = LoggerFactory.getLogger(HttpServerSharedInitializerFactory.class); private final NettySharedHttpServerBootstrapConfiguration configuration; private final HttpServerConsumerChannelFactory channelFactory; private final CamelContext camelContext; private SSLContext sslContext; public HttpServerSharedInitializerFactory(NettySharedHttpServerBootstrapConfiguration configuration, HttpServerConsumerChannelFactory channelFactory, CamelContext camelContext) { this.configuration = configuration; this.channelFactory = channelFactory; // fallback and use default resolver this.camelContext = camelContext; try { this.sslContext = createSSLContext(); } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } if (sslContext != null) { LOG.info("Created SslContext {}", sslContext); } } @Override public ServerInitializerFactory createPipelineFactory(NettyConsumer nettyConsumer) { throw new UnsupportedOperationException("Should not call this operation"); } @Override protected void initChannel(Channel ch) throws Exception { // create a new pipeline ChannelPipeline pipeline = ch.pipeline(); SslHandler sslHandler = configureServerSSLOnDemand(); if (sslHandler != null) { LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler); pipeline.addLast("ssl", sslHandler); } pipeline.addLast("decoder", new HttpRequestDecoder(4096, configuration.getMaxHeaderSize(), 8192)); pipeline.addLast("encoder", new HttpResponseEncoder()); if (configuration.isChunked()) { pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength())); } if (configuration.isCompression()) { pipeline.addLast("deflater", new HttpContentCompressor()); } pipeline.addLast("handler", channelFactory.getChannelHandler()); } private SSLContext createSSLContext() throws Exception { if (!configuration.isSsl()) { return null; } SSLContext answer; // create ssl context once if (configuration.getSslContextParameters() != null) { answer = configuration.getSslContextParameters().createSSLContext(null); } else { if (configuration.getKeyStoreFile() == null && configuration.getKeyStoreResource() == null) { LOG.debug("keystorefile is null"); } if (configuration.getTrustStoreFile() == null && configuration.getTrustStoreResource() == null) { LOG.debug("truststorefile is null"); } if (configuration.getPassphrase().toCharArray() == null) { LOG.debug("passphrase is null"); } SSLEngineFactory sslEngineFactory; if (configuration.getKeyStoreFile() != null || configuration.getTrustStoreFile() != null) { sslEngineFactory = new SSLEngineFactory(); answer = sslEngineFactory.createSSLContext(camelContext, configuration.getKeyStoreFormat(), configuration.getSecurityProvider(), "file:" + configuration.getKeyStoreFile().getPath(), "file:" + configuration.getTrustStoreFile().getPath(), configuration.getPassphrase().toCharArray()); } else { sslEngineFactory = new SSLEngineFactory(); answer = sslEngineFactory.createSSLContext(camelContext, configuration.getKeyStoreFormat(), configuration.getSecurityProvider(), configuration.getKeyStoreResource(), configuration.getTrustStoreResource(), configuration.getPassphrase().toCharArray()); } } return answer; } private SslHandler configureServerSSLOnDemand() throws Exception { if (!configuration.isSsl()) { return null; } if (configuration.getSslHandler() != null) { return configuration.getSslHandler(); } else if (sslContext != null) { SSLEngine engine = sslContext.createSSLEngine(); engine.setUseClientMode(false); engine.setNeedClientAuth(configuration.isNeedClientAuth()); if (configuration.getSslContextParameters() == null) { // just set the enabledProtocols if the SslContextParameter doesn't set engine.setEnabledProtocols(configuration.getEnabledProtocols().split(",")); } return new SslHandler(engine); } return null; } }
kevinearls/camel
components/camel-netty4-http/src/main/java/org/apache/camel/component/netty4/http/HttpServerSharedInitializerFactory.java
Java
apache-2.0
6,904
package org.dainst.gazetteer.dao; import org.dainst.gazetteer.domain.HelpText; import org.springframework.data.repository.PagingAndSortingRepository; public interface HelpTextRepository extends PagingAndSortingRepository<HelpText, String> { public HelpText findByLanguageAndLoginNeeded(String language, boolean loginNeeded); }
dainst/gazetteer
src/main/java/org/dainst/gazetteer/dao/HelpTextRepository.java
Java
apache-2.0
332
/** * * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.geronimo.kernel.basic; import java.lang.reflect.Method; import javax.management.ObjectName; import org.apache.geronimo.kernel.Kernel; /** * @version $Rev$ $Date$ */ public final class KernelOperationInvoker implements ProxyInvoker { private final Kernel kernel; private final String name; private final String[] argumentTypes; public KernelOperationInvoker(Kernel kernel, Method method) { this.kernel = kernel; name = method.getName(); // convert the parameters to a MBeanServer friendly string array Class[] parameters = method.getParameterTypes(); argumentTypes = new String[parameters.length]; for (int i = 0; i < parameters.length; i++) { argumentTypes[i] = parameters[i].getName(); } } public Object invoke(ObjectName objectName, Object[] arguments) throws Throwable { return kernel.invoke(objectName, name, arguments, argumentTypes); } }
meetdestiny/geronimo-trader
modules/kernel/src/java/org/apache/geronimo/kernel/basic/KernelOperationInvoker.java
Java
apache-2.0
1,607
/* * 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.activemq.artemis.tests.integration.client; import org.apache.activemq.artemis.api.core.BroadcastGroupConfiguration; import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.ha.SharedStoreMasterPolicyConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.tests.util.RandomUtil; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Arrays; public class SessionFactoryTest extends ActiveMQTestBase { private final DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration() .setBroadcastEndpointFactory(new UDPBroadcastEndpointFactory() .setGroupAddress(getUDPDiscoveryAddress()) .setGroupPort(getUDPDiscoveryPort())); private ActiveMQServer liveService; private TransportConfiguration liveTC; @Override @Before public void setUp() throws Exception { super.setUp(); startServer(); } @Test public void testCloseUnusedClientSessionFactoryWithoutGlobalPools() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(liveTC); ClientSessionFactory csf = createSessionFactory(locator); csf.close(); } @Test public void testDiscoveryConstructor() throws Exception { ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(groupConfiguration); assertFactoryParams(locator, null, groupConfiguration, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); Assert.assertNotNull(session); session.close(); testSettersThrowException(cf); cf.close(); locator.close(); } @Test public void testStaticConnectorListConstructor() throws Exception { TransportConfiguration[] tc = new TransportConfiguration[]{liveTC}; ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(tc); assertFactoryParams(locator, tc, null, ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, ActiveMQClient.DEFAULT_CONNECTION_TTL, ActiveMQClient.DEFAULT_CALL_TIMEOUT, ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE, ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE, ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE, ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE, ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE, ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND, ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND, ActiveMQClient.DEFAULT_AUTO_GROUP, ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE, ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE, ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS, ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_THREAD_POOL_MAX_SIZE, ActiveMQClient.DEFAULT_RETRY_INTERVAL, ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS); ClientSessionFactory cf = createSessionFactory(locator); ClientSession session = cf.createSession(false, true, true); Assert.assertNotNull(session); session.close(); testSettersThrowException(cf); cf.close(); } @Test public void testGettersAndSetters() throws Exception { long clientFailureCheckPeriod = RandomUtil.randomPositiveLong(); long connectionTTL = RandomUtil.randomPositiveLong(); long callTimeout = RandomUtil.randomPositiveLong(); int minLargeMessageSize = RandomUtil.randomPositiveInt(); int consumerWindowSize = RandomUtil.randomPositiveInt(); int consumerMaxRate = RandomUtil.randomPositiveInt(); int confirmationWindowSize = RandomUtil.randomPositiveInt(); int producerMaxRate = RandomUtil.randomPositiveInt(); boolean blockOnAcknowledge = RandomUtil.randomBoolean(); boolean blockOnDurableSend = RandomUtil.randomBoolean(); boolean blockOnNonDurableSend = RandomUtil.randomBoolean(); boolean autoGroup = RandomUtil.randomBoolean(); boolean preAcknowledge = RandomUtil.randomBoolean(); String loadBalancingPolicyClassName = RandomUtil.randomString(); int ackBatchSize = RandomUtil.randomPositiveInt(); boolean useGlobalPools = RandomUtil.randomBoolean(); int scheduledThreadPoolMaxSize = RandomUtil.randomPositiveInt(); int threadPoolMaxSize = RandomUtil.randomPositiveInt(); long retryInterval = RandomUtil.randomPositiveLong(); double retryIntervalMultiplier = RandomUtil.randomDouble(); int reconnectAttempts = RandomUtil.randomPositiveInt(); TransportConfiguration[] tc = new TransportConfiguration[]{liveTC}; ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(tc) .setClientFailureCheckPeriod(clientFailureCheckPeriod) .setConnectionTTL(connectionTTL) .setCallTimeout(callTimeout) .setMinLargeMessageSize(minLargeMessageSize) .setConsumerWindowSize(consumerWindowSize) .setConsumerMaxRate(consumerMaxRate) .setConfirmationWindowSize(confirmationWindowSize) .setProducerMaxRate(producerMaxRate) .setBlockOnAcknowledge(blockOnAcknowledge) .setBlockOnDurableSend(blockOnDurableSend) .setBlockOnNonDurableSend(blockOnNonDurableSend) .setAutoGroup(autoGroup) .setPreAcknowledge(preAcknowledge) .setConnectionLoadBalancingPolicyClassName(loadBalancingPolicyClassName) .setAckBatchSize(ackBatchSize) .setUseGlobalPools(useGlobalPools) .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize) .setThreadPoolMaxSize(threadPoolMaxSize) .setRetryInterval(retryInterval) .setRetryIntervalMultiplier(retryIntervalMultiplier) .setReconnectAttempts(reconnectAttempts); assertEqualsTransportConfigurations(tc, locator.getStaticTransportConfigurations()); Assert.assertEquals(clientFailureCheckPeriod, locator.getClientFailureCheckPeriod()); Assert.assertEquals(connectionTTL, locator.getConnectionTTL()); Assert.assertEquals(callTimeout, locator.getCallTimeout()); Assert.assertEquals(minLargeMessageSize, locator.getMinLargeMessageSize()); Assert.assertEquals(consumerWindowSize, locator.getConsumerWindowSize()); Assert.assertEquals(consumerMaxRate, locator.getConsumerMaxRate()); Assert.assertEquals(confirmationWindowSize, locator.getConfirmationWindowSize()); Assert.assertEquals(producerMaxRate, locator.getProducerMaxRate()); Assert.assertEquals(blockOnAcknowledge, locator.isBlockOnAcknowledge()); Assert.assertEquals(blockOnDurableSend, locator.isBlockOnDurableSend()); Assert.assertEquals(blockOnNonDurableSend, locator.isBlockOnNonDurableSend()); Assert.assertEquals(autoGroup, locator.isAutoGroup()); Assert.assertEquals(preAcknowledge, locator.isPreAcknowledge()); Assert.assertEquals(loadBalancingPolicyClassName, locator.getConnectionLoadBalancingPolicyClassName()); Assert.assertEquals(ackBatchSize, locator.getAckBatchSize()); Assert.assertEquals(useGlobalPools, locator.isUseGlobalPools()); Assert.assertEquals(scheduledThreadPoolMaxSize, locator.getScheduledThreadPoolMaxSize()); Assert.assertEquals(threadPoolMaxSize, locator.getThreadPoolMaxSize()); Assert.assertEquals(retryInterval, locator.getRetryInterval()); Assert.assertEquals(retryIntervalMultiplier, locator.getRetryIntervalMultiplier(), 0.000001); Assert.assertEquals(reconnectAttempts, locator.getReconnectAttempts()); } private void testSettersThrowException(final ClientSessionFactory cf) { long clientFailureCheckPeriod = RandomUtil.randomPositiveLong(); long connectionTTL = RandomUtil.randomPositiveLong(); long callTimeout = RandomUtil.randomPositiveLong(); int minLargeMessageSize = RandomUtil.randomPositiveInt(); int consumerWindowSize = RandomUtil.randomPositiveInt(); int consumerMaxRate = RandomUtil.randomPositiveInt(); int confirmationWindowSize = RandomUtil.randomPositiveInt(); int producerMaxRate = RandomUtil.randomPositiveInt(); boolean blockOnAcknowledge = RandomUtil.randomBoolean(); boolean blockOnDurableSend = RandomUtil.randomBoolean(); boolean blockOnNonDurableSend = RandomUtil.randomBoolean(); boolean autoGroup = RandomUtil.randomBoolean(); boolean preAcknowledge = RandomUtil.randomBoolean(); String loadBalancingPolicyClassName = RandomUtil.randomString(); int ackBatchSize = RandomUtil.randomPositiveInt(); boolean useGlobalPools = RandomUtil.randomBoolean(); int scheduledThreadPoolMaxSize = RandomUtil.randomPositiveInt(); int threadPoolMaxSize = RandomUtil.randomPositiveInt(); long retryInterval = RandomUtil.randomPositiveLong(); double retryIntervalMultiplier = RandomUtil.randomDouble(); int reconnectAttempts = RandomUtil.randomPositiveInt(); try { cf.getServerLocator().setClientFailureCheckPeriod(clientFailureCheckPeriod); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setConnectionTTL(connectionTTL); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setCallTimeout(callTimeout); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setMinLargeMessageSize(minLargeMessageSize); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setConsumerWindowSize(consumerWindowSize); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setConsumerMaxRate(consumerMaxRate); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setConfirmationWindowSize(confirmationWindowSize); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setProducerMaxRate(producerMaxRate); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setBlockOnAcknowledge(blockOnAcknowledge); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setBlockOnDurableSend(blockOnDurableSend); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setBlockOnNonDurableSend(blockOnNonDurableSend); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setAutoGroup(autoGroup); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setPreAcknowledge(preAcknowledge); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setConnectionLoadBalancingPolicyClassName(loadBalancingPolicyClassName); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setAckBatchSize(ackBatchSize); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setUseGlobalPools(useGlobalPools); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setThreadPoolMaxSize(threadPoolMaxSize); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setRetryInterval(retryInterval); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setRetryIntervalMultiplier(retryIntervalMultiplier); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { cf.getServerLocator().setReconnectAttempts(reconnectAttempts); Assert.fail("Should throw exception"); } catch (IllegalStateException e) { // OK } cf.getServerLocator().getStaticTransportConfigurations(); cf.getServerLocator().getClientFailureCheckPeriod(); cf.getServerLocator().getConnectionTTL(); cf.getServerLocator().getCallTimeout(); cf.getServerLocator().getMinLargeMessageSize(); cf.getServerLocator().getConsumerWindowSize(); cf.getServerLocator().getConsumerMaxRate(); cf.getServerLocator().getConfirmationWindowSize(); cf.getServerLocator().getProducerMaxRate(); cf.getServerLocator().isBlockOnAcknowledge(); cf.getServerLocator().isBlockOnDurableSend(); cf.getServerLocator().isBlockOnNonDurableSend(); cf.getServerLocator().isAutoGroup(); cf.getServerLocator().isPreAcknowledge(); cf.getServerLocator().getConnectionLoadBalancingPolicyClassName(); cf.getServerLocator().getAckBatchSize(); cf.getServerLocator().isUseGlobalPools(); cf.getServerLocator().getScheduledThreadPoolMaxSize(); cf.getServerLocator().getThreadPoolMaxSize(); cf.getServerLocator().getRetryInterval(); cf.getServerLocator().getRetryIntervalMultiplier(); cf.getServerLocator().getReconnectAttempts(); } private void assertFactoryParams(final ServerLocator locator, final TransportConfiguration[] staticConnectors, final DiscoveryGroupConfiguration discoveryGroupConfiguration, final long clientFailureCheckPeriod, final long connectionTTL, final long callTimeout, final int minLargeMessageSize, final int consumerWindowSize, final int consumerMaxRate, final int confirmationWindowSize, final int producerMaxRate, final boolean blockOnAcknowledge, final boolean blockOnDurableSend, final boolean blockOnNonDurableSend, final boolean autoGroup, final boolean preAcknowledge, final String loadBalancingPolicyClassName, final int ackBatchSize, final boolean useGlobalPools, final int scheduledThreadPoolMaxSize, final int threadPoolMaxSize, final long retryInterval, final double retryIntervalMultiplier, final int reconnectAttempts) { if (staticConnectors == null) { Assert.assertTrue("no static connectors", Arrays.equals(new String[]{}, locator.getStaticTransportConfigurations())); } else { assertEqualsTransportConfigurations(staticConnectors, locator.getStaticTransportConfigurations()); } Assert.assertEquals(locator.getDiscoveryGroupConfiguration(), discoveryGroupConfiguration); Assert.assertEquals(locator.getClientFailureCheckPeriod(), clientFailureCheckPeriod); Assert.assertEquals(locator.getConnectionTTL(), connectionTTL); Assert.assertEquals(locator.getCallTimeout(), callTimeout); Assert.assertEquals(locator.getMinLargeMessageSize(), minLargeMessageSize); Assert.assertEquals(locator.getConsumerWindowSize(), consumerWindowSize); Assert.assertEquals(locator.getConsumerMaxRate(), consumerMaxRate); Assert.assertEquals(locator.getConfirmationWindowSize(), confirmationWindowSize); Assert.assertEquals(locator.getProducerMaxRate(), producerMaxRate); Assert.assertEquals(locator.isBlockOnAcknowledge(), blockOnAcknowledge); Assert.assertEquals(locator.isBlockOnDurableSend(), blockOnDurableSend); Assert.assertEquals(locator.isBlockOnNonDurableSend(), blockOnNonDurableSend); Assert.assertEquals(locator.isAutoGroup(), autoGroup); Assert.assertEquals(locator.isPreAcknowledge(), preAcknowledge); Assert.assertEquals(locator.getConnectionLoadBalancingPolicyClassName(), loadBalancingPolicyClassName); Assert.assertEquals(locator.getAckBatchSize(), ackBatchSize); Assert.assertEquals(locator.isUseGlobalPools(), useGlobalPools); Assert.assertEquals(locator.getScheduledThreadPoolMaxSize(), scheduledThreadPoolMaxSize); Assert.assertEquals(locator.getThreadPoolMaxSize(), threadPoolMaxSize); Assert.assertEquals(locator.getRetryInterval(), retryInterval); Assert.assertEquals(locator.getRetryIntervalMultiplier(), retryIntervalMultiplier, 0.000001); Assert.assertEquals(locator.getReconnectAttempts(), reconnectAttempts); } private void startServer() throws Exception { liveTC = new TransportConfiguration(INVM_CONNECTOR_FACTORY); final long broadcastPeriod = 250; final String bcGroupName = "bc1"; final int localBindPort = 5432; BroadcastGroupConfiguration broadcastGroupConfiguration = new BroadcastGroupConfiguration() .setName(bcGroupName) .setBroadcastPeriod(broadcastPeriod) .setConnectorInfos(Arrays.asList(liveTC.getName())) .setEndpointFactory(new UDPBroadcastEndpointFactory() .setGroupAddress(getUDPDiscoveryAddress()) .setGroupPort(getUDPDiscoveryPort()) .setLocalBindPort(localBindPort)); Configuration liveConf = createDefaultInVMConfig() .addConnectorConfiguration(liveTC.getName(), liveTC) .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()) .addBroadcastGroupConfiguration(broadcastGroupConfiguration); liveService = createServer(false, liveConf); liveService.start(); } }
ryanemerson/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionFactoryTest.java
Java
apache-2.0
23,399
/* * 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.kafka.streams.kstream.internals; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.Predicate; import org.apache.kafka.test.KStreamTestDriver; import org.apache.kafka.test.MockProcessorSupplier; import org.junit.Rule; import org.junit.Test; import java.lang.reflect.Array; import static org.junit.Assert.assertEquals; public class KStreamBranchTest { private String topicName = "topic"; @Rule public final KStreamTestDriver driver = new KStreamTestDriver(); @SuppressWarnings("unchecked") @Test public void testKStreamBranch() { final StreamsBuilder builder = new StreamsBuilder(); Predicate<Integer, String> isEven = new Predicate<Integer, String>() { @Override public boolean test(Integer key, String value) { return (key % 2) == 0; } }; Predicate<Integer, String> isMultipleOfThree = new Predicate<Integer, String>() { @Override public boolean test(Integer key, String value) { return (key % 3) == 0; } }; Predicate<Integer, String> isOdd = new Predicate<Integer, String>() { @Override public boolean test(Integer key, String value) { return (key % 2) != 0; } }; final int[] expectedKeys = new int[]{1, 2, 3, 4, 5, 6}; KStream<Integer, String> stream; KStream<Integer, String>[] branches; MockProcessorSupplier<Integer, String>[] processors; stream = builder.stream(Serdes.Integer(), Serdes.String(), topicName); branches = stream.branch(isEven, isMultipleOfThree, isOdd); assertEquals(3, branches.length); processors = (MockProcessorSupplier<Integer, String>[]) Array.newInstance(MockProcessorSupplier.class, branches.length); for (int i = 0; i < branches.length; i++) { processors[i] = new MockProcessorSupplier<>(); branches[i].process(processors[i]); } driver.setUp(builder); for (int expectedKey : expectedKeys) { driver.process(topicName, expectedKey, "V" + expectedKey); } assertEquals(3, processors[0].processed.size()); assertEquals(1, processors[1].processed.size()); assertEquals(2, processors[2].processed.size()); } @Test public void testTypeVariance() { Predicate<Number, Object> positive = new Predicate<Number, Object>() { @Override public boolean test(Number key, Object value) { return key.doubleValue() > 0; } }; Predicate<Number, Object> negative = new Predicate<Number, Object>() { @Override public boolean test(Number key, Object value) { return key.doubleValue() < 0; } }; @SuppressWarnings("unchecked") final KStream<Integer, String>[] branches = new StreamsBuilder() .<Integer, String>stream("empty") .branch(positive, negative); } }
ErikKringen/kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KStreamBranchTest.java
Java
apache-2.0
4,029
/* * Copyright 2012 Google 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.google.gwt.aria.client; ///////////////////////////////////////////////////////// // This is auto-generated code. Do not manually edit! // ///////////////////////////////////////////////////////// import com.google.gwt.dom.client.Element; /** * <p>Implements {@link ListitemRole}.</p> */ class ListitemRoleImpl extends RoleImpl implements ListitemRole { ListitemRoleImpl(String roleName) { super(roleName); } @Override public String getAriaExpandedState(Element element) { return State.EXPANDED.get(element); } @Override public String getAriaLevelProperty(Element element) { return Property.LEVEL.get(element); } @Override public String getAriaPosinsetProperty(Element element) { return Property.POSINSET.get(element); } @Override public String getAriaSetsizeProperty(Element element) { return Property.SETSIZE.get(element); } @Override public void removeAriaExpandedState(Element element) { State.EXPANDED.remove(element); } @Override public void removeAriaLevelProperty(Element element) { Property.LEVEL.remove(element); } @Override public void removeAriaPosinsetProperty(Element element) { Property.POSINSET.remove(element); } @Override public void removeAriaSetsizeProperty(Element element) { Property.SETSIZE.remove(element); } @Override public void setAriaExpandedState(Element element, ExpandedValue value) { State.EXPANDED.set(element, value); } @Override public void setAriaLevelProperty(Element element, int value) { Property.LEVEL.set(element, value); } @Override public void setAriaPosinsetProperty(Element element, int value) { Property.POSINSET.set(element, value); } @Override public void setAriaSetsizeProperty(Element element, int value) { Property.SETSIZE.set(element, value); } }
syntelos/gwtcc
src/com/google/gwt/aria/client/ListitemRoleImpl.java
Java
apache-2.0
2,442
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_interface.java // Do not modify package org.projectfloodlight.openflow.protocol.oxm; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import io.netty.buffer.ByteBuf; public interface OFOxmBsnVlanXlatePortGroupId extends OFObject, OFOxm<ClassId> { long getTypeLen(); ClassId getValue(); MatchField<ClassId> getMatchField(); boolean isMasked(); OFOxm<ClassId> getCanonical(); ClassId getMask(); OFVersion getVersion(); void writeTo(ByteBuf channelBuffer); Builder createBuilder(); public interface Builder extends OFOxm.Builder<ClassId> { OFOxmBsnVlanXlatePortGroupId build(); long getTypeLen(); ClassId getValue(); Builder setValue(ClassId value); MatchField<ClassId> getMatchField(); boolean isMasked(); OFOxm<ClassId> getCanonical(); ClassId getMask(); OFVersion getVersion(); } }
mehdi149/OF_COMPILER_0.1
gen-src/main/java/org/projectfloodlight/openflow/protocol/oxm/OFOxmBsnVlanXlatePortGroupId.java
Java
apache-2.0
2,136
/** * Copyright 2017 TerraMeta Software, 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 org.plasma.provisioning.xsd; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xerces.dom.ElementNSImpl; import org.plasma.common.provisioning.NameUtils; import org.plasma.metamodel.Body; import org.plasma.metamodel.Class; import org.plasma.metamodel.ClassRef; import org.plasma.metamodel.Documentation; import org.plasma.metamodel.DocumentationType; import org.plasma.metamodel.Enumeration; import org.plasma.metamodel.EnumerationLiteral; import org.plasma.metamodel.Property; import org.plasma.sdo.DataType; import org.plasma.xml.schema.AbstractSimpleType; import org.plasma.xml.schema.Annotated; import org.plasma.xml.schema.Annotation; import org.plasma.xml.schema.Appinfo; import org.plasma.xml.schema.AttributeGroup; import org.plasma.xml.schema.ComplexType; import org.plasma.xml.schema.Element; import org.plasma.xml.schema.LocalElement; import org.plasma.xml.schema.OpenAttrs; import org.plasma.xml.schema.Restriction; import org.plasma.xml.schema.Schema; import org.plasma.xml.schema.SimpleType; import org.plasma.xml.schema.XSDBuiltInType; import org.plasma.xml.sdox.SDOXConstants; public class ConverterSupport { private static Log log = LogFactory.getLog(ConverterSupport.class); protected String destNamespaceURI; protected String destNamespacePrefix; protected Map<String, Class> classQualifiedNameMap = new HashMap<String, Class>(); protected Map<String, Class> classLocalNameMap = new HashMap<String, Class>(); protected Map<Class, Map<String, Property>> classPropertyMap = new HashMap<Class, Map<String, Property>>(); protected Map<Class, HashSet<Class>> subclassMap = new HashMap<Class, HashSet<Class>>(); protected Schema schema; /** maps top-level complex type names to complex type structures */ protected Map<String, ComplexType> complexTypeMap = new HashMap<String, ComplexType>(); /** maps top-level element names to element structures */ protected Map<String, Element> elementMap = new HashMap<String, Element>(); /** maps top-level simple type names to simple type structures */ protected Map<String, SimpleType> simpleTypeMap = new HashMap<String, SimpleType>(); /** maps top-level attribute group names to attribute group structures */ protected Map<String, AttributeGroup> attributeGroupMap = new HashMap<String, AttributeGroup>(); @SuppressWarnings("unused") private ConverterSupport() { } public ConverterSupport(Schema schema, String destNamespaceURI, String destNamespacePrefix) { super(); this.schema = schema; this.destNamespaceURI = destNamespaceURI; this.destNamespacePrefix = destNamespacePrefix; if (schema.getTargetNamespace() == null) throw new IllegalArgumentException("given schema has no target namespace"); } public String getDestNamespaceURI() { return destNamespaceURI; } public String getDestNamespacePrefix() { return destNamespacePrefix; } public Map<String, Class> getClassQualifiedNameMap() { return classQualifiedNameMap; } public Map<String, Class> getClassLocalNameMap() { return classLocalNameMap; } public Map<Class, Map<String, Property>> getClassPropertyMap() { return classPropertyMap; } public Map<Class, HashSet<Class>> getSubclassMap() { return subclassMap; } public Schema getSchema() { return schema; } public Map<String, ComplexType> getComplexTypeMap() { return complexTypeMap; } public Map<String, Element> getElementMap() { return elementMap; } public Map<String, SimpleType> getSimpleTypeMap() { return simpleTypeMap; } public Map<String, AttributeGroup> getAttributeGroupMap() { return attributeGroupMap; } public String formatLocalClassName(String localName) { String result = localName; result = NameUtils.firstToUpperCase(result); return result; } public String formatLocalPropertyName(String localName) { String result = localName; result = NameUtils.firstToLowerCase(result); return result; } public boolean logicalNameConflict(Class clss, String name) { Map<String, Property> existingProps = this.classPropertyMap.get(clss); if (existingProps != null) return existingProps.get(name) != null; return false; } public String buildLogicalPropertyName(Class clss, String name) { String logicalName = name; Map<String, Property> existingProps = this.getAllExistingProps(clss); Property existing = existingProps.get(logicalName); if (existing != null) { int count = 1; while (existing != null) { int underscore = logicalName.lastIndexOf("_"); if (underscore > 0) { logicalName = logicalName.substring(0, underscore); } logicalName = logicalName + "_" + String.valueOf(count); log.warn("detected name colision for property '" + clss.getName() + "." + existing.getName() + "' - using synthetic name '" + logicalName + "'"); count++; existing = existingProps.get(logicalName); } } return logicalName; } private Map<String, Property> getAllExistingProps(Class clss) { Map<String, Property> result = new HashMap<String, Property>(); collect(clss, result); return result; } private void collect(Class clss, Map<String, Property> properties) { Map<String, Property> baseResult = this.classPropertyMap.get(clss); if (baseResult != null) properties.putAll(baseResult); for (ClassRef ref : clss.getSuperClasses()) { Class base = this.classQualifiedNameMap.get(ref.getUri() + "#" + ref.getName()); collect(base, properties); } } public List<Class> getRootClasses() { List<Class> result = new ArrayList<Class>(); for (Class clss : this.classQualifiedNameMap.values()) { if (clss.getSuperClasses() == null || clss.getSuperClasses().size() == 0) result.add(clss); } return result; } public void accept(Class root, ClassVisitor visitor) { traverse(root, null, visitor); } private void traverse(Class target, Class source, ClassVisitor visitor) { visitor.visit(target, source); HashSet<Class> subclasses = this.subclassMap.get(target); if (subclasses != null) { Iterator<Class> iter = subclasses.iterator(); while (iter.hasNext()) { traverse(iter.next(), target, visitor); } } } public void collectSubclasses() { for (Class clss : this.getClassQualifiedNameMap().values()) { for (ClassRef ref : clss.getSuperClasses()) { Class base = this.getClassQualifiedNameMap().get(ref.getUri() + "#" + ref.getName()); HashSet<Class> subclasses = this.subclassMap.get(base); if (subclasses == null) { subclasses = new HashSet<Class>(); this.subclassMap.put(base, subclasses); } subclasses.add(clss); } } } public String buildLogicalEnumerationLiteralName(Enumeration enm, String name, Map<String, EnumerationLiteral> literalMap) { String logicalName = name; EnumerationLiteral existing = literalMap.get(logicalName); if (existing != null) { int count = 1; while (existing != null) { int underscore = logicalName.lastIndexOf("_"); if (underscore > 0) { logicalName = logicalName.substring(0, underscore); } logicalName = logicalName + "_" + String.valueOf(count); log.warn("detected name colision for literal '" + enm.getName() + "." + existing.getName() + "' - using synthetic name '" + logicalName + "'"); count++; existing = literalMap.get(logicalName); } } return logicalName; } public boolean isEnumeration(AbstractSimpleType simpleType) { Restriction restriction = simpleType.getRestriction(); if (restriction != null) { if (restriction.getMinExclusivesAndMinInclusivesAndMaxExclusives().size() > 0) for (Object obj : restriction.getMinExclusivesAndMinInclusivesAndMaxExclusives()) if (obj instanceof org.plasma.xml.schema.Enumeration) return true; } return false; } public String getOpenAttributeValue(QName qname, OpenAttrs attrs) { return findOpenAttributeValue(qname, attrs, false); } public String findOpenAttributeValue(QName qname, OpenAttrs attrs) { return findOpenAttributeValue(qname, attrs, true); } public String findOpenAttributeValue(QName qname, OpenAttrs attrs, boolean supressError) { Iterator<QName> iter = attrs.getOtherAttributes().keySet().iterator(); while (iter.hasNext()) { QName key = iter.next(); if (key.equals(qname)) { String result = attrs.getOtherAttributes().get(key); return result; } } if (!supressError) throw new IllegalArgumentException("attribute '" + qname.toString() + "' not found"); return null; } public QName getOpenAttributeQNameByValue(String value, OpenAttrs attrs) { Iterator<QName> iter = attrs.getOtherAttributes().keySet().iterator(); while (iter.hasNext()) { QName key = iter.next(); String s = attrs.getOtherAttributes().get(key); if (s != null && s.equals(value)) return key; } throw new IllegalArgumentException("attribute value '" + value + "' not found"); } public QName findOpenAttributeQNameByValue(String value, OpenAttrs attrs) { Iterator<QName> iter = attrs.getOtherAttributes().keySet().iterator(); while (iter.hasNext()) { QName key = iter.next(); String s = attrs.getOtherAttributes().get(key); if (s != null && s.equals(value)) return key; } return null; } public String getDocumentationContent(Annotation annotation) { StringBuilder buf = new StringBuilder(); for (Object annotationObj : annotation.getAppinfosAndDocumentations()) { buf.append(getContent(annotationObj)); } return buf.toString(); } public String getDocumentationContent(Annotated annotated) { StringBuilder buf = new StringBuilder(); if (annotated != null && annotated.getAnnotation() != null) { for (Object annotationObj : annotated.getAnnotation().getAppinfosAndDocumentations()) { buf.append(getContent(annotationObj)); } } return buf.toString(); } private String getContent(Object annotationObj) { StringBuilder buf = new StringBuilder(); if (annotationObj instanceof org.plasma.xml.schema.Documentation) { org.plasma.xml.schema.Documentation doc = (org.plasma.xml.schema.Documentation) annotationObj; for (Object content : doc.getContent()) if (content instanceof String) { buf.append(content); } else if (content instanceof ElementNSImpl) { ElementNSImpl nsElem = (ElementNSImpl) content; buf.append(serializeElement(nsElem)); } else throw new IllegalStateException("unexpected content class, " + annotationObj.getClass().getName()); } else if (annotationObj instanceof Appinfo) { log.warn("ignoring app-info: " + String.valueOf(annotationObj)); } return buf.toString(); } public String serializeElement(ElementNSImpl nsElem) { String result = ""; TransformerFactory transFactory = TransformerFactory.newInstance(); log.debug("transformer factory: " + transFactory.getClass().getName()); // transFactory.setAttribute("indent-number", 2); Transformer idTransform = null; ByteArrayOutputStream stream = null; try { idTransform = transFactory.newTransformer(); idTransform.setOutputProperty(OutputKeys.METHOD, "xml"); idTransform.setOutputProperty(OutputKeys.INDENT, "yes"); idTransform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Source input = new DOMSource(nsElem.getOwnerDocument()); stream = new ByteArrayOutputStream(); Result output = new StreamResult(stream); idTransform.transform(input, output); stream.flush(); result = new String(stream.toByteArray()); return result; } catch (TransformerConfigurationException e1) { log.error(e1.getMessage(), e1); } catch (TransformerException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (stream != null) try { stream.close(); } catch (Throwable t) { } } return result; } public String getSDOXValue(ComplexType complexType, String localName) { QName nameQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, localName, SDOXConstants.SDOX_NAMESPACE_PREFIX); String value = getOpenAttributeValue(nameQName, complexType); return value; } public String findSDOXValue(ComplexType complexType, String localName) { QName nameQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, localName, SDOXConstants.SDOX_NAMESPACE_PREFIX); String value = findOpenAttributeValue(nameQName, complexType); return value; } public String getSDOXValue(LocalElement element, String localName) { QName nameQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, localName, SDOXConstants.SDOX_NAMESPACE_PREFIX); String value = getOpenAttributeValue(nameQName, element); return value; } public DataType mapType(XSDBuiltInType xsdType) { switch (xsdType) { case xsd_anySimpleType: return DataType.Object; case xsd_anyType: return DataType.Object; case xsd_anyURI: return DataType.URI; case xsd_base64Binary: return DataType.Bytes; case xsd_boolean: return DataType.Boolean; case xsd_byte: return DataType.Byte; case xsd_date: return DataType.YearMonthDay; case xsd_dateTime: return DataType.DateTime; case xsd_decimal: return DataType.Decimal; case xsd_double: return DataType.Double; case xsd_duration: return DataType.Duration; case xsd_ENTITIES: return DataType.Strings; case xsd_ENTITY: return DataType.String; case xsd_float: return DataType.Float; case xsd_gDay: return DataType.Day; case xsd_gMonth: return DataType.Month; case xsd_gMonthDay: return DataType.MonthDay; case xsd_gYear: return DataType.Year; case xsd_gYearMonth: return DataType.YearMonth; case xsd_hexBinary: return DataType.Bytes; case xsd_ID: return DataType.String; case xsd_IDREF: return DataType.String; case xsd_IDREFS: return DataType.Strings; case xsd_int: return DataType.Int; case xsd_integer: return DataType.Integer; case xsd_language: return DataType.String; case xsd_long: return DataType.Long; case xsd_Name: return DataType.String; case xsd_NCName: return DataType.String; case xsd_negativeInteger: return DataType.Integer; case xsd_NMTOKEN: return DataType.String; case xsd_NMTOKENS: return DataType.Strings; case xsd_nonNegativeInteger: return DataType.Integer; case xsd_nonPositiveInteger: return DataType.Integer; case xsd_normalizedString: return DataType.String; case xsd_NOTATION: return DataType.String; case xsd_positiveInteger: return DataType.Integer; case xsd_QName: return DataType.URI; case xsd_short: return DataType.Short; case xsd_string: return DataType.String; case xsd_time: return DataType.Time; case xsd_token: return DataType.String; case xsd_unsignedByte: return DataType.Short; case xsd_unsignedInt: return DataType.Long; case xsd_unsignedLong: return DataType.Integer; case xsd_unsignedShort: return DataType.Int; default: return DataType.String; } } public String findAppInfoValue(org.plasma.xml.schema.Enumeration schemaEnum) { String result = null; if (schemaEnum.getAnnotation() != null) for (Object o2 : schemaEnum.getAnnotation().getAppinfosAndDocumentations()) { if (o2 instanceof Appinfo) { Appinfo appinfo = (Appinfo) o2; result = (String) appinfo.getContent().get(0); if (result != null) { result.trim(); if (result.length() == 0) result = null; } break; } } return result; } public Documentation createDocumentation(DocumentationType type, String content) { Documentation documentation = new Documentation(); documentation.setType(type); Body body = new Body(); body.setValue(content); documentation.setBody(body); return documentation; } }
plasma-framework/plasma
plasma-core/src/main/java/org/plasma/provisioning/xsd/ConverterSupport.java
Java
apache-2.0
18,002
/* * Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package org.omg.CORBA; /** * The interface for <tt>IDLType</tt>. For more information on * Operations interfaces, see <a href="doc-files/generatedfiles.html#operations"> * "Generated Files: Operations files"</a>. */ /* tempout/org/omg/CORBA/IDLTypeOperations.java Generated by the IBM IDL-to-Java compiler, version 1.0 from ../../Lib/ir.idl Thursday, February 25, 1999 2:11:23 o'clock PM PST */ /** * This interface must be implemented by all IDLType objects. * The IDLType is inherited by all IR objects that * represent IDL types, including interfaces, typedefs, and * anonymous types. * @see IDLType * @see IRObject * @see IRObjectOperations */ public interface IDLTypeOperations extends IRObjectOperations { /** * The type attribute describes the type defined by an object * derived from <code>IDLType</code>. * @return the <code>TypeCode</code> defined by this object. */ TypeCode type(); } // interface IDLTypeOperations
wangsongpeng/jdk-src
src/main/java/org/omg/CORBA/IDLTypeOperations.java
Java
apache-2.0
1,189
/* * 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.ignite.internal.stat; /** * Tests for cache IO statistics for persistence mode. */ public class IoStatisticsCachePersistenceSelfTest extends IoStatisticsCacheSelfTest { /** {@inheritDoc} */ @Override protected boolean persist() { return true; } }
ptupitsyn/ignite
modules/core/src/test/java/org/apache/ignite/internal/stat/IoStatisticsCachePersistenceSelfTest.java
Java
apache-2.0
1,097
/* * 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.kafka.streams.kstream.internals; import org.apache.kafka.clients.producer.internals.DefaultPartitioner; import org.apache.kafka.common.Cluster; import org.apache.kafka.common.Node; import org.apache.kafka.common.PartitionInfo; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.Deserializer; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.Windowed; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Map; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class WindowedStreamPartitionerTest { private String topicName = "topic"; private IntegerSerializer intSerializer = new IntegerSerializer(); private StringSerializer stringSerializer = new StringSerializer(); private List<PartitionInfo> infos = Arrays.asList( new PartitionInfo(topicName, 0, Node.noNode(), new Node[0], new Node[0]), new PartitionInfo(topicName, 1, Node.noNode(), new Node[0], new Node[0]), new PartitionInfo(topicName, 2, Node.noNode(), new Node[0], new Node[0]), new PartitionInfo(topicName, 3, Node.noNode(), new Node[0], new Node[0]), new PartitionInfo(topicName, 4, Node.noNode(), new Node[0], new Node[0]), new PartitionInfo(topicName, 5, Node.noNode(), new Node[0], new Node[0]) ); private Cluster cluster = new Cluster("cluster", Collections.singletonList(Node.noNode()), infos, Collections.<String>emptySet(), Collections.<String>emptySet()); @Test public void testCopartitioning() { Random rand = new Random(); DefaultPartitioner defaultPartitioner = new DefaultPartitioner(); WindowedSerializer<Integer> windowedSerializer = new WindowedSerializer<>(intSerializer); WindowedStreamPartitioner<Integer, String> streamPartitioner = new WindowedStreamPartitioner<>(topicName, windowedSerializer); for (int k = 0; k < 10; k++) { Integer key = rand.nextInt(); byte[] keyBytes = intSerializer.serialize(topicName, key); String value = key.toString(); byte[] valueBytes = stringSerializer.serialize(topicName, value); Integer expected = defaultPartitioner.partition("topic", key, keyBytes, value, valueBytes, cluster); for (int w = 1; w < 10; w++) { TimeWindow window = new TimeWindow(10 * w, 20 * w); Windowed<Integer> windowedKey = new Windowed<>(key, window); Integer actual = streamPartitioner.partition(windowedKey, value, infos.size()); assertEquals(expected, actual); } } defaultPartitioner.close(); } @Test public void testWindowedSerializerNoArgConstructors() { Map<String, String> props = new HashMap<>(); // test key[value].serializer.inner.class takes precedence over serializer.inner.class WindowedSerializer<StringSerializer> windowedSerializer = new WindowedSerializer<>(); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "host:1"); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "appId"); props.put("key.serializer.inner.class", "org.apache.kafka.common.serialization.StringSerializer"); props.put("serializer.inner.class", "org.apache.kafka.common.serialization.StringSerializer"); windowedSerializer.configure(props, true); Serializer<?> inner = windowedSerializer.innerSerializer(); assertNotNull("Inner serializer should be not null", inner); assertTrue("Inner serializer type should be StringSerializer", inner instanceof StringSerializer); // test serializer.inner.class props.put("serializer.inner.class", "org.apache.kafka.common.serialization.ByteArraySerializer"); props.remove("key.serializer.inner.class"); props.remove("value.serializer.inner.class"); WindowedSerializer<?> windowedSerializer1 = new WindowedSerializer<>(); windowedSerializer1.configure(props, false); Serializer<?> inner1 = windowedSerializer1.innerSerializer(); assertNotNull("Inner serializer should be not null", inner1); assertTrue("Inner serializer type should be ByteArraySerializer", inner1 instanceof ByteArraySerializer); windowedSerializer.close(); windowedSerializer1.close(); } @Test public void testWindowedDeserializerNoArgConstructors() { Map<String, String> props = new HashMap<>(); // test key[value].deserializer.inner.class takes precedence over serializer.inner.class WindowedDeserializer<StringSerializer> windowedDeserializer = new WindowedDeserializer<>(); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "host:1"); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "appId"); props.put("key.deserializer.inner.class", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("deserializer.inner.class", "org.apache.kafka.common.serialization.StringDeserializer"); windowedDeserializer.configure(props, true); Deserializer<?> inner = windowedDeserializer.innerDeserializer(); assertNotNull("Inner deserializer should be not null", inner); assertTrue("Inner deserializer type should be StringDeserializer", inner instanceof StringDeserializer); // test deserializer.inner.class props.put("deserializer.inner.class", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); props.remove("key.deserializer.inner.class"); props.remove("value.deserializer.inner.class"); WindowedDeserializer<?> windowedDeserializer1 = new WindowedDeserializer<>(); windowedDeserializer1.configure(props, false); Deserializer<?> inner1 = windowedDeserializer1.innerDeserializer(); assertNotNull("Inner deserializer should be not null", inner1); assertTrue("Inner deserializer type should be ByteArrayDeserializer", inner1 instanceof ByteArrayDeserializer); windowedDeserializer.close(); windowedDeserializer1.close(); } }
ErikKringen/kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/WindowedStreamPartitionerTest.java
Java
apache-2.0
7,481
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.onosproject.influxdbmetrics; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Modified; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onlab.util.Tools; import org.onosproject.cfg.ComponentConfigService; import org.onosproject.core.CoreService; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import java.util.Dictionary; import static org.slf4j.LoggerFactory.getLogger; /** * A configuration service for InfluxDB metrics. * Both InfluxDbMetrics Reporter and Retriever rely on this configuration service. */ @Component(immediate = true) public class InfluxDbMetricsConfig { private final Logger log = getLogger(getClass()); private static final String DEFAULT_ADDRESS = "localhost"; private static final int DEFAULT_PORT = 8086; private static final String DEFAULT_DATABASE = "onos"; private static final String DEFAULT_USERNAME = "onos"; private static final String DEFAULT_PASSWORD = "onos.password"; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected InfluxDbMetricsReporter influxDbMetricsReporter; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected InfluxDbMetricsRetriever influxDbMetricsRetriever; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ComponentConfigService cfgService; @Property(name = "address", value = DEFAULT_ADDRESS, label = "IP address of influxDB server; default is localhost") protected String address = DEFAULT_ADDRESS; @Property(name = "port", intValue = DEFAULT_PORT, label = "Port number of influxDB server; default is 8086") protected int port = DEFAULT_PORT; @Property(name = "database", value = DEFAULT_DATABASE, label = "Database name of influxDB server; default is onos") protected String database = DEFAULT_DATABASE; @Property(name = "username", value = DEFAULT_USERNAME, label = "Username of influxDB server; default is onos") protected String username = DEFAULT_USERNAME; @Property(name = "password", value = DEFAULT_PASSWORD, label = "Password of influxDB server; default is onos.password") protected String password = DEFAULT_PASSWORD; @Activate public void activate() { cfgService.registerProperties(getClass()); coreService.registerApplication("org.onosproject.influxdbmetrics"); configReporter(influxDbMetricsReporter); configRetriever(influxDbMetricsRetriever); log.info("Started"); } @Deactivate public void deactivate() { cfgService.unregisterProperties(getClass(), false); log.info("Stopped"); } @Modified public void modified(ComponentContext context) { readComponentConfiguration(context); configReporter(influxDbMetricsReporter); influxDbMetricsReporter.restartReport(); configRetriever(influxDbMetricsRetriever); } private void configReporter(InfluxDbMetricsReporter reporter) { reporter.config(address, port, database, username, password); } private void configRetriever(InfluxDbMetricsRetriever retriever) { retriever.config(address, port, database, username, password); } /** * Extracts properties from the component configuration context. * * @param context the component context */ private void readComponentConfiguration(ComponentContext context) { Dictionary<?, ?> properties = context.getProperties(); String addressStr = Tools.get(properties, "address"); address = addressStr != null ? addressStr : DEFAULT_ADDRESS; log.info("Configured. InfluxDB server address is {}", address); String databaseStr = Tools.get(properties, "database"); database = databaseStr != null ? databaseStr : DEFAULT_DATABASE; log.info("Configured. InfluxDB server database is {}", database); String usernameStr = Tools.get(properties, "username"); username = usernameStr != null ? usernameStr : DEFAULT_USERNAME; log.info("Configured. InfluxDB server username is {}", username); String passwordStr = Tools.get(properties, "password"); password = passwordStr != null ? passwordStr : DEFAULT_PASSWORD; log.info("Configured. InfluxDB server password is {}", password); Integer portConfigured = Tools.getIntegerProperty(properties, "port"); if (portConfigured == null) { port = DEFAULT_PORT; log.info("InfluxDB port is not configured, default value is {}", port); } else { port = portConfigured; log.info("Configured. InfluxDB port is configured to {}", port); } } }
sdnwiselab/onos
apps/influxdbmetrics/src/main/java/org/onosproject/influxdbmetrics/InfluxDbMetricsConfig.java
Java
apache-2.0
5,759
/* * (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected]. * * Created on 06.09.2015 */ package net.finmath.integration; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import net.finmath.compatibility.java.util.function.DoubleUnaryOperator; import net.finmath.interpolation.RationalFunctionInterpolation; import net.finmath.interpolation.RationalFunctionInterpolation.ExtrapolationMethod; import net.finmath.interpolation.RationalFunctionInterpolation.InterpolationMethod; /** * @author Christian Fries * */ public class TrapezoidalRealIntegratorTest { private AbstractRealIntegral integral; @Before public void setUp() { final double lowerBound = 1.0; final double upperBound = 5.0; final int numberOfEvaluationPoints = 10000; integral = new TrapezoidalRealIntegrator(lowerBound, upperBound, numberOfEvaluationPoints); } @Test public void testCos() { DoubleUnaryOperator integrand = new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return Math.cos(x); } }; DoubleUnaryOperator integralAnalytic = new DoubleUnaryOperator() { @Override public double applyAsDouble(double x) { return Math.sin(x); } }; double value = integral.integrate(integrand); double valueAnalytic = integralAnalytic.applyAsDouble(integral.getUpperBound())-integralAnalytic.applyAsDouble(integral.getLowerBound()); double error = value-valueAnalytic; System.out.println("Result: " + value + ". \tError: " + error); Assert.assertEquals("Integreation error.", 0.0, error, 1E-7); } @Test public void testCubic() { DoubleUnaryOperator integrand = new DoubleUnaryOperator() { public double applyAsDouble(double x) { return 2 * x * x - x; } }; DoubleUnaryOperator integralAnalytic = new DoubleUnaryOperator() { public double applyAsDouble(double x) { return 2 * x * x * x / 3 - x * x / 2; } }; double value = integral.integrate(integrand); double valueAnalytic = integralAnalytic.applyAsDouble(integral.getUpperBound())-integralAnalytic.applyAsDouble(integral.getLowerBound()); double error = value-valueAnalytic; System.out.println("Result: " + value + ". \tError: " + error); Assert.assertEquals("Integreation error.", 0.0, error, 2.5E-7); } @Test public void testWithInterpolationFunction() { double[] points = { 0.0, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0 }; double[] values = { 1.0, 2.1, 3.5, 1.0, 4.0, 1.0, 7.0 }; RationalFunctionInterpolation interpolation = new RationalFunctionInterpolation(points, values, InterpolationMethod.LINEAR, ExtrapolationMethod.CONSTANT); double[] evaluationPoints = points; AbstractRealIntegral trapezoidalRealIntegrator = new TrapezoidalRealIntegrator(0.75, 3.5, evaluationPoints); AbstractRealIntegral simpsonRealIntegrator = new SimpsonRealIntegrator(0.75, 3.5, 2000); /* * Trapezoidal integration of the piece-wise linear function is exact, if we use points as integration points. * Simpson's rule is using an equi-distant discretization and is not exact. */ double valueTrapezoidal = trapezoidalRealIntegrator.integrate(interpolation); double valueSimpsons = simpsonRealIntegrator.integrate(interpolation); Assert.assertEquals("Difference of trapezoidal and Simpson's rule", 0.0, valueSimpsons-valueTrapezoidal, 0.000001); } }
NiklasRodi/finmath-lib
src/test/java6/net/finmath/integration/TrapezoidalRealIntegratorTest.java
Java
apache-2.0
3,395
/* * 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.jackrabbit.oak.index.indexer.document; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.io.Closer; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.index.IndexHelper; import org.apache.jackrabbit.oak.index.IndexerSupport; import org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileNodeStoreBuilder; import org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileStore; import org.apache.jackrabbit.oak.plugins.document.DocumentNodeState; import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore; import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore; import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection; import org.apache.jackrabbit.oak.plugins.index.IndexConstants; import org.apache.jackrabbit.oak.plugins.index.IndexUpdateCallback; import org.apache.jackrabbit.oak.plugins.index.NodeTraversalCallback; import org.apache.jackrabbit.oak.plugins.index.progress.IndexingProgressReporter; import org.apache.jackrabbit.oak.plugins.index.progress.MetricRateEstimator; import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore; import org.apache.jackrabbit.oak.plugins.metric.MetricStatisticsProvider; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.EmptyHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStateUtils; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.apache.jackrabbit.oak.stats.StatisticsProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.TYPE_PROPERTY_NAME; public class DocumentStoreIndexer implements Closeable{ private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger traversalLog = LoggerFactory.getLogger(DocumentStoreIndexer.class.getName()+".traversal"); private final Closer closer = Closer.create(); private final IndexHelper indexHelper; private final List<NodeStateIndexerProvider> indexerProviders; private final IndexerSupport indexerSupport; private final IndexingProgressReporter progressReporter = new IndexingProgressReporter(IndexUpdateCallback.NOOP, NodeTraversalCallback.NOOP); private final Set<String> indexerPaths = new HashSet<>(); public DocumentStoreIndexer(IndexHelper indexHelper, IndexerSupport indexerSupport) throws IOException { this.indexHelper = indexHelper; this.indexerSupport = indexerSupport; this.indexerProviders = createProviders(); } public void reindex() throws CommitFailedException, IOException { configureEstimators(); NodeState checkpointedState = indexerSupport.retrieveNodeStateForCheckpoint(); NodeStore copyOnWriteStore = new MemoryNodeStore(checkpointedState); indexerSupport.switchIndexLanesAndReindexFlag(copyOnWriteStore); NodeBuilder builder = copyOnWriteStore.getRoot().builder(); CompositeIndexer indexer = prepareIndexers(copyOnWriteStore, builder); if (indexer.isEmpty()) { return; } closer.register(indexer); //TODO How to ensure we can safely read from secondary DocumentNodeState rootDocumentState = (DocumentNodeState) checkpointedState; DocumentNodeStore nodeStore = (DocumentNodeStore) indexHelper.getNodeStore(); NodeStateEntryTraverser nsep = new NodeStateEntryTraverser(rootDocumentState.getRootRevision(), nodeStore, getMongoDocumentStore()) .withProgressCallback(this::reportDocumentRead) .withPathPredicate(indexer::shouldInclude); closer.register(nsep); //As first traversal is for dumping change the message prefix progressReporter.setMessagePrefix("Dumping"); //TODO Use flatFileStore only if we have relative nodes to be indexed FlatFileStore flatFileStore = new FlatFileNodeStoreBuilder(nsep, indexHelper.getWorkDir()) .withBlobStore(indexHelper.getGCBlobStore()) .withPreferredPathElements(indexer.getRelativeIndexedNodeNames()) .build(); closer.register(flatFileStore); progressReporter.reset(); if (flatFileStore.getEntryCount() > 0){ progressReporter.setNodeCountEstimator((String basePath, Set<String> indexPaths) -> flatFileStore.getEntryCount()); } progressReporter.reindexingTraversalStart("/"); Stopwatch indexerWatch = Stopwatch.createStarted(); for (NodeStateEntry entry : flatFileStore) { reportDocumentRead(entry.getPath()); indexer.index(entry); } progressReporter.reindexingTraversalEnd(); progressReporter.logReport(); log.info("Completed the indexing in {}", indexerWatch); copyOnWriteStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY); indexerSupport.postIndexWork(copyOnWriteStore); } private MongoDocumentStore getMongoDocumentStore() { return checkNotNull(indexHelper.getService(MongoDocumentStore.class)); } private void configureEstimators() { StatisticsProvider statsProvider = indexHelper.getStatisticsProvider(); if (statsProvider instanceof MetricStatisticsProvider) { MetricRegistry registry = ((MetricStatisticsProvider) statsProvider).getRegistry(); progressReporter.setTraversalRateEstimator(new MetricRateEstimator("async", registry)); } long nodesCount = getEstimatedDocumentCount(); if (nodesCount > 0) { progressReporter.setNodeCountEstimator((String basePath, Set<String> indexPaths) -> nodesCount); progressReporter.setEstimatedCount(nodesCount); log.info("Estimated number of documents in Mongo are {}", nodesCount); } } private long getEstimatedDocumentCount(){ MongoConnection mongoConnection = indexHelper.getService(MongoConnection.class); if (mongoConnection != null) { return mongoConnection.getDB().getCollection("nodes").count(); } return 0; } @Override public void close() throws IOException { closer.close(); } private void reportDocumentRead(String id) { try { progressReporter.traversedNode(() -> id); } catch (CommitFailedException e) { throw new RuntimeException(e); } traversalLog.trace(id); } protected CompositeIndexer prepareIndexers(NodeStore copyOnWriteStore, NodeBuilder builder) { NodeState root = copyOnWriteStore.getRoot(); List<NodeStateIndexer> indexers = new ArrayList<>(); for (String indexPath : indexHelper.getIndexPaths()) { NodeState indexState = NodeStateUtils.getNode(root, indexPath); NodeBuilder idxBuilder = IndexerSupport.childBuilder(builder, indexPath, false); String type = indexState.getString(TYPE_PROPERTY_NAME); if (type == null) { log.warn("No 'type' property found on indexPath [{}]. Skipping it", indexPath); continue; } removeIndexState(idxBuilder); idxBuilder.setProperty(IndexConstants.REINDEX_PROPERTY_NAME, false); for (NodeStateIndexerProvider indexerProvider : indexerProviders) { NodeStateIndexer indexer = indexerProvider.getIndexer(type, indexPath, idxBuilder, root, progressReporter); if (indexer != null) { indexers.add(indexer); closer.register(indexer); progressReporter.registerIndex(indexPath, true, -1); indexerPaths.add(indexPath); } } } return new CompositeIndexer(indexers); } private List<NodeStateIndexerProvider> createProviders() throws IOException { List<NodeStateIndexerProvider> providers = ImmutableList.of( createLuceneIndexProvider() ); providers.forEach(closer::register); return providers; } private NodeStateIndexerProvider createLuceneIndexProvider() throws IOException { return new LuceneIndexerProvider(indexHelper, indexerSupport); } //TODO OAK-7098 - Taken from IndexUpdate. Refactor to abstract out common logic like this private void removeIndexState(NodeBuilder definition) { // as we don't know the index content node name // beforehand, we'll remove all child nodes for (String rm : definition.getChildNodeNames()) { if (NodeStateUtils.isHidden(rm)) { NodeBuilder childNode = definition.getChildNode(rm); if (!childNode.getBoolean(IndexConstants.REINDEX_RETAIN)) { definition.getChildNode(rm).remove(); } } } } }
FlakyTestDetection/jackrabbit-oak
oak-run/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/DocumentStoreIndexer.java
Java
apache-2.0
10,248
/* * Copyright 2019 Netflix, 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.netflix.spinnaker.orca.webhook.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @Order @Component public class DefaultRestTemplateProvider implements RestTemplateProvider { private final RestTemplate restTemplate; @Autowired public DefaultRestTemplateProvider(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Override public boolean supports(String targetUrl) { return true; } @Override public RestTemplate getRestTemplate(String targetUrl) { return restTemplate; } }
duftler/orca
orca-webhook/src/main/groovy/com/netflix/spinnaker/orca/webhook/service/DefaultRestTemplateProvider.java
Java
apache-2.0
1,305
/* * 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.features.python.toolchain; import com.facebook.buck.core.rulekey.AddToRuleKey; import com.facebook.buck.core.rulekey.AddsToRuleKey; import com.facebook.buck.core.util.immutables.BuckStyleImmutable; import org.immutables.value.Value; @Value.Immutable(builder = false, copy = false) @BuckStyleImmutable public abstract class AbstractPythonVersion implements AddsToRuleKey { // TODO(cjhopman): This should add the interpreter name to the rulekey. @Value.Parameter public abstract String getInterpreterName(); @Value.Parameter @AddToRuleKey public abstract String getVersionString(); // X.Y @Override public String toString() { return getInterpreterName() + " " + getVersionString(); } }
shs96c/buck
src/com/facebook/buck/features/python/toolchain/AbstractPythonVersion.java
Java
apache-2.0
1,344
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT 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 was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.displayvideo.v1.model; /** * Represents a targetable authorized seller status. This will be populated in the * authorized_seller_status_details field when targeting_type is * `TARGETING_TYPE_AUTHORIZED_SELLER_STATUS`. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Display & Video 360 API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class AuthorizedSellerStatusTargetingOptionDetails extends com.google.api.client.json.GenericJson { /** * Output only. The authorized seller status. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String authorizedSellerStatus; /** * Output only. The authorized seller status. * @return value or {@code null} for none */ public java.lang.String getAuthorizedSellerStatus() { return authorizedSellerStatus; } /** * Output only. The authorized seller status. * @param authorizedSellerStatus authorizedSellerStatus or {@code null} for none */ public AuthorizedSellerStatusTargetingOptionDetails setAuthorizedSellerStatus(java.lang.String authorizedSellerStatus) { this.authorizedSellerStatus = authorizedSellerStatus; return this; } @Override public AuthorizedSellerStatusTargetingOptionDetails set(String fieldName, Object value) { return (AuthorizedSellerStatusTargetingOptionDetails) super.set(fieldName, value); } @Override public AuthorizedSellerStatusTargetingOptionDetails clone() { return (AuthorizedSellerStatusTargetingOptionDetails) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-displayvideo/v1/1.31.0/com/google/api/services/displayvideo/v1/model/AuthorizedSellerStatusTargetingOptionDetails.java
Java
apache-2.0
2,591
/* * 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.commons.proxy2.interceptor.matcher; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import org.apache.commons.proxy2.Invocation; import org.apache.commons.proxy2.interceptor.matcher.invocation.DeclaredByMatcher; import org.apache.commons.proxy2.util.AbstractTestCase; import org.apache.commons.proxy2.util.Echo; import org.apache.commons.proxy2.util.EchoImpl; import org.apache.commons.proxy2.util.MockInvocation; import org.junit.Test; public class DeclaredByMatcherTest extends AbstractTestCase { //---------------------------------------------------------------------------------------------------------------------- // Other Methods //---------------------------------------------------------------------------------------------------------------------- @Test public void testExactMatchNonMatching() throws Throwable { Method method = Echo.class.getMethod("echoBack", String.class); Invocation invocation = new MockInvocation(method, "foo"); InvocationMatcher matcher = new DeclaredByMatcher(EchoImpl.class, true); assertFalse(matcher.matches(invocation)); } @Test public void testWithSupertypeMatch() throws Throwable { Method method = Echo.class.getMethod("echoBack", String.class); Invocation invocation = new MockInvocation(method, "foo"); InvocationMatcher matcher = new DeclaredByMatcher(EchoImpl.class); assertTrue(matcher.matches(invocation)); } }
apache/commons-proxy
core/src/test/java/org/apache/commons/proxy2/interceptor/matcher/DeclaredByMatcherTest.java
Java
apache-2.0
2,369
package org.insightech.er.preference.page.template; import org.eclipse.swt.widgets.Composite; import org.insightech.er.preference.PreferenceInitializer; import org.insightech.er.preference.editor.FileListEditor; public class TemplateFileListEditor extends FileListEditor { public TemplateFileListEditor(final String name, final String labelText, final Composite parent) { super(name, labelText, parent, "*.xls"); } @Override protected String getStorePath(final String name) { return PreferenceInitializer.getTemplatePath(name); } }
roundrop/ermaster-fast
src/org/insightech/er/preference/page/template/TemplateFileListEditor.java
Java
apache-2.0
591
/* * Copyright 2002-2006,2009 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.opensymphony.xwork2.ognl; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.XWorkException; import com.opensymphony.xwork2.XWorkTestCase; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.interceptor.ChainingInterceptor; import com.opensymphony.xwork2.test.User; import com.opensymphony.xwork2.util.*; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; import ognl.*; import java.lang.reflect.Method; import java.util.*; /** * Unit test of {@link ognlUtil}. * * @version $Date: 2009-12-27 19:18:29 +0100 (Sun, 27 Dec 2009) $ $Id: OgnlUtilTest.java 894090 2009-12-27 18:18:29Z martinc $ */ public class OgnlUtilTest extends XWorkTestCase { private OgnlUtil ognlUtil; @Override public void setUp() throws Exception { super.setUp(); ognlUtil = container.getInstance(OgnlUtil.class); } public void testCanSetADependentObject() throws Exception { String dogName = "fido"; OgnlRuntime.setNullHandler(Owner.class, new NullHandler() { public Object nullMethodResult(Map map, Object o, String s, Object[] objects) { return null; } public Object nullPropertyValue(Map map, Object o, Object o1) { String methodName = o1.toString(); String getter = "set" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1); Method[] methods = o.getClass().getDeclaredMethods(); System.out.println(getter); for (Method method : methods) { String name = method.getName(); if (!getter.equals(name) || (method.getParameterTypes().length != 1)) { continue; } else { Class clazz = method.getParameterTypes()[0]; try { Object param = clazz.newInstance(); method.invoke(o, new Object[]{param}); return param; } catch (Exception e) { throw new RuntimeException(e); } } } return null; } }); Owner owner = new Owner(); Map context = Ognl.createDefaultContext(owner); Map props = new HashMap(); props.put("dog.name", dogName); ognlUtil.setProperties(props, owner, context); assertNotNull("expected Ognl to create an instance of Dog", owner.getDog()); assertEquals(dogName, owner.getDog().getName()); } public void testCacheEnabled() throws OgnlException { OgnlUtil.setEnableExpressionCache("true"); Object expr0 = ognlUtil.compile("test"); Object expr2 = ognlUtil.compile("test"); assertSame(expr0, expr2); } public void testCacheDisabled() throws OgnlException { OgnlUtil.setEnableExpressionCache("false"); Object expr0 = ognlUtil.compile("test"); Object expr2 = ognlUtil.compile("test"); assertNotSame(expr0, expr2); } public void testCanSetDependentObjectArray() { EmailAction action = new EmailAction(); Map<String, Object> context = Ognl.createDefaultContext(action); Map<String, Object> props = new HashMap<String, Object>(); props.put("email[0].address", "addr1"); props.put("email[1].address", "addr2"); props.put("email[2].address", "addr3"); ognlUtil.setProperties(props, action, context); assertEquals(3, action.email.size()); assertEquals("addr1", action.email.get(0).toString()); assertEquals("addr2", action.email.get(1).toString()); assertEquals("addr3", action.email.get(2).toString()); } public void testCopySameType() { Foo foo1 = new Foo(); Foo foo2 = new Foo(); Map context = Ognl.createDefaultContext(foo1); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.FEBRUARY); cal.set(Calendar.DAY_OF_MONTH, 12); cal.set(Calendar.YEAR, 1982); foo1.setTitle("blah"); foo1.setNumber(1); foo1.setPoints(new long[]{1, 2, 3}); foo1.setBirthday(cal.getTime()); foo1.setUseful(false); ognlUtil.copy(foo1, foo2, context); assertEquals(foo1.getTitle(), foo2.getTitle()); assertEquals(foo1.getNumber(), foo2.getNumber()); assertEquals(foo1.getPoints(), foo2.getPoints()); assertEquals(foo1.getBirthday(), foo2.getBirthday()); assertEquals(foo1.isUseful(), foo2.isUseful()); } public void testIncudeExcludes() { Foo foo1 = new Foo(); Foo foo2 = new Foo(); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.FEBRUARY); cal.set(Calendar.DAY_OF_MONTH, 12); cal.set(Calendar.YEAR, 1982); foo1.setPoints(new long[]{1, 2, 3}); foo1.setBirthday(cal.getTime()); foo1.setUseful(false); foo1.setTitle("foo1 title"); foo1.setNumber(1); foo2.setTitle("foo2 title"); foo2.setNumber(2); Map<String, Object> context = Ognl.createDefaultContext(foo1); List<String> excludes = new ArrayList<String>(); excludes.add("title"); excludes.add("number"); ognlUtil.copy(foo1, foo2, context, excludes, null); // these values should remain unchanged in foo2 assertEquals(foo2.getTitle(), "foo2 title"); assertEquals(foo2.getNumber(), 2); // these values should be changed/copied assertEquals(foo1.getPoints(), foo2.getPoints()); assertEquals(foo1.getBirthday(), foo2.getBirthday()); assertEquals(foo1.isUseful(), foo2.isUseful()); Bar b1 = new Bar(); Bar b2 = new Bar(); b1.setTitle("bar1 title"); b1.setSomethingElse(10); b1.setId(new Long(1)); b2.setTitle(""); b2.setId(new Long(2)); context = Ognl.createDefaultContext(b1); List<String> includes = new ArrayList<String>(); includes.add("title"); includes.add("somethingElse"); ognlUtil.copy(b1, b2, context, null, includes); // includes properties got copied assertEquals(b1.getTitle(), b2.getTitle()); assertEquals(b1.getSomethingElse(), b2.getSomethingElse()); // id properties did not assertEquals(b2.getId(), new Long(2)); } public void testCopyUnevenObjects() { Foo foo = new Foo(); Bar bar = new Bar(); Map<String, Object> context = Ognl.createDefaultContext(foo); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.FEBRUARY); cal.set(Calendar.DAY_OF_MONTH, 12); cal.set(Calendar.YEAR, 1982); foo.setTitle("blah"); foo.setNumber(1); foo.setPoints(new long[]{1, 2, 3}); foo.setBirthday(cal.getTime()); foo.setUseful(false); ognlUtil.copy(foo, bar, context); assertEquals(foo.getTitle(), bar.getTitle()); assertEquals(0, bar.getSomethingElse()); } public void testDeepSetting() { Foo foo = new Foo(); foo.setBar(new Bar()); Map<String, Object> context = Ognl.createDefaultContext(foo); Map<String, Object> props = new HashMap(); props.put("bar.title", "i am barbaz"); ognlUtil.setProperties(props, foo, context); assertEquals(foo.getBar().getTitle(), "i am barbaz"); } public void testNoExceptionForUnmatchedGetterAndSetterWithThrowPropertyException() { Map<String, Object> props = new HashMap<String, Object>(); props.put("myIntegerProperty", new Integer(1234)); TestObject testObject = new TestObject(); //this used to fail in OGNL versions < 2.7 ognlUtil.setProperties(props, testObject, true); assertEquals(1234, props.get("myIntegerProperty")); } public void testExceptionForWrongPropertyNameWithThrowPropertyException() { Map<String, Object> props = new HashMap<String, Object>(); props.put("myStringProperty", "testString"); TestObject testObject = new TestObject(); try { ognlUtil.setProperties(props, testObject, true); fail("Should rise NoSuchPropertyException because of wrong property name"); } catch (Exception e) { //expected } } public void testOgnlHandlesCrapAtTheEndOfANumber() { Foo foo = new Foo(); Map<String, Object> context = Ognl.createDefaultContext(foo); Map<String, Object> props = new HashMap<String, Object>(); props.put("aLong", "123a"); ognlUtil.setProperties(props, foo, context); assertEquals(0, foo.getALong()); } /** * Test that type conversion is performed on indexed collection properties. */ public void testSetIndexedValue() { ValueStack stack = ActionContext.getContext().getValueStack(); Map<String, Object> stackContext = stack.getContext(); stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.TRUE); stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE); stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE); User user = new User(); stack.push(user); // indexed string w/ existing array user.setList(new ArrayList<String>()); user.getList().add(""); String[] foo = new String[]{"asdf"}; stack.setValue("list[0]", foo); assertNotNull(user.getList()); assertEquals(1, user.getList().size()); assertEquals(String.class, user.getList().get(0).getClass()); assertEquals("asdf", user.getList().get(0)); } public void testSetPropertiesBoolean() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); Map props = new HashMap(); props.put("useful", "true"); ognlUtil.setProperties(props, foo, context); assertEquals(true, foo.isUseful()); props = new HashMap(); props.put("useful", "false"); ognlUtil.setProperties(props, foo, context); assertEquals(false, foo.isUseful()); } public void testSetPropertiesDate() { Locale orig = Locale.getDefault(); Locale.setDefault(Locale.US); Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); Map props = new HashMap(); props.put("birthday", "02/12/1982"); // US style test ognlUtil.setProperties(props, foo, context); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.FEBRUARY); cal.set(Calendar.DAY_OF_MONTH, 12); cal.set(Calendar.YEAR, 1982); assertEquals(cal.getTime(), foo.getBirthday()); Locale.setDefault(Locale.UK); //UK style test props.put("event", "18/10/2006 14:23:45"); props.put("meeting", "09/09/2006 14:30"); ognlUtil.setProperties(props, foo, context); cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.OCTOBER); cal.set(Calendar.DAY_OF_MONTH, 18); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.HOUR_OF_DAY, 14); cal.set(Calendar.MINUTE, 23); cal.set(Calendar.SECOND, 45); assertEquals(cal.getTime(), foo.getEvent()); cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.SEPTEMBER); cal.set(Calendar.DAY_OF_MONTH, 9); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.HOUR_OF_DAY, 14); cal.set(Calendar.MINUTE, 30); assertEquals(cal.getTime(), foo.getMeeting()); Locale.setDefault(orig); Locale.setDefault(orig); //test RFC 3339 date format for JSON props.put("event", "1996-12-19T16:39:57Z"); ognlUtil.setProperties(props, foo, context); cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 19); cal.set(Calendar.YEAR, 1996); cal.set(Calendar.HOUR_OF_DAY, 16); cal.set(Calendar.MINUTE, 39); cal.set(Calendar.SECOND, 57); assertEquals(cal.getTime(), foo.getEvent()); //test setting a calendar property props.put("calendar", "1996-12-19T16:39:57Z"); ognlUtil.setProperties(props, foo, context); assertEquals(cal, foo.getCalendar()); } public void testSetPropertiesInt() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); Map props = new HashMap(); props.put("number", "2"); ognlUtil.setProperties(props, foo, context); assertEquals(2, foo.getNumber()); } public void testSetPropertiesLongArray() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); Map props = new HashMap(); props.put("points", new String[]{"1", "2"}); ognlUtil.setProperties(props, foo, context); assertNotNull(foo.getPoints()); assertEquals(2, foo.getPoints().length); assertEquals(1, foo.getPoints()[0]); assertEquals(2, foo.getPoints()[1]); } public void testSetPropertiesString() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); Map props = new HashMap(); props.put("title", "this is a title"); ognlUtil.setProperties(props, foo, context); assertEquals(foo.getTitle(), "this is a title"); } public void testSetProperty() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); assertFalse(123456 == foo.getNumber()); ognlUtil.setProperty("number", "123456", foo, context); assertEquals(123456, foo.getNumber()); } public void testSetList() throws Exception { ChainingInterceptor foo = new ChainingInterceptor(); ChainingInterceptor foo2 = new ChainingInterceptor(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null); SimpleNode expression = (SimpleNode) Ognl.parseExpression("{'a','ruby','b','tom'}"); Ognl.getValue(expression, context, "aksdj"); final ValueStack stack = ActionContext.getContext().getValueStack(); Object result = Ognl.getValue(ognlUtil.compile("{\"foo\",'ruby','b','tom'}"), context, foo); foo.setIncludes((Collection) result); assertEquals(4, foo.getIncludes().size()); assertEquals("foo", foo.getIncludes().toArray()[0]); assertEquals("ruby", foo.getIncludes().toArray()[1]); assertEquals("b", "" + foo.getIncludes().toArray()[2]); assertEquals("tom", foo.getIncludes().toArray()[3]); Object result2 = Ognl.getValue(ognlUtil.compile("{\"foo\",'ruby','b','tom'}"), context, foo2); ognlUtil.setProperty("includes", result2, foo2, context); assertEquals(4, foo.getIncludes().size()); assertEquals("foo", foo.getIncludes().toArray()[0]); assertEquals("ruby", foo.getIncludes().toArray()[1]); assertEquals("b", "" + foo.getIncludes().toArray()[2]); assertEquals("tom", foo.getIncludes().toArray()[3]); result = ActionContext.getContext().getValueStack().findValue("{\"foo\",'ruby','b','tom'}"); foo.setIncludes((Collection) result); assertEquals(ArrayList.class, result.getClass()); assertEquals(4, foo.getIncludes().size()); assertEquals("foo", foo.getIncludes().toArray()[0]); assertEquals("ruby", foo.getIncludes().toArray()[1]); assertEquals("b", "" + foo.getIncludes().toArray()[2]); assertEquals("tom", foo.getIncludes().toArray()[3]); } public void testStringToLong() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); Map props = new HashMap(); props.put("aLong", "123"); ognlUtil.setProperties(props, foo, context); assertEquals(123, foo.getALong()); props.put("aLong", new String[]{"123"}); foo.setALong(0); ognlUtil.setProperties(props, foo, context); assertEquals(123, foo.getALong()); } public void testNullProperties() { Foo foo = new Foo(); foo.setALong(88); Map context = Ognl.createDefaultContext(foo); ognlUtil.setProperties(null, foo, context); assertEquals(88, foo.getALong()); Map props = new HashMap(); props.put("aLong", "99"); ognlUtil.setProperties(props, foo, context); assertEquals(99, foo.getALong()); } public void testCopyNull() { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); ognlUtil.copy(null, null, context); ognlUtil.copy(foo, null, context); ognlUtil.copy(null, foo, context); } public void testGetTopTarget() throws Exception { Foo foo = new Foo(); Map context = Ognl.createDefaultContext(foo); CompoundRoot root = new CompoundRoot(); Object top = ognlUtil.getRealTarget("top", context, root); assertEquals(root, top); // top should be root root.push(foo); Object val = ognlUtil.getRealTarget("unknown", context, root); assertNull(val); // not found } public void testGetBeanMap() throws Exception { Bar bar = new Bar(); bar.setTitle("I have beer"); Foo foo = new Foo(); foo.setALong(123); foo.setNumber(44); foo.setBar(bar); foo.setTitle("Hello Santa"); foo.setUseful(true); // just do some of the 15 tests Map beans = ognlUtil.getBeanMap(foo); assertNotNull(beans); assertEquals(19, beans.size()); assertEquals("Hello Santa", beans.get("title")); assertEquals(new Long("123"), beans.get("ALong")); assertEquals(new Integer("44"), beans.get("number")); assertEquals(bar, beans.get("bar")); assertEquals(Boolean.TRUE, beans.get("useful")); } public void testGetBeanMapNoReadMethod() throws Exception { MyWriteBar bar = new MyWriteBar(); bar.setBar("Sams"); Map beans = ognlUtil.getBeanMap(bar); assertEquals(2, beans.size()); assertEquals(new Integer("1"), beans.get("id")); assertEquals("There is no read method for bar", beans.get("bar")); } /** * XW-281 */ public void testSetBigIndexedValue() { ValueStack stack = ActionContext.getContext().getValueStack(); Map stackContext = stack.getContext(); stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.FALSE); stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE); stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE); User user = new User(); stack.push(user); // indexed string w/ existing array user.setList(new ArrayList()); String[] foo = new String[]{"asdf"}; ((OgnlValueStack)stack).setDevMode("true"); try { stack.setValue("list.1114778947765", foo); fail("non-valid expression: list.1114778947765"); } catch(RuntimeException ex) { ; // it's oke } try { stack.setValue("1114778947765", foo); fail("non-valid expression: 1114778947765"); } catch(RuntimeException ex) { ; } try { stack.setValue("1234", foo); fail("non-valid expression: 1114778947765"); } catch(RuntimeException ex) { ; } ((OgnlValueStack)stack).setDevMode("false"); stack.setValue("list.1114778947765", foo); stack.setValue("1114778947765", foo); stack.setValue("1234", foo); } public static class Email { String address; public void setAddress(String address) { this.address = address; } @Override public String toString() { return address; } } static class TestObject { private Integer myIntegerProperty; private Long myLongProperty; private String myStrProperty; public void setMyIntegerProperty(Integer myIntegerProperty) { this.myIntegerProperty = myIntegerProperty; } public String getMyIntegerProperty() { return myIntegerProperty.toString(); } public void setMyLongProperty(Long myLongProperty) { this.myLongProperty = myLongProperty; } public Long getMyLongProperty() { return myLongProperty; } public void setMyStrProperty(String myStrProperty) { this.myStrProperty = myStrProperty; } public String getMyStrProperty() { return myStrProperty; } } class EmailAction { public List email = new OgnlList(Email.class); public List getEmail() { return this.email; } } class OgnlList extends ArrayList { private Class clazz; public OgnlList(Class clazz) { this.clazz = clazz; } @Override public synchronized Object get(int index) { while (index >= this.size()) { try { this.add(clazz.newInstance()); } catch (Exception e) { throw new XWorkException(e); } } return super.get(index); } } private class MyWriteBar { private int id; public int getId() { return id; } public void setBar(String name) { if ("Sams".equals(name)) id = 1; else id = 999; } } }
yuzhongyousida/struts-2.3.1.2
src/xwork-core/src/test/java/com/opensymphony/xwork2/ognl/OgnlUtilTest.java
Java
apache-2.0
23,045
/** * Copyright 2017 Eternita LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.frontcache.wrapper; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; /** * * Wrapper for response * */ public class HttpResponseWrapperImpl extends HttpServletResponseWrapper implements FrontCacheHttpResponseWrapper { int BUFFER_SIZE = 4000; private StringWriter sw = new StringWriter(BUFFER_SIZE); public HttpResponseWrapperImpl(HttpServletResponse response) { super(response); } public PrintWriter getWriter() throws IOException { return new PrintWriter(sw); } public String getContentString() { return sw.toString(); } }
frontcache/frontcache
frontcache-core/src/main/java/org/frontcache/wrapper/HttpResponseWrapperImpl.java
Java
apache-2.0
1,316
/** * 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 io.hops.erasure_coding; import io.hops.metadata.hdfs.entity.EncodingStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.ErasureCodingFileSystem; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSOutputStream; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.util.Progressable; import org.apache.hadoop.util.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public abstract class BaseEncodingManager extends EncodingManager { public static enum LOGTYPES { ONLINE_RECONSTRUCTION, OFFLINE_RECONSTRUCTION, ENCODING } ; public static final Log LOG = LogFactory.getLog(BaseEncodingManager.class); public static final Log ENCODER_METRICS_LOG = LogFactory.getLog("RaidMetrics"); public static final String JOBUSER = "erasure_coding"; public static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); /** * hadoop configuration */ protected Configuration conf; // statistics about RAW hdfs blocks. This counts all replicas of a block. public static class Statistics { long numProcessedBlocks; // total blocks encountered in namespace long processedSize; // disk space occupied by all blocks long remainingSize; // total disk space post RAID long numMetaBlocks; // total blocks in metafile long metaSize; // total disk space for meta files public void clear() { numProcessedBlocks = 0; processedSize = 0; remainingSize = 0; numMetaBlocks = 0; metaSize = 0; } public String toString() { long save = processedSize - (remainingSize + metaSize); long savep = 0; if (processedSize > 0) { savep = (save * 100) / processedSize; } String msg = " numProcessedBlocks = " + numProcessedBlocks + " processedSize = " + processedSize + " postRaidSize = " + remainingSize + " numMetaBlocks = " + numMetaBlocks + " metaSize = " + metaSize + " %save in raw disk space = " + savep; return msg; } } BaseEncodingManager(Configuration conf) throws IOException { super(conf); try { initialize(conf); } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); throw e; } catch (Exception e) { throw new IOException(e); } } private void initialize(Configuration conf) throws IOException, SAXException, InterruptedException, ClassNotFoundException, ParserConfigurationException { this.conf = conf; } static long numBlocks(FileStatus stat) { return (long) Math.ceil(stat.getLen() * 1.0 / stat.getBlockSize()); } static long numStripes(long numBlocks, int stripeSize) { return (long) Math.ceil(numBlocks * 1.0 / stripeSize); } /** * RAID a list of files / directories */ void doRaid(Configuration conf, PolicyInfo info) throws IOException { int targetRepl = Integer.parseInt(info.getProperty( PolicyInfo.PROPERTY_REPLICATION)); int metaRepl = Integer.parseInt(info.getProperty( PolicyInfo.PROPERTY_PARITY_REPLICATION)); Codec codec = Codec.getCodec(info.getCodecId()); Path destPref = new Path(codec.parityDirectory); boolean copy = Boolean.valueOf(info.getProperty(PolicyInfo.PROPERTY_COPY)); Statistics statistics = new Statistics(); doRaid(conf, info.getSrcPath(), destPref, codec, statistics, RaidUtils.NULL_PROGRESSABLE, targetRepl, metaRepl, copy); LOG.info("RAID statistics " + statistics.toString()); } /** * RAID an individual file/directory */ static public boolean doRaid(Configuration conf, PolicyInfo info, Path src, Statistics statistics, Progressable reporter) throws IOException { int targetRepl = Integer.parseInt(info.getProperty( PolicyInfo.PROPERTY_REPLICATION)); int metaRepl = Integer.parseInt(info.getProperty( PolicyInfo.PROPERTY_PARITY_REPLICATION)); Codec codec = Codec.getCodec(info.getCodecId()); Path parityPath = new Path(info.getProperty( PolicyInfo.PROPERTY_PARITY_PATH)); boolean copy = Boolean.valueOf(info.getProperty(PolicyInfo.PROPERTY_COPY)); return doRaid(conf, src, parityPath, codec, statistics, reporter, targetRepl, metaRepl, copy); } public static boolean doRaid(Configuration conf, Path path, Path parityPath, Codec codec, Statistics statistics, Progressable reporter, int targetRepl, int metaRepl, boolean copy) throws IOException { long startTime = System.currentTimeMillis(); boolean success = false; try { return doFileRaid(conf, path, parityPath, codec, statistics, reporter, targetRepl, metaRepl, copy); } catch (IOException ioe) { throw ioe; } finally { long delay = System.currentTimeMillis() - startTime; long savingBytes = statistics.processedSize - statistics.remainingSize - statistics.metaSize; FileSystem srcFs = path.getFileSystem(conf); if (success) { logRaidEncodingMetrics("SUCCESS", codec, delay, statistics.processedSize, statistics.numProcessedBlocks, statistics.numMetaBlocks, statistics.metaSize, savingBytes, path, LOGTYPES.ENCODING, srcFs); } else { logRaidEncodingMetrics("FAILURE", codec, delay, statistics.processedSize, statistics.numProcessedBlocks, statistics.numMetaBlocks, statistics.metaSize, savingBytes, path, LOGTYPES.ENCODING, srcFs); } } } public static long getNumBlocks(FileStatus stat) { long numBlocks = stat.getLen() / stat.getBlockSize(); if (stat.getLen() % stat.getBlockSize() == 0) { return numBlocks; } else { return numBlocks + 1; } } /** * RAID an individual file */ public static boolean doFileRaid(Configuration conf, Path sourceFile, Path parityPath, Codec codec, Statistics statistics, Progressable reporter, int targetRepl, int metaRepl, boolean copy) throws IOException { DistributedFileSystem srcFs = Helper.getDFS(conf, sourceFile); FileStatus sourceStatus = srcFs.getFileStatus(sourceFile); // extract block locations from File system BlockLocation[] locations = srcFs.getFileBlockLocations(sourceFile, 0, sourceStatus.getLen()); // if the file has fewer than 2 blocks, then nothing to do if (locations.length <= 2) { return false; } // add up the raw disk space occupied by this file long diskSpace = 0; for (BlockLocation l : locations) { diskSpace += (l.getLength() * sourceStatus.getReplication()); } statistics.numProcessedBlocks += locations.length; statistics.processedSize += diskSpace; Path tmpFile = null; FSDataOutputStream out = null; try { if (copy) { tmpFile = new Path("/tmp" + sourceFile); out = srcFs.create(tmpFile, (short) targetRepl); DFSOutputStream dfsOut = (DFSOutputStream) out.getWrappedStream(); dfsOut.enableSourceStream(codec.getStripeLength()); } // generate parity file generateParityFile(conf, sourceStatus, reporter, srcFs, parityPath, codec, metaRepl, sourceStatus.getBlockSize(), tmpFile, out); if (copy) { out.close(); srcFs.rename(tmpFile, sourceFile, Options.Rename.OVERWRITE, Options.Rename.KEEP_ENCODING_STATUS); } else if (srcFs.setReplication(sourceFile, (short) targetRepl) == false) { LOG.info("Error in reducing replication of " + sourceFile + " to " + targetRepl); statistics.remainingSize += diskSpace; return false; } } catch (IOException e) { if (out != null) { out.close(); } throw e; } diskSpace = 0; for (BlockLocation l : locations) { diskSpace += (l.getLength() * targetRepl); } statistics.remainingSize += diskSpace; // the metafile will have this many number of blocks int numMeta = locations.length / codec.stripeLength; if (locations.length % codec.stripeLength != 0) { numMeta++; } // we create numMeta for every file. This metablock has metaRepl # replicas. // the last block of the metafile might not be completely filled up, but we // ignore that for now. statistics.numMetaBlocks += (numMeta * metaRepl); statistics.metaSize += (numMeta * metaRepl * sourceStatus.getBlockSize()); return true; } /** * Generate parity file */ static private void generateParityFile(Configuration conf, FileStatus sourceFile, Progressable reporter, FileSystem inFs, Path destPath, Codec codec, int metaRepl, long blockSize, Path copyPath, FSDataOutputStream copy) throws IOException { Path inpath = sourceFile.getPath(); FileSystem outFs = inFs; Encoder encoder = new Encoder(conf, codec); FileStatus srcStat = inFs.getFileStatus(inpath); long srcSize = srcStat.getLen(); long numBlocks = (srcSize % blockSize == 0) ? (srcSize / blockSize) : ((srcSize / blockSize) + 1); long numStripes = (numBlocks % codec.stripeLength == 0) ? (numBlocks / codec.stripeLength) : ((numBlocks / codec.stripeLength) + 1); StripeReader sReader = new FileStripeReader(conf, blockSize, codec, inFs, 0, inpath, srcSize); encoder.encodeFile(conf, inFs, inpath, outFs, destPath, (short) metaRepl, numStripes, blockSize, reporter, sReader, copyPath, copy); FileStatus outstat = outFs.getFileStatus(destPath); FileStatus inStat = inFs.getFileStatus(inpath); LOG.info("Source file " + inpath + " of size " + inStat.getLen() + " Parity file " + destPath + " of size " + outstat.getLen() + " src mtime " + sourceFile.getModificationTime() + " parity mtime " + outstat.getModificationTime()); } public static Decoder.DecoderInputStream unRaidCorruptInputStream( Configuration conf, Path srcPath, long blockSize, long corruptOffset, long limit) throws IOException { DistributedFileSystem srcFs = Helper.getDFS(conf, srcPath); EncodingStatus encodingStatus = srcFs.getEncodingStatus(srcPath.toUri().getPath()); Decoder decoder = new Decoder(conf, Codec.getCodec(encodingStatus.getEncodingPolicy().getCodec())); String parityFolder = conf.get(DFSConfigKeys.PARITY_FOLDER, DFSConfigKeys.DEFAULT_PARITY_FOLDER); return decoder.generateAlternateStream(srcFs, srcPath, srcFs, new Path(parityFolder + "/" + encodingStatus.getParityFileName()), blockSize, corruptOffset, limit, null); } /** * Returns current time. */ static long now() { return System.currentTimeMillis(); } /** * Make an absolute path relative by stripping the leading / */ static Path makeRelative(Path path) { if (!path.isAbsolute()) { return path; } String p = path.toUri().getPath(); String relative = p.substring(1, p.length()); return new Path(relative); } /** * Get the job id from the configuration */ public static String getJobID(Configuration conf) { return conf.get("mapred.job.id", "localRaid" + df.format(new Date())); } static public void logRaidEncodingMetrics(String result, Codec codec, long delay, long numReadBytes, long numReadBlocks, long metaBlocks, long metaBytes, long savingBytes, Path srcPath, LOGTYPES type, FileSystem fs) { try { JSONObject json = new JSONObject(); json.put("result", result); json.put("code", codec.id); json.put("delay", delay); json.put("readbytes", numReadBytes); json.put("readblocks", numReadBlocks); json.put("metablocks", metaBlocks); json.put("metabytes", metaBytes); json.put("savingbytes", savingBytes); json.put("path", srcPath.toString()); json.put("type", type.name()); json.put("cluster", fs.getUri().getAuthority()); ENCODER_METRICS_LOG.info(json.toString()); } catch (JSONException e) { LOG.warn("Exception when logging the Raid metrics: " + e.getMessage(), e); } } }
robzor92/hops
hops-erasure-coding-project/hops-erasure-coding/src/main/java/io/hops/erasure_coding/BaseEncodingManager.java
Java
apache-2.0
13,554
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.intellij.psi.codeStyle; import com.intellij.configurationStore.UnknownElementCollector; import com.intellij.configurationStore.UnknownElementWriter; import com.intellij.lang.Language; import com.intellij.lang.LanguageUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.ExtensionException; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.util.Processor; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ClassMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.util.*; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class CodeStyleSettings extends CommonCodeStyleSettings implements Cloneable, JDOMExternalizable { public static final int MAX_RIGHT_MARGIN = 1000; private static final Logger LOG = Logger.getInstance(CodeStyleSettings.class); private final ClassMap<CustomCodeStyleSettings> myCustomSettings = new ClassMap<>(); @NonNls private static final String ADDITIONAL_INDENT_OPTIONS = "ADDITIONAL_INDENT_OPTIONS"; @NonNls private static final String FILETYPE = "fileType"; private CommonCodeStyleSettingsManager myCommonSettingsManager = new CommonCodeStyleSettingsManager(this); private UnknownElementWriter myUnknownElementWriter = UnknownElementWriter.EMPTY; public CodeStyleSettings() { this(true); } public CodeStyleSettings(boolean loadExtensions) { super(null); initTypeToName(); initImportsByDefault(); if (loadExtensions) { final CodeStyleSettingsProvider[] codeStyleSettingsProviders = Extensions.getExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME); for (final CodeStyleSettingsProvider provider : codeStyleSettingsProviders) { addCustomSettings(provider.createCustomSettings(this)); } } } private void initImportsByDefault() { PACKAGES_TO_USE_IMPORT_ON_DEMAND.addEntry(new PackageEntry(false, "java.awt", false)); PACKAGES_TO_USE_IMPORT_ON_DEMAND.addEntry(new PackageEntry(false,"javax.swing", false)); IMPORT_LAYOUT_TABLE.addEntry(PackageEntry.ALL_OTHER_IMPORTS_ENTRY); IMPORT_LAYOUT_TABLE.addEntry(PackageEntry.BLANK_LINE_ENTRY); IMPORT_LAYOUT_TABLE.addEntry(new PackageEntry(false, "javax", true)); IMPORT_LAYOUT_TABLE.addEntry(new PackageEntry(false, "java", true)); IMPORT_LAYOUT_TABLE.addEntry(PackageEntry.BLANK_LINE_ENTRY); IMPORT_LAYOUT_TABLE.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY); } private void initTypeToName() { initGeneralLocalVariable(PARAMETER_TYPE_TO_NAME); initGeneralLocalVariable(LOCAL_VARIABLE_TYPE_TO_NAME); PARAMETER_TYPE_TO_NAME.addPair("*Exception", "e"); } private static void initGeneralLocalVariable(@NonNls TypeToNameMap map) { map.addPair("int", "i"); map.addPair("byte", "b"); map.addPair("char", "c"); map.addPair("long", "l"); map.addPair("short", "i"); map.addPair("boolean", "b"); map.addPair("double", "v"); map.addPair("float", "v"); map.addPair("java.lang.Object", "o"); map.addPair("java.lang.String", "s"); } public void setParentSettings(CodeStyleSettings parent) { myParentSettings = parent; } public CodeStyleSettings getParentSettings() { return myParentSettings; } private void addCustomSettings(CustomCodeStyleSettings settings) { if (settings != null) { synchronized (myCustomSettings) { myCustomSettings.put(settings.getClass(), settings); } } } public <T extends CustomCodeStyleSettings> T getCustomSettings(@NotNull Class<T> aClass) { synchronized (myCustomSettings) { //noinspection unchecked return (T)myCustomSettings.get(aClass); } } @Override public CodeStyleSettings clone() { CodeStyleSettings clone = new CodeStyleSettings(); clone.copyFrom(this); return clone; } private void copyCustomSettingsFrom(@NotNull CodeStyleSettings from) { synchronized (myCustomSettings) { myCustomSettings.clear(); for (final CustomCodeStyleSettings settings : from.getCustomSettingsValues()) { addCustomSettings((CustomCodeStyleSettings)settings.clone()); } FIELD_TYPE_TO_NAME.copyFrom(from.FIELD_TYPE_TO_NAME); STATIC_FIELD_TYPE_TO_NAME.copyFrom(from.STATIC_FIELD_TYPE_TO_NAME); PARAMETER_TYPE_TO_NAME.copyFrom(from.PARAMETER_TYPE_TO_NAME); LOCAL_VARIABLE_TYPE_TO_NAME.copyFrom(from.LOCAL_VARIABLE_TYPE_TO_NAME); PACKAGES_TO_USE_IMPORT_ON_DEMAND.copyFrom(from.PACKAGES_TO_USE_IMPORT_ON_DEMAND); IMPORT_LAYOUT_TABLE.copyFrom(from.IMPORT_LAYOUT_TABLE); OTHER_INDENT_OPTIONS.copyFrom(from.OTHER_INDENT_OPTIONS); myAdditionalIndentOptions.clear(); for (Map.Entry<FileType, IndentOptions> optionEntry : from.myAdditionalIndentOptions.entrySet()) { IndentOptions options = optionEntry.getValue(); myAdditionalIndentOptions.put(optionEntry.getKey(), (IndentOptions)options.clone()); } myCommonSettingsManager = from.myCommonSettingsManager.clone(this); } } public void copyFrom(CodeStyleSettings from) { copyPublicFields(from, this); copyCustomSettingsFrom(from); } public boolean USE_SAME_INDENTS; public boolean IGNORE_SAME_INDENTS_FOR_LANGUAGES; public boolean AUTODETECT_INDENTS = true; @SuppressWarnings("UnusedDeclaration") @Deprecated public final IndentOptions JAVA_INDENT_OPTIONS = new IndentOptions(); @SuppressWarnings("UnusedDeclaration") @Deprecated public final IndentOptions JSP_INDENT_OPTIONS = new IndentOptions(); @SuppressWarnings("UnusedDeclaration") @Deprecated public final IndentOptions XML_INDENT_OPTIONS = new IndentOptions(); public final IndentOptions OTHER_INDENT_OPTIONS = new IndentOptions(); private final Map<FileType,IndentOptions> myAdditionalIndentOptions = new LinkedHashMap<>(); private static final String ourSystemLineSeparator = SystemProperties.getLineSeparator(); /** * Line separator. It can be null if choosen line separator is "System-dependent"! */ public String LINE_SEPARATOR; /** * @return line separator. If choosen line separator is "System-dependent" method returns default separator for this OS. */ public String getLineSeparator() { return LINE_SEPARATOR != null ? LINE_SEPARATOR : ourSystemLineSeparator; } //----------------- NAMING CONVENTIONS -------------------- public String FIELD_NAME_PREFIX = ""; public String STATIC_FIELD_NAME_PREFIX = ""; public String PARAMETER_NAME_PREFIX = ""; public String LOCAL_VARIABLE_NAME_PREFIX = ""; public String FIELD_NAME_SUFFIX = ""; public String STATIC_FIELD_NAME_SUFFIX = ""; public String PARAMETER_NAME_SUFFIX = ""; public String LOCAL_VARIABLE_NAME_SUFFIX = ""; public boolean PREFER_LONGER_NAMES = true; public final TypeToNameMap FIELD_TYPE_TO_NAME = new TypeToNameMap(); public final TypeToNameMap STATIC_FIELD_TYPE_TO_NAME = new TypeToNameMap(); @NonNls public final TypeToNameMap PARAMETER_TYPE_TO_NAME = new TypeToNameMap(); public final TypeToNameMap LOCAL_VARIABLE_TYPE_TO_NAME = new TypeToNameMap(); //----------------- 'final' modifier settings ------- public boolean GENERATE_FINAL_LOCALS; public boolean GENERATE_FINAL_PARAMETERS; //----------------- visibility ----------------------------- public String VISIBILITY = "public"; //----------------- generate parentheses around method arguments ---------- public boolean PARENTHESES_AROUND_METHOD_ARGUMENTS = true; //----------------- annotations ---------------- public boolean USE_EXTERNAL_ANNOTATIONS; public boolean INSERT_OVERRIDE_ANNOTATION = true; //----------------- override ------------------- public boolean REPEAT_SYNCHRONIZED = true; //----------------- IMPORTS -------------------- public boolean LAYOUT_STATIC_IMPORTS_SEPARATELY = true; public boolean USE_FQ_CLASS_NAMES; @Deprecated public boolean USE_FQ_CLASS_NAMES_IN_JAVADOC = true; public boolean USE_SINGLE_CLASS_IMPORTS = true; public boolean INSERT_INNER_CLASS_IMPORTS; public int CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 5; public int NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = 3; public final PackageEntryTable PACKAGES_TO_USE_IMPORT_ON_DEMAND = new PackageEntryTable(); public final PackageEntryTable IMPORT_LAYOUT_TABLE = new PackageEntryTable(); //----------------- ORDER OF MEMBERS ------------------ public int STATIC_FIELDS_ORDER_WEIGHT = 1; public int FIELDS_ORDER_WEIGHT = 2; public int CONSTRUCTORS_ORDER_WEIGHT = 3; public int STATIC_METHODS_ORDER_WEIGHT = 4; public int METHODS_ORDER_WEIGHT = 5; public int STATIC_INNER_CLASSES_ORDER_WEIGHT = 6; public int INNER_CLASSES_ORDER_WEIGHT = 7; //----------------- WRAPPING --------------------------- /** * @deprecated Use get/setRightMargin() methods instead. */ @Deprecated public int RIGHT_MARGIN = 120; /** * <b>Do not use this field directly since it doesn't reflect a setting for a specific language which may * overwrite this one. Call {@link #isWrapOnTyping(Language)} method instead.</b> * * @see #WRAP_ON_TYPING */ public boolean WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN; // ---------------------------------- Javadoc formatting options ------------------------- public boolean ENABLE_JAVADOC_FORMATTING = true; /** * Align parameter comments to longest parameter name */ public boolean JD_ALIGN_PARAM_COMMENTS = true; /** * Align exception comments to longest exception name */ public boolean JD_ALIGN_EXCEPTION_COMMENTS = true; public boolean JD_ADD_BLANK_AFTER_PARM_COMMENTS; public boolean JD_ADD_BLANK_AFTER_RETURN; public boolean JD_ADD_BLANK_AFTER_DESCRIPTION = true; public boolean JD_P_AT_EMPTY_LINES = true; public boolean JD_KEEP_INVALID_TAGS = true; public boolean JD_KEEP_EMPTY_LINES = true; public boolean JD_DO_NOT_WRAP_ONE_LINE_COMMENTS; public boolean JD_USE_THROWS_NOT_EXCEPTION = true; public boolean JD_KEEP_EMPTY_PARAMETER = true; public boolean JD_KEEP_EMPTY_EXCEPTION = true; public boolean JD_KEEP_EMPTY_RETURN = true; public boolean JD_LEADING_ASTERISKS_ARE_ENABLED = true; public boolean JD_PRESERVE_LINE_FEEDS; public boolean JD_PARAM_DESCRIPTION_ON_NEW_LINE; // --------------------------------------------------------------------------------------- // ---------------------------------- Legacy(!) XML formatting options ------------------- /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_KEEP_WHITESPACES; /** * @deprecated Use XmlCodeStyleSettings. */ public int XML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; /** * @deprecated Use XmlCodeStyleSettings. */ public int XML_TEXT_WRAP = WRAP_AS_NEEDED; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_KEEP_LINE_BREAKS = true; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_KEEP_LINE_BREAKS_IN_TEXT = true; /** * @deprecated Use XmlCodeStyleSettings. */ public int XML_KEEP_BLANK_LINES = 2; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_ALIGN_ATTRIBUTES = true; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_ALIGN_TEXT; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_SPACE_AFTER_TAG_NAME; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_SPACE_INSIDE_EMPTY_TAG; /** * @deprecated Use XmlCodeStyleSettings. */ public boolean XML_KEEP_WHITE_SPACES_INSIDE_CDATA; /** * @deprecated Use XmlCodeStyleSettings. */ public int XML_WHITE_SPACE_AROUND_CDATA; // --------------------------------------------------------------------------------------- // ---------------------------------- HTML formatting options ------------------------- public boolean HTML_KEEP_WHITESPACES; public int HTML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; public int HTML_TEXT_WRAP = WRAP_AS_NEEDED; public boolean HTML_KEEP_LINE_BREAKS = true; public boolean HTML_KEEP_LINE_BREAKS_IN_TEXT = true; public int HTML_KEEP_BLANK_LINES = 2; public boolean HTML_ALIGN_ATTRIBUTES = true; public boolean HTML_ALIGN_TEXT; public boolean HTML_SPACE_AROUND_EQUALITY_IN_ATTRINUTE; public boolean HTML_SPACE_AFTER_TAG_NAME; public boolean HTML_SPACE_INSIDE_EMPTY_TAG; @NonNls public String HTML_ELEMENTS_TO_INSERT_NEW_LINE_BEFORE = "body,div,p,form,h1,h2,h3"; @NonNls public String HTML_ELEMENTS_TO_REMOVE_NEW_LINE_BEFORE = "br"; @NonNls public String HTML_DO_NOT_INDENT_CHILDREN_OF = "html,body,thead,tbody,tfoot"; public int HTML_DO_NOT_ALIGN_CHILDREN_OF_MIN_LINES; @NonNls public String HTML_KEEP_WHITESPACES_INSIDE = "span,pre,textarea"; @NonNls public String HTML_INLINE_ELEMENTS = "a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,input,kbd,label,q,s,samp,select,span,strike,strong,sub,sup,textarea,tt,u,var"; @NonNls public String HTML_DONT_ADD_BREAKS_IF_INLINE_CONTENT = "title,h1,h2,h3,h4,h5,h6,p"; public QuoteStyle HTML_QUOTE_STYLE = QuoteStyle.Double; public boolean HTML_ENFORCE_QUOTES = false; // --------------------------------------------------------------------------------------- // true if <%page import="x.y.z, x.y.t"%> // false if <%page import="x.y.z"%> // <%page import="x.y.t"%> public boolean JSP_PREFER_COMMA_SEPARATED_IMPORT_LIST; //---------------------------------------------------------------------------------------- // region Formatter control public boolean FORMATTER_TAGS_ENABLED; public String FORMATTER_ON_TAG = "@formatter:on"; public String FORMATTER_OFF_TAG = "@formatter:off"; public volatile boolean FORMATTER_TAGS_ACCEPT_REGEXP; private volatile Pattern myFormatterOffPattern; private volatile Pattern myFormatterOnPattern; @Nullable public Pattern getFormatterOffPattern() { if (myFormatterOffPattern == null && FORMATTER_TAGS_ENABLED && FORMATTER_TAGS_ACCEPT_REGEXP) { myFormatterOffPattern = getPatternOrDisableRegexp(FORMATTER_OFF_TAG); } return myFormatterOffPattern; } public void setFormatterOffPattern(@Nullable Pattern formatterOffPattern) { myFormatterOffPattern = formatterOffPattern; } @Nullable public Pattern getFormatterOnPattern() { if (myFormatterOffPattern == null && FORMATTER_TAGS_ENABLED && FORMATTER_TAGS_ACCEPT_REGEXP) { myFormatterOnPattern = getPatternOrDisableRegexp(FORMATTER_ON_TAG); } return myFormatterOnPattern; } public void setFormatterOnPattern(@Nullable Pattern formatterOnPattern) { myFormatterOnPattern = formatterOnPattern; } @Nullable private Pattern getPatternOrDisableRegexp(@NotNull String markerText) { try { return Pattern.compile(markerText); } catch (PatternSyntaxException pse) { LOG.error("Loaded regexp pattern is invalid: '" + markerText + "', error message: " + pse.getMessage()); FORMATTER_TAGS_ACCEPT_REGEXP = false; return null; } } // endregion //---------------------------------------------------------------------------------------- private CodeStyleSettings myParentSettings; private boolean myLoadedAdditionalIndentOptions; @NotNull private Collection<CustomCodeStyleSettings> getCustomSettingsValues() { synchronized (myCustomSettings) { return Collections.unmodifiableCollection(myCustomSettings.values()); } } @Override public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); if (LAYOUT_STATIC_IMPORTS_SEPARATELY) { // add <all other static imports> entry if there is none boolean found = false; for (PackageEntry entry : IMPORT_LAYOUT_TABLE.getEntries()) { if (entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY) { found = true; break; } } if (!found) { PackageEntry last = IMPORT_LAYOUT_TABLE.getEntryCount() == 0 ? null : IMPORT_LAYOUT_TABLE.getEntryAt(IMPORT_LAYOUT_TABLE.getEntryCount() - 1); if (last != PackageEntry.BLANK_LINE_ENTRY) { IMPORT_LAYOUT_TABLE.addEntry(PackageEntry.BLANK_LINE_ENTRY); } IMPORT_LAYOUT_TABLE.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY); } } UnknownElementCollector unknownElementCollector = new UnknownElementCollector(); for (CustomCodeStyleSettings settings : getCustomSettingsValues()) { settings.getKnownTagNames().forEach(unknownElementCollector::addKnownName); settings.readExternal(element); } unknownElementCollector.addKnownName(ADDITIONAL_INDENT_OPTIONS); List<Element> list = element.getChildren(ADDITIONAL_INDENT_OPTIONS); if (list != null) { for (Element additionalIndentElement : list) { String fileTypeId = additionalIndentElement.getAttributeValue(FILETYPE); if (!StringUtil.isEmpty(fileTypeId)) { FileType target = FileTypeManager.getInstance().getFileTypeByExtension(fileTypeId); if (FileTypes.UNKNOWN == target || FileTypes.PLAIN_TEXT == target || target.getDefaultExtension().isEmpty()) { target = new TempFileType(fileTypeId); } IndentOptions options = getDefaultIndentOptions(target); options.readExternal(additionalIndentElement); registerAdditionalIndentOptions(target, options); } } } unknownElementCollector.addKnownName(CommonCodeStyleSettingsManager.COMMON_SETTINGS_TAG); myCommonSettingsManager.readExternal(element); myUnknownElementWriter = unknownElementCollector.createWriter(element); if (USE_SAME_INDENTS) { IGNORE_SAME_INDENTS_FOR_LANGUAGES = true; } } @Override public void writeExternal(Element element) throws WriteExternalException { CodeStyleSettings parentSettings = new CodeStyleSettings(); DefaultJDOMExternalizer.writeExternal(this, element, new DifferenceFilter<>(this, parentSettings)); myUnknownElementWriter.write(element, getCustomSettingsValues(), CustomCodeStyleSettings::getTagName, settings -> { CustomCodeStyleSettings parentCustomSettings = parentSettings.getCustomSettings(settings.getClass()); if (parentCustomSettings == null) { throw new WriteExternalException("Custom settings are null for " + settings.getClass()); } settings.writeExternal(element, parentCustomSettings); }); if (!myAdditionalIndentOptions.isEmpty()) { FileType[] fileTypes = myAdditionalIndentOptions.keySet().toArray(new FileType[myAdditionalIndentOptions.keySet().size()]); Arrays.sort(fileTypes, (o1, o2) -> o1.getDefaultExtension().compareTo(o2.getDefaultExtension())); for (FileType fileType : fileTypes) { Element additionalIndentOptions = new Element(ADDITIONAL_INDENT_OPTIONS); myAdditionalIndentOptions.get(fileType).serialize(additionalIndentOptions, getDefaultIndentOptions(fileType)); additionalIndentOptions.setAttribute(FILETYPE, fileType.getDefaultExtension()); if (!additionalIndentOptions.getChildren().isEmpty()) { element.addContent(additionalIndentOptions); } } } myCommonSettingsManager.writeExternal(element); } private static IndentOptions getDefaultIndentOptions(FileType fileType) { final FileTypeIndentOptionsProvider[] providers = Extensions.getExtensions(FileTypeIndentOptionsProvider.EP_NAME); for (final FileTypeIndentOptionsProvider provider : providers) { if (provider.getFileType().equals(fileType)) { return getFileTypeIndentOptions(provider); } } return new IndentOptions(); } @Override @Nullable public IndentOptions getIndentOptions() { return OTHER_INDENT_OPTIONS; } /** * If the file type has an associated language and language indent options are defined, returns these options. Otherwise attempts to find * indent options from <code>FileTypeIndentOptionsProvider</code>. If none are found, other indent options are returned. * @param fileType The file type to search indent options for. * @return File type indent options or <code>OTHER_INDENT_OPTIONS</code>. * * @see FileTypeIndentOptionsProvider * @see LanguageCodeStyleSettingsProvider */ public IndentOptions getIndentOptions(@Nullable FileType fileType) { IndentOptions indentOptions = getLanguageIndentOptions(fileType); if (indentOptions != null) return indentOptions; if (USE_SAME_INDENTS || fileType == null) return OTHER_INDENT_OPTIONS; if (!myLoadedAdditionalIndentOptions) { loadAdditionalIndentOptions(); } indentOptions = myAdditionalIndentOptions.get(fileType); if (indentOptions != null) return indentOptions; return OTHER_INDENT_OPTIONS; } /** * If the document has an associated PsiFile, returns options for this file. Otherwise attempts to find associated VirtualFile and * return options for corresponding FileType. If none are found, other indent options are returned. * * @param project The project in which PsiFile should be searched. * @param document The document to search indent options for. * @return Indent options from the indent options providers or file type indent options or <code>OTHER_INDENT_OPTIONS</code>. * @see FileIndentOptionsProvider * @see FileTypeIndentOptionsProvider * @see LanguageCodeStyleSettingsProvider */ @NotNull public IndentOptions getIndentOptionsByDocument(@Nullable Project project, @NotNull Document document) { PsiFile file = project != null ? PsiDocumentManager.getInstance(project).getPsiFile(document) : null; if (file != null) return getIndentOptionsByFile(file); VirtualFile vFile = FileDocumentManager.getInstance().getFile(document); FileType fileType = vFile != null ? vFile.getFileType() : null; return getIndentOptions(fileType); } @NotNull public IndentOptions getIndentOptionsByFile(@Nullable PsiFile file) { return getIndentOptionsByFile(file, null); } @NotNull public IndentOptions getIndentOptionsByFile(@Nullable PsiFile file, @Nullable TextRange formatRange) { return getIndentOptionsByFile(file, formatRange, false, null); } /** * Retrieves indent options for PSI file from an associated document or (if not defined in the document) from file indent options * providers. * @param file The PSI file to retrieve options for. * @param formatRange The text range within the file for formatting purposes or null if there is either no specific range or multiple * ranges. If the range covers the entire file (full reformat), options stored in the document are ignored and * indent options are taken from file indent options providers. * @param ignoreDocOptions Ignore options stored in the document and use file indent options providers even if there is no text range * or the text range doesn't cover the entire file. * @param providerProcessor A callback object containing a reference to indent option provider which has returned indent options. * @return Indent options from the associated document or file indent options providers. * @see com.intellij.psi.codeStyle.FileIndentOptionsProvider */ @NotNull public IndentOptions getIndentOptionsByFile(@Nullable PsiFile file, @Nullable TextRange formatRange, boolean ignoreDocOptions, @Nullable Processor<FileIndentOptionsProvider> providerProcessor) { if (file != null && file.isValid()) { boolean isFullReformat = isFileFullyCoveredByRange(file, formatRange); if (!ignoreDocOptions && !isFullReformat) { IndentOptions options = IndentOptions.retrieveFromAssociatedDocument(file); if (options != null) { FileIndentOptionsProvider provider = options.getFileIndentOptionsProvider(); if (providerProcessor != null && provider != null) { providerProcessor.process(provider); } return options; } } for (FileIndentOptionsProvider provider : Extensions.getExtensions(FileIndentOptionsProvider.EP_NAME)) { if (!isFullReformat || provider.useOnFullReformat()) { IndentOptions indentOptions = provider.getIndentOptions(this, file); if (indentOptions != null) { if (providerProcessor != null) { providerProcessor.process(provider); } indentOptions.setFileIndentOptionsProvider(provider); logIndentOptions(file, provider, indentOptions); return indentOptions; } } } Language language = LanguageUtil.getLanguageForPsi(file.getProject(), file.getVirtualFile()); if (language != null) { IndentOptions options = getIndentOptions(language); if (options != null) { return options; } } return getIndentOptions(file.getFileType()); } else return OTHER_INDENT_OPTIONS; } private static boolean isFileFullyCoveredByRange(@NotNull PsiFile file, @Nullable TextRange formatRange) { return formatRange != null && file.getTextRange().equals(formatRange); } private static void logIndentOptions(@NotNull PsiFile file, @NotNull FileIndentOptionsProvider provider, @NotNull IndentOptions options) { LOG.debug("Indent options returned by " + provider.getClass().getName() + " for " + file.getName() + ": indent size=" + options.INDENT_SIZE + ", use tabs=" + options.USE_TAB_CHARACTER + ", tab size=" + options.TAB_SIZE); } @Nullable private IndentOptions getLanguageIndentOptions(@Nullable FileType fileType) { if (fileType == null || !(fileType instanceof LanguageFileType)) return null; Language lang = ((LanguageFileType)fileType).getLanguage(); return getIndentOptions(lang); } @Nullable private IndentOptions getIndentOptions(Language lang) { CommonCodeStyleSettings langSettings = getCommonSettings(lang); return langSettings == this ? null : langSettings.getIndentOptions(); } public boolean isSmartTabs(FileType fileType) { return getIndentOptions(fileType).SMART_TABS; } public int getIndentSize(FileType fileType) { return getIndentOptions(fileType).INDENT_SIZE; } public int getContinuationIndentSize(FileType fileType) { return getIndentOptions(fileType).CONTINUATION_INDENT_SIZE; } public int getLabelIndentSize(FileType fileType) { return getIndentOptions(fileType).LABEL_INDENT_SIZE; } public boolean getLabelIndentAbsolute(FileType fileType) { return getIndentOptions(fileType).LABEL_INDENT_ABSOLUTE; } public int getTabSize(FileType fileType) { return getIndentOptions(fileType).TAB_SIZE; } public boolean useTabCharacter(FileType fileType) { return getIndentOptions(fileType).USE_TAB_CHARACTER; } //used in generate equals/hashCode @SuppressWarnings("unused") public boolean isGenerateFinalLocals() { return GENERATE_FINAL_LOCALS; } //used in generate equals/hashCode @SuppressWarnings("unused") public boolean isGenerateFinalParameters() { return GENERATE_FINAL_PARAMETERS; } public static class TypeToNameMap implements JDOMExternalizable { private final List<String> myPatterns = new ArrayList<>(); private final List<String> myNames = new ArrayList<>(); public void addPair(String pattern, String name) { myPatterns.add(pattern); myNames.add(name); } public String nameByType(String type) { for (int i = 0; i < myPatterns.size(); i++) { String pattern = myPatterns.get(i); if (StringUtil.startsWithChar(pattern, '*')) { if (type.endsWith(pattern.substring(1))) { return myNames.get(i); } } else { if (type.equals(pattern)) { return myNames.get(i); } } } return null; } @Override public void readExternal(@NonNls Element element) throws InvalidDataException { myPatterns.clear(); myNames.clear(); for (final Object o : element.getChildren("pair")) { @NonNls Element e = (Element)o; String pattern = e.getAttributeValue("type"); String name = e.getAttributeValue("name"); if (pattern == null || name == null) { throw new InvalidDataException(); } myPatterns.add(pattern); myNames.add(name); } } @Override public void writeExternal(Element parentNode) throws WriteExternalException { for (int i = 0; i < myPatterns.size(); i++) { String pattern = myPatterns.get(i); String name = myNames.get(i); @NonNls Element element = new Element("pair"); parentNode.addContent(element); element.setAttribute("type", pattern); element.setAttribute("name", name); } } public void copyFrom(TypeToNameMap from) { assert from != this; myPatterns.clear(); myPatterns.addAll(from.myPatterns); myNames.clear(); myNames.addAll(from.myNames); } @Override public boolean equals(Object other) { if (other instanceof TypeToNameMap) { TypeToNameMap otherMap = (TypeToNameMap)other; return myPatterns.equals(otherMap.myPatterns) && myNames.equals(otherMap.myNames); } return false; } @Override public int hashCode() { int code = 0; for (String myPattern : myPatterns) { code += myPattern.hashCode(); } for (String myName : myNames) { code += myName.hashCode(); } return code; } } private void registerAdditionalIndentOptions(FileType fileType, IndentOptions options) { boolean exist = false; for (final FileType existing : myAdditionalIndentOptions.keySet()) { if (Comparing.strEqual(existing.getDefaultExtension(), fileType.getDefaultExtension())) { exist = true; break; } } if (!exist) { myAdditionalIndentOptions.put(fileType, options); } } public IndentOptions getAdditionalIndentOptions(FileType fileType) { if (!myLoadedAdditionalIndentOptions) { loadAdditionalIndentOptions(); } return myAdditionalIndentOptions.get(fileType); } private void loadAdditionalIndentOptions() { synchronized (myAdditionalIndentOptions) { myLoadedAdditionalIndentOptions = true; final FileTypeIndentOptionsProvider[] providers = Extensions.getExtensions(FileTypeIndentOptionsProvider.EP_NAME); for (final FileTypeIndentOptionsProvider provider : providers) { if (!myAdditionalIndentOptions.containsKey(provider.getFileType())) { registerAdditionalIndentOptions(provider.getFileType(), getFileTypeIndentOptions(provider)); } } } } private static IndentOptions getFileTypeIndentOptions(FileTypeIndentOptionsProvider provider) { try { return provider.createIndentOptions(); } catch (AbstractMethodError error) { LOG.error("Plugin uses obsolete API.", new ExtensionException(provider.getClass())); return new IndentOptions(); } } @TestOnly public void clearCodeStyleSettings() { CodeStyleSettings cleanSettings = new CodeStyleSettings(); copyFrom(cleanSettings); myAdditionalIndentOptions.clear(); //hack myLoadedAdditionalIndentOptions = false; } private static class TempFileType implements FileType { private final String myExtension; private TempFileType(@NotNull final String extension) { myExtension = extension; } @Override @NotNull public String getName() { return "TempFileType"; } @Override @NotNull public String getDescription() { return "TempFileType"; } @Override @NotNull public String getDefaultExtension() { return myExtension; } @Override public Icon getIcon() { return null; } @Override public boolean isBinary() { return false; } @Override public boolean isReadOnly() { return false; } @Override public String getCharset(@NotNull VirtualFile file, @NotNull byte[] content) { return null; } } public CommonCodeStyleSettings getCommonSettings(Language lang) { return myCommonSettingsManager.getCommonSettings(lang); } /** * @param langName The language name. * @return Language-specific code style settings or shared settings if not found. * @see CommonCodeStyleSettingsManager#getCommonSettings */ public CommonCodeStyleSettings getCommonSettings(String langName) { return myCommonSettingsManager.getCommonSettings(langName); } /** * Retrieves right margin for the given language. The language may overwrite default RIGHT_MARGIN value with its own RIGHT_MARGIN * in language's CommonCodeStyleSettings instance. * * @param language The language to get right margin for or null if root (default) right margin is requested. * @return The right margin for the language if it is defined (not null) and its settings contain non-negative margin. Root (default) * margin otherwise (CodeStyleSettings.RIGHT_MARGIN). */ public int getRightMargin(@Nullable Language language) { if (language != null) { CommonCodeStyleSettings langSettings = getCommonSettings(language); if (langSettings != null) { if (langSettings.RIGHT_MARGIN >= 0) return langSettings.RIGHT_MARGIN; } } return getDefaultRightMargin(); } /** * Assigns another right margin for the language or (if it is null) to root (default) margin. * * @param language The language to assign the right margin to or null if root (default) right margin is to be changed. * @param rightMargin New right margin. */ public void setRightMargin(@Nullable Language language, int rightMargin) { if (language != null) { CommonCodeStyleSettings langSettings = getCommonSettings(language); if (langSettings != null) { langSettings.RIGHT_MARGIN = rightMargin; return; } } setDefaultRightMargin(rightMargin); } @SuppressWarnings("deprecation") public int getDefaultRightMargin() { return RIGHT_MARGIN; } @SuppressWarnings("deprecation") public void setDefaultRightMargin(int rightMargin) { RIGHT_MARGIN = rightMargin; } /** * Defines whether or not wrapping should occur when typing reaches right margin. * @param language The language to check the option for or null for a global option. * @return True if wrapping on right margin is enabled. */ public boolean isWrapOnTyping(@Nullable Language language) { if (language != null) { CommonCodeStyleSettings langSettings = getCommonSettings(language); if (langSettings != null) { if (langSettings.WRAP_ON_TYPING != WrapOnTyping.DEFAULT.intValue) { return langSettings.WRAP_ON_TYPING == WrapOnTyping.WRAP.intValue; } } } //noinspection deprecation return WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN; } public enum QuoteStyle { Single("'"), Double("\""), None(""); public final String quote; QuoteStyle(String quote) { this.quote = quote; } } }
michaelgallacher/intellij-community
platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java
Java
apache-2.0
36,944
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.avro.ipc; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.avro.AvroRuntimeException; import org.apache.avro.UnresolvedUnionException; import org.apache.avro.Protocol; import org.apache.avro.Schema; import org.apache.avro.Protocol.Message; import org.apache.avro.util.ByteBufferInputStream; import org.apache.avro.util.ByteBufferOutputStream; import org.apache.avro.util.Utf8; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.Decoder; import org.apache.avro.io.Encoder; import org.apache.avro.io.EncoderFactory; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; /** Base class for the server side of a protocol interaction. */ public abstract class Responder { private static final Logger LOG = LoggerFactory.getLogger(Responder.class); private static final Schema META = Schema.createMap(Schema.create(Schema.Type.BYTES)); private static final GenericDatumReader<Map<String, ByteBuffer>> META_READER = new GenericDatumReader<>(META); private static final GenericDatumWriter<Map<String, ByteBuffer>> META_WRITER = new GenericDatumWriter<>(META); private static final ThreadLocal<Protocol> REMOTE = new ThreadLocal<>(); private final Map<MD5, Protocol> protocols = new ConcurrentHashMap<>(); private final Protocol local; private final MD5 localHash; protected final List<RPCPlugin> rpcMetaPlugins; protected Responder(Protocol local) { this.local = local; this.localHash = new MD5(); localHash.bytes(local.getMD5()); protocols.put(localHash, local); this.rpcMetaPlugins = new CopyOnWriteArrayList<>(); } /** * Return the remote protocol. Accesses a {@link ThreadLocal} that's set around * calls to {@link #respond(Protocol.Message, Object)}. */ public static Protocol getRemote() { return REMOTE.get(); } /** Return the local protocol. */ public Protocol getLocal() { return local; } /** * Adds a new plugin to manipulate per-call metadata. Plugins are executed in * the order that they are added. * * @param plugin a plugin that will manipulate RPC metadata */ public void addRPCPlugin(RPCPlugin plugin) { rpcMetaPlugins.add(plugin); } /** * Called by a server to deserialize a request, compute and serialize a response * or error. */ public List<ByteBuffer> respond(List<ByteBuffer> buffers) throws IOException { return respond(buffers, null); } /** * Called by a server to deserialize a request, compute and serialize a response * or error. Transceiver is used by connection-based servers to track handshake * status of connection. */ public List<ByteBuffer> respond(List<ByteBuffer> buffers, Transceiver connection) throws IOException { Decoder in = DecoderFactory.get().binaryDecoder(new ByteBufferInputStream(buffers), null); ByteBufferOutputStream bbo = new ByteBufferOutputStream(); BinaryEncoder out = EncoderFactory.get().binaryEncoder(bbo, null); Exception error = null; RPCContext context = new RPCContext(); List<ByteBuffer> payload = null; List<ByteBuffer> handshake = null; boolean wasConnected = connection != null && connection.isConnected(); try { Protocol remote = handshake(in, out, connection); out.flush(); if (remote == null) // handshake failed return bbo.getBufferList(); handshake = bbo.getBufferList(); // read request using remote protocol specification context.setRequestCallMeta(META_READER.read(null, in)); String messageName = in.readString(null).toString(); if (messageName.equals("")) // a handshake ping return handshake; Message rm = remote.getMessages().get(messageName); if (rm == null) throw new AvroRuntimeException("No such remote message: " + messageName); Message m = getLocal().getMessages().get(messageName); if (m == null) throw new AvroRuntimeException("No message named " + messageName + " in " + getLocal()); Object request = readRequest(rm.getRequest(), m.getRequest(), in); context.setMessage(rm); for (RPCPlugin plugin : rpcMetaPlugins) { plugin.serverReceiveRequest(context); } // create response using local protocol specification if ((m.isOneWay() != rm.isOneWay()) && wasConnected) throw new AvroRuntimeException("Not both one-way: " + messageName); Object response = null; try { REMOTE.set(remote); response = respond(m, request); context.setResponse(response); } catch (Exception e) { error = e; context.setError(error); LOG.warn("user error", e); } finally { REMOTE.set(null); } if (m.isOneWay() && wasConnected) // no response data return null; out.writeBoolean(error != null); if (error == null) writeResponse(m.getResponse(), response, out); else try { writeError(m.getErrors(), error, out); } catch (UnresolvedUnionException e) { // unexpected error throw error; } } catch (Exception e) { // system error LOG.warn("system error", e); context.setError(e); bbo = new ByteBufferOutputStream(); out = EncoderFactory.get().binaryEncoder(bbo, null); out.writeBoolean(true); writeError(Protocol.SYSTEM_ERRORS, new Utf8(e.toString()), out); if (null == handshake) { handshake = new ByteBufferOutputStream().getBufferList(); } } out.flush(); payload = bbo.getBufferList(); // Grab meta-data from plugins context.setResponsePayload(payload); for (RPCPlugin plugin : rpcMetaPlugins) { plugin.serverSendResponse(context); } META_WRITER.write(context.responseCallMeta(), out); out.flush(); // Prepend handshake and append payload bbo.prepend(handshake); bbo.append(payload); return bbo.getBufferList(); } private SpecificDatumWriter<HandshakeResponse> handshakeWriter = new SpecificDatumWriter<>(HandshakeResponse.class); private SpecificDatumReader<HandshakeRequest> handshakeReader = new SpecificDatumReader<>(HandshakeRequest.class); private Protocol handshake(Decoder in, Encoder out, Transceiver connection) throws IOException { if (connection != null && connection.isConnected()) return connection.getRemote(); HandshakeRequest request = handshakeReader.read(null, in); Protocol remote = protocols.get(request.getClientHash()); if (remote == null && request.getClientProtocol() != null) { remote = Protocol.parse(request.getClientProtocol().toString()); protocols.put(request.getClientHash(), remote); } HandshakeResponse response = new HandshakeResponse(); if (localHash.equals(request.getServerHash())) { response.setMatch(remote == null ? HandshakeMatch.NONE : HandshakeMatch.BOTH); } else { response.setMatch(remote == null ? HandshakeMatch.NONE : HandshakeMatch.CLIENT); } if (response.getMatch() != HandshakeMatch.BOTH) { response.setServerProtocol(local.toString()); response.setServerHash(localHash); } RPCContext context = new RPCContext(); context.setHandshakeRequest(request); context.setHandshakeResponse(response); for (RPCPlugin plugin : rpcMetaPlugins) { plugin.serverConnecting(context); } handshakeWriter.write(response, out); if (connection != null && response.getMatch() != HandshakeMatch.NONE) connection.setRemote(remote); return remote; } /** Computes the response for a message. */ public abstract Object respond(Message message, Object request) throws Exception; /** Reads a request message. */ public abstract Object readRequest(Schema actual, Schema expected, Decoder in) throws IOException; /** Writes a response message. */ public abstract void writeResponse(Schema schema, Object response, Encoder out) throws IOException; /** Writes an error message. */ public abstract void writeError(Schema schema, Object error, Encoder out) throws IOException; }
apache/avro
lang/java/ipc/src/main/java/org/apache/avro/ipc/Responder.java
Java
apache-2.0
9,308
/* Derby - Class org.apache.derby.impl.sql.compile.IndexToBaseRowNode 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.derby.impl.sql.compile; import java.util.List; import java.util.Properties; import org.apache.derby.catalog.types.ReferencedColumnsDescriptorImpl; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.reference.ClassName; import org.apache.derby.iapi.services.classfile.VMOpcode; import org.apache.derby.iapi.services.compiler.MethodBuilder; import org.apache.derby.iapi.services.context.ContextManager; import org.apache.derby.iapi.services.io.FormatableBitSet; import org.apache.derby.iapi.sql.compile.AccessPath; import org.apache.derby.iapi.sql.compile.CostEstimate; import org.apache.derby.iapi.sql.compile.Optimizable; import org.apache.derby.iapi.sql.compile.RequiredRowOrdering; import org.apache.derby.iapi.sql.compile.Visitor; import org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor; import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo; /** * This node type translates an index row to a base row. It takes a * FromBaseTable as its source ResultSetNode, and generates an * IndexRowToBaseRowResultSet that takes a TableScanResultSet on an * index conglomerate as its source. */ class IndexToBaseRowNode extends FromTable { protected FromBaseTable source; protected ConglomerateDescriptor baseCD; protected boolean cursorTargetTable; protected PredicateList restrictionList; protected boolean forUpdate; private FormatableBitSet heapReferencedCols; private FormatableBitSet indexReferencedCols; private FormatableBitSet allReferencedCols; private FormatableBitSet heapOnlyReferencedCols; IndexToBaseRowNode( FromBaseTable source, ConglomerateDescriptor baseCD, ResultColumnList resultColumns, boolean cursorTargetTable, FormatableBitSet heapReferencedCols, FormatableBitSet indexReferencedCols, PredicateList restrictionList, boolean forUpdate, Properties tableProperties, ContextManager cm) { super(null, tableProperties, cm); this.source = source; this.baseCD = baseCD; setResultColumns( resultColumns ); this.cursorTargetTable = cursorTargetTable; this.restrictionList = restrictionList; this.forUpdate = forUpdate; this.heapReferencedCols = heapReferencedCols; this.indexReferencedCols = indexReferencedCols; if (this.indexReferencedCols == null) { this.allReferencedCols = this.heapReferencedCols; heapOnlyReferencedCols = this.heapReferencedCols; } else { this.allReferencedCols = new FormatableBitSet(this.heapReferencedCols); this.allReferencedCols.or(this.indexReferencedCols); heapOnlyReferencedCols = new FormatableBitSet(allReferencedCols); heapOnlyReferencedCols.xor(this.indexReferencedCols); } } /** @see Optimizable#forUpdate */ @Override public boolean forUpdate() { return source.forUpdate(); } /** @see Optimizable#getTrulyTheBestAccessPath */ @Override public AccessPath getTrulyTheBestAccessPath() { // Get AccessPath comes from base table. return ((Optimizable) source).getTrulyTheBestAccessPath(); } @Override CostEstimate getCostEstimate() { return source.getTrulyTheBestAccessPath().getCostEstimate(); } @Override CostEstimate getFinalCostEstimate() { return source.getFinalCostEstimate(); } /** * Return whether or not the underlying ResultSet tree * is ordered on the specified columns. * RESOLVE - This method currently only considers the outermost table * of the query block. * * @param crs The specified ColumnReference[] * @param permuteOrdering Whether or not the order of the CRs in the array can be permuted * @param fbtHolder List that is to be filled with the FromBaseTable * * @return Whether the underlying ResultSet tree * is ordered on the specified column. * * @exception StandardException Thrown on error */ @Override boolean isOrderedOn(ColumnReference[] crs, boolean permuteOrdering, List<FromBaseTable> fbtHolder) throws StandardException { return source.isOrderedOn(crs, permuteOrdering, fbtHolder); } /** * Generation of an IndexToBaseRowNode creates an * IndexRowToBaseRowResultSet, which uses the RowLocation in the last * column of an index row to get the row from the base conglomerate (heap). * * @param acb The ActivationClassBuilder for the class being built * @param mb the method for the method to be built * * @exception StandardException Thrown on error */ @Override void generate(ActivationClassBuilder acb, MethodBuilder mb) throws StandardException { ValueNode restriction = null; /* ** Get the next ResultSet #, so that we can number this ResultSetNode, ** its ResultColumnList and ResultSet. */ assignResultSetNumber(); // Get the CostEstimate info for the underlying scan setCostEstimate( getFinalCostEstimate() ); /* Put the predicates back into the tree */ if (restrictionList != null) { restriction = restrictionList.restorePredicates(); /* Allow the restrictionList to get garbage collected now * that we're done with it. */ restrictionList = null; } // for the restriction, we generate an exprFun // that evaluates the expression of the clause // against the current row of the child's result. // if the restriction is empty, simply pass null // to optimize for run time performance. // generate the function and initializer: // Note: Boolean lets us return nulls (boolean would not) // private Boolean exprN() // { // return <<restriction.generate(ps)>>; // } // static Method exprN = method pointer to exprN; int heapColRefItem = -1; if (heapReferencedCols != null) { heapColRefItem = acb.addItem(heapReferencedCols); } int allColRefItem = -1; if (allReferencedCols != null) { allColRefItem = acb.addItem(allReferencedCols); } int heapOnlyColRefItem = -1; if (heapOnlyReferencedCols != null) { heapOnlyColRefItem = acb.addItem(heapOnlyReferencedCols); } /* Create the ReferencedColumnsDescriptorImpl which tells which columns * come from the index. */ int indexColMapItem = acb.addItem(new ReferencedColumnsDescriptorImpl(getIndexColMapping())); long heapConglomNumber = baseCD.getConglomerateNumber(); StaticCompiledOpenConglomInfo scoci = getLanguageConnectionContext(). getTransactionCompile(). getStaticCompiledConglomInfo(heapConglomNumber); acb.pushGetResultSetFactoryExpression(mb); mb.push(heapConglomNumber); mb.push(acb.addItem(scoci)); source.generate(acb, mb); mb.upCast(ClassName.NoPutResultSet); // Skip over the index columns that are propagated from the source // result set, if there are such columns. We won't pass the SQL NULL // wrappers down to store for those columns anyways, so no need to // generate them in the row template. // NOTE: We have to check for the case where indexReferencedCols is // not null, but no bits are set. This can happen when we need to get // all of the columns from the heap due to a check constraint. boolean skipPropagatedCols = indexReferencedCols != null && indexReferencedCols.getNumBitsSet() != 0; mb.push(acb.addItem(getResultColumns() .buildRowTemplate(heapReferencedCols, skipPropagatedCols))); mb.push(getResultSetNumber()); mb.push(source.getBaseTableName()); mb.push(heapColRefItem); mb.push(allColRefItem); mb.push(heapOnlyColRefItem); mb.push(indexColMapItem); // if there is no restriction, we just want to pass null. if (restriction == null) { mb.pushNull(ClassName.GeneratedMethod); } else { // this sets up the method and the static field. // generates: // Object userExprFun { } MethodBuilder userExprFun = acb.newUserExprFun(); // restriction knows it is returning its value; /* generates: * return <restriction.generate(acb)>; * and adds it to userExprFun * NOTE: The explicit cast to DataValueDescriptor is required * since the restriction may simply be a boolean column or subquery * which returns a boolean. For example: * where booleanColumn */ restriction.generate(acb, userExprFun); userExprFun.methodReturn(); // we are done modifying userExprFun, complete it. userExprFun.complete(); // restriction is used in the final result set as an access of the new static // field holding a reference to this new method. // generates: // ActivationClass.userExprFun // which is the static field that "points" to the userExprFun // that evaluates the where clause. acb.pushMethodReference(mb, userExprFun); } mb.push(forUpdate); mb.push(getCostEstimate().rowCount()); mb.push(getCostEstimate().getEstimatedCost()); mb.push( source.getTableDescriptor().getNumberOfColumns() ); mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getIndexRowToBaseRowResultSet", ClassName.NoPutResultSet, 15); /* The IndexRowToBaseRowResultSet generator is what we return */ /* ** Remember if this result set is the cursor target table, so we ** can know which table to use when doing positioned update and delete. */ if (cursorTargetTable) { acb.rememberCursorTarget(mb); } } /** * Return whether or not the underlying ResultSet tree will return * a single row, at most. * This is important for join nodes where we can save the extra next * on the right side if we know that it will return at most 1 row. * * @return Whether or not the underlying ResultSet tree will return a single row. * @exception StandardException Thrown on error */ @Override boolean isOneRowResultSet() throws StandardException { // Default is false return source.isOneRowResultSet(); } /** * Return whether or not the underlying FBT is for NOT EXISTS. * * @return Whether or not the underlying FBT is for NOT EXISTS. */ @Override boolean isNotExists() { return source.isNotExists(); } /** * Decrement (query block) level (0-based) for this FromTable. * This is useful when flattening a subquery. * * @param decrement The amount to decrement by. */ @Override void decrementLevel(int decrement) { source.decrementLevel(decrement); } /** * Get the lock mode for the target of an update statement * (a delete or update). The update mode will always be row for * CurrentOfNodes. It will be table if there is no where clause. * * @return The lock mode */ @Override int updateTargetLockMode() { return source.updateTargetLockMode(); } /** * @see ResultSetNode#adjustForSortElimination */ @Override void adjustForSortElimination() { /* NOTE: We use a different method to tell a FBT that * it cannot do a bulk fetch as the ordering issues are * specific to a FBT being under an IRTBR as opposed to a * FBT being under a PRN, etc. */ source.disableBulkFetch(); } /** * @see ResultSetNode#adjustForSortElimination */ @Override void adjustForSortElimination(RequiredRowOrdering rowOrdering) throws StandardException { /* rowOrdering is not important to this specific node, so * just call the no-arg version of the method. */ adjustForSortElimination(); /* Now pass the rowOrdering down to source, which may * need to do additional work. DERBY-3279. */ source.adjustForSortElimination(rowOrdering); } /** * Fill in the column mapping for those columns coming from the index. * * @return The int[] with the mapping. */ private int[] getIndexColMapping() { int rclSize = getResultColumns().size(); int[] indexColMapping = new int[rclSize]; for (int index = 0; index < rclSize; index++) { ResultColumn rc = getResultColumns().elementAt(index); if (indexReferencedCols != null && rc.getExpression() instanceof VirtualColumnNode) { // Column is coming from index VirtualColumnNode vcn = (VirtualColumnNode) rc.getExpression(); indexColMapping[index] = vcn.getSourceColumn().getVirtualColumnId() - 1; } else { // Column is not coming from index indexColMapping[index] = -1; } } return indexColMapping; } /** * Accept the visitor for all visitable children of this node. * * @param v the visitor * * @exception StandardException on error */ @Override void acceptChildren(Visitor v) throws StandardException { super.acceptChildren(v); if (source != null) { source = (FromBaseTable)source.accept(v); } } }
scnakandala/derby
java/engine/org/apache/derby/impl/sql/compile/IndexToBaseRowNode.java
Java
apache-2.0
13,664
// Copyright 2021 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES 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.tapestry5.commons.util; import org.apache.tapestry5.commons.internal.util.TapestryException; import org.apache.tapestry5.commons.services.Coercion; /** * Exception used when a {@link Coercion} throws an exception while * trying to coerce a value. * * @since 5.8.0 */ public class CoercionFailedException extends TapestryException { private static final long serialVersionUID = 1L; public CoercionFailedException(String message, Throwable cause) { super(message, cause); } }
apache/tapestry-5
commons/src/main/java/org/apache/tapestry5/commons/util/CoercionFailedException.java
Java
apache-2.0
1,142
/* * Copyright (c) 2005 - 2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.siddhi.core.executor.math.multiply; import org.wso2.siddhi.core.event.ComplexEvent; import org.wso2.siddhi.core.executor.ExpressionExecutor; import org.wso2.siddhi.query.api.definition.Attribute; public class MultiplyExpressionExecutorInt implements ExpressionExecutor { private ExpressionExecutor leftExpressionExecutor; private ExpressionExecutor rightExpressionExecutor; public MultiplyExpressionExecutorInt(ExpressionExecutor leftExpressionExecutor, ExpressionExecutor rightExpressionExecutor) { this.leftExpressionExecutor = leftExpressionExecutor; this.rightExpressionExecutor = rightExpressionExecutor; } @Override public Object execute(ComplexEvent event) { return ((Number) leftExpressionExecutor.execute(event)).intValue() * ((Number) rightExpressionExecutor.execute(event)).intValue(); } public Attribute.Type getReturnType() { return Attribute.Type.INT; } @Override public ExpressionExecutor cloneExecutor(String key) { return new MultiplyExpressionExecutorInt(leftExpressionExecutor.cloneExecutor(key), rightExpressionExecutor.cloneExecutor(key)); } }
lasanthafdo/siddhi
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/executor/math/multiply/MultiplyExpressionExecutorInt.java
Java
apache-2.0
1,863
/** * 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.jms; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; public class JmsNotIncludeAllJMSXPropertiesTest extends CamelTestSupport { @Test public void testNotIncludeAll() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:result").expectedHeaderReceived("foo", "bar"); getMockEndpoint("mock:result").expectedHeaderReceived("JMSXUserID", null); getMockEndpoint("mock:result").expectedHeaderReceived("JMSXAppID", null); Map headers = new HashMap(); headers.put("foo", "bar"); headers.put("JMSXUserID", "Donald"); headers.put("JMSXAppID", "MyApp"); template.sendBodyAndHeaders("activemq:queue:in", "Hello World", headers); assertMockEndpointsSatisfied(); } protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); JmsComponent jms = jmsComponentAutoAcknowledge(connectionFactory); jms.setIncludeAllJMSXProperties(false); camelContext.addComponent("activemq", jms); return camelContext; } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("activemq:queue:in") .to("mock:result"); } }; } }
kevinearls/camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsNotIncludeAllJMSXPropertiesTest.java
Java
apache-2.0
2,642
package com.medical.medicate; import android.annotation.TargetApi; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.IgnoreExtraProperties; import com.google.firebase.database.ValueEventListener; import android.Manifest; public class Navigation_SOS extends AppCompatActivity { private Button save_edit,activate_deactivate; private FirebaseDatabase mDatabase; private DatabaseReference mReference; private EditText enumber1,enumber2,enumber3; private String enumber1_value,enumber2_value,enumber3_value; public final static int REQUEST_CODE = 10101; int MY_PERMISSIONS_REQUEST_SEND_SMS; Intent service; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.navigation_sos); mDatabase = FirebaseDatabase.getInstance(); save_edit = (Button) findViewById(R.id.save_edit); activate_deactivate = (Button) findViewById(R.id.activate_deactivate); enumber1 = (EditText) findViewById(R.id.navigation_sos_number1); enumber2 = (EditText) findViewById(R.id.navigation_sos_number2); enumber3 = (EditText) findViewById(R.id.navigation_sos_number3); final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); mDatabase.getReference().child("users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI SOS sos = dataSnapshot.child("SOS_Service").getValue(SOS.class); if (sos != null) { enumber1.setText(sos.number1); enumber2.setText(sos.number2); enumber3.setText(sos.number3); enumber1.setEnabled(false); enumber2.setEnabled(false); enumber3.setEnabled(false); save_edit.setText("Edit"); } } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w("Read", "loadPost:onCancelled", databaseError.toException()); // ... } }); activate_deactivate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String check_activate=activate_deactivate.getText().toString(); Log.d("Success",""+check_activate); if(check_activate.equals("Start")) { Log.d("Here","Inside Activate"); if (checkDrawOverlayPermission()) { if (ContextCompat.checkSelfPermission(Navigation_SOS.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(Navigation_SOS.this, Manifest.permission.SEND_SMS)) { } else { ActivityCompat.requestPermissions(Navigation_SOS.this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS); } } else { startService(new Intent(getApplicationContext(), Navigation_SOS_Service.class)); activate_deactivate.setText("Stop"); } } } if(check_activate.equals("Stop")) { stopService(new Intent(getApplicationContext(), Navigation_SOS_Service.class)); Intent main=new Intent(getApplicationContext(),module_navigation.class); finish(); activate_deactivate.setText("Start"); startActivity(main); } } }); save_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String check=save_edit.getText().toString(); Log.d("Success",check+""); if(check.equals("Save")) { enumber1_value = enumber1.getText().toString(); enumber2_value = enumber2.getText().toString(); enumber3_value = enumber3.getText().toString(); if (validateNumber()) { mReference = mDatabase.getReference(); mReference.push().getKey(); SOS sos = new SOS(enumber1_value, enumber2_value, enumber3_value); mReference.child("users").child(userId).child("SOS_Service").setValue(sos); } enumber1.setText(enumber1_value); enumber2.setText(enumber2_value); enumber3.setText(enumber3_value); enumber1.setEnabled(false); enumber2.setEnabled(false); enumber3.setEnabled(false); save_edit.setText("Edit"); } if(check.equals("Edit")) { enumber1.setEnabled(true); enumber2.setEnabled(true); enumber3.setEnabled(true); save_edit.setText("Save"); } } }); } public boolean checkDrawOverlayPermission() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } if (!Settings.canDrawOverlays(this)) { /** if not construct intent to request permission */ Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); /** request permission via start activity for result */ startActivityForResult(intent, REQUEST_CODE); return false; } else { return true; } } @Override @TargetApi(Build.VERSION_CODES.M) protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) { if (Settings.canDrawOverlays(this)) { //startService(new Intent(this, Navigation_SOS_Service.class)); } } } public boolean validateNumber() { if (enumber1_value.length()!=10) { enumber1.setError("Invalid Phone Number"); enumber1.requestFocus(); return false; } if (enumber2_value.length()!=10) { enumber2.setError("Invalid Phone Number"); enumber2.requestFocus(); return false; } if (enumber3_value.length()!=10) { enumber3.setError("Invalid Phone Number"); enumber3.requestFocus(); return false; } return true; } @IgnoreExtraProperties public static class SOS { public String number1; public String number2; public String number3; public SOS() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public SOS(String number1, String number2,String number3) { this.number1 = number1; this.number2 = number2; this.number3 = number3; } } }
Nitin135/Medicate
app/src/main/java/com/medical/medicate/Navigation_SOS.java
Java
apache-2.0
10,385
package com.linkedin.thirdeye.bootstrap.topkrollup.phase2; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class TopKDimensionValues { private Map<String, Set<String>> topKDimensions; public TopKDimensionValues() { topKDimensions = new HashMap<String, Set<String>>(); } public Map<String, Set<String>> getTopKDimensions() { return topKDimensions; } public void setTopKDimensions(Map<String, Set<String>> topKDimensions) { this.topKDimensions = topKDimensions; } public void addValue(String dimension, String value) { if (topKDimensions.get(dimension) == null) { topKDimensions.put(dimension, new HashSet<String>()); } topKDimensions.get(dimension).add(value); } public void addMap(TopKDimensionValues valuesFile) { Map<String, Set<String>> values = valuesFile.getTopKDimensions(); for (Entry<String, Set<String>> entry : values.entrySet()) { if (topKDimensions.get(entry.getKey()) == null) { topKDimensions.put(entry.getKey(), new HashSet<String>()); } topKDimensions.get(entry.getKey()).addAll(entry.getValue()); } } }
pinotlytics/pinot
thirdeye/thirdeye-bootstrap/src/main/java/com/linkedin/thirdeye/bootstrap/topkrollup/phase2/TopKDimensionValues.java
Java
apache-2.0
1,255
/* * Copyright (C) 2017 The Android Open Source 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 com.google.android.exoplayer2.offline; import android.net.Uri; import androidx.annotation.Nullable; import com.google.android.exoplayer2.offline.DownloadRequest.UnsupportedRequestException; import com.google.android.exoplayer2.util.AtomicFile; import com.google.android.exoplayer2.util.Util; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Loads {@link DownloadRequest DownloadRequests} from legacy action files. * * @deprecated Legacy action files should be merged into download indices using {@link * ActionFileUpgradeUtil}. */ @Deprecated /* package */ final class ActionFile { private static final int VERSION = 0; private final AtomicFile atomicFile; /** * @param actionFile The file from which {@link DownloadRequest DownloadRequests} will be loaded. */ public ActionFile(File actionFile) { atomicFile = new AtomicFile(actionFile); } /** Returns whether the file or its backup exists. */ public boolean exists() { return atomicFile.exists(); } /** Deletes the action file and its backup. */ public void delete() { atomicFile.delete(); } /** * Loads {@link DownloadRequest DownloadRequests} from the file. * * @return The loaded {@link DownloadRequest DownloadRequests}, or an empty array if the file does * not exist. * @throws IOException If there is an error reading the file. */ public DownloadRequest[] load() throws IOException { if (!exists()) { return new DownloadRequest[0]; } InputStream inputStream = null; try { inputStream = atomicFile.openRead(); DataInputStream dataInputStream = new DataInputStream(inputStream); int version = dataInputStream.readInt(); if (version > VERSION) { throw new IOException("Unsupported action file version: " + version); } int actionCount = dataInputStream.readInt(); ArrayList<DownloadRequest> actions = new ArrayList<>(); for (int i = 0; i < actionCount; i++) { try { actions.add(readDownloadRequest(dataInputStream)); } catch (UnsupportedRequestException e) { // remove DownloadRequest is not supported. Ignore and continue loading rest. } } return actions.toArray(new DownloadRequest[0]); } finally { Util.closeQuietly(inputStream); } } private static DownloadRequest readDownloadRequest(DataInputStream input) throws IOException { String type = input.readUTF(); int version = input.readInt(); Uri uri = Uri.parse(input.readUTF()); boolean isRemoveAction = input.readBoolean(); int dataLength = input.readInt(); byte[] data; if (dataLength != 0) { data = new byte[dataLength]; input.readFully(data); } else { data = null; } // Serialized version 0 progressive actions did not contain keys. boolean isLegacyProgressive = version == 0 && DownloadRequest.TYPE_PROGRESSIVE.equals(type); List<StreamKey> keys = new ArrayList<>(); if (!isLegacyProgressive) { int keyCount = input.readInt(); for (int i = 0; i < keyCount; i++) { keys.add(readKey(type, version, input)); } } // Serialized version 0 and 1 DASH/HLS/SS actions did not contain a custom cache key. boolean isLegacySegmented = version < 2 && (DownloadRequest.TYPE_DASH.equals(type) || DownloadRequest.TYPE_HLS.equals(type) || DownloadRequest.TYPE_SS.equals(type)); String customCacheKey = null; if (!isLegacySegmented) { customCacheKey = input.readBoolean() ? input.readUTF() : null; } // Serialized version 0, 1 and 2 did not contain an id. We need to generate one. String id = version < 3 ? generateDownloadId(uri, customCacheKey) : input.readUTF(); if (isRemoveAction) { // Remove actions are not supported anymore. throw new UnsupportedRequestException(); } return new DownloadRequest(id, type, uri, keys, customCacheKey, data); } private static StreamKey readKey(String type, int version, DataInputStream input) throws IOException { int periodIndex; int groupIndex; int trackIndex; // Serialized version 0 HLS/SS actions did not contain a period index. if ((DownloadRequest.TYPE_HLS.equals(type) || DownloadRequest.TYPE_SS.equals(type)) && version == 0) { periodIndex = 0; groupIndex = input.readInt(); trackIndex = input.readInt(); } else { periodIndex = input.readInt(); groupIndex = input.readInt(); trackIndex = input.readInt(); } return new StreamKey(periodIndex, groupIndex, trackIndex); } private static String generateDownloadId(Uri uri, @Nullable String customCacheKey) { return customCacheKey != null ? customCacheKey : uri.toString(); } }
saki4510t/ExoPlayer
library/core/src/main/java/com/google/android/exoplayer2/offline/ActionFile.java
Java
apache-2.0
5,559
/** @hide */ @RestrictTo(LIBRARY_GROUP) package android.support.design.internal; import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.support.annotation.RestrictTo;
WeRockStar/iosched
third_party/material-components-android/lib/src/android/support/design/internal/package-info.java
Java
apache-2.0
202
/******************************************************************************* * Copyright (c) quickfixengine.org All rights reserved. * * This file is part of the QuickFIX FIX Engine * * This file may be distributed under the terms of the quickfixengine.org * license as defined by quickfixengine.org and appearing in the file * LICENSE included in the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.quickfixengine.org/LICENSE for licensing information. * * Contact [email protected] if any conditions of this licensing * are not clear to you. ******************************************************************************/ package quickfix.field; import quickfix.IntField; public class AllocLinkType extends IntField { static final long serialVersionUID = 20050617; public static final int FIELD = 197; public static final int F_X_NETTING = 0; public static final int F_X_SWAP = 1; public AllocLinkType() { super(197); } public AllocLinkType(int data) { super(197, data); } }
Forexware/quickfixj
src/main/java/quickfix/field/AllocLinkType.java
Java
apache-2.0
1,228
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.application.mgt.ui.client; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.common.model.xsd.ApplicationBasicInfo; import org.wso2.carbon.identity.application.common.model.xsd.IdentityProvider; import org.wso2.carbon.identity.application.common.model.xsd.ImportResponse; import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig; import org.wso2.carbon.identity.application.common.model.xsd.LocalAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.xsd.RequestPathAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider; import org.wso2.carbon.identity.application.common.model.xsd.SpFileContent; import org.wso2.carbon.identity.application.common.model.xsd.SpTemplate; import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceIdentityApplicationManagementClientException; import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceIdentityApplicationManagementException; import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub; import org.wso2.carbon.user.mgt.stub.UserAdminStub; import org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException; import org.wso2.carbon.user.mgt.stub.types.carbon.UserStoreInfo; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; /** * SOAP service client to perform Applicationmanagement operations. */ public class ApplicationManagementServiceClient { private IdentityApplicationManagementServiceStub stub; private static final Log log = LogFactory.getLog(ApplicationManagementServiceClient.class); boolean debugEnabled = log.isErrorEnabled(); private UserAdminStub userAdminStub; /** * A static variable is used to track if pagination support from the remote API is verified, as the client is * initiated per request. */ private static boolean paginationSupportVerified = false; /** * A static variable is used to track if pagination is supported from the remote API, as the client is * initiated per request. */ private static boolean paginationSupported = false; /** * @param cookie * @param backendServerURL * @param configCtx * @throws AxisFault */ public ApplicationManagementServiceClient(String cookie, String backendServerURL, ConfigurationContext configCtx) throws AxisFault { String serviceURL = backendServerURL + "IdentityApplicationManagementService"; String userAdminServiceURL = backendServerURL + "UserAdmin"; stub = new IdentityApplicationManagementServiceStub(configCtx, serviceURL); userAdminStub = new UserAdminStub(configCtx, userAdminServiceURL); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); ServiceClient userAdminClient = userAdminStub._getServiceClient(); Options userAdminOptions = userAdminClient.getOptions(); userAdminOptions.setManageSession(true); userAdminOptions.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); if (debugEnabled) { log.debug("Invoking service " + serviceURL); } } /** * @param serviceProvider * @throws AxisFault */ public void createApplicationWithTemplate(ServiceProvider serviceProvider, String templateName) throws AxisFault { try { if (debugEnabled) { log.debug(String.format("Registering Service Provider: %s using the SP Template: %s.", serviceProvider.getApplicationName(), templateName)); } stub.createApplicationWithTemplate(serviceProvider, templateName); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } } /** * @param applicationName * @return * @throws AxisFault */ public ServiceProvider getApplication(String applicationName) throws AxisFault { try { if (debugEnabled) { log.debug("Loading Service Provider " + applicationName); } return stub.getApplication(applicationName); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return null; } /** * @return * @throws AxisFault */ public ApplicationBasicInfo[] getAllApplicationBasicInfo() throws Exception { try { return stub.getAllApplicationBasicInfo(); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new ApplicationBasicInfo[0]; } /** * Get all basic application information for a matching filter. * * @param filter Application name filter * @return Application Basic Information array * @throws AxisFault */ public ApplicationBasicInfo[] getApplicationBasicInfo(String filter) throws AxisFault { try { return stub.getApplicationBasicInfo(filter); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new ApplicationBasicInfo[0]; } /** * Get all basic application information with pagination. * * @return * @throws AxisFault */ public ApplicationBasicInfo[] getAllPaginatedApplicationBasicInfo(int pageNumber) throws Exception { try { return stub.getAllPaginatedApplicationBasicInfo(pageNumber); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new ApplicationBasicInfo[0]; } /** * Get all basic application information for a matching filter with pagination. * * @param filter Application name filter * @return Application Basic Information array * @throws AxisFault */ public ApplicationBasicInfo[] getPaginatedApplicationBasicInfo(int pageNumber, String filter) throws AxisFault { try { return stub.getPaginatedApplicationBasicInfo(pageNumber, filter); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new ApplicationBasicInfo[0]; } /** * Get count of all basic applications. * * @return * @throws AxisFault */ public int getCountOfAllApplications() throws Exception { try { return stub.getCountOfAllApplications(); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return 0; } /** * Get count of all basic applications for a matching filter. * * @param filter Application name filter * @return Count of applications match the filter * @throws AxisFault */ public int getCountOfApplications(String filter) throws AxisFault { try { return stub.getCountOfApplications(filter); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return 0; } /** * @param serviceProvider * @throws AxisFault */ public void updateApplicationData(ServiceProvider serviceProvider) throws Exception { try { stub.updateApplication(serviceProvider); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } } /** * @param applicationID * @throws AxisFault */ public void deleteApplication(String applicationID) throws Exception { try { stub.deleteApplication(applicationID); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } } /** * @param identityProviderName * @throws AxisFault */ public IdentityProvider getFederatedIdentityProvider(String identityProviderName) throws AxisFault { try { return stub.getIdentityProvider(identityProviderName); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return null; } /** * @return * @throws AxisFault */ public RequestPathAuthenticatorConfig[] getAllRequestPathAuthenticators() throws AxisFault { try { return stub.getAllRequestPathAuthenticators(); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new RequestPathAuthenticatorConfig[0]; } /** * @return * @throws AxisFault */ public LocalAuthenticatorConfig[] getAllLocalAuthenticators() throws AxisFault { try { return stub.getAllLocalAuthenticators(); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new LocalAuthenticatorConfig[0]; } /** * @return * @throws AxisFault */ public IdentityProvider[] getAllFederatedIdentityProvider() throws AxisFault { try { return stub.getAllIdentityProviders(); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new IdentityProvider[0]; } /** * @return * @throws AxisFault */ public String[] getAllClaimUris() throws AxisFault { try { return stub.getAllLocalClaimUris(); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new String[0]; } /** * Get User Store Domains * * @return * @throws AxisFault */ public String[] getUserStoreDomains() throws AxisFault { try { List<String> readWriteDomainNames = new ArrayList<String>(); UserStoreInfo[] storesInfo = userAdminStub.getUserRealmInfo().getUserStoresInfo(); for (UserStoreInfo storeInfo : storesInfo) { if (!storeInfo.getReadOnly()) { readWriteDomainNames.add(storeInfo.getDomainName()); } } return readWriteDomainNames.toArray(new String[readWriteDomainNames.size()]); } catch (RemoteException | UserAdminUserAdminException e) { throw new AxisFault("Error occurred while retrieving Read-Write User Store Domain IDs for logged-in" + " user's tenant realm"); } } /** * Retrieve the configured authentication templates as a JSON String. * * @return Authentication template configuration * @throws AxisFault */ public String getAuthenticationTemplatesJson() throws AxisFault { try { return stub.getAuthenticationTemplatesJSON(); } catch (RemoteException e) { throw new AxisFault("Error occurred while retrieving authentication flow templates", e); } } public ImportResponse importApplication(SpFileContent spFileContent) throws AxisFault { try { if (debugEnabled) { log.debug("Importing Service Provider from file : " + spFileContent.getFileName()); } return stub.importApplication(spFileContent); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return new ImportResponse(); } public String exportApplication(String appid, boolean exportSecrets) throws AxisFault { try { if (debugEnabled) { log.debug("Exporting Service Provider to file"); } return stub.exportApplication(appid, exportSecrets); } catch (RemoteException | IdentityApplicationManagementServiceIdentityApplicationManagementException e) { handleException(e); } return null; } /** * Create an application template. * * @param spTemplate service provider template info * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public void createApplicationTemplate(SpTemplate spTemplate) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Registering Service Provider template: " + spTemplate.getName()); } stub.createApplicationTemplate(spTemplate); } catch (RemoteException e) { handleException(e, "Error occurred when creating Service Provider template: " + spTemplate.getName()); } } /** * Add configured service provider as a template. * * @param serviceProvider Service provider to be configured as a template * @param spTemplate service provider template basic info * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public void createApplicationTemplateFromSP(ServiceProvider serviceProvider, SpTemplate spTemplate) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Adding Service Provider:" + serviceProvider.getApplicationName() + " as a template " + "with name: " + spTemplate.getName()); } stub.createApplicationTemplateFromSP(serviceProvider, spTemplate); } catch (RemoteException e) { handleException(e, "Error occurred when creating Service Provider template: " + spTemplate.getName() + " from service provider: " + serviceProvider.getApplicationName()); } } /** * Get Service provider template. * * @param templateName template name * @return service provider template info * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public SpTemplate getApplicationTemplate(String templateName) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Retrieving Service Provider template: " + templateName); } return stub.getApplicationTemplate(templateName); } catch (RemoteException e) { handleException(e, "Error occurred when retrieving Service Provider template: " + templateName); } return null; } /** * Delete an application template. * * @param templateName name of the template * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public void deleteApplicationTemplate(String templateName) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Deleting Service Provider template: " + templateName); } stub.deleteApplicationTemplate(templateName); } catch (RemoteException e) { handleException(e, "Error occurred when deleting Service Provider template: " + templateName); } } /** * Update an application template. * * @param spTemplate SP template info to be updated * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public void updateApplicationTemplate(String templateName, SpTemplate spTemplate) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Updating Service Provider template: " + templateName); } stub.updateApplicationTemplate(templateName, spTemplate); } catch (RemoteException e) { handleException(e, "Error occurred when updating Service Provider template: " + templateName); } } /** * Check existence of a application template. * * @param templateName template name * @return true if a template with the specified name exists * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public boolean isExistingApplicationTemplate(String templateName) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Checking existence of application template: " + templateName); } return stub.isExistingApplicationTemplate(templateName); } catch (RemoteException e) { handleException(e, "Error occurred when checking existence of Service Provider template: " + templateName); } return false; } /** * Get basic info of all the service provider templates. * * @return Array of all application templates * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public SpTemplate[] getAllApplicationTemplateInfo() throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { if (debugEnabled) { log.debug("Get all service provider template basic info."); } return stub.getAllApplicationTemplateInfo(); } catch (RemoteException e) { handleException(e, "Error occurred when retrieving service provider template basic info"); } return new SpTemplate[0]; } private void handleException(Exception e) throws AxisFault { String errorMessage = "Unknown error occurred."; if (e instanceof IdentityApplicationManagementServiceIdentityApplicationManagementException) { IdentityApplicationManagementServiceIdentityApplicationManagementException exception = (IdentityApplicationManagementServiceIdentityApplicationManagementException) e; if (exception.getFaultMessage().getIdentityApplicationManagementException() != null) { errorMessage = exception.getFaultMessage().getIdentityApplicationManagementException().getMessage(); } } else { errorMessage = e.getMessage(); } throw new AxisFault(errorMessage, e); } private void handleException(RemoteException e, String msg) throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { log.error(msg, e); throw new IdentityApplicationManagementServiceIdentityApplicationManagementClientException( "Server error occurred."); } /** * Returns if pagination is supported in the remote API. * This API is introduced to ensure that nothing breaks by invoking paginated APIs when API backend is not * available. * * @return 'true' if pagination is supported */ public boolean isPaginationSupported() { if (!paginationSupportVerified) { try { this.getCountOfAllApplications(); paginationSupported = true; if (log.isDebugEnabled()) { log.debug("IdentityApplicationManagementService stub and backend supports for SP pagination. Set " + "'paginationSupported' flag to 'true'."); } } catch (Exception | NoSuchMethodError e) { if (log.isDebugEnabled()) { log.debug("IdentityApplicationManagementService stub or backend does not supports for SP " + "pagination. Set 'paginationSupported' flag to 'false'."); } paginationSupported = false; } paginationSupportVerified = true; } return paginationSupported; } /** * Returns an array of custom inbound authenticator configs. * * @return InboundAuthenticationRequestConfig[] * @throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException */ public InboundAuthenticationRequestConfig[] getCustomInboundAuthenticatorConfigs() throws IdentityApplicationManagementServiceIdentityApplicationManagementClientException { try { return stub.getCustomInboundAuthenticatorConfigs(); } catch (RemoteException e) { handleException(e, "Error occurrred while retrieving inbound custom authenticator configs."); } return new InboundAuthenticationRequestConfig[0]; } }
wso2/carbon-identity-framework
components/application-mgt/org.wso2.carbon.identity.application.mgt.ui/src/main/java/org/wso2/carbon/identity/application/mgt/ui/client/ApplicationManagementServiceClient.java
Java
apache-2.0
22,835
/* * 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.commons.jci2.examples.commandline; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Iterator; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.jci2.compilers.CompilationResult; import org.apache.commons.jci2.compilers.JavaCompiler; import org.apache.commons.jci2.compilers.JavaCompilerFactory; import org.apache.commons.jci2.compilers.JavaCompilerSettings; import org.apache.commons.jci2.problems.CompilationProblem; import org.apache.commons.jci2.problems.CompilationProblemHandler; import org.apache.commons.jci2.readers.FileResourceReader; import org.apache.commons.jci2.readers.ResourceReader; import org.apache.commons.jci2.stores.FileResourceStore; import org.apache.commons.jci2.stores.ResourceStore; /** * A simple front end to jci2 mimicking the javac command line * * @author tcurdt */ public final class CommandlineCompiler { public static void main( final String[] args ) throws Exception { final Options options = new Options(); options.addOption( OptionBuilder.withArgName("a.jar:b.jar") .hasArg() .withValueSeparator( ':' ) .withDescription("Specify where to find user class files") .create( "classpath" )); options.addOption( OptionBuilder.withArgName("release") .hasArg() .withDescription("Provide source compatibility with specified release") .create( "source" )); options.addOption( OptionBuilder.withArgName("release") .hasArg() .withDescription("Generate class files for specific VM version") .create( "target" )); options.addOption( OptionBuilder.withArgName("path") .hasArg() .withDescription("Specify where to find input source files") .create( "sourcepath" )); options.addOption( OptionBuilder.withArgName("directory") .hasArg() .withDescription("Specify where to place generated class files") .create( "d" )); options.addOption( OptionBuilder.withArgName("num") .hasArg() .withDescription("Stop compilation after these number of errors") .create( "Xmaxerrs" )); options.addOption( OptionBuilder.withArgName("num") .hasArg() .withDescription("Stop compilation after these number of warning") .create( "Xmaxwarns" )); options.addOption( OptionBuilder.withDescription("Generate no warnings") .create( "nowarn" )); // final HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("jci2", options); final CommandLineParser parser = new GnuParser(); final CommandLine cmd = parser.parse(options, args, true); ClassLoader classloader = CommandlineCompiler.class.getClassLoader(); File sourcepath = new File("."); File targetpath = new File("."); int maxerrs = 10; int maxwarns = 10; final boolean nowarn = cmd.hasOption("nowarn"); final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse"); final JavaCompilerSettings settings = compiler.createDefaultSettings(); for (final Iterator it = cmd.iterator(); it.hasNext();) { final Option option = (Option) it.next(); if ("classpath".equals(option.getOpt())) { final String[] values = option.getValues(); final URL[] urls = new URL[values.length]; for (int i = 0; i < urls.length; i++) { urls[i] = new File(values[i]).toURL(); } classloader = new URLClassLoader(urls); } else if ("source".equals(option.getOpt())) { settings.setSourceVersion(option.getValue()); } else if ("target".equals(option.getOpt())) { settings.setTargetVersion(option.getValue()); } else if ("sourcepath".equals(option.getOpt())) { sourcepath = new File(option.getValue()); } else if ("d".equals(option.getOpt())) { targetpath = new File(option.getValue()); } else if ("Xmaxerrs".equals(option.getOpt())) { maxerrs = Integer.parseInt(option.getValue()); } else if ("Xmaxwarns".equals(option.getOpt())) { maxwarns = Integer.parseInt(option.getValue()); } } final ResourceReader reader = new FileResourceReader(sourcepath); final ResourceStore store = new FileResourceStore(targetpath); final int maxErrors = maxerrs; final int maxWarnings = maxwarns; compiler.setCompilationProblemHandler(new CompilationProblemHandler() { int errors = 0; int warnings = 0; public boolean handle(final CompilationProblem pProblem) { if (pProblem.isError()) { System.err.println(pProblem); errors++; if (errors >= maxErrors) { return false; } } else { if (!nowarn) { System.err.println(pProblem); } warnings++; if (warnings >= maxWarnings) { return false; } } return true; } }); final String[] resource = cmd.getArgs(); for (final String element : resource) { System.out.println("compiling " + element); } final CompilationResult result = compiler.compile(resource, reader, store, classloader); System.out.println( result.getErrors().length + " errors"); System.out.println( result.getWarnings().length + " warnings"); } }
apache/commons-jci
examples/src/main/java/org/apache/commons/jci2/examples/commandline/CommandlineCompiler.java
Java
apache-2.0
7,267
/* * JBoss, Home of Professional Open Source * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. */ package org.searchisko.api.tasker; import java.io.InterruptedIOException; import java.util.logging.Level; import java.util.logging.Logger; import org.elasticsearch.indices.IndexMissingException; /** * Abstract base class for task implementation. Main task work is done inside {@link #performTask()} method. * * @author Vlastimil Elias (velias at redhat dot com) */ public abstract class Task extends Thread { protected String taskId; private Logger log = null; protected TaskExecutionContext context; private transient boolean canceled; public Task() { log = Logger.getLogger(getClass().getName()); } /** * Called from {@link TaskManager} before task execution is started. * * @param taskId id of task * @param context callback */ public void setExecutionContext(String taskId, TaskExecutionContext context) { this.taskId = taskId; this.context = context; setName("Task thread for task.id=" + taskId); setDaemon(false); } /** * Implement your long running task here. Do not forget to check {@link #isCanceledOrInterrupted()} and return from * method immediately. * * @throws RuntimeException runtime exception is treated as system error, so task is marked as * {@link TaskStatus#FAILOVER} and run again later * @throws Exception checked permission is treated as permanent error, so task is marked as * {@link TaskStatus#FINISHED_ERROR} */ protected abstract void performTask() throws Exception; @Override public void run() { log.fine("Starting task " + taskId); try { performTask(); if (isInterrupted()) { writeStatus(TaskStatus.FAILOVER, "Task execution was interrupted"); } else if (canceled) { writeStatus(TaskStatus.CANCELED, null); } else { writeStatus(TaskStatus.FINISHED_OK, null); } } catch (InterruptedException | InterruptedIOException e) { writeStatus(TaskStatus.FAILOVER, "Task execution was interrupted"); } catch (IndexMissingException e) { writeStatus(TaskStatus.FINISHED_ERROR, "ERROR: Task finished due missing search index: " + e.getMessage()); } catch (RuntimeException e) { String msg = "Task execution interrupted due " + e.getClass().getName() + ": " + e.getMessage(); if (e instanceof NullPointerException) { msg = "Task execution interrupted due NullPointerException, see log file for stacktrace"; log.log(Level.SEVERE, "Task finished due NullPointerException", e); } writeStatus(TaskStatus.FAILOVER, "ERROR: " + msg); } catch (Exception e) { writeStatus(TaskStatus.FINISHED_ERROR, "ERROR: Task finished due exception: " + e.getMessage()); } finally { log.fine("Finished task " + taskId); } } private void writeStatus(TaskStatus status, String message) { context.changeTaskStatus(taskId, status, message); } /** * Write new row into task log. * * @param message */ protected void writeTaskLog(String message) { context.writeTaskLog(taskId, message); } /** * Check if task is cancelled or interrupted. Use this check in {@link #performTask()} implementation to finish long * running task if this method returns true! * * @return true if task interruption/cancel is requested. */ public boolean isCanceledOrInterrupted() { return canceled || isInterrupted(); } /** * Used from {@link TaskManager} to request cancellation for this task. You have to use * {@link #isCanceledOrInterrupted()} in your {@link #performTask()} implementation to allow correct task * cancellation! * * @param canceled */ public void setCanceled(boolean canceled) { this.canceled = canceled; } }
ollyjshaw/searchisko
api/src/main/java/org/searchisko/api/tasker/Task.java
Java
apache-2.0
3,796
/* * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.siyeh.ig.abstraction; import com.intellij.psi.PsiCatchSection; import com.intellij.psi.PsiParameter; import com.intellij.psi.PsiTypeElement; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import org.jetbrains.annotations.NotNull; public class ParameterOfConcreteClassInspection extends BaseInspection { @NotNull public String getID() { return "MethodParameterOfConcreteClass"; } @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "concrete.class.method.parameter.display.name"); } @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "concrete.class.method.parameter.problem.descriptor", infos); } public BaseInspectionVisitor buildVisitor() { return new ParameterOfConcreteClassVisitor(); } private static class ParameterOfConcreteClassVisitor extends BaseInspectionVisitor { @Override public void visitParameter(@NotNull PsiParameter parameter) { super.visitParameter(parameter); if (parameter.getDeclarationScope() instanceof PsiCatchSection) { return; } final PsiTypeElement typeElement = parameter.getTypeElement(); if (!ConcreteClassUtil.typeIsConcreteClass(typeElement)) { return; } final String variableName = parameter.getName(); registerError(typeElement, variableName); } } }
jexp/idea2
plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/ParameterOfConcreteClassInspection.java
Java
apache-2.0
2,261
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.grid.internal; import net.jcip.annotations.ThreadSafe; import org.openqa.grid.internal.listeners.RegistrationListener; import org.openqa.grid.internal.listeners.SelfHealingProxy; import org.openqa.grid.web.Hub; import org.openqa.grid.web.servlet.handler.RequestHandler; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.server.log.LoggingManager; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; /** * Kernel of the grid. Keeps track of what's happening, what's free/used and assigns resources to * incoming requests. */ @ThreadSafe public class DefaultGridRegistry extends BaseGridRegistry implements GridRegistry { private static final Logger LOG = Logger.getLogger(DefaultGridRegistry.class.getName()); protected static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { LOG.log(Level.SEVERE, "Matcher thread dying due to unhandled exception.", e); } } // lock for anything modifying the tests session currently running on this // registry. private final ReentrantLock lock = new ReentrantLock(); private final Condition testSessionAvailable = lock.newCondition(); private final ProxySet proxies; private final ActiveTestSessions activeTestSessions = new ActiveTestSessions(); private final NewSessionRequestQueue newSessionQueue; private final Matcher matcherThread = new Matcher(); private final List<RemoteProxy> registeringProxies = new CopyOnWriteArrayList<>(); private volatile boolean stop = false; public DefaultGridRegistry() { this(null); } public DefaultGridRegistry(Hub hub) { super(hub); this.newSessionQueue = new NewSessionRequestQueue(); proxies = new ProxySet((hub != null) ? hub.getConfiguration().throwOnCapabilityNotPresent : true); this.matcherThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler()); } public void start() { matcherThread.start(); // freynaud : TODO // Grid registry is in a valid state when testSessionAvailable.await(); from // assignRequestToProxy is reached. Not before. try { Thread.sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Creates a new {@link GridRegistry} that is not associated with a Hub and starts it. * * @return the registry */ @SuppressWarnings({"NullableProblems"}) public static GridRegistry newInstance() { return newInstance(null); } /** * Creates a new {@link GridRegistry} and starts it. * * @param hub the {@link Hub} to associate this registry with * @return the registry */ public static GridRegistry newInstance(Hub hub) { DefaultGridRegistry registry = new DefaultGridRegistry(hub); registry.start(); return registry; } /** * Ends this test session for the hub, releasing the resources in the hub / registry. It does not * release anything on the remote. The resources are released in a separate thread, so the call * returns immediately. It allows release with long duration not to block the test while the hub is * releasing the resource. * * @param session The session to terminate * @param reason the reason for termination */ public void terminate(final TestSession session, final SessionTerminationReason reason) { // Thread safety reviewed new Thread(() -> _release(session.getSlot(), reason)).start(); } /** * Release the test slot. Free the resource on the slot itself and the registry. If also invokes * the {@link org.openqa.grid.internal.listeners.TestSessionListener#afterSession(TestSession)} if * applicable. * * @param testSlot The slot to release */ private void _release(TestSlot testSlot, SessionTerminationReason reason) { if (!testSlot.startReleaseProcess()) { return; } if (!testSlot.performAfterSessionEvent()) { return; } final String internalKey = testSlot.getInternalKey(); try { lock.lock(); testSlot.finishReleaseProcess(); release(internalKey, reason); } finally { lock.unlock(); } } void terminateSynchronousFOR_TEST_ONLY(TestSession testSession) { _release(testSession.getSlot(), SessionTerminationReason.CLIENT_STOPPED_SESSION); } /** * @see GridRegistry#removeIfPresent(RemoteProxy) */ public void removeIfPresent(RemoteProxy proxy) { // Find the original proxy. While the supplied one is logically equivalent, it may be a fresh object with // an empty TestSlot list, which doesn't figure into the proxy equivalence check. Since we want to free up // those test sessions, we need to operate on that original object. if (proxies.contains(proxy)) { LOG.warning(String.format( "Cleaning up stale test sessions on the unregistered node %s", proxy)); final RemoteProxy p = proxies.remove(proxy); p.getTestSlots().forEach(testSlot -> forceRelease(testSlot, SessionTerminationReason.PROXY_REREGISTRATION) ); p.teardown(); } } /** * @see GridRegistry#forceRelease(TestSlot, SessionTerminationReason) */ public void forceRelease(TestSlot testSlot, SessionTerminationReason reason) { if (testSlot.getSession() == null) { return; } String internalKey = testSlot.getInternalKey(); release(internalKey, reason); testSlot.doFinishRelease(); } /** * iterates the queue of incoming new session request and assign them to proxy after they've been * sorted by priority, with priority defined by the prioritizer. */ class Matcher extends Thread { // Thread safety reviewed Matcher() { super("Matcher thread"); } @Override public void run() { try { lock.lock(); assignRequestToProxy(); } finally { lock.unlock(); } } } /** * @see GridRegistry#stop() */ public void stop() { stop = true; matcherThread.interrupt(); newSessionQueue.stop(); proxies.teardown(); httpClientFactory.close(); } /** * @see GridRegistry#addNewSessionRequest(RequestHandler) */ public void addNewSessionRequest(RequestHandler handler) { try { lock.lock(); proxies.verifyAbilityToHandleDesiredCapabilities(handler.getRequest().getDesiredCapabilities()); newSessionQueue.add(handler); fireMatcherStateChanged(); } finally { lock.unlock(); } } /** * iterates the list of incoming session request to find a potential match in the list of proxies. * If something changes in the registry, the matcher iteration is stopped to account for that * change. */ private void assignRequestToProxy() { while (!stop) { try { testSessionAvailable.await(5, TimeUnit.SECONDS); newSessionQueue.processQueue(this::takeRequestHandler, configuration.prioritizer); // Just make sure we delete anything that is logged on this thread from memory LoggingManager.perSessionLogHandler().clearThreadTempLogs(); } catch (InterruptedException e) { LOG.info("Shutting down registry."); } catch (Throwable t) { LOG.log(Level.SEVERE, "Unhandled exception in Matcher thread.", t); } } } private boolean takeRequestHandler(RequestHandler handler) { final TestSession session = proxies.getNewSession(handler.getRequest().getDesiredCapabilities()); final boolean sessionCreated = session != null; if (sessionCreated) { activeTestSessions.add(session); handler.bindSession(session); } return sessionCreated; } /** * mark the session as finished for the registry. The resources that were associated to it are now * free to be reserved by other tests * * @param session The session * @param reason the reason for the release */ private void release(TestSession session, SessionTerminationReason reason) { try { lock.lock(); boolean removed = activeTestSessions.remove(session, reason); if (removed) { fireMatcherStateChanged(); } } finally { lock.unlock(); } } private void release(String internalKey, SessionTerminationReason reason) { if (internalKey == null) { return; } final TestSession session1 = activeTestSessions.findSessionByInternalKey(internalKey); if (session1 != null) { release(session1, reason); return; } LOG.warning("Tried to release session with internal key " + internalKey + " but couldn't find it."); } /** * @see GridRegistry#add(RemoteProxy) */ public void add(RemoteProxy proxy) { if (proxy == null) { return; } LOG.info("Registered a node " + proxy); try { lock.lock(); removeIfPresent(proxy); if (registeringProxies.contains(proxy)) { LOG.warning(String.format("Proxy '%s' is already queued for registration.", proxy)); return; } registeringProxies.add(proxy); fireMatcherStateChanged(); } finally { lock.unlock(); } boolean listenerOk = true; try { if (proxy instanceof RegistrationListener) { ((RegistrationListener) proxy).beforeRegistration(); } } catch (Throwable t) { LOG.severe("Error running the registration listener on " + proxy + ", " + t.getMessage()); t.printStackTrace(); listenerOk = false; } try { lock.lock(); registeringProxies.remove(proxy); if (listenerOk) { if (proxy instanceof SelfHealingProxy) { ((SelfHealingProxy) proxy).startPolling(); } proxies.add(proxy); fireMatcherStateChanged(); } } finally { lock.unlock(); } } /** * @see GridRegistry#setThrowOnCapabilityNotPresent(boolean) */ public void setThrowOnCapabilityNotPresent(boolean throwOnCapabilityNotPresent) { proxies.setThrowOnCapabilityNotPresent(throwOnCapabilityNotPresent); } private void fireMatcherStateChanged() { testSessionAvailable.signalAll(); } /** * @see GridRegistry#getAllProxies() */ public ProxySet getAllProxies() { return proxies; } /** * @see GridRegistry#getUsedProxies() */ public List<RemoteProxy> getUsedProxies() { return proxies.getBusyProxies(); } /** * @see GridRegistry#getSession(ExternalSessionKey) */ public TestSession getSession(ExternalSessionKey externalKey) { return activeTestSessions.findSessionByExternalKey(externalKey); } /** * @see GridRegistry#getExistingSession(ExternalSessionKey) */ public TestSession getExistingSession(ExternalSessionKey externalKey) { return activeTestSessions.getExistingSession(externalKey); } /** * @see GridRegistry#getNewSessionRequestCount() */ public int getNewSessionRequestCount() { // may race return newSessionQueue.getNewSessionRequestCount(); } /** * @see GridRegistry#clearNewSessionRequests() */ public void clearNewSessionRequests() { newSessionQueue.clearNewSessionRequests(); } /** * @see GridRegistry#removeNewSessionRequest(RequestHandler) */ public boolean removeNewSessionRequest(RequestHandler request) { return newSessionQueue.removeNewSessionRequest(request); } /** * @see GridRegistry#getDesiredCapabilities() */ public Iterable<DesiredCapabilities> getDesiredCapabilities() { return newSessionQueue.getDesiredCapabilities(); } /** * @see GridRegistry#getActiveSessions() */ public Set<TestSession> getActiveSessions() { return activeTestSessions.unmodifiableSet(); } /** * @see GridRegistry#getProxyById(String) */ public RemoteProxy getProxyById(String id) { return proxies.getProxyById(id); } }
juangj/selenium
java/server/src/org/openqa/grid/internal/DefaultGridRegistry.java
Java
apache-2.0
12,889
// Copyright 2013 GridLine // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nl.gridline.leveldb.bindings; import static nl.gridline.leveldb.bindings.utils.Bytes.toBytes; import static nl.gridline.leveldb.bindings.utils.Bytes.toFloat; import nl.gridline.leveldb.EntryBinding; /** * Binding for float values. * @author <a href="mailto:[email protected]">Job</a> */ public class FloatBinding implements EntryBinding<Float> { @Override public byte[] serialize(Float object) { return toBytes(object.floatValue()); } @Override public Float deserialize(byte[] object) { return toFloat(object); } }
jobtg/leveldb-mapapi
src/main/java/nl/gridline/leveldb/bindings/FloatBinding.java
Java
apache-2.0
1,123
package quickfix.fix50; import quickfix.FieldNotFound; import quickfix.Group; public class RequestForPositions extends Message { static final long serialVersionUID = 20050617; public static final String MSGTYPE = "AN"; public RequestForPositions() { super(); getHeader().setField(new quickfix.field.MsgType(MSGTYPE)); } public RequestForPositions(quickfix.field.PosReqID posReqID, quickfix.field.PosReqType posReqType, quickfix.field.ClearingBusinessDate clearingBusinessDate, quickfix.field.TransactTime transactTime) { this(); setField(posReqID); setField(posReqType); setField(clearingBusinessDate); setField(transactTime); } public void set(quickfix.field.PosReqID value) { setField(value); } public quickfix.field.PosReqID get(quickfix.field.PosReqID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PosReqID getPosReqID() throws FieldNotFound { quickfix.field.PosReqID value = new quickfix.field.PosReqID(); getField(value); return value; } public boolean isSet(quickfix.field.PosReqID field) { return isSetField(field); } public boolean isSetPosReqID() { return isSetField(710); } public void set(quickfix.field.PosReqType value) { setField(value); } public quickfix.field.PosReqType get(quickfix.field.PosReqType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PosReqType getPosReqType() throws FieldNotFound { quickfix.field.PosReqType value = new quickfix.field.PosReqType(); getField(value); return value; } public boolean isSet(quickfix.field.PosReqType field) { return isSetField(field); } public boolean isSetPosReqType() { return isSetField(724); } public void set(quickfix.field.MatchStatus value) { setField(value); } public quickfix.field.MatchStatus get(quickfix.field.MatchStatus value) throws FieldNotFound { getField(value); return value; } public quickfix.field.MatchStatus getMatchStatus() throws FieldNotFound { quickfix.field.MatchStatus value = new quickfix.field.MatchStatus(); getField(value); return value; } public boolean isSet(quickfix.field.MatchStatus field) { return isSetField(field); } public boolean isSetMatchStatus() { return isSetField(573); } public void set(quickfix.field.SubscriptionRequestType value) { setField(value); } public quickfix.field.SubscriptionRequestType get(quickfix.field.SubscriptionRequestType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SubscriptionRequestType getSubscriptionRequestType() throws FieldNotFound { quickfix.field.SubscriptionRequestType value = new quickfix.field.SubscriptionRequestType(); getField(value); return value; } public boolean isSet(quickfix.field.SubscriptionRequestType field) { return isSetField(field); } public boolean isSetSubscriptionRequestType() { return isSetField(263); } public void set(quickfix.fix50.component.Parties component) { setComponent(component); } public quickfix.fix50.component.Parties get(quickfix.fix50.component.Parties component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.Parties getParties() throws FieldNotFound { quickfix.fix50.component.Parties component = new quickfix.fix50.component.Parties(); getComponent(component); return component; } public void set(quickfix.field.NoPartyIDs value) { setField(value); } public quickfix.field.NoPartyIDs get(quickfix.field.NoPartyIDs value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoPartyIDs getNoPartyIDs() throws FieldNotFound { quickfix.field.NoPartyIDs value = new quickfix.field.NoPartyIDs(); getField(value); return value; } public boolean isSet(quickfix.field.NoPartyIDs field) { return isSetField(field); } public boolean isSetNoPartyIDs() { return isSetField(453); } public static class NoPartyIDs extends Group { static final long serialVersionUID = 20050617; public NoPartyIDs() { super(453, 448, new int[] {448, 447, 452, 802, 0 } ); } public void set(quickfix.field.PartyID value) { setField(value); } public quickfix.field.PartyID get(quickfix.field.PartyID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PartyID getPartyID() throws FieldNotFound { quickfix.field.PartyID value = new quickfix.field.PartyID(); getField(value); return value; } public boolean isSet(quickfix.field.PartyID field) { return isSetField(field); } public boolean isSetPartyID() { return isSetField(448); } public void set(quickfix.field.PartyIDSource value) { setField(value); } public quickfix.field.PartyIDSource get(quickfix.field.PartyIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PartyIDSource getPartyIDSource() throws FieldNotFound { quickfix.field.PartyIDSource value = new quickfix.field.PartyIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.PartyIDSource field) { return isSetField(field); } public boolean isSetPartyIDSource() { return isSetField(447); } public void set(quickfix.field.PartyRole value) { setField(value); } public quickfix.field.PartyRole get(quickfix.field.PartyRole value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PartyRole getPartyRole() throws FieldNotFound { quickfix.field.PartyRole value = new quickfix.field.PartyRole(); getField(value); return value; } public boolean isSet(quickfix.field.PartyRole field) { return isSetField(field); } public boolean isSetPartyRole() { return isSetField(452); } public void set(quickfix.fix50.component.PtysSubGrp component) { setComponent(component); } public quickfix.fix50.component.PtysSubGrp get(quickfix.fix50.component.PtysSubGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.PtysSubGrp getPtysSubGrp() throws FieldNotFound { quickfix.fix50.component.PtysSubGrp component = new quickfix.fix50.component.PtysSubGrp(); getComponent(component); return component; } public void set(quickfix.field.NoPartySubIDs value) { setField(value); } public quickfix.field.NoPartySubIDs get(quickfix.field.NoPartySubIDs value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoPartySubIDs getNoPartySubIDs() throws FieldNotFound { quickfix.field.NoPartySubIDs value = new quickfix.field.NoPartySubIDs(); getField(value); return value; } public boolean isSet(quickfix.field.NoPartySubIDs field) { return isSetField(field); } public boolean isSetNoPartySubIDs() { return isSetField(802); } public static class NoPartySubIDs extends Group { static final long serialVersionUID = 20050617; public NoPartySubIDs() { super(802, 523, new int[] {523, 803, 0 } ); } public void set(quickfix.field.PartySubID value) { setField(value); } public quickfix.field.PartySubID get(quickfix.field.PartySubID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PartySubID getPartySubID() throws FieldNotFound { quickfix.field.PartySubID value = new quickfix.field.PartySubID(); getField(value); return value; } public boolean isSet(quickfix.field.PartySubID field) { return isSetField(field); } public boolean isSetPartySubID() { return isSetField(523); } public void set(quickfix.field.PartySubIDType value) { setField(value); } public quickfix.field.PartySubIDType get(quickfix.field.PartySubIDType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PartySubIDType getPartySubIDType() throws FieldNotFound { quickfix.field.PartySubIDType value = new quickfix.field.PartySubIDType(); getField(value); return value; } public boolean isSet(quickfix.field.PartySubIDType field) { return isSetField(field); } public boolean isSetPartySubIDType() { return isSetField(803); } } } public void set(quickfix.field.Account value) { setField(value); } public quickfix.field.Account get(quickfix.field.Account value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Account getAccount() throws FieldNotFound { quickfix.field.Account value = new quickfix.field.Account(); getField(value); return value; } public boolean isSet(quickfix.field.Account field) { return isSetField(field); } public boolean isSetAccount() { return isSetField(1); } public void set(quickfix.field.AcctIDSource value) { setField(value); } public quickfix.field.AcctIDSource get(quickfix.field.AcctIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.AcctIDSource getAcctIDSource() throws FieldNotFound { quickfix.field.AcctIDSource value = new quickfix.field.AcctIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.AcctIDSource field) { return isSetField(field); } public boolean isSetAcctIDSource() { return isSetField(660); } public void set(quickfix.field.AccountType value) { setField(value); } public quickfix.field.AccountType get(quickfix.field.AccountType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.AccountType getAccountType() throws FieldNotFound { quickfix.field.AccountType value = new quickfix.field.AccountType(); getField(value); return value; } public boolean isSet(quickfix.field.AccountType field) { return isSetField(field); } public boolean isSetAccountType() { return isSetField(581); } public void set(quickfix.fix50.component.Instrument component) { setComponent(component); } public quickfix.fix50.component.Instrument get(quickfix.fix50.component.Instrument component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.Instrument getInstrument() throws FieldNotFound { quickfix.fix50.component.Instrument component = new quickfix.fix50.component.Instrument(); getComponent(component); return component; } public void set(quickfix.field.Symbol value) { setField(value); } public quickfix.field.Symbol get(quickfix.field.Symbol value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Symbol getSymbol() throws FieldNotFound { quickfix.field.Symbol value = new quickfix.field.Symbol(); getField(value); return value; } public boolean isSet(quickfix.field.Symbol field) { return isSetField(field); } public boolean isSetSymbol() { return isSetField(55); } public void set(quickfix.field.SymbolSfx value) { setField(value); } public quickfix.field.SymbolSfx get(quickfix.field.SymbolSfx value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SymbolSfx getSymbolSfx() throws FieldNotFound { quickfix.field.SymbolSfx value = new quickfix.field.SymbolSfx(); getField(value); return value; } public boolean isSet(quickfix.field.SymbolSfx field) { return isSetField(field); } public boolean isSetSymbolSfx() { return isSetField(65); } public void set(quickfix.field.SecurityID value) { setField(value); } public quickfix.field.SecurityID get(quickfix.field.SecurityID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityID getSecurityID() throws FieldNotFound { quickfix.field.SecurityID value = new quickfix.field.SecurityID(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityID field) { return isSetField(field); } public boolean isSetSecurityID() { return isSetField(48); } public void set(quickfix.field.SecurityIDSource value) { setField(value); } public quickfix.field.SecurityIDSource get(quickfix.field.SecurityIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityIDSource getSecurityIDSource() throws FieldNotFound { quickfix.field.SecurityIDSource value = new quickfix.field.SecurityIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityIDSource field) { return isSetField(field); } public boolean isSetSecurityIDSource() { return isSetField(22); } public void set(quickfix.fix50.component.SecAltIDGrp component) { setComponent(component); } public quickfix.fix50.component.SecAltIDGrp get(quickfix.fix50.component.SecAltIDGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.SecAltIDGrp getSecAltIDGrp() throws FieldNotFound { quickfix.fix50.component.SecAltIDGrp component = new quickfix.fix50.component.SecAltIDGrp(); getComponent(component); return component; } public void set(quickfix.field.NoSecurityAltID value) { setField(value); } public quickfix.field.NoSecurityAltID get(quickfix.field.NoSecurityAltID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoSecurityAltID getNoSecurityAltID() throws FieldNotFound { quickfix.field.NoSecurityAltID value = new quickfix.field.NoSecurityAltID(); getField(value); return value; } public boolean isSet(quickfix.field.NoSecurityAltID field) { return isSetField(field); } public boolean isSetNoSecurityAltID() { return isSetField(454); } public static class NoSecurityAltID extends Group { static final long serialVersionUID = 20050617; public NoSecurityAltID() { super(454, 455, new int[] {455, 456, 0 } ); } public void set(quickfix.field.SecurityAltID value) { setField(value); } public quickfix.field.SecurityAltID get(quickfix.field.SecurityAltID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityAltID getSecurityAltID() throws FieldNotFound { quickfix.field.SecurityAltID value = new quickfix.field.SecurityAltID(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityAltID field) { return isSetField(field); } public boolean isSetSecurityAltID() { return isSetField(455); } public void set(quickfix.field.SecurityAltIDSource value) { setField(value); } public quickfix.field.SecurityAltIDSource get(quickfix.field.SecurityAltIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityAltIDSource getSecurityAltIDSource() throws FieldNotFound { quickfix.field.SecurityAltIDSource value = new quickfix.field.SecurityAltIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityAltIDSource field) { return isSetField(field); } public boolean isSetSecurityAltIDSource() { return isSetField(456); } } public void set(quickfix.field.Product value) { setField(value); } public quickfix.field.Product get(quickfix.field.Product value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Product getProduct() throws FieldNotFound { quickfix.field.Product value = new quickfix.field.Product(); getField(value); return value; } public boolean isSet(quickfix.field.Product field) { return isSetField(field); } public boolean isSetProduct() { return isSetField(460); } public void set(quickfix.field.CFICode value) { setField(value); } public quickfix.field.CFICode get(quickfix.field.CFICode value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CFICode getCFICode() throws FieldNotFound { quickfix.field.CFICode value = new quickfix.field.CFICode(); getField(value); return value; } public boolean isSet(quickfix.field.CFICode field) { return isSetField(field); } public boolean isSetCFICode() { return isSetField(461); } public void set(quickfix.field.SecurityType value) { setField(value); } public quickfix.field.SecurityType get(quickfix.field.SecurityType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityType getSecurityType() throws FieldNotFound { quickfix.field.SecurityType value = new quickfix.field.SecurityType(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityType field) { return isSetField(field); } public boolean isSetSecurityType() { return isSetField(167); } public void set(quickfix.field.SecuritySubType value) { setField(value); } public quickfix.field.SecuritySubType get(quickfix.field.SecuritySubType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecuritySubType getSecuritySubType() throws FieldNotFound { quickfix.field.SecuritySubType value = new quickfix.field.SecuritySubType(); getField(value); return value; } public boolean isSet(quickfix.field.SecuritySubType field) { return isSetField(field); } public boolean isSetSecuritySubType() { return isSetField(762); } public void set(quickfix.field.MaturityMonthYear value) { setField(value); } public quickfix.field.MaturityMonthYear get(quickfix.field.MaturityMonthYear value) throws FieldNotFound { getField(value); return value; } public quickfix.field.MaturityMonthYear getMaturityMonthYear() throws FieldNotFound { quickfix.field.MaturityMonthYear value = new quickfix.field.MaturityMonthYear(); getField(value); return value; } public boolean isSet(quickfix.field.MaturityMonthYear field) { return isSetField(field); } public boolean isSetMaturityMonthYear() { return isSetField(200); } public void set(quickfix.field.MaturityDate value) { setField(value); } public quickfix.field.MaturityDate get(quickfix.field.MaturityDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.MaturityDate getMaturityDate() throws FieldNotFound { quickfix.field.MaturityDate value = new quickfix.field.MaturityDate(); getField(value); return value; } public boolean isSet(quickfix.field.MaturityDate field) { return isSetField(field); } public boolean isSetMaturityDate() { return isSetField(541); } public void set(quickfix.field.CouponPaymentDate value) { setField(value); } public quickfix.field.CouponPaymentDate get(quickfix.field.CouponPaymentDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CouponPaymentDate getCouponPaymentDate() throws FieldNotFound { quickfix.field.CouponPaymentDate value = new quickfix.field.CouponPaymentDate(); getField(value); return value; } public boolean isSet(quickfix.field.CouponPaymentDate field) { return isSetField(field); } public boolean isSetCouponPaymentDate() { return isSetField(224); } public void set(quickfix.field.IssueDate value) { setField(value); } public quickfix.field.IssueDate get(quickfix.field.IssueDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.IssueDate getIssueDate() throws FieldNotFound { quickfix.field.IssueDate value = new quickfix.field.IssueDate(); getField(value); return value; } public boolean isSet(quickfix.field.IssueDate field) { return isSetField(field); } public boolean isSetIssueDate() { return isSetField(225); } public void set(quickfix.field.RepoCollateralSecurityType value) { setField(value); } public quickfix.field.RepoCollateralSecurityType get(quickfix.field.RepoCollateralSecurityType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.RepoCollateralSecurityType getRepoCollateralSecurityType() throws FieldNotFound { quickfix.field.RepoCollateralSecurityType value = new quickfix.field.RepoCollateralSecurityType(); getField(value); return value; } public boolean isSet(quickfix.field.RepoCollateralSecurityType field) { return isSetField(field); } public boolean isSetRepoCollateralSecurityType() { return isSetField(239); } public void set(quickfix.field.RepurchaseTerm value) { setField(value); } public quickfix.field.RepurchaseTerm get(quickfix.field.RepurchaseTerm value) throws FieldNotFound { getField(value); return value; } public quickfix.field.RepurchaseTerm getRepurchaseTerm() throws FieldNotFound { quickfix.field.RepurchaseTerm value = new quickfix.field.RepurchaseTerm(); getField(value); return value; } public boolean isSet(quickfix.field.RepurchaseTerm field) { return isSetField(field); } public boolean isSetRepurchaseTerm() { return isSetField(226); } public void set(quickfix.field.RepurchaseRate value) { setField(value); } public quickfix.field.RepurchaseRate get(quickfix.field.RepurchaseRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.RepurchaseRate getRepurchaseRate() throws FieldNotFound { quickfix.field.RepurchaseRate value = new quickfix.field.RepurchaseRate(); getField(value); return value; } public boolean isSet(quickfix.field.RepurchaseRate field) { return isSetField(field); } public boolean isSetRepurchaseRate() { return isSetField(227); } public void set(quickfix.field.Factor value) { setField(value); } public quickfix.field.Factor get(quickfix.field.Factor value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Factor getFactor() throws FieldNotFound { quickfix.field.Factor value = new quickfix.field.Factor(); getField(value); return value; } public boolean isSet(quickfix.field.Factor field) { return isSetField(field); } public boolean isSetFactor() { return isSetField(228); } public void set(quickfix.field.CreditRating value) { setField(value); } public quickfix.field.CreditRating get(quickfix.field.CreditRating value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CreditRating getCreditRating() throws FieldNotFound { quickfix.field.CreditRating value = new quickfix.field.CreditRating(); getField(value); return value; } public boolean isSet(quickfix.field.CreditRating field) { return isSetField(field); } public boolean isSetCreditRating() { return isSetField(255); } public void set(quickfix.field.InstrRegistry value) { setField(value); } public quickfix.field.InstrRegistry get(quickfix.field.InstrRegistry value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrRegistry getInstrRegistry() throws FieldNotFound { quickfix.field.InstrRegistry value = new quickfix.field.InstrRegistry(); getField(value); return value; } public boolean isSet(quickfix.field.InstrRegistry field) { return isSetField(field); } public boolean isSetInstrRegistry() { return isSetField(543); } public void set(quickfix.field.CountryOfIssue value) { setField(value); } public quickfix.field.CountryOfIssue get(quickfix.field.CountryOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CountryOfIssue getCountryOfIssue() throws FieldNotFound { quickfix.field.CountryOfIssue value = new quickfix.field.CountryOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.CountryOfIssue field) { return isSetField(field); } public boolean isSetCountryOfIssue() { return isSetField(470); } public void set(quickfix.field.StateOrProvinceOfIssue value) { setField(value); } public quickfix.field.StateOrProvinceOfIssue get(quickfix.field.StateOrProvinceOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.StateOrProvinceOfIssue getStateOrProvinceOfIssue() throws FieldNotFound { quickfix.field.StateOrProvinceOfIssue value = new quickfix.field.StateOrProvinceOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.StateOrProvinceOfIssue field) { return isSetField(field); } public boolean isSetStateOrProvinceOfIssue() { return isSetField(471); } public void set(quickfix.field.LocaleOfIssue value) { setField(value); } public quickfix.field.LocaleOfIssue get(quickfix.field.LocaleOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LocaleOfIssue getLocaleOfIssue() throws FieldNotFound { quickfix.field.LocaleOfIssue value = new quickfix.field.LocaleOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.LocaleOfIssue field) { return isSetField(field); } public boolean isSetLocaleOfIssue() { return isSetField(472); } public void set(quickfix.field.RedemptionDate value) { setField(value); } public quickfix.field.RedemptionDate get(quickfix.field.RedemptionDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.RedemptionDate getRedemptionDate() throws FieldNotFound { quickfix.field.RedemptionDate value = new quickfix.field.RedemptionDate(); getField(value); return value; } public boolean isSet(quickfix.field.RedemptionDate field) { return isSetField(field); } public boolean isSetRedemptionDate() { return isSetField(240); } public void set(quickfix.field.StrikePrice value) { setField(value); } public quickfix.field.StrikePrice get(quickfix.field.StrikePrice value) throws FieldNotFound { getField(value); return value; } public quickfix.field.StrikePrice getStrikePrice() throws FieldNotFound { quickfix.field.StrikePrice value = new quickfix.field.StrikePrice(); getField(value); return value; } public boolean isSet(quickfix.field.StrikePrice field) { return isSetField(field); } public boolean isSetStrikePrice() { return isSetField(202); } public void set(quickfix.field.StrikeCurrency value) { setField(value); } public quickfix.field.StrikeCurrency get(quickfix.field.StrikeCurrency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.StrikeCurrency getStrikeCurrency() throws FieldNotFound { quickfix.field.StrikeCurrency value = new quickfix.field.StrikeCurrency(); getField(value); return value; } public boolean isSet(quickfix.field.StrikeCurrency field) { return isSetField(field); } public boolean isSetStrikeCurrency() { return isSetField(947); } public void set(quickfix.field.OptAttribute value) { setField(value); } public quickfix.field.OptAttribute get(quickfix.field.OptAttribute value) throws FieldNotFound { getField(value); return value; } public quickfix.field.OptAttribute getOptAttribute() throws FieldNotFound { quickfix.field.OptAttribute value = new quickfix.field.OptAttribute(); getField(value); return value; } public boolean isSet(quickfix.field.OptAttribute field) { return isSetField(field); } public boolean isSetOptAttribute() { return isSetField(206); } public void set(quickfix.field.ContractMultiplier value) { setField(value); } public quickfix.field.ContractMultiplier get(quickfix.field.ContractMultiplier value) throws FieldNotFound { getField(value); return value; } public quickfix.field.ContractMultiplier getContractMultiplier() throws FieldNotFound { quickfix.field.ContractMultiplier value = new quickfix.field.ContractMultiplier(); getField(value); return value; } public boolean isSet(quickfix.field.ContractMultiplier field) { return isSetField(field); } public boolean isSetContractMultiplier() { return isSetField(231); } public void set(quickfix.field.CouponRate value) { setField(value); } public quickfix.field.CouponRate get(quickfix.field.CouponRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CouponRate getCouponRate() throws FieldNotFound { quickfix.field.CouponRate value = new quickfix.field.CouponRate(); getField(value); return value; } public boolean isSet(quickfix.field.CouponRate field) { return isSetField(field); } public boolean isSetCouponRate() { return isSetField(223); } public void set(quickfix.field.SecurityExchange value) { setField(value); } public quickfix.field.SecurityExchange get(quickfix.field.SecurityExchange value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityExchange getSecurityExchange() throws FieldNotFound { quickfix.field.SecurityExchange value = new quickfix.field.SecurityExchange(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityExchange field) { return isSetField(field); } public boolean isSetSecurityExchange() { return isSetField(207); } public void set(quickfix.field.Issuer value) { setField(value); } public quickfix.field.Issuer get(quickfix.field.Issuer value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Issuer getIssuer() throws FieldNotFound { quickfix.field.Issuer value = new quickfix.field.Issuer(); getField(value); return value; } public boolean isSet(quickfix.field.Issuer field) { return isSetField(field); } public boolean isSetIssuer() { return isSetField(106); } public void set(quickfix.field.EncodedIssuerLen value) { setField(value); } public quickfix.field.EncodedIssuerLen get(quickfix.field.EncodedIssuerLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedIssuerLen getEncodedIssuerLen() throws FieldNotFound { quickfix.field.EncodedIssuerLen value = new quickfix.field.EncodedIssuerLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedIssuerLen field) { return isSetField(field); } public boolean isSetEncodedIssuerLen() { return isSetField(348); } public void set(quickfix.field.EncodedIssuer value) { setField(value); } public quickfix.field.EncodedIssuer get(quickfix.field.EncodedIssuer value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedIssuer getEncodedIssuer() throws FieldNotFound { quickfix.field.EncodedIssuer value = new quickfix.field.EncodedIssuer(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedIssuer field) { return isSetField(field); } public boolean isSetEncodedIssuer() { return isSetField(349); } public void set(quickfix.field.SecurityDesc value) { setField(value); } public quickfix.field.SecurityDesc get(quickfix.field.SecurityDesc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityDesc getSecurityDesc() throws FieldNotFound { quickfix.field.SecurityDesc value = new quickfix.field.SecurityDesc(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityDesc field) { return isSetField(field); } public boolean isSetSecurityDesc() { return isSetField(107); } public void set(quickfix.field.EncodedSecurityDescLen value) { setField(value); } public quickfix.field.EncodedSecurityDescLen get(quickfix.field.EncodedSecurityDescLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedSecurityDescLen getEncodedSecurityDescLen() throws FieldNotFound { quickfix.field.EncodedSecurityDescLen value = new quickfix.field.EncodedSecurityDescLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedSecurityDescLen field) { return isSetField(field); } public boolean isSetEncodedSecurityDescLen() { return isSetField(350); } public void set(quickfix.field.EncodedSecurityDesc value) { setField(value); } public quickfix.field.EncodedSecurityDesc get(quickfix.field.EncodedSecurityDesc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedSecurityDesc getEncodedSecurityDesc() throws FieldNotFound { quickfix.field.EncodedSecurityDesc value = new quickfix.field.EncodedSecurityDesc(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedSecurityDesc field) { return isSetField(field); } public boolean isSetEncodedSecurityDesc() { return isSetField(351); } public void set(quickfix.field.Pool value) { setField(value); } public quickfix.field.Pool get(quickfix.field.Pool value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Pool getPool() throws FieldNotFound { quickfix.field.Pool value = new quickfix.field.Pool(); getField(value); return value; } public boolean isSet(quickfix.field.Pool field) { return isSetField(field); } public boolean isSetPool() { return isSetField(691); } public void set(quickfix.field.ContractSettlMonth value) { setField(value); } public quickfix.field.ContractSettlMonth get(quickfix.field.ContractSettlMonth value) throws FieldNotFound { getField(value); return value; } public quickfix.field.ContractSettlMonth getContractSettlMonth() throws FieldNotFound { quickfix.field.ContractSettlMonth value = new quickfix.field.ContractSettlMonth(); getField(value); return value; } public boolean isSet(quickfix.field.ContractSettlMonth field) { return isSetField(field); } public boolean isSetContractSettlMonth() { return isSetField(667); } public void set(quickfix.field.CPProgram value) { setField(value); } public quickfix.field.CPProgram get(quickfix.field.CPProgram value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CPProgram getCPProgram() throws FieldNotFound { quickfix.field.CPProgram value = new quickfix.field.CPProgram(); getField(value); return value; } public boolean isSet(quickfix.field.CPProgram field) { return isSetField(field); } public boolean isSetCPProgram() { return isSetField(875); } public void set(quickfix.field.CPRegType value) { setField(value); } public quickfix.field.CPRegType get(quickfix.field.CPRegType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.CPRegType getCPRegType() throws FieldNotFound { quickfix.field.CPRegType value = new quickfix.field.CPRegType(); getField(value); return value; } public boolean isSet(quickfix.field.CPRegType field) { return isSetField(field); } public boolean isSetCPRegType() { return isSetField(876); } public void set(quickfix.fix50.component.EvntGrp component) { setComponent(component); } public quickfix.fix50.component.EvntGrp get(quickfix.fix50.component.EvntGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.EvntGrp getEvntGrp() throws FieldNotFound { quickfix.fix50.component.EvntGrp component = new quickfix.fix50.component.EvntGrp(); getComponent(component); return component; } public void set(quickfix.field.NoEvents value) { setField(value); } public quickfix.field.NoEvents get(quickfix.field.NoEvents value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoEvents getNoEvents() throws FieldNotFound { quickfix.field.NoEvents value = new quickfix.field.NoEvents(); getField(value); return value; } public boolean isSet(quickfix.field.NoEvents field) { return isSetField(field); } public boolean isSetNoEvents() { return isSetField(864); } public static class NoEvents extends Group { static final long serialVersionUID = 20050617; public NoEvents() { super(864, 865, new int[] {865, 866, 867, 868, 0 } ); } public void set(quickfix.field.EventType value) { setField(value); } public quickfix.field.EventType get(quickfix.field.EventType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EventType getEventType() throws FieldNotFound { quickfix.field.EventType value = new quickfix.field.EventType(); getField(value); return value; } public boolean isSet(quickfix.field.EventType field) { return isSetField(field); } public boolean isSetEventType() { return isSetField(865); } public void set(quickfix.field.EventDate value) { setField(value); } public quickfix.field.EventDate get(quickfix.field.EventDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EventDate getEventDate() throws FieldNotFound { quickfix.field.EventDate value = new quickfix.field.EventDate(); getField(value); return value; } public boolean isSet(quickfix.field.EventDate field) { return isSetField(field); } public boolean isSetEventDate() { return isSetField(866); } public void set(quickfix.field.EventPx value) { setField(value); } public quickfix.field.EventPx get(quickfix.field.EventPx value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EventPx getEventPx() throws FieldNotFound { quickfix.field.EventPx value = new quickfix.field.EventPx(); getField(value); return value; } public boolean isSet(quickfix.field.EventPx field) { return isSetField(field); } public boolean isSetEventPx() { return isSetField(867); } public void set(quickfix.field.EventText value) { setField(value); } public quickfix.field.EventText get(quickfix.field.EventText value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EventText getEventText() throws FieldNotFound { quickfix.field.EventText value = new quickfix.field.EventText(); getField(value); return value; } public boolean isSet(quickfix.field.EventText field) { return isSetField(field); } public boolean isSetEventText() { return isSetField(868); } } public void set(quickfix.field.DatedDate value) { setField(value); } public quickfix.field.DatedDate get(quickfix.field.DatedDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.DatedDate getDatedDate() throws FieldNotFound { quickfix.field.DatedDate value = new quickfix.field.DatedDate(); getField(value); return value; } public boolean isSet(quickfix.field.DatedDate field) { return isSetField(field); } public boolean isSetDatedDate() { return isSetField(873); } public void set(quickfix.field.InterestAccrualDate value) { setField(value); } public quickfix.field.InterestAccrualDate get(quickfix.field.InterestAccrualDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InterestAccrualDate getInterestAccrualDate() throws FieldNotFound { quickfix.field.InterestAccrualDate value = new quickfix.field.InterestAccrualDate(); getField(value); return value; } public boolean isSet(quickfix.field.InterestAccrualDate field) { return isSetField(field); } public boolean isSetInterestAccrualDate() { return isSetField(874); } public void set(quickfix.field.SecurityStatus value) { setField(value); } public quickfix.field.SecurityStatus get(quickfix.field.SecurityStatus value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SecurityStatus getSecurityStatus() throws FieldNotFound { quickfix.field.SecurityStatus value = new quickfix.field.SecurityStatus(); getField(value); return value; } public boolean isSet(quickfix.field.SecurityStatus field) { return isSetField(field); } public boolean isSetSecurityStatus() { return isSetField(965); } public void set(quickfix.field.SettleOnOpenFlag value) { setField(value); } public quickfix.field.SettleOnOpenFlag get(quickfix.field.SettleOnOpenFlag value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SettleOnOpenFlag getSettleOnOpenFlag() throws FieldNotFound { quickfix.field.SettleOnOpenFlag value = new quickfix.field.SettleOnOpenFlag(); getField(value); return value; } public boolean isSet(quickfix.field.SettleOnOpenFlag field) { return isSetField(field); } public boolean isSetSettleOnOpenFlag() { return isSetField(966); } public void set(quickfix.field.InstrmtAssignmentMethod value) { setField(value); } public quickfix.field.InstrmtAssignmentMethod get(quickfix.field.InstrmtAssignmentMethod value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrmtAssignmentMethod getInstrmtAssignmentMethod() throws FieldNotFound { quickfix.field.InstrmtAssignmentMethod value = new quickfix.field.InstrmtAssignmentMethod(); getField(value); return value; } public boolean isSet(quickfix.field.InstrmtAssignmentMethod field) { return isSetField(field); } public boolean isSetInstrmtAssignmentMethod() { return isSetField(1049); } public void set(quickfix.field.StrikeMultiplier value) { setField(value); } public quickfix.field.StrikeMultiplier get(quickfix.field.StrikeMultiplier value) throws FieldNotFound { getField(value); return value; } public quickfix.field.StrikeMultiplier getStrikeMultiplier() throws FieldNotFound { quickfix.field.StrikeMultiplier value = new quickfix.field.StrikeMultiplier(); getField(value); return value; } public boolean isSet(quickfix.field.StrikeMultiplier field) { return isSetField(field); } public boolean isSetStrikeMultiplier() { return isSetField(967); } public void set(quickfix.field.StrikeValue value) { setField(value); } public quickfix.field.StrikeValue get(quickfix.field.StrikeValue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.StrikeValue getStrikeValue() throws FieldNotFound { quickfix.field.StrikeValue value = new quickfix.field.StrikeValue(); getField(value); return value; } public boolean isSet(quickfix.field.StrikeValue field) { return isSetField(field); } public boolean isSetStrikeValue() { return isSetField(968); } public void set(quickfix.field.MinPriceIncrement value) { setField(value); } public quickfix.field.MinPriceIncrement get(quickfix.field.MinPriceIncrement value) throws FieldNotFound { getField(value); return value; } public quickfix.field.MinPriceIncrement getMinPriceIncrement() throws FieldNotFound { quickfix.field.MinPriceIncrement value = new quickfix.field.MinPriceIncrement(); getField(value); return value; } public boolean isSet(quickfix.field.MinPriceIncrement field) { return isSetField(field); } public boolean isSetMinPriceIncrement() { return isSetField(969); } public void set(quickfix.field.PositionLimit value) { setField(value); } public quickfix.field.PositionLimit get(quickfix.field.PositionLimit value) throws FieldNotFound { getField(value); return value; } public quickfix.field.PositionLimit getPositionLimit() throws FieldNotFound { quickfix.field.PositionLimit value = new quickfix.field.PositionLimit(); getField(value); return value; } public boolean isSet(quickfix.field.PositionLimit field) { return isSetField(field); } public boolean isSetPositionLimit() { return isSetField(970); } public void set(quickfix.field.NTPositionLimit value) { setField(value); } public quickfix.field.NTPositionLimit get(quickfix.field.NTPositionLimit value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NTPositionLimit getNTPositionLimit() throws FieldNotFound { quickfix.field.NTPositionLimit value = new quickfix.field.NTPositionLimit(); getField(value); return value; } public boolean isSet(quickfix.field.NTPositionLimit field) { return isSetField(field); } public boolean isSetNTPositionLimit() { return isSetField(971); } public void set(quickfix.fix50.component.InstrumentParties component) { setComponent(component); } public quickfix.fix50.component.InstrumentParties get(quickfix.fix50.component.InstrumentParties component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.InstrumentParties getInstrumentParties() throws FieldNotFound { quickfix.fix50.component.InstrumentParties component = new quickfix.fix50.component.InstrumentParties(); getComponent(component); return component; } public void set(quickfix.field.NoInstrumentParties value) { setField(value); } public quickfix.field.NoInstrumentParties get(quickfix.field.NoInstrumentParties value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoInstrumentParties getNoInstrumentParties() throws FieldNotFound { quickfix.field.NoInstrumentParties value = new quickfix.field.NoInstrumentParties(); getField(value); return value; } public boolean isSet(quickfix.field.NoInstrumentParties field) { return isSetField(field); } public boolean isSetNoInstrumentParties() { return isSetField(1018); } public static class NoInstrumentParties extends Group { static final long serialVersionUID = 20050617; public NoInstrumentParties() { super(1018, 1019, new int[] {1019, 1050, 1051, 1052, 0 } ); } public void set(quickfix.field.InstrumentPartyID value) { setField(value); } public quickfix.field.InstrumentPartyID get(quickfix.field.InstrumentPartyID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrumentPartyID getInstrumentPartyID() throws FieldNotFound { quickfix.field.InstrumentPartyID value = new quickfix.field.InstrumentPartyID(); getField(value); return value; } public boolean isSet(quickfix.field.InstrumentPartyID field) { return isSetField(field); } public boolean isSetInstrumentPartyID() { return isSetField(1019); } public void set(quickfix.field.InstrumentPartyIDSource value) { setField(value); } public quickfix.field.InstrumentPartyIDSource get(quickfix.field.InstrumentPartyIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrumentPartyIDSource getInstrumentPartyIDSource() throws FieldNotFound { quickfix.field.InstrumentPartyIDSource value = new quickfix.field.InstrumentPartyIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.InstrumentPartyIDSource field) { return isSetField(field); } public boolean isSetInstrumentPartyIDSource() { return isSetField(1050); } public void set(quickfix.field.InstrumentPartyRole value) { setField(value); } public quickfix.field.InstrumentPartyRole get(quickfix.field.InstrumentPartyRole value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrumentPartyRole getInstrumentPartyRole() throws FieldNotFound { quickfix.field.InstrumentPartyRole value = new quickfix.field.InstrumentPartyRole(); getField(value); return value; } public boolean isSet(quickfix.field.InstrumentPartyRole field) { return isSetField(field); } public boolean isSetInstrumentPartyRole() { return isSetField(1051); } public void set(quickfix.fix50.component.InstrumentPtysSubGrp component) { setComponent(component); } public quickfix.fix50.component.InstrumentPtysSubGrp get(quickfix.fix50.component.InstrumentPtysSubGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.InstrumentPtysSubGrp getInstrumentPtysSubGrp() throws FieldNotFound { quickfix.fix50.component.InstrumentPtysSubGrp component = new quickfix.fix50.component.InstrumentPtysSubGrp(); getComponent(component); return component; } public void set(quickfix.field.NoInstrumentPartySubIDs value) { setField(value); } public quickfix.field.NoInstrumentPartySubIDs get(quickfix.field.NoInstrumentPartySubIDs value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoInstrumentPartySubIDs getNoInstrumentPartySubIDs() throws FieldNotFound { quickfix.field.NoInstrumentPartySubIDs value = new quickfix.field.NoInstrumentPartySubIDs(); getField(value); return value; } public boolean isSet(quickfix.field.NoInstrumentPartySubIDs field) { return isSetField(field); } public boolean isSetNoInstrumentPartySubIDs() { return isSetField(1052); } public static class NoInstrumentPartySubIDs extends Group { static final long serialVersionUID = 20050617; public NoInstrumentPartySubIDs() { super(1052, 1053, new int[] {1053, 1054, 0 } ); } public void set(quickfix.field.InstrumentPartySubID value) { setField(value); } public quickfix.field.InstrumentPartySubID get(quickfix.field.InstrumentPartySubID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrumentPartySubID getInstrumentPartySubID() throws FieldNotFound { quickfix.field.InstrumentPartySubID value = new quickfix.field.InstrumentPartySubID(); getField(value); return value; } public boolean isSet(quickfix.field.InstrumentPartySubID field) { return isSetField(field); } public boolean isSetInstrumentPartySubID() { return isSetField(1053); } public void set(quickfix.field.InstrumentPartySubIDType value) { setField(value); } public quickfix.field.InstrumentPartySubIDType get(quickfix.field.InstrumentPartySubIDType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.InstrumentPartySubIDType getInstrumentPartySubIDType() throws FieldNotFound { quickfix.field.InstrumentPartySubIDType value = new quickfix.field.InstrumentPartySubIDType(); getField(value); return value; } public boolean isSet(quickfix.field.InstrumentPartySubIDType field) { return isSetField(field); } public boolean isSetInstrumentPartySubIDType() { return isSetField(1054); } } } public void set(quickfix.field.UnitofMeasure value) { setField(value); } public quickfix.field.UnitofMeasure get(quickfix.field.UnitofMeasure value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnitofMeasure getUnitofMeasure() throws FieldNotFound { quickfix.field.UnitofMeasure value = new quickfix.field.UnitofMeasure(); getField(value); return value; } public boolean isSet(quickfix.field.UnitofMeasure field) { return isSetField(field); } public boolean isSetUnitofMeasure() { return isSetField(996); } public void set(quickfix.field.TimeUnit value) { setField(value); } public quickfix.field.TimeUnit get(quickfix.field.TimeUnit value) throws FieldNotFound { getField(value); return value; } public quickfix.field.TimeUnit getTimeUnit() throws FieldNotFound { quickfix.field.TimeUnit value = new quickfix.field.TimeUnit(); getField(value); return value; } public boolean isSet(quickfix.field.TimeUnit field) { return isSetField(field); } public boolean isSetTimeUnit() { return isSetField(997); } public void set(quickfix.field.MaturityTime value) { setField(value); } public quickfix.field.MaturityTime get(quickfix.field.MaturityTime value) throws FieldNotFound { getField(value); return value; } public quickfix.field.MaturityTime getMaturityTime() throws FieldNotFound { quickfix.field.MaturityTime value = new quickfix.field.MaturityTime(); getField(value); return value; } public boolean isSet(quickfix.field.MaturityTime field) { return isSetField(field); } public boolean isSetMaturityTime() { return isSetField(1079); } public void set(quickfix.field.Currency value) { setField(value); } public quickfix.field.Currency get(quickfix.field.Currency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Currency getCurrency() throws FieldNotFound { quickfix.field.Currency value = new quickfix.field.Currency(); getField(value); return value; } public boolean isSet(quickfix.field.Currency field) { return isSetField(field); } public boolean isSetCurrency() { return isSetField(15); } public void set(quickfix.fix50.component.InstrmtLegGrp component) { setComponent(component); } public quickfix.fix50.component.InstrmtLegGrp get(quickfix.fix50.component.InstrmtLegGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.InstrmtLegGrp getInstrmtLegGrp() throws FieldNotFound { quickfix.fix50.component.InstrmtLegGrp component = new quickfix.fix50.component.InstrmtLegGrp(); getComponent(component); return component; } public void set(quickfix.field.NoLegs value) { setField(value); } public quickfix.field.NoLegs get(quickfix.field.NoLegs value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoLegs getNoLegs() throws FieldNotFound { quickfix.field.NoLegs value = new quickfix.field.NoLegs(); getField(value); return value; } public boolean isSet(quickfix.field.NoLegs field) { return isSetField(field); } public boolean isSetNoLegs() { return isSetField(555); } public static class NoLegs extends Group { static final long serialVersionUID = 20050617; public NoLegs() { super(555, 600, new int[] {600, 601, 602, 603, 604, 607, 608, 609, 764, 610, 611, 248, 249, 250, 251, 252, 253, 257, 599, 596, 597, 598, 254, 612, 942, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 556, 740, 739, 955, 956, 999, 1001, 0 } ); } public void set(quickfix.fix50.component.InstrumentLeg component) { setComponent(component); } public quickfix.fix50.component.InstrumentLeg get(quickfix.fix50.component.InstrumentLeg component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.InstrumentLeg getInstrumentLeg() throws FieldNotFound { quickfix.fix50.component.InstrumentLeg component = new quickfix.fix50.component.InstrumentLeg(); getComponent(component); return component; } public void set(quickfix.field.LegSymbol value) { setField(value); } public quickfix.field.LegSymbol get(quickfix.field.LegSymbol value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSymbol getLegSymbol() throws FieldNotFound { quickfix.field.LegSymbol value = new quickfix.field.LegSymbol(); getField(value); return value; } public boolean isSet(quickfix.field.LegSymbol field) { return isSetField(field); } public boolean isSetLegSymbol() { return isSetField(600); } public void set(quickfix.field.LegSymbolSfx value) { setField(value); } public quickfix.field.LegSymbolSfx get(quickfix.field.LegSymbolSfx value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSymbolSfx getLegSymbolSfx() throws FieldNotFound { quickfix.field.LegSymbolSfx value = new quickfix.field.LegSymbolSfx(); getField(value); return value; } public boolean isSet(quickfix.field.LegSymbolSfx field) { return isSetField(field); } public boolean isSetLegSymbolSfx() { return isSetField(601); } public void set(quickfix.field.LegSecurityID value) { setField(value); } public quickfix.field.LegSecurityID get(quickfix.field.LegSecurityID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSecurityID getLegSecurityID() throws FieldNotFound { quickfix.field.LegSecurityID value = new quickfix.field.LegSecurityID(); getField(value); return value; } public boolean isSet(quickfix.field.LegSecurityID field) { return isSetField(field); } public boolean isSetLegSecurityID() { return isSetField(602); } public void set(quickfix.field.LegSecurityIDSource value) { setField(value); } public quickfix.field.LegSecurityIDSource get(quickfix.field.LegSecurityIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSecurityIDSource getLegSecurityIDSource() throws FieldNotFound { quickfix.field.LegSecurityIDSource value = new quickfix.field.LegSecurityIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.LegSecurityIDSource field) { return isSetField(field); } public boolean isSetLegSecurityIDSource() { return isSetField(603); } public void set(quickfix.fix50.component.LegSecAltIDGrp component) { setComponent(component); } public quickfix.fix50.component.LegSecAltIDGrp get(quickfix.fix50.component.LegSecAltIDGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.LegSecAltIDGrp getLegSecAltIDGrp() throws FieldNotFound { quickfix.fix50.component.LegSecAltIDGrp component = new quickfix.fix50.component.LegSecAltIDGrp(); getComponent(component); return component; } public void set(quickfix.field.NoLegSecurityAltID value) { setField(value); } public quickfix.field.NoLegSecurityAltID get(quickfix.field.NoLegSecurityAltID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoLegSecurityAltID getNoLegSecurityAltID() throws FieldNotFound { quickfix.field.NoLegSecurityAltID value = new quickfix.field.NoLegSecurityAltID(); getField(value); return value; } public boolean isSet(quickfix.field.NoLegSecurityAltID field) { return isSetField(field); } public boolean isSetNoLegSecurityAltID() { return isSetField(604); } public void set(quickfix.field.LegProduct value) { setField(value); } public quickfix.field.LegProduct get(quickfix.field.LegProduct value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegProduct getLegProduct() throws FieldNotFound { quickfix.field.LegProduct value = new quickfix.field.LegProduct(); getField(value); return value; } public boolean isSet(quickfix.field.LegProduct field) { return isSetField(field); } public boolean isSetLegProduct() { return isSetField(607); } public void set(quickfix.field.LegCFICode value) { setField(value); } public quickfix.field.LegCFICode get(quickfix.field.LegCFICode value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegCFICode getLegCFICode() throws FieldNotFound { quickfix.field.LegCFICode value = new quickfix.field.LegCFICode(); getField(value); return value; } public boolean isSet(quickfix.field.LegCFICode field) { return isSetField(field); } public boolean isSetLegCFICode() { return isSetField(608); } public void set(quickfix.field.LegSecurityType value) { setField(value); } public quickfix.field.LegSecurityType get(quickfix.field.LegSecurityType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSecurityType getLegSecurityType() throws FieldNotFound { quickfix.field.LegSecurityType value = new quickfix.field.LegSecurityType(); getField(value); return value; } public boolean isSet(quickfix.field.LegSecurityType field) { return isSetField(field); } public boolean isSetLegSecurityType() { return isSetField(609); } public void set(quickfix.field.LegSecuritySubType value) { setField(value); } public quickfix.field.LegSecuritySubType get(quickfix.field.LegSecuritySubType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSecuritySubType getLegSecuritySubType() throws FieldNotFound { quickfix.field.LegSecuritySubType value = new quickfix.field.LegSecuritySubType(); getField(value); return value; } public boolean isSet(quickfix.field.LegSecuritySubType field) { return isSetField(field); } public boolean isSetLegSecuritySubType() { return isSetField(764); } public void set(quickfix.field.LegMaturityMonthYear value) { setField(value); } public quickfix.field.LegMaturityMonthYear get(quickfix.field.LegMaturityMonthYear value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegMaturityMonthYear getLegMaturityMonthYear() throws FieldNotFound { quickfix.field.LegMaturityMonthYear value = new quickfix.field.LegMaturityMonthYear(); getField(value); return value; } public boolean isSet(quickfix.field.LegMaturityMonthYear field) { return isSetField(field); } public boolean isSetLegMaturityMonthYear() { return isSetField(610); } public void set(quickfix.field.LegMaturityDate value) { setField(value); } public quickfix.field.LegMaturityDate get(quickfix.field.LegMaturityDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegMaturityDate getLegMaturityDate() throws FieldNotFound { quickfix.field.LegMaturityDate value = new quickfix.field.LegMaturityDate(); getField(value); return value; } public boolean isSet(quickfix.field.LegMaturityDate field) { return isSetField(field); } public boolean isSetLegMaturityDate() { return isSetField(611); } public void set(quickfix.field.LegCouponPaymentDate value) { setField(value); } public quickfix.field.LegCouponPaymentDate get(quickfix.field.LegCouponPaymentDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegCouponPaymentDate getLegCouponPaymentDate() throws FieldNotFound { quickfix.field.LegCouponPaymentDate value = new quickfix.field.LegCouponPaymentDate(); getField(value); return value; } public boolean isSet(quickfix.field.LegCouponPaymentDate field) { return isSetField(field); } public boolean isSetLegCouponPaymentDate() { return isSetField(248); } public void set(quickfix.field.LegIssueDate value) { setField(value); } public quickfix.field.LegIssueDate get(quickfix.field.LegIssueDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegIssueDate getLegIssueDate() throws FieldNotFound { quickfix.field.LegIssueDate value = new quickfix.field.LegIssueDate(); getField(value); return value; } public boolean isSet(quickfix.field.LegIssueDate field) { return isSetField(field); } public boolean isSetLegIssueDate() { return isSetField(249); } public void set(quickfix.field.LegRepoCollateralSecurityType value) { setField(value); } public quickfix.field.LegRepoCollateralSecurityType get(quickfix.field.LegRepoCollateralSecurityType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegRepoCollateralSecurityType getLegRepoCollateralSecurityType() throws FieldNotFound { quickfix.field.LegRepoCollateralSecurityType value = new quickfix.field.LegRepoCollateralSecurityType(); getField(value); return value; } public boolean isSet(quickfix.field.LegRepoCollateralSecurityType field) { return isSetField(field); } public boolean isSetLegRepoCollateralSecurityType() { return isSetField(250); } public void set(quickfix.field.LegRepurchaseTerm value) { setField(value); } public quickfix.field.LegRepurchaseTerm get(quickfix.field.LegRepurchaseTerm value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegRepurchaseTerm getLegRepurchaseTerm() throws FieldNotFound { quickfix.field.LegRepurchaseTerm value = new quickfix.field.LegRepurchaseTerm(); getField(value); return value; } public boolean isSet(quickfix.field.LegRepurchaseTerm field) { return isSetField(field); } public boolean isSetLegRepurchaseTerm() { return isSetField(251); } public void set(quickfix.field.LegRepurchaseRate value) { setField(value); } public quickfix.field.LegRepurchaseRate get(quickfix.field.LegRepurchaseRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegRepurchaseRate getLegRepurchaseRate() throws FieldNotFound { quickfix.field.LegRepurchaseRate value = new quickfix.field.LegRepurchaseRate(); getField(value); return value; } public boolean isSet(quickfix.field.LegRepurchaseRate field) { return isSetField(field); } public boolean isSetLegRepurchaseRate() { return isSetField(252); } public void set(quickfix.field.LegFactor value) { setField(value); } public quickfix.field.LegFactor get(quickfix.field.LegFactor value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegFactor getLegFactor() throws FieldNotFound { quickfix.field.LegFactor value = new quickfix.field.LegFactor(); getField(value); return value; } public boolean isSet(quickfix.field.LegFactor field) { return isSetField(field); } public boolean isSetLegFactor() { return isSetField(253); } public void set(quickfix.field.LegCreditRating value) { setField(value); } public quickfix.field.LegCreditRating get(quickfix.field.LegCreditRating value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegCreditRating getLegCreditRating() throws FieldNotFound { quickfix.field.LegCreditRating value = new quickfix.field.LegCreditRating(); getField(value); return value; } public boolean isSet(quickfix.field.LegCreditRating field) { return isSetField(field); } public boolean isSetLegCreditRating() { return isSetField(257); } public void set(quickfix.field.LegInstrRegistry value) { setField(value); } public quickfix.field.LegInstrRegistry get(quickfix.field.LegInstrRegistry value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegInstrRegistry getLegInstrRegistry() throws FieldNotFound { quickfix.field.LegInstrRegistry value = new quickfix.field.LegInstrRegistry(); getField(value); return value; } public boolean isSet(quickfix.field.LegInstrRegistry field) { return isSetField(field); } public boolean isSetLegInstrRegistry() { return isSetField(599); } public void set(quickfix.field.LegCountryOfIssue value) { setField(value); } public quickfix.field.LegCountryOfIssue get(quickfix.field.LegCountryOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegCountryOfIssue getLegCountryOfIssue() throws FieldNotFound { quickfix.field.LegCountryOfIssue value = new quickfix.field.LegCountryOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.LegCountryOfIssue field) { return isSetField(field); } public boolean isSetLegCountryOfIssue() { return isSetField(596); } public void set(quickfix.field.LegStateOrProvinceOfIssue value) { setField(value); } public quickfix.field.LegStateOrProvinceOfIssue get(quickfix.field.LegStateOrProvinceOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegStateOrProvinceOfIssue getLegStateOrProvinceOfIssue() throws FieldNotFound { quickfix.field.LegStateOrProvinceOfIssue value = new quickfix.field.LegStateOrProvinceOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.LegStateOrProvinceOfIssue field) { return isSetField(field); } public boolean isSetLegStateOrProvinceOfIssue() { return isSetField(597); } public void set(quickfix.field.LegLocaleOfIssue value) { setField(value); } public quickfix.field.LegLocaleOfIssue get(quickfix.field.LegLocaleOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegLocaleOfIssue getLegLocaleOfIssue() throws FieldNotFound { quickfix.field.LegLocaleOfIssue value = new quickfix.field.LegLocaleOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.LegLocaleOfIssue field) { return isSetField(field); } public boolean isSetLegLocaleOfIssue() { return isSetField(598); } public void set(quickfix.field.LegRedemptionDate value) { setField(value); } public quickfix.field.LegRedemptionDate get(quickfix.field.LegRedemptionDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegRedemptionDate getLegRedemptionDate() throws FieldNotFound { quickfix.field.LegRedemptionDate value = new quickfix.field.LegRedemptionDate(); getField(value); return value; } public boolean isSet(quickfix.field.LegRedemptionDate field) { return isSetField(field); } public boolean isSetLegRedemptionDate() { return isSetField(254); } public void set(quickfix.field.LegStrikePrice value) { setField(value); } public quickfix.field.LegStrikePrice get(quickfix.field.LegStrikePrice value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegStrikePrice getLegStrikePrice() throws FieldNotFound { quickfix.field.LegStrikePrice value = new quickfix.field.LegStrikePrice(); getField(value); return value; } public boolean isSet(quickfix.field.LegStrikePrice field) { return isSetField(field); } public boolean isSetLegStrikePrice() { return isSetField(612); } public void set(quickfix.field.LegStrikeCurrency value) { setField(value); } public quickfix.field.LegStrikeCurrency get(quickfix.field.LegStrikeCurrency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegStrikeCurrency getLegStrikeCurrency() throws FieldNotFound { quickfix.field.LegStrikeCurrency value = new quickfix.field.LegStrikeCurrency(); getField(value); return value; } public boolean isSet(quickfix.field.LegStrikeCurrency field) { return isSetField(field); } public boolean isSetLegStrikeCurrency() { return isSetField(942); } public void set(quickfix.field.LegOptAttribute value) { setField(value); } public quickfix.field.LegOptAttribute get(quickfix.field.LegOptAttribute value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegOptAttribute getLegOptAttribute() throws FieldNotFound { quickfix.field.LegOptAttribute value = new quickfix.field.LegOptAttribute(); getField(value); return value; } public boolean isSet(quickfix.field.LegOptAttribute field) { return isSetField(field); } public boolean isSetLegOptAttribute() { return isSetField(613); } public void set(quickfix.field.LegContractMultiplier value) { setField(value); } public quickfix.field.LegContractMultiplier get(quickfix.field.LegContractMultiplier value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegContractMultiplier getLegContractMultiplier() throws FieldNotFound { quickfix.field.LegContractMultiplier value = new quickfix.field.LegContractMultiplier(); getField(value); return value; } public boolean isSet(quickfix.field.LegContractMultiplier field) { return isSetField(field); } public boolean isSetLegContractMultiplier() { return isSetField(614); } public void set(quickfix.field.LegCouponRate value) { setField(value); } public quickfix.field.LegCouponRate get(quickfix.field.LegCouponRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegCouponRate getLegCouponRate() throws FieldNotFound { quickfix.field.LegCouponRate value = new quickfix.field.LegCouponRate(); getField(value); return value; } public boolean isSet(quickfix.field.LegCouponRate field) { return isSetField(field); } public boolean isSetLegCouponRate() { return isSetField(615); } public void set(quickfix.field.LegSecurityExchange value) { setField(value); } public quickfix.field.LegSecurityExchange get(quickfix.field.LegSecurityExchange value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSecurityExchange getLegSecurityExchange() throws FieldNotFound { quickfix.field.LegSecurityExchange value = new quickfix.field.LegSecurityExchange(); getField(value); return value; } public boolean isSet(quickfix.field.LegSecurityExchange field) { return isSetField(field); } public boolean isSetLegSecurityExchange() { return isSetField(616); } public void set(quickfix.field.LegIssuer value) { setField(value); } public quickfix.field.LegIssuer get(quickfix.field.LegIssuer value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegIssuer getLegIssuer() throws FieldNotFound { quickfix.field.LegIssuer value = new quickfix.field.LegIssuer(); getField(value); return value; } public boolean isSet(quickfix.field.LegIssuer field) { return isSetField(field); } public boolean isSetLegIssuer() { return isSetField(617); } public void set(quickfix.field.EncodedLegIssuerLen value) { setField(value); } public quickfix.field.EncodedLegIssuerLen get(quickfix.field.EncodedLegIssuerLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedLegIssuerLen getEncodedLegIssuerLen() throws FieldNotFound { quickfix.field.EncodedLegIssuerLen value = new quickfix.field.EncodedLegIssuerLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedLegIssuerLen field) { return isSetField(field); } public boolean isSetEncodedLegIssuerLen() { return isSetField(618); } public void set(quickfix.field.EncodedLegIssuer value) { setField(value); } public quickfix.field.EncodedLegIssuer get(quickfix.field.EncodedLegIssuer value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedLegIssuer getEncodedLegIssuer() throws FieldNotFound { quickfix.field.EncodedLegIssuer value = new quickfix.field.EncodedLegIssuer(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedLegIssuer field) { return isSetField(field); } public boolean isSetEncodedLegIssuer() { return isSetField(619); } public void set(quickfix.field.LegSecurityDesc value) { setField(value); } public quickfix.field.LegSecurityDesc get(quickfix.field.LegSecurityDesc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSecurityDesc getLegSecurityDesc() throws FieldNotFound { quickfix.field.LegSecurityDesc value = new quickfix.field.LegSecurityDesc(); getField(value); return value; } public boolean isSet(quickfix.field.LegSecurityDesc field) { return isSetField(field); } public boolean isSetLegSecurityDesc() { return isSetField(620); } public void set(quickfix.field.EncodedLegSecurityDescLen value) { setField(value); } public quickfix.field.EncodedLegSecurityDescLen get(quickfix.field.EncodedLegSecurityDescLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedLegSecurityDescLen getEncodedLegSecurityDescLen() throws FieldNotFound { quickfix.field.EncodedLegSecurityDescLen value = new quickfix.field.EncodedLegSecurityDescLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedLegSecurityDescLen field) { return isSetField(field); } public boolean isSetEncodedLegSecurityDescLen() { return isSetField(621); } public void set(quickfix.field.EncodedLegSecurityDesc value) { setField(value); } public quickfix.field.EncodedLegSecurityDesc get(quickfix.field.EncodedLegSecurityDesc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedLegSecurityDesc getEncodedLegSecurityDesc() throws FieldNotFound { quickfix.field.EncodedLegSecurityDesc value = new quickfix.field.EncodedLegSecurityDesc(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedLegSecurityDesc field) { return isSetField(field); } public boolean isSetEncodedLegSecurityDesc() { return isSetField(622); } public void set(quickfix.field.LegRatioQty value) { setField(value); } public quickfix.field.LegRatioQty get(quickfix.field.LegRatioQty value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegRatioQty getLegRatioQty() throws FieldNotFound { quickfix.field.LegRatioQty value = new quickfix.field.LegRatioQty(); getField(value); return value; } public boolean isSet(quickfix.field.LegRatioQty field) { return isSetField(field); } public boolean isSetLegRatioQty() { return isSetField(623); } public void set(quickfix.field.LegSide value) { setField(value); } public quickfix.field.LegSide get(quickfix.field.LegSide value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegSide getLegSide() throws FieldNotFound { quickfix.field.LegSide value = new quickfix.field.LegSide(); getField(value); return value; } public boolean isSet(quickfix.field.LegSide field) { return isSetField(field); } public boolean isSetLegSide() { return isSetField(624); } public void set(quickfix.field.LegCurrency value) { setField(value); } public quickfix.field.LegCurrency get(quickfix.field.LegCurrency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegCurrency getLegCurrency() throws FieldNotFound { quickfix.field.LegCurrency value = new quickfix.field.LegCurrency(); getField(value); return value; } public boolean isSet(quickfix.field.LegCurrency field) { return isSetField(field); } public boolean isSetLegCurrency() { return isSetField(556); } public void set(quickfix.field.LegPool value) { setField(value); } public quickfix.field.LegPool get(quickfix.field.LegPool value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegPool getLegPool() throws FieldNotFound { quickfix.field.LegPool value = new quickfix.field.LegPool(); getField(value); return value; } public boolean isSet(quickfix.field.LegPool field) { return isSetField(field); } public boolean isSetLegPool() { return isSetField(740); } public void set(quickfix.field.LegDatedDate value) { setField(value); } public quickfix.field.LegDatedDate get(quickfix.field.LegDatedDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegDatedDate getLegDatedDate() throws FieldNotFound { quickfix.field.LegDatedDate value = new quickfix.field.LegDatedDate(); getField(value); return value; } public boolean isSet(quickfix.field.LegDatedDate field) { return isSetField(field); } public boolean isSetLegDatedDate() { return isSetField(739); } public void set(quickfix.field.LegContractSettlMonth value) { setField(value); } public quickfix.field.LegContractSettlMonth get(quickfix.field.LegContractSettlMonth value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegContractSettlMonth getLegContractSettlMonth() throws FieldNotFound { quickfix.field.LegContractSettlMonth value = new quickfix.field.LegContractSettlMonth(); getField(value); return value; } public boolean isSet(quickfix.field.LegContractSettlMonth field) { return isSetField(field); } public boolean isSetLegContractSettlMonth() { return isSetField(955); } public void set(quickfix.field.LegInterestAccrualDate value) { setField(value); } public quickfix.field.LegInterestAccrualDate get(quickfix.field.LegInterestAccrualDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegInterestAccrualDate getLegInterestAccrualDate() throws FieldNotFound { quickfix.field.LegInterestAccrualDate value = new quickfix.field.LegInterestAccrualDate(); getField(value); return value; } public boolean isSet(quickfix.field.LegInterestAccrualDate field) { return isSetField(field); } public boolean isSetLegInterestAccrualDate() { return isSetField(956); } public void set(quickfix.field.LegUnitofMeasure value) { setField(value); } public quickfix.field.LegUnitofMeasure get(quickfix.field.LegUnitofMeasure value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegUnitofMeasure getLegUnitofMeasure() throws FieldNotFound { quickfix.field.LegUnitofMeasure value = new quickfix.field.LegUnitofMeasure(); getField(value); return value; } public boolean isSet(quickfix.field.LegUnitofMeasure field) { return isSetField(field); } public boolean isSetLegUnitofMeasure() { return isSetField(999); } public void set(quickfix.field.LegTimeUnit value) { setField(value); } public quickfix.field.LegTimeUnit get(quickfix.field.LegTimeUnit value) throws FieldNotFound { getField(value); return value; } public quickfix.field.LegTimeUnit getLegTimeUnit() throws FieldNotFound { quickfix.field.LegTimeUnit value = new quickfix.field.LegTimeUnit(); getField(value); return value; } public boolean isSet(quickfix.field.LegTimeUnit field) { return isSetField(field); } public boolean isSetLegTimeUnit() { return isSetField(1001); } } public void set(quickfix.fix50.component.UndInstrmtGrp component) { setComponent(component); } public quickfix.fix50.component.UndInstrmtGrp get(quickfix.fix50.component.UndInstrmtGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.UndInstrmtGrp getUndInstrmtGrp() throws FieldNotFound { quickfix.fix50.component.UndInstrmtGrp component = new quickfix.fix50.component.UndInstrmtGrp(); getComponent(component); return component; } public void set(quickfix.field.NoUnderlyings value) { setField(value); } public quickfix.field.NoUnderlyings get(quickfix.field.NoUnderlyings value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoUnderlyings getNoUnderlyings() throws FieldNotFound { quickfix.field.NoUnderlyings value = new quickfix.field.NoUnderlyings(); getField(value); return value; } public boolean isSet(quickfix.field.NoUnderlyings field) { return isSetField(field); } public boolean isSetNoUnderlyings() { return isSetField(711); } public static class NoUnderlyings extends Group { static final long serialVersionUID = 20050617; public NoUnderlyings() { super(711, 311, new int[] {311, 312, 309, 305, 457, 462, 463, 310, 763, 313, 542, 241, 242, 243, 244, 245, 246, 256, 595, 592, 593, 594, 247, 316, 941, 317, 436, 435, 308, 306, 362, 363, 307, 364, 365, 877, 878, 318, 879, 810, 882, 883, 884, 885, 886, 887, 972, 975, 973, 974, 998, 1000, 1038, 1058, 1039, 1044, 1045, 1046, 0 } ); } public void set(quickfix.fix50.component.UnderlyingInstrument component) { setComponent(component); } public quickfix.fix50.component.UnderlyingInstrument get(quickfix.fix50.component.UnderlyingInstrument component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.UnderlyingInstrument getUnderlyingInstrument() throws FieldNotFound { quickfix.fix50.component.UnderlyingInstrument component = new quickfix.fix50.component.UnderlyingInstrument(); getComponent(component); return component; } public void set(quickfix.field.UnderlyingSymbol value) { setField(value); } public quickfix.field.UnderlyingSymbol get(quickfix.field.UnderlyingSymbol value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSymbol getUnderlyingSymbol() throws FieldNotFound { quickfix.field.UnderlyingSymbol value = new quickfix.field.UnderlyingSymbol(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSymbol field) { return isSetField(field); } public boolean isSetUnderlyingSymbol() { return isSetField(311); } public void set(quickfix.field.UnderlyingSymbolSfx value) { setField(value); } public quickfix.field.UnderlyingSymbolSfx get(quickfix.field.UnderlyingSymbolSfx value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSymbolSfx getUnderlyingSymbolSfx() throws FieldNotFound { quickfix.field.UnderlyingSymbolSfx value = new quickfix.field.UnderlyingSymbolSfx(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSymbolSfx field) { return isSetField(field); } public boolean isSetUnderlyingSymbolSfx() { return isSetField(312); } public void set(quickfix.field.UnderlyingSecurityID value) { setField(value); } public quickfix.field.UnderlyingSecurityID get(quickfix.field.UnderlyingSecurityID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityID getUnderlyingSecurityID() throws FieldNotFound { quickfix.field.UnderlyingSecurityID value = new quickfix.field.UnderlyingSecurityID(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityID field) { return isSetField(field); } public boolean isSetUnderlyingSecurityID() { return isSetField(309); } public void set(quickfix.field.UnderlyingSecurityIDSource value) { setField(value); } public quickfix.field.UnderlyingSecurityIDSource get(quickfix.field.UnderlyingSecurityIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityIDSource getUnderlyingSecurityIDSource() throws FieldNotFound { quickfix.field.UnderlyingSecurityIDSource value = new quickfix.field.UnderlyingSecurityIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityIDSource field) { return isSetField(field); } public boolean isSetUnderlyingSecurityIDSource() { return isSetField(305); } public void set(quickfix.fix50.component.UndSecAltIDGrp component) { setComponent(component); } public quickfix.fix50.component.UndSecAltIDGrp get(quickfix.fix50.component.UndSecAltIDGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.UndSecAltIDGrp getUndSecAltIDGrp() throws FieldNotFound { quickfix.fix50.component.UndSecAltIDGrp component = new quickfix.fix50.component.UndSecAltIDGrp(); getComponent(component); return component; } public void set(quickfix.field.NoUnderlyingSecurityAltID value) { setField(value); } public quickfix.field.NoUnderlyingSecurityAltID get(quickfix.field.NoUnderlyingSecurityAltID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoUnderlyingSecurityAltID getNoUnderlyingSecurityAltID() throws FieldNotFound { quickfix.field.NoUnderlyingSecurityAltID value = new quickfix.field.NoUnderlyingSecurityAltID(); getField(value); return value; } public boolean isSet(quickfix.field.NoUnderlyingSecurityAltID field) { return isSetField(field); } public boolean isSetNoUnderlyingSecurityAltID() { return isSetField(457); } public static class NoUnderlyingSecurityAltID extends Group { static final long serialVersionUID = 20050617; public NoUnderlyingSecurityAltID() { super(457, 458, new int[] {458, 459, 0 } ); } public void set(quickfix.field.UnderlyingSecurityAltID value) { setField(value); } public quickfix.field.UnderlyingSecurityAltID get(quickfix.field.UnderlyingSecurityAltID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityAltID getUnderlyingSecurityAltID() throws FieldNotFound { quickfix.field.UnderlyingSecurityAltID value = new quickfix.field.UnderlyingSecurityAltID(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityAltID field) { return isSetField(field); } public boolean isSetUnderlyingSecurityAltID() { return isSetField(458); } public void set(quickfix.field.UnderlyingSecurityAltIDSource value) { setField(value); } public quickfix.field.UnderlyingSecurityAltIDSource get(quickfix.field.UnderlyingSecurityAltIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityAltIDSource getUnderlyingSecurityAltIDSource() throws FieldNotFound { quickfix.field.UnderlyingSecurityAltIDSource value = new quickfix.field.UnderlyingSecurityAltIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityAltIDSource field) { return isSetField(field); } public boolean isSetUnderlyingSecurityAltIDSource() { return isSetField(459); } } public void set(quickfix.field.UnderlyingProduct value) { setField(value); } public quickfix.field.UnderlyingProduct get(quickfix.field.UnderlyingProduct value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingProduct getUnderlyingProduct() throws FieldNotFound { quickfix.field.UnderlyingProduct value = new quickfix.field.UnderlyingProduct(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingProduct field) { return isSetField(field); } public boolean isSetUnderlyingProduct() { return isSetField(462); } public void set(quickfix.field.UnderlyingCFICode value) { setField(value); } public quickfix.field.UnderlyingCFICode get(quickfix.field.UnderlyingCFICode value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCFICode getUnderlyingCFICode() throws FieldNotFound { quickfix.field.UnderlyingCFICode value = new quickfix.field.UnderlyingCFICode(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCFICode field) { return isSetField(field); } public boolean isSetUnderlyingCFICode() { return isSetField(463); } public void set(quickfix.field.UnderlyingSecurityType value) { setField(value); } public quickfix.field.UnderlyingSecurityType get(quickfix.field.UnderlyingSecurityType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityType getUnderlyingSecurityType() throws FieldNotFound { quickfix.field.UnderlyingSecurityType value = new quickfix.field.UnderlyingSecurityType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityType field) { return isSetField(field); } public boolean isSetUnderlyingSecurityType() { return isSetField(310); } public void set(quickfix.field.UnderlyingSecuritySubType value) { setField(value); } public quickfix.field.UnderlyingSecuritySubType get(quickfix.field.UnderlyingSecuritySubType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecuritySubType getUnderlyingSecuritySubType() throws FieldNotFound { quickfix.field.UnderlyingSecuritySubType value = new quickfix.field.UnderlyingSecuritySubType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecuritySubType field) { return isSetField(field); } public boolean isSetUnderlyingSecuritySubType() { return isSetField(763); } public void set(quickfix.field.UnderlyingMaturityMonthYear value) { setField(value); } public quickfix.field.UnderlyingMaturityMonthYear get(quickfix.field.UnderlyingMaturityMonthYear value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingMaturityMonthYear getUnderlyingMaturityMonthYear() throws FieldNotFound { quickfix.field.UnderlyingMaturityMonthYear value = new quickfix.field.UnderlyingMaturityMonthYear(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingMaturityMonthYear field) { return isSetField(field); } public boolean isSetUnderlyingMaturityMonthYear() { return isSetField(313); } public void set(quickfix.field.UnderlyingMaturityDate value) { setField(value); } public quickfix.field.UnderlyingMaturityDate get(quickfix.field.UnderlyingMaturityDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingMaturityDate getUnderlyingMaturityDate() throws FieldNotFound { quickfix.field.UnderlyingMaturityDate value = new quickfix.field.UnderlyingMaturityDate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingMaturityDate field) { return isSetField(field); } public boolean isSetUnderlyingMaturityDate() { return isSetField(542); } public void set(quickfix.field.UnderlyingCouponPaymentDate value) { setField(value); } public quickfix.field.UnderlyingCouponPaymentDate get(quickfix.field.UnderlyingCouponPaymentDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCouponPaymentDate getUnderlyingCouponPaymentDate() throws FieldNotFound { quickfix.field.UnderlyingCouponPaymentDate value = new quickfix.field.UnderlyingCouponPaymentDate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCouponPaymentDate field) { return isSetField(field); } public boolean isSetUnderlyingCouponPaymentDate() { return isSetField(241); } public void set(quickfix.field.UnderlyingIssueDate value) { setField(value); } public quickfix.field.UnderlyingIssueDate get(quickfix.field.UnderlyingIssueDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingIssueDate getUnderlyingIssueDate() throws FieldNotFound { quickfix.field.UnderlyingIssueDate value = new quickfix.field.UnderlyingIssueDate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingIssueDate field) { return isSetField(field); } public boolean isSetUnderlyingIssueDate() { return isSetField(242); } public void set(quickfix.field.UnderlyingRepoCollateralSecurityType value) { setField(value); } public quickfix.field.UnderlyingRepoCollateralSecurityType get(quickfix.field.UnderlyingRepoCollateralSecurityType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingRepoCollateralSecurityType getUnderlyingRepoCollateralSecurityType() throws FieldNotFound { quickfix.field.UnderlyingRepoCollateralSecurityType value = new quickfix.field.UnderlyingRepoCollateralSecurityType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingRepoCollateralSecurityType field) { return isSetField(field); } public boolean isSetUnderlyingRepoCollateralSecurityType() { return isSetField(243); } public void set(quickfix.field.UnderlyingRepurchaseTerm value) { setField(value); } public quickfix.field.UnderlyingRepurchaseTerm get(quickfix.field.UnderlyingRepurchaseTerm value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingRepurchaseTerm getUnderlyingRepurchaseTerm() throws FieldNotFound { quickfix.field.UnderlyingRepurchaseTerm value = new quickfix.field.UnderlyingRepurchaseTerm(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingRepurchaseTerm field) { return isSetField(field); } public boolean isSetUnderlyingRepurchaseTerm() { return isSetField(244); } public void set(quickfix.field.UnderlyingRepurchaseRate value) { setField(value); } public quickfix.field.UnderlyingRepurchaseRate get(quickfix.field.UnderlyingRepurchaseRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingRepurchaseRate getUnderlyingRepurchaseRate() throws FieldNotFound { quickfix.field.UnderlyingRepurchaseRate value = new quickfix.field.UnderlyingRepurchaseRate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingRepurchaseRate field) { return isSetField(field); } public boolean isSetUnderlyingRepurchaseRate() { return isSetField(245); } public void set(quickfix.field.UnderlyingFactor value) { setField(value); } public quickfix.field.UnderlyingFactor get(quickfix.field.UnderlyingFactor value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingFactor getUnderlyingFactor() throws FieldNotFound { quickfix.field.UnderlyingFactor value = new quickfix.field.UnderlyingFactor(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingFactor field) { return isSetField(field); } public boolean isSetUnderlyingFactor() { return isSetField(246); } public void set(quickfix.field.UnderlyingCreditRating value) { setField(value); } public quickfix.field.UnderlyingCreditRating get(quickfix.field.UnderlyingCreditRating value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCreditRating getUnderlyingCreditRating() throws FieldNotFound { quickfix.field.UnderlyingCreditRating value = new quickfix.field.UnderlyingCreditRating(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCreditRating field) { return isSetField(field); } public boolean isSetUnderlyingCreditRating() { return isSetField(256); } public void set(quickfix.field.UnderlyingInstrRegistry value) { setField(value); } public quickfix.field.UnderlyingInstrRegistry get(quickfix.field.UnderlyingInstrRegistry value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingInstrRegistry getUnderlyingInstrRegistry() throws FieldNotFound { quickfix.field.UnderlyingInstrRegistry value = new quickfix.field.UnderlyingInstrRegistry(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingInstrRegistry field) { return isSetField(field); } public boolean isSetUnderlyingInstrRegistry() { return isSetField(595); } public void set(quickfix.field.UnderlyingCountryOfIssue value) { setField(value); } public quickfix.field.UnderlyingCountryOfIssue get(quickfix.field.UnderlyingCountryOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCountryOfIssue getUnderlyingCountryOfIssue() throws FieldNotFound { quickfix.field.UnderlyingCountryOfIssue value = new quickfix.field.UnderlyingCountryOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCountryOfIssue field) { return isSetField(field); } public boolean isSetUnderlyingCountryOfIssue() { return isSetField(592); } public void set(quickfix.field.UnderlyingStateOrProvinceOfIssue value) { setField(value); } public quickfix.field.UnderlyingStateOrProvinceOfIssue get(quickfix.field.UnderlyingStateOrProvinceOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingStateOrProvinceOfIssue getUnderlyingStateOrProvinceOfIssue() throws FieldNotFound { quickfix.field.UnderlyingStateOrProvinceOfIssue value = new quickfix.field.UnderlyingStateOrProvinceOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingStateOrProvinceOfIssue field) { return isSetField(field); } public boolean isSetUnderlyingStateOrProvinceOfIssue() { return isSetField(593); } public void set(quickfix.field.UnderlyingLocaleOfIssue value) { setField(value); } public quickfix.field.UnderlyingLocaleOfIssue get(quickfix.field.UnderlyingLocaleOfIssue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingLocaleOfIssue getUnderlyingLocaleOfIssue() throws FieldNotFound { quickfix.field.UnderlyingLocaleOfIssue value = new quickfix.field.UnderlyingLocaleOfIssue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingLocaleOfIssue field) { return isSetField(field); } public boolean isSetUnderlyingLocaleOfIssue() { return isSetField(594); } public void set(quickfix.field.UnderlyingRedemptionDate value) { setField(value); } public quickfix.field.UnderlyingRedemptionDate get(quickfix.field.UnderlyingRedemptionDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingRedemptionDate getUnderlyingRedemptionDate() throws FieldNotFound { quickfix.field.UnderlyingRedemptionDate value = new quickfix.field.UnderlyingRedemptionDate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingRedemptionDate field) { return isSetField(field); } public boolean isSetUnderlyingRedemptionDate() { return isSetField(247); } public void set(quickfix.field.UnderlyingStrikePrice value) { setField(value); } public quickfix.field.UnderlyingStrikePrice get(quickfix.field.UnderlyingStrikePrice value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingStrikePrice getUnderlyingStrikePrice() throws FieldNotFound { quickfix.field.UnderlyingStrikePrice value = new quickfix.field.UnderlyingStrikePrice(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingStrikePrice field) { return isSetField(field); } public boolean isSetUnderlyingStrikePrice() { return isSetField(316); } public void set(quickfix.field.UnderlyingStrikeCurrency value) { setField(value); } public quickfix.field.UnderlyingStrikeCurrency get(quickfix.field.UnderlyingStrikeCurrency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingStrikeCurrency getUnderlyingStrikeCurrency() throws FieldNotFound { quickfix.field.UnderlyingStrikeCurrency value = new quickfix.field.UnderlyingStrikeCurrency(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingStrikeCurrency field) { return isSetField(field); } public boolean isSetUnderlyingStrikeCurrency() { return isSetField(941); } public void set(quickfix.field.UnderlyingOptAttribute value) { setField(value); } public quickfix.field.UnderlyingOptAttribute get(quickfix.field.UnderlyingOptAttribute value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingOptAttribute getUnderlyingOptAttribute() throws FieldNotFound { quickfix.field.UnderlyingOptAttribute value = new quickfix.field.UnderlyingOptAttribute(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingOptAttribute field) { return isSetField(field); } public boolean isSetUnderlyingOptAttribute() { return isSetField(317); } public void set(quickfix.field.UnderlyingContractMultiplier value) { setField(value); } public quickfix.field.UnderlyingContractMultiplier get(quickfix.field.UnderlyingContractMultiplier value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingContractMultiplier getUnderlyingContractMultiplier() throws FieldNotFound { quickfix.field.UnderlyingContractMultiplier value = new quickfix.field.UnderlyingContractMultiplier(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingContractMultiplier field) { return isSetField(field); } public boolean isSetUnderlyingContractMultiplier() { return isSetField(436); } public void set(quickfix.field.UnderlyingCouponRate value) { setField(value); } public quickfix.field.UnderlyingCouponRate get(quickfix.field.UnderlyingCouponRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCouponRate getUnderlyingCouponRate() throws FieldNotFound { quickfix.field.UnderlyingCouponRate value = new quickfix.field.UnderlyingCouponRate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCouponRate field) { return isSetField(field); } public boolean isSetUnderlyingCouponRate() { return isSetField(435); } public void set(quickfix.field.UnderlyingSecurityExchange value) { setField(value); } public quickfix.field.UnderlyingSecurityExchange get(quickfix.field.UnderlyingSecurityExchange value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityExchange getUnderlyingSecurityExchange() throws FieldNotFound { quickfix.field.UnderlyingSecurityExchange value = new quickfix.field.UnderlyingSecurityExchange(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityExchange field) { return isSetField(field); } public boolean isSetUnderlyingSecurityExchange() { return isSetField(308); } public void set(quickfix.field.UnderlyingIssuer value) { setField(value); } public quickfix.field.UnderlyingIssuer get(quickfix.field.UnderlyingIssuer value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingIssuer getUnderlyingIssuer() throws FieldNotFound { quickfix.field.UnderlyingIssuer value = new quickfix.field.UnderlyingIssuer(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingIssuer field) { return isSetField(field); } public boolean isSetUnderlyingIssuer() { return isSetField(306); } public void set(quickfix.field.EncodedUnderlyingIssuerLen value) { setField(value); } public quickfix.field.EncodedUnderlyingIssuerLen get(quickfix.field.EncodedUnderlyingIssuerLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedUnderlyingIssuerLen getEncodedUnderlyingIssuerLen() throws FieldNotFound { quickfix.field.EncodedUnderlyingIssuerLen value = new quickfix.field.EncodedUnderlyingIssuerLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedUnderlyingIssuerLen field) { return isSetField(field); } public boolean isSetEncodedUnderlyingIssuerLen() { return isSetField(362); } public void set(quickfix.field.EncodedUnderlyingIssuer value) { setField(value); } public quickfix.field.EncodedUnderlyingIssuer get(quickfix.field.EncodedUnderlyingIssuer value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedUnderlyingIssuer getEncodedUnderlyingIssuer() throws FieldNotFound { quickfix.field.EncodedUnderlyingIssuer value = new quickfix.field.EncodedUnderlyingIssuer(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedUnderlyingIssuer field) { return isSetField(field); } public boolean isSetEncodedUnderlyingIssuer() { return isSetField(363); } public void set(quickfix.field.UnderlyingSecurityDesc value) { setField(value); } public quickfix.field.UnderlyingSecurityDesc get(quickfix.field.UnderlyingSecurityDesc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSecurityDesc getUnderlyingSecurityDesc() throws FieldNotFound { quickfix.field.UnderlyingSecurityDesc value = new quickfix.field.UnderlyingSecurityDesc(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSecurityDesc field) { return isSetField(field); } public boolean isSetUnderlyingSecurityDesc() { return isSetField(307); } public void set(quickfix.field.EncodedUnderlyingSecurityDescLen value) { setField(value); } public quickfix.field.EncodedUnderlyingSecurityDescLen get(quickfix.field.EncodedUnderlyingSecurityDescLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedUnderlyingSecurityDescLen getEncodedUnderlyingSecurityDescLen() throws FieldNotFound { quickfix.field.EncodedUnderlyingSecurityDescLen value = new quickfix.field.EncodedUnderlyingSecurityDescLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedUnderlyingSecurityDescLen field) { return isSetField(field); } public boolean isSetEncodedUnderlyingSecurityDescLen() { return isSetField(364); } public void set(quickfix.field.EncodedUnderlyingSecurityDesc value) { setField(value); } public quickfix.field.EncodedUnderlyingSecurityDesc get(quickfix.field.EncodedUnderlyingSecurityDesc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedUnderlyingSecurityDesc getEncodedUnderlyingSecurityDesc() throws FieldNotFound { quickfix.field.EncodedUnderlyingSecurityDesc value = new quickfix.field.EncodedUnderlyingSecurityDesc(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedUnderlyingSecurityDesc field) { return isSetField(field); } public boolean isSetEncodedUnderlyingSecurityDesc() { return isSetField(365); } public void set(quickfix.field.UnderlyingCPProgram value) { setField(value); } public quickfix.field.UnderlyingCPProgram get(quickfix.field.UnderlyingCPProgram value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCPProgram getUnderlyingCPProgram() throws FieldNotFound { quickfix.field.UnderlyingCPProgram value = new quickfix.field.UnderlyingCPProgram(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCPProgram field) { return isSetField(field); } public boolean isSetUnderlyingCPProgram() { return isSetField(877); } public void set(quickfix.field.UnderlyingCPRegType value) { setField(value); } public quickfix.field.UnderlyingCPRegType get(quickfix.field.UnderlyingCPRegType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCPRegType getUnderlyingCPRegType() throws FieldNotFound { quickfix.field.UnderlyingCPRegType value = new quickfix.field.UnderlyingCPRegType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCPRegType field) { return isSetField(field); } public boolean isSetUnderlyingCPRegType() { return isSetField(878); } public void set(quickfix.field.UnderlyingCurrency value) { setField(value); } public quickfix.field.UnderlyingCurrency get(quickfix.field.UnderlyingCurrency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCurrency getUnderlyingCurrency() throws FieldNotFound { quickfix.field.UnderlyingCurrency value = new quickfix.field.UnderlyingCurrency(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCurrency field) { return isSetField(field); } public boolean isSetUnderlyingCurrency() { return isSetField(318); } public void set(quickfix.field.UnderlyingQty value) { setField(value); } public quickfix.field.UnderlyingQty get(quickfix.field.UnderlyingQty value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingQty getUnderlyingQty() throws FieldNotFound { quickfix.field.UnderlyingQty value = new quickfix.field.UnderlyingQty(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingQty field) { return isSetField(field); } public boolean isSetUnderlyingQty() { return isSetField(879); } public void set(quickfix.field.UnderlyingPx value) { setField(value); } public quickfix.field.UnderlyingPx get(quickfix.field.UnderlyingPx value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingPx getUnderlyingPx() throws FieldNotFound { quickfix.field.UnderlyingPx value = new quickfix.field.UnderlyingPx(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingPx field) { return isSetField(field); } public boolean isSetUnderlyingPx() { return isSetField(810); } public void set(quickfix.field.UnderlyingDirtyPrice value) { setField(value); } public quickfix.field.UnderlyingDirtyPrice get(quickfix.field.UnderlyingDirtyPrice value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingDirtyPrice getUnderlyingDirtyPrice() throws FieldNotFound { quickfix.field.UnderlyingDirtyPrice value = new quickfix.field.UnderlyingDirtyPrice(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingDirtyPrice field) { return isSetField(field); } public boolean isSetUnderlyingDirtyPrice() { return isSetField(882); } public void set(quickfix.field.UnderlyingEndPrice value) { setField(value); } public quickfix.field.UnderlyingEndPrice get(quickfix.field.UnderlyingEndPrice value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingEndPrice getUnderlyingEndPrice() throws FieldNotFound { quickfix.field.UnderlyingEndPrice value = new quickfix.field.UnderlyingEndPrice(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingEndPrice field) { return isSetField(field); } public boolean isSetUnderlyingEndPrice() { return isSetField(883); } public void set(quickfix.field.UnderlyingStartValue value) { setField(value); } public quickfix.field.UnderlyingStartValue get(quickfix.field.UnderlyingStartValue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingStartValue getUnderlyingStartValue() throws FieldNotFound { quickfix.field.UnderlyingStartValue value = new quickfix.field.UnderlyingStartValue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingStartValue field) { return isSetField(field); } public boolean isSetUnderlyingStartValue() { return isSetField(884); } public void set(quickfix.field.UnderlyingCurrentValue value) { setField(value); } public quickfix.field.UnderlyingCurrentValue get(quickfix.field.UnderlyingCurrentValue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCurrentValue getUnderlyingCurrentValue() throws FieldNotFound { quickfix.field.UnderlyingCurrentValue value = new quickfix.field.UnderlyingCurrentValue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCurrentValue field) { return isSetField(field); } public boolean isSetUnderlyingCurrentValue() { return isSetField(885); } public void set(quickfix.field.UnderlyingEndValue value) { setField(value); } public quickfix.field.UnderlyingEndValue get(quickfix.field.UnderlyingEndValue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingEndValue getUnderlyingEndValue() throws FieldNotFound { quickfix.field.UnderlyingEndValue value = new quickfix.field.UnderlyingEndValue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingEndValue field) { return isSetField(field); } public boolean isSetUnderlyingEndValue() { return isSetField(886); } public void set(quickfix.fix50.component.UnderlyingStipulations component) { setComponent(component); } public quickfix.fix50.component.UnderlyingStipulations get(quickfix.fix50.component.UnderlyingStipulations component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.UnderlyingStipulations getUnderlyingStipulations() throws FieldNotFound { quickfix.fix50.component.UnderlyingStipulations component = new quickfix.fix50.component.UnderlyingStipulations(); getComponent(component); return component; } public void set(quickfix.field.NoUnderlyingStips value) { setField(value); } public quickfix.field.NoUnderlyingStips get(quickfix.field.NoUnderlyingStips value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoUnderlyingStips getNoUnderlyingStips() throws FieldNotFound { quickfix.field.NoUnderlyingStips value = new quickfix.field.NoUnderlyingStips(); getField(value); return value; } public boolean isSet(quickfix.field.NoUnderlyingStips field) { return isSetField(field); } public boolean isSetNoUnderlyingStips() { return isSetField(887); } public static class NoUnderlyingStips extends Group { static final long serialVersionUID = 20050617; public NoUnderlyingStips() { super(887, 888, new int[] {888, 889, 0 } ); } public void set(quickfix.field.UnderlyingStipType value) { setField(value); } public quickfix.field.UnderlyingStipType get(quickfix.field.UnderlyingStipType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingStipType getUnderlyingStipType() throws FieldNotFound { quickfix.field.UnderlyingStipType value = new quickfix.field.UnderlyingStipType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingStipType field) { return isSetField(field); } public boolean isSetUnderlyingStipType() { return isSetField(888); } public void set(quickfix.field.UnderlyingStipValue value) { setField(value); } public quickfix.field.UnderlyingStipValue get(quickfix.field.UnderlyingStipValue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingStipValue getUnderlyingStipValue() throws FieldNotFound { quickfix.field.UnderlyingStipValue value = new quickfix.field.UnderlyingStipValue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingStipValue field) { return isSetField(field); } public boolean isSetUnderlyingStipValue() { return isSetField(889); } } public void set(quickfix.field.UnderlyingAllocationPercent value) { setField(value); } public quickfix.field.UnderlyingAllocationPercent get(quickfix.field.UnderlyingAllocationPercent value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingAllocationPercent getUnderlyingAllocationPercent() throws FieldNotFound { quickfix.field.UnderlyingAllocationPercent value = new quickfix.field.UnderlyingAllocationPercent(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingAllocationPercent field) { return isSetField(field); } public boolean isSetUnderlyingAllocationPercent() { return isSetField(972); } public void set(quickfix.field.UnderlyingSettlementType value) { setField(value); } public quickfix.field.UnderlyingSettlementType get(quickfix.field.UnderlyingSettlementType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSettlementType getUnderlyingSettlementType() throws FieldNotFound { quickfix.field.UnderlyingSettlementType value = new quickfix.field.UnderlyingSettlementType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSettlementType field) { return isSetField(field); } public boolean isSetUnderlyingSettlementType() { return isSetField(975); } public void set(quickfix.field.UnderlyingCashAmount value) { setField(value); } public quickfix.field.UnderlyingCashAmount get(quickfix.field.UnderlyingCashAmount value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCashAmount getUnderlyingCashAmount() throws FieldNotFound { quickfix.field.UnderlyingCashAmount value = new quickfix.field.UnderlyingCashAmount(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCashAmount field) { return isSetField(field); } public boolean isSetUnderlyingCashAmount() { return isSetField(973); } public void set(quickfix.field.UnderlyingCashType value) { setField(value); } public quickfix.field.UnderlyingCashType get(quickfix.field.UnderlyingCashType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCashType getUnderlyingCashType() throws FieldNotFound { quickfix.field.UnderlyingCashType value = new quickfix.field.UnderlyingCashType(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCashType field) { return isSetField(field); } public boolean isSetUnderlyingCashType() { return isSetField(974); } public void set(quickfix.field.UnderlyingUnitofMeasure value) { setField(value); } public quickfix.field.UnderlyingUnitofMeasure get(quickfix.field.UnderlyingUnitofMeasure value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingUnitofMeasure getUnderlyingUnitofMeasure() throws FieldNotFound { quickfix.field.UnderlyingUnitofMeasure value = new quickfix.field.UnderlyingUnitofMeasure(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingUnitofMeasure field) { return isSetField(field); } public boolean isSetUnderlyingUnitofMeasure() { return isSetField(998); } public void set(quickfix.field.UnderlyingTimeUnit value) { setField(value); } public quickfix.field.UnderlyingTimeUnit get(quickfix.field.UnderlyingTimeUnit value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingTimeUnit getUnderlyingTimeUnit() throws FieldNotFound { quickfix.field.UnderlyingTimeUnit value = new quickfix.field.UnderlyingTimeUnit(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingTimeUnit field) { return isSetField(field); } public boolean isSetUnderlyingTimeUnit() { return isSetField(1000); } public void set(quickfix.field.UnderlyingCapValue value) { setField(value); } public quickfix.field.UnderlyingCapValue get(quickfix.field.UnderlyingCapValue value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingCapValue getUnderlyingCapValue() throws FieldNotFound { quickfix.field.UnderlyingCapValue value = new quickfix.field.UnderlyingCapValue(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingCapValue field) { return isSetField(field); } public boolean isSetUnderlyingCapValue() { return isSetField(1038); } public void set(quickfix.fix50.component.UndlyInstrumentParties component) { setComponent(component); } public quickfix.fix50.component.UndlyInstrumentParties get(quickfix.fix50.component.UndlyInstrumentParties component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.UndlyInstrumentParties getUndlyInstrumentParties() throws FieldNotFound { quickfix.fix50.component.UndlyInstrumentParties component = new quickfix.fix50.component.UndlyInstrumentParties(); getComponent(component); return component; } public void set(quickfix.field.NoUndlyInstrumentParties value) { setField(value); } public quickfix.field.NoUndlyInstrumentParties get(quickfix.field.NoUndlyInstrumentParties value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoUndlyInstrumentParties getNoUndlyInstrumentParties() throws FieldNotFound { quickfix.field.NoUndlyInstrumentParties value = new quickfix.field.NoUndlyInstrumentParties(); getField(value); return value; } public boolean isSet(quickfix.field.NoUndlyInstrumentParties field) { return isSetField(field); } public boolean isSetNoUndlyInstrumentParties() { return isSetField(1058); } public static class NoUndlyInstrumentParties extends Group { static final long serialVersionUID = 20050617; public NoUndlyInstrumentParties() { super(1058, 1059, new int[] {1059, 1060, 1061, 1062, 0 } ); } public void set(quickfix.field.UndlyInstrumentPartyID value) { setField(value); } public quickfix.field.UndlyInstrumentPartyID get(quickfix.field.UndlyInstrumentPartyID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UndlyInstrumentPartyID getUndlyInstrumentPartyID() throws FieldNotFound { quickfix.field.UndlyInstrumentPartyID value = new quickfix.field.UndlyInstrumentPartyID(); getField(value); return value; } public boolean isSet(quickfix.field.UndlyInstrumentPartyID field) { return isSetField(field); } public boolean isSetUndlyInstrumentPartyID() { return isSetField(1059); } public void set(quickfix.field.UndlyInstrumentPartyIDSource value) { setField(value); } public quickfix.field.UndlyInstrumentPartyIDSource get(quickfix.field.UndlyInstrumentPartyIDSource value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UndlyInstrumentPartyIDSource getUndlyInstrumentPartyIDSource() throws FieldNotFound { quickfix.field.UndlyInstrumentPartyIDSource value = new quickfix.field.UndlyInstrumentPartyIDSource(); getField(value); return value; } public boolean isSet(quickfix.field.UndlyInstrumentPartyIDSource field) { return isSetField(field); } public boolean isSetUndlyInstrumentPartyIDSource() { return isSetField(1060); } public void set(quickfix.field.UndlyInstrumentPartyRole value) { setField(value); } public quickfix.field.UndlyInstrumentPartyRole get(quickfix.field.UndlyInstrumentPartyRole value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UndlyInstrumentPartyRole getUndlyInstrumentPartyRole() throws FieldNotFound { quickfix.field.UndlyInstrumentPartyRole value = new quickfix.field.UndlyInstrumentPartyRole(); getField(value); return value; } public boolean isSet(quickfix.field.UndlyInstrumentPartyRole field) { return isSetField(field); } public boolean isSetUndlyInstrumentPartyRole() { return isSetField(1061); } public void set(quickfix.fix50.component.UndlyInstrumentPtysSubGrp component) { setComponent(component); } public quickfix.fix50.component.UndlyInstrumentPtysSubGrp get(quickfix.fix50.component.UndlyInstrumentPtysSubGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.UndlyInstrumentPtysSubGrp getUndlyInstrumentPtysSubGrp() throws FieldNotFound { quickfix.fix50.component.UndlyInstrumentPtysSubGrp component = new quickfix.fix50.component.UndlyInstrumentPtysSubGrp(); getComponent(component); return component; } public void set(quickfix.field.NoUndlyInstrumentPartySubIDs value) { setField(value); } public quickfix.field.NoUndlyInstrumentPartySubIDs get(quickfix.field.NoUndlyInstrumentPartySubIDs value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoUndlyInstrumentPartySubIDs getNoUndlyInstrumentPartySubIDs() throws FieldNotFound { quickfix.field.NoUndlyInstrumentPartySubIDs value = new quickfix.field.NoUndlyInstrumentPartySubIDs(); getField(value); return value; } public boolean isSet(quickfix.field.NoUndlyInstrumentPartySubIDs field) { return isSetField(field); } public boolean isSetNoUndlyInstrumentPartySubIDs() { return isSetField(1062); } public static class NoUndlyInstrumentPartySubIDs extends Group { static final long serialVersionUID = 20050617; public NoUndlyInstrumentPartySubIDs() { super(1062, 1063, new int[] {1063, 1064, 0 } ); } public void set(quickfix.field.UndlyInstrumentPartySubID value) { setField(value); } public quickfix.field.UndlyInstrumentPartySubID get(quickfix.field.UndlyInstrumentPartySubID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UndlyInstrumentPartySubID getUndlyInstrumentPartySubID() throws FieldNotFound { quickfix.field.UndlyInstrumentPartySubID value = new quickfix.field.UndlyInstrumentPartySubID(); getField(value); return value; } public boolean isSet(quickfix.field.UndlyInstrumentPartySubID field) { return isSetField(field); } public boolean isSetUndlyInstrumentPartySubID() { return isSetField(1063); } public void set(quickfix.field.UndlyInstrumentPartySubIDType value) { setField(value); } public quickfix.field.UndlyInstrumentPartySubIDType get(quickfix.field.UndlyInstrumentPartySubIDType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UndlyInstrumentPartySubIDType getUndlyInstrumentPartySubIDType() throws FieldNotFound { quickfix.field.UndlyInstrumentPartySubIDType value = new quickfix.field.UndlyInstrumentPartySubIDType(); getField(value); return value; } public boolean isSet(quickfix.field.UndlyInstrumentPartySubIDType field) { return isSetField(field); } public boolean isSetUndlyInstrumentPartySubIDType() { return isSetField(1064); } } } public void set(quickfix.field.UnderlyingSettlMethod value) { setField(value); } public quickfix.field.UnderlyingSettlMethod get(quickfix.field.UnderlyingSettlMethod value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingSettlMethod getUnderlyingSettlMethod() throws FieldNotFound { quickfix.field.UnderlyingSettlMethod value = new quickfix.field.UnderlyingSettlMethod(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingSettlMethod field) { return isSetField(field); } public boolean isSetUnderlyingSettlMethod() { return isSetField(1039); } public void set(quickfix.field.UnderlyingAdjustedQuantity value) { setField(value); } public quickfix.field.UnderlyingAdjustedQuantity get(quickfix.field.UnderlyingAdjustedQuantity value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingAdjustedQuantity getUnderlyingAdjustedQuantity() throws FieldNotFound { quickfix.field.UnderlyingAdjustedQuantity value = new quickfix.field.UnderlyingAdjustedQuantity(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingAdjustedQuantity field) { return isSetField(field); } public boolean isSetUnderlyingAdjustedQuantity() { return isSetField(1044); } public void set(quickfix.field.UnderlyingFXRate value) { setField(value); } public quickfix.field.UnderlyingFXRate get(quickfix.field.UnderlyingFXRate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingFXRate getUnderlyingFXRate() throws FieldNotFound { quickfix.field.UnderlyingFXRate value = new quickfix.field.UnderlyingFXRate(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingFXRate field) { return isSetField(field); } public boolean isSetUnderlyingFXRate() { return isSetField(1045); } public void set(quickfix.field.UnderlyingFXRateCalc value) { setField(value); } public quickfix.field.UnderlyingFXRateCalc get(quickfix.field.UnderlyingFXRateCalc value) throws FieldNotFound { getField(value); return value; } public quickfix.field.UnderlyingFXRateCalc getUnderlyingFXRateCalc() throws FieldNotFound { quickfix.field.UnderlyingFXRateCalc value = new quickfix.field.UnderlyingFXRateCalc(); getField(value); return value; } public boolean isSet(quickfix.field.UnderlyingFXRateCalc field) { return isSetField(field); } public boolean isSetUnderlyingFXRateCalc() { return isSetField(1046); } } public void set(quickfix.field.ClearingBusinessDate value) { setField(value); } public quickfix.field.ClearingBusinessDate get(quickfix.field.ClearingBusinessDate value) throws FieldNotFound { getField(value); return value; } public quickfix.field.ClearingBusinessDate getClearingBusinessDate() throws FieldNotFound { quickfix.field.ClearingBusinessDate value = new quickfix.field.ClearingBusinessDate(); getField(value); return value; } public boolean isSet(quickfix.field.ClearingBusinessDate field) { return isSetField(field); } public boolean isSetClearingBusinessDate() { return isSetField(715); } public void set(quickfix.field.SettlSessID value) { setField(value); } public quickfix.field.SettlSessID get(quickfix.field.SettlSessID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SettlSessID getSettlSessID() throws FieldNotFound { quickfix.field.SettlSessID value = new quickfix.field.SettlSessID(); getField(value); return value; } public boolean isSet(quickfix.field.SettlSessID field) { return isSetField(field); } public boolean isSetSettlSessID() { return isSetField(716); } public void set(quickfix.field.SettlSessSubID value) { setField(value); } public quickfix.field.SettlSessSubID get(quickfix.field.SettlSessSubID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SettlSessSubID getSettlSessSubID() throws FieldNotFound { quickfix.field.SettlSessSubID value = new quickfix.field.SettlSessSubID(); getField(value); return value; } public boolean isSet(quickfix.field.SettlSessSubID field) { return isSetField(field); } public boolean isSetSettlSessSubID() { return isSetField(717); } public void set(quickfix.fix50.component.TrdgSesGrp component) { setComponent(component); } public quickfix.fix50.component.TrdgSesGrp get(quickfix.fix50.component.TrdgSesGrp component) throws FieldNotFound { getComponent(component); return component; } public quickfix.fix50.component.TrdgSesGrp getTrdgSesGrp() throws FieldNotFound { quickfix.fix50.component.TrdgSesGrp component = new quickfix.fix50.component.TrdgSesGrp(); getComponent(component); return component; } public void set(quickfix.field.NoTradingSessions value) { setField(value); } public quickfix.field.NoTradingSessions get(quickfix.field.NoTradingSessions value) throws FieldNotFound { getField(value); return value; } public quickfix.field.NoTradingSessions getNoTradingSessions() throws FieldNotFound { quickfix.field.NoTradingSessions value = new quickfix.field.NoTradingSessions(); getField(value); return value; } public boolean isSet(quickfix.field.NoTradingSessions field) { return isSetField(field); } public boolean isSetNoTradingSessions() { return isSetField(386); } public static class NoTradingSessions extends Group { static final long serialVersionUID = 20050617; public NoTradingSessions() { super(386, 336, new int[] {336, 625, 0 } ); } public void set(quickfix.field.TradingSessionID value) { setField(value); } public quickfix.field.TradingSessionID get(quickfix.field.TradingSessionID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.TradingSessionID getTradingSessionID() throws FieldNotFound { quickfix.field.TradingSessionID value = new quickfix.field.TradingSessionID(); getField(value); return value; } public boolean isSet(quickfix.field.TradingSessionID field) { return isSetField(field); } public boolean isSetTradingSessionID() { return isSetField(336); } public void set(quickfix.field.TradingSessionSubID value) { setField(value); } public quickfix.field.TradingSessionSubID get(quickfix.field.TradingSessionSubID value) throws FieldNotFound { getField(value); return value; } public quickfix.field.TradingSessionSubID getTradingSessionSubID() throws FieldNotFound { quickfix.field.TradingSessionSubID value = new quickfix.field.TradingSessionSubID(); getField(value); return value; } public boolean isSet(quickfix.field.TradingSessionSubID field) { return isSetField(field); } public boolean isSetTradingSessionSubID() { return isSetField(625); } } public void set(quickfix.field.TransactTime value) { setField(value); } public quickfix.field.TransactTime get(quickfix.field.TransactTime value) throws FieldNotFound { getField(value); return value; } public quickfix.field.TransactTime getTransactTime() throws FieldNotFound { quickfix.field.TransactTime value = new quickfix.field.TransactTime(); getField(value); return value; } public boolean isSet(quickfix.field.TransactTime field) { return isSetField(field); } public boolean isSetTransactTime() { return isSetField(60); } public void set(quickfix.field.ResponseTransportType value) { setField(value); } public quickfix.field.ResponseTransportType get(quickfix.field.ResponseTransportType value) throws FieldNotFound { getField(value); return value; } public quickfix.field.ResponseTransportType getResponseTransportType() throws FieldNotFound { quickfix.field.ResponseTransportType value = new quickfix.field.ResponseTransportType(); getField(value); return value; } public boolean isSet(quickfix.field.ResponseTransportType field) { return isSetField(field); } public boolean isSetResponseTransportType() { return isSetField(725); } public void set(quickfix.field.ResponseDestination value) { setField(value); } public quickfix.field.ResponseDestination get(quickfix.field.ResponseDestination value) throws FieldNotFound { getField(value); return value; } public quickfix.field.ResponseDestination getResponseDestination() throws FieldNotFound { quickfix.field.ResponseDestination value = new quickfix.field.ResponseDestination(); getField(value); return value; } public boolean isSet(quickfix.field.ResponseDestination field) { return isSetField(field); } public boolean isSetResponseDestination() { return isSetField(726); } public void set(quickfix.field.Text value) { setField(value); } public quickfix.field.Text get(quickfix.field.Text value) throws FieldNotFound { getField(value); return value; } public quickfix.field.Text getText() throws FieldNotFound { quickfix.field.Text value = new quickfix.field.Text(); getField(value); return value; } public boolean isSet(quickfix.field.Text field) { return isSetField(field); } public boolean isSetText() { return isSetField(58); } public void set(quickfix.field.EncodedTextLen value) { setField(value); } public quickfix.field.EncodedTextLen get(quickfix.field.EncodedTextLen value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedTextLen getEncodedTextLen() throws FieldNotFound { quickfix.field.EncodedTextLen value = new quickfix.field.EncodedTextLen(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedTextLen field) { return isSetField(field); } public boolean isSetEncodedTextLen() { return isSetField(354); } public void set(quickfix.field.EncodedText value) { setField(value); } public quickfix.field.EncodedText get(quickfix.field.EncodedText value) throws FieldNotFound { getField(value); return value; } public quickfix.field.EncodedText getEncodedText() throws FieldNotFound { quickfix.field.EncodedText value = new quickfix.field.EncodedText(); getField(value); return value; } public boolean isSet(quickfix.field.EncodedText field) { return isSetField(field); } public boolean isSetEncodedText() { return isSetField(355); } public void set(quickfix.field.SettlCurrency value) { setField(value); } public quickfix.field.SettlCurrency get(quickfix.field.SettlCurrency value) throws FieldNotFound { getField(value); return value; } public quickfix.field.SettlCurrency getSettlCurrency() throws FieldNotFound { quickfix.field.SettlCurrency value = new quickfix.field.SettlCurrency(); getField(value); return value; } public boolean isSet(quickfix.field.SettlCurrency field) { return isSetField(field); } public boolean isSetSettlCurrency() { return isSetField(120); } }
Forexware/quickfixj
src/main/java/quickfix/fix50/RequestForPositions.java
Java
apache-2.0
147,576
/* * Copyright (C) 2013 The Android Open Source 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 com.android.inputmethod.keyboard.internal; import android.util.Log; import android.view.MotionEvent; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.KeyDetector; import com.android.inputmethod.keyboard.PointerTracker; import com.android.inputmethod.latin.utils.CoordinateUtils; public final class NonDistinctMultitouchHelper { private static final String TAG = NonDistinctMultitouchHelper.class.getSimpleName(); private static final int MAIN_POINTER_TRACKER_ID = 0; private int mOldPointerCount = 1; private Key mOldKey; private int[] mLastCoords = CoordinateUtils.newInstance(); public void processMotionEvent(final MotionEvent me, final KeyDetector keyDetector) { final int pointerCount = me.getPointerCount(); final int oldPointerCount = mOldPointerCount; mOldPointerCount = pointerCount; // Ignore continuous multi-touch events because we can't trust the coordinates // in multi-touch events. if (pointerCount > 1 && oldPointerCount > 1) { return; } // Use only main pointer tracker. final PointerTracker mainTracker = PointerTracker.getPointerTracker( MAIN_POINTER_TRACKER_ID); final int action = me.getActionMasked(); final int index = me.getActionIndex(); final long eventTime = me.getEventTime(); final long downTime = me.getDownTime(); // In single-touch. if (oldPointerCount == 1 && pointerCount == 1) { if (me.getPointerId(index) == mainTracker.mPointerId) { mainTracker.processMotionEvent(me, keyDetector); return; } // Inject a copied event. injectMotionEvent(action, me.getX(index), me.getY(index), downTime, eventTime, mainTracker, keyDetector); return; } // Single-touch to multi-touch transition. if (oldPointerCount == 1 && pointerCount == 2) { // Send an up event for the last pointer, be cause we can't trust the coordinates of // this multi-touch event. mainTracker.getLastCoordinates(mLastCoords); final int x = CoordinateUtils.x(mLastCoords); final int y = CoordinateUtils.y(mLastCoords); mOldKey = mainTracker.getKeyOn(x, y); // Inject an artifact up event for the old key. injectMotionEvent(MotionEvent.ACTION_UP, x, y, downTime, eventTime, mainTracker, keyDetector); return; } // Multi-touch to single-touch transition. if (oldPointerCount == 2 && pointerCount == 1) { // Send a down event for the latest pointer if the key is different from the previous // key. final int x = (int)me.getX(index); final int y = (int)me.getY(index); final Key newKey = mainTracker.getKeyOn(x, y); if (mOldKey != newKey) { // Inject an artifact down event for the new key. // An artifact up event for the new key will usually be injected as a single-touch. injectMotionEvent(MotionEvent.ACTION_DOWN, x, y, downTime, eventTime, mainTracker, keyDetector); if (action == MotionEvent.ACTION_UP) { // Inject an artifact up event for the new key also. injectMotionEvent(MotionEvent.ACTION_UP, x, y, downTime, eventTime, mainTracker, keyDetector); } } return; } Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount + " (previously " + oldPointerCount + ")"); } private static void injectMotionEvent(final int action, final float x, final float y, final long downTime, final long eventTime, final PointerTracker tracker, final KeyDetector keyDetector) { final MotionEvent me = MotionEvent.obtain( downTime, eventTime, action, x, y, 0 /* metaState */); try { tracker.processMotionEvent(me, keyDetector); } finally { me.recycle(); } } }
vorgoron/LatinIME-extended-with-Russian-languages
app/src/main/java/com/android/inputmethod/keyboard/internal/NonDistinctMultitouchHelper.java
Java
apache-2.0
4,904
/* * 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.geode.test.junit.rules; import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT; import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT; import static org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPorts; import static org.apache.geode.test.junit.rules.MemberStarterRule.getSSLProperties; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Properties; import java.util.function.UnaryOperator; import org.junit.rules.TemporaryFolder; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.distributed.LocatorLauncher; import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource; import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder; public class LocatorLauncherStartupRule extends SerializableExternalResource { private LocatorLauncher launcher; private final TemporaryFolder temp = new SerializableTemporaryFolder(); private final Properties properties = defaultProperties(); private boolean autoStart; private UnaryOperator<LocatorLauncher.Builder> builderOperator; public LocatorLauncherStartupRule withAutoStart() { autoStart = true; return this; } public LocatorLauncherStartupRule withProperties(Properties properties) { this.properties.putAll(properties); return this; } public LocatorLauncherStartupRule withProperty(String key, String value) { properties.put(key, value); return this; } public LocatorLauncherStartupRule withSSL(String components, boolean requireAuth, boolean endPointIdentification) { Properties sslProps = getSSLProperties(components, requireAuth, endPointIdentification); properties.putAll(sslProps); return this; } public LocatorLauncherStartupRule withBuilder( UnaryOperator<LocatorLauncher.Builder> builderOperator) { this.builderOperator = builderOperator; return this; } @Override public void before() { if (autoStart) { start(); } } public void start() { LocatorLauncher.Builder builder = new LocatorLauncher.Builder() .setPort(0) .set(properties) .set(ConfigurationProperties.LOG_LEVEL, "config"); if (builderOperator != null) { builder = builderOperator.apply(builder); } if (builder.getMemberName() == null) { builder.setMemberName("locator-0"); } try { temp.create(); } catch (IOException e) { throw new UncheckedIOException(e); } builder.setWorkingDirectory(temp.getRoot().getAbsolutePath()); launcher = builder.build(); launcher.start(); } public LocatorLauncher getLauncher() { return launcher; } public File getWorkingDir() { return temp.getRoot(); } @Override public void after() { if (launcher != null) { launcher.stop(); } temp.delete(); } /** * By default, assign available HTTP and JMX ports. */ private static Properties defaultProperties() { Properties props = new Properties(); int[] ports = getRandomAvailableTCPPorts(2); props.setProperty(HTTP_SERVICE_PORT, String.valueOf(ports[0])); props.setProperty(JMX_MANAGER_PORT, String.valueOf(ports[1])); return props; } }
jdeppe-pivotal/geode
geode-dunit/src/main/java/org/apache/geode/test/junit/rules/LocatorLauncherStartupRule.java
Java
apache-2.0
4,130
package org.iidp.ostmap.rest_service; import org.apache.accumulo.core.client.*; import org.apache.accumulo.core.data.Range; import org.iidp.ostmap.commons.accumulo.AccumuloService; import org.iidp.ostmap.rest_service.helper.JsonHelper; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Value; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Controller @RequestMapping("/api") public class TokenSearchController { static Logger log = LoggerFactory.getLogger(TokenSearchController.class); /** * Mapping method for path /tokensearch * @param paramCommaSeparatedFieldList * @param paramToken * @return the result as json */ @RequestMapping( value = "/tokensearch", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseBody String getTweetsByFieldsAndToken( @RequestParam(name = "field") String paramCommaSeparatedFieldList, @RequestParam(name = "token") String paramToken ) { try { paramCommaSeparatedFieldList = URLDecoder.decode(paramCommaSeparatedFieldList, "UTF-8"); paramToken = URLDecoder.decode(paramToken, "UTF-8").toLowerCase(); log.info("Get Request received - FieldList: " + paramCommaSeparatedFieldList + " Token: " + paramToken); System.out.println("Get Request received - FieldList: " + paramCommaSeparatedFieldList + " Token: " + paramToken); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Cannot decode query parameters."); } validateQueryParams(paramCommaSeparatedFieldList,paramToken); return getResultsFromAccumulo(paramCommaSeparatedFieldList,paramToken,MainController.configFilePath); } /** * Validates the Query parameters. Returns true, if both parameters are valid, false if not. */ void validateQueryParams(String fields, String token) throws IllegalArgumentException { boolean consistent = true; if(fields == null || Objects.equals(fields, "") || fields.length() < 2){ throw new IllegalArgumentException("Value of query parameter 'field' is invalid."); } String[] fieldArray = fields.split(","); if(fieldArray.length > 1){ for(String singleField : fieldArray) { if(singleField == null || Objects.equals(singleField, "") || singleField.length() < 2){ throw new IllegalArgumentException("One comma separated values of the query parameter 'field' is invalid."); } } } if(token == null || Objects.equals(token, "") || token.length() < 2){ throw new IllegalArgumentException("Value of query parameter 'token' is invalid."); } } public String getResultsFromAccumulo(String fields, String token, String configFilePath){ AccumuloService accumuloService = new AccumuloService(); String result = null; List<Range> rawKeys = null; String[] fieldArray = fields.split(","); try { accumuloService.readConfig(configFilePath); result = "["; rawKeys = new ArrayList<>(); for(String field:fieldArray){ // get all results from tokenIndex to the list Scanner termIndexScanner = accumuloService.getTermIndexScanner(token,field); for (Map.Entry<Key, Value> termIndexEntry : termIndexScanner) { rawKeys.add(new Range(termIndexEntry.getKey().getColumnQualifier())); } termIndexScanner.close(); } boolean isFirst = true; if(rawKeys.size() > 0){ BatchScanner bs = accumuloService.getRawDataBatchScanner(rawKeys); for (Map.Entry<Key, Value> rawDataEntry : bs) { if(!isFirst){ result += ","; }else{ isFirst=false; } String json = rawDataEntry.getValue().toString(); json = JsonHelper.generateCoordinates(json); result += json; } bs.close(); } result += "]"; } catch (IOException | AccumuloSecurityException | TableNotFoundException | AccumuloException e){ throw new RuntimeException("There was a failure during Accumulo communication.",e); } return result; } }
IIDP2016/OSTMap
rest_service/src/main/java/org/iidp/ostmap/rest_service/TokenSearchController.java
Java
apache-2.0
4,962
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.intellij.ide.util; import com.intellij.icons.AllIcons; import com.intellij.ide.actions.GotoClassPresentationUpdater; import com.intellij.ide.util.gotoByName.*; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.ToggleAction; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.roots.FileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.refactoring.RefactoringBundle; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.SideBorder; import com.intellij.ui.TabbedPaneWrapper; import com.intellij.util.ArrayUtil; import com.intellij.util.PlatformIcons; import com.intellij.util.Processor; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; public class DirectoryChooser extends DialogWrapper { @NonNls private static final String FILTER_NON_EXISTING = "filter_non_existing"; private static final String DEFAULT_SELECTION = "last_directory_selection"; private final DirectoryChooserView myView; private boolean myFilterExisting; private PsiDirectory myDefaultSelection; private final List<ItemWrapper> myItems = new ArrayList<>(); private PsiElement mySelection; private final TabbedPaneWrapper myTabbedPaneWrapper; private final ChooseByNamePanel myChooseByNamePanel; private final String myChooseByNameTabTitle; public DirectoryChooser(@NotNull Project project){ this(project, new DirectoryChooserModuleTreeView(project)); } public DirectoryChooser(@NotNull Project project, @NotNull DirectoryChooserView view){ super(project, true); myView = view; final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); myFilterExisting = propertiesComponent.isTrueValue(FILTER_NON_EXISTING); myTabbedPaneWrapper = new TabbedPaneWrapper(getDisposable()); String gotoClassText = GotoClassPresentationUpdater.getTabTitle(false); boolean useClass = gotoClassText.startsWith("Class"); myChooseByNameTabTitle = useClass ? gotoClassText : "File"; ChooseByNameModel model = useClass ? new GotoClassModel2(project) { @Override public void processNames(Processor<? super String> nameProcessor, boolean checkBoxState) { super.processNames(nameProcessor, false); } } : new GotoFileModel(project) { @Override public void processNames(Processor<? super String> nameProcessor, boolean checkBoxState) { super.processNames(nameProcessor, false); } }; myChooseByNamePanel = new ChooseByNamePanel(project, model, "", false, null) { @Override protected void showTextFieldPanel() { } @Override protected void close(boolean isOk) { super.close(isOk); if (isOk) { final List<Object> elements = getChosenElements(); if (elements.size() > 0) { myActionListener.elementChosen(elements.get(0)); } doOKAction(); } else { doCancelAction(); } } }; Disposer.register(myDisposable, myChooseByNamePanel); init(); } @Override protected void doOKAction() { PropertiesComponent.getInstance().setValue(FILTER_NON_EXISTING, myFilterExisting); if (myTabbedPaneWrapper.getSelectedIndex() == 1) { setSelection(myChooseByNamePanel.getChosenElement()); } final ItemWrapper item = myView.getSelectedItem(); if (item != null) { final PsiDirectory directory = item.getDirectory(); if (directory != null) { PropertiesComponent.getInstance(directory.getProject()).setValue(DEFAULT_SELECTION, directory.getVirtualFile().getPath()); } } super.doOKAction(); } @Override protected JComponent createCenterPanel(){ final JPanel panel = new JPanel(new BorderLayout()); final DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.add(new FilterExistentAction()); final JComponent toolbarComponent = ActionManager.getInstance().createActionToolbar("DirectoryChooser", actionGroup, true).getComponent(); toolbarComponent.setBorder(null); panel.add(toolbarComponent, BorderLayout.NORTH); final Runnable runnable = () -> enableButtons(); myView.onSelectionChange(runnable); final JComponent component = myView.getComponent(); final JScrollPane jScrollPane = ScrollPaneFactory.createScrollPane(component); //noinspection HardCodedStringLiteral int prototypeWidth = component.getFontMetrics(component.getFont()).stringWidth("X:\\1234567890\\1234567890\\com\\company\\system\\subsystem"); jScrollPane.setPreferredSize(new Dimension(Math.max(300, prototypeWidth),300)); jScrollPane.putClientProperty(UIUtil.KEEP_BORDER_SIDES, SideBorder.ALL); installEnterAction(component); panel.add(jScrollPane, BorderLayout.CENTER); myTabbedPaneWrapper.addTab("Directory Structure", panel); myChooseByNamePanel.invoke(new ChooseByNamePopupComponent.Callback() { @Override public void elementChosen(Object element) { setSelection(element); } }, ModalityState.stateForComponent(getRootPane()), false); myTabbedPaneWrapper.addTab("Choose by Neighbor " + myChooseByNameTabTitle, myChooseByNamePanel.getPanel()); return myTabbedPaneWrapper.getComponent(); } private void setSelection(Object element) { if (element instanceof PsiElement) { mySelection = (PsiElement)element; } } private void installEnterAction(final JComponent component) { final KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0); final InputMap inputMap = component.getInputMap(); final ActionMap actionMap = component.getActionMap(); final Object oldActionKey = inputMap.get(enterKeyStroke); final Action oldAction = oldActionKey != null ? actionMap.get(oldActionKey) : null; inputMap.put(enterKeyStroke, "clickButton"); actionMap.put("clickButton", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (isOKActionEnabled()) { doOKAction(); } else if (oldAction != null) { oldAction.actionPerformed(e); } } }); } @Override protected String getDimensionServiceKey() { return "chooseDestDirectoryDialog"; } private void buildFragments() { ArrayList<String[]> paths = new ArrayList<>(); for (int i = 0; i < myView.getItemsSize(); i++) { ItemWrapper item = myView.getItemByIndex(i); paths.add(ArrayUtil.toStringArray(FileUtil.splitPath(item.getPresentableUrl()))); } FragmentBuilder headBuilder = new FragmentBuilder(paths){ @Override protected void append(String fragment, StringBuffer buffer) { buffer.append(mySeparator); buffer.append(fragment); } @Override protected int getFragmentIndex(String[] path, int index) { return path.length > index ? index : -1; } }; String commonHead = headBuilder.execute(); final int headLimit = headBuilder.getIndex(); FragmentBuilder tailBuilder = new FragmentBuilder(paths) { @Override protected void append(String fragment, StringBuffer buffer) { buffer.insert(0, fragment + mySeparator); } @Override protected int getFragmentIndex(String[] path, int index) { int result = path.length - 1 - index; return result > headLimit ? result : -1; } }; String commonTail = tailBuilder.execute(); int tailLimit = tailBuilder.getIndex(); for (int i = 0; i < myView.getItemsSize(); i++) { ItemWrapper item = myView.getItemByIndex(i); String special = concat(paths.get(i), headLimit, tailLimit); item.setFragments(createFragments(commonHead, special, commonTail)); } } @Nullable private static String concat(String[] strings, int headLimit, int tailLimit) { if (strings.length <= headLimit + tailLimit) return null; StringBuilder buffer = new StringBuilder(); String separator = ""; for (int i = headLimit; i < strings.length - tailLimit; i++) { buffer.append(separator); buffer.append(strings[i]); separator = File.separator; } return buffer.toString(); } private static PathFragment[] createFragments(String head, String special, String tail) { ArrayList<PathFragment> list = new ArrayList<>(3); if (head != null) { if (special != null || tail != null) list.add(new PathFragment(head + File.separatorChar, true)); else return new PathFragment[]{new PathFragment(head, true)}; } if (special != null) { if (tail != null) list.add(new PathFragment(special + File.separatorChar, false)); else list.add(new PathFragment(special, false)); } if (tail != null) list.add(new PathFragment(tail, true)); return list.toArray(new PathFragment[0]); } private static abstract class FragmentBuilder { private final ArrayList<String[]> myPaths; private final StringBuffer myBuffer = new StringBuffer(); private int myIndex; protected String mySeparator = ""; FragmentBuilder(ArrayList<String[]> pathes) { myPaths = pathes; myIndex = 0; } public int getIndex() { return myIndex; } @Nullable public String execute() { while (true) { String commonHead = getCommonFragment(myIndex); if (commonHead == null) break; append(commonHead, myBuffer); mySeparator = File.separator; myIndex++; } return myIndex > 0 ? myBuffer.toString() : null; } protected abstract void append(String fragment, StringBuffer buffer); @Nullable private String getCommonFragment(int count) { String commonFragment = null; for (String[] path : myPaths) { int index = getFragmentIndex(path, count); if (index == -1) return null; if (commonFragment == null) { commonFragment = path[index]; continue; } if (!Comparing.strEqual(commonFragment, path[index], SystemInfo.isFileSystemCaseSensitive)) return null; } return commonFragment; } protected abstract int getFragmentIndex(String[] path, int index); } public static class ItemWrapper { final PsiDirectory myDirectory; private PathFragment[] myFragments; private final String myPostfix; private String myRelativeToProjectPath = null; public ItemWrapper(PsiDirectory directory, String postfix) { myDirectory = directory; myPostfix = postfix != null && postfix.length() > 0 ? postfix : null; } public PathFragment[] getFragments() { return myFragments; } public void setFragments(PathFragment[] fragments) { myFragments = fragments; } public Icon getIcon(FileIndex fileIndex) { if (myDirectory != null) { VirtualFile virtualFile = myDirectory.getVirtualFile(); if (fileIndex.isInTestSourceContent(virtualFile)){ return PlatformIcons.MODULES_TEST_SOURCE_FOLDER; } else if (fileIndex.isInSourceContent(virtualFile)){ return PlatformIcons.MODULES_SOURCE_FOLDERS_ICON; } } return PlatformIcons.FOLDER_ICON; } public String getPresentableUrl() { String directoryUrl; if (myDirectory != null) { directoryUrl = myDirectory.getVirtualFile().getPresentableUrl(); final VirtualFile baseDir = myDirectory.getProject().getBaseDir(); if (baseDir != null) { final String projectHomeUrl = baseDir.getPresentableUrl(); if (directoryUrl.startsWith(projectHomeUrl)) { directoryUrl = "..." + directoryUrl.substring(projectHomeUrl.length()); } } } else { directoryUrl = ""; } return myPostfix != null ? directoryUrl + myPostfix : directoryUrl; } public PsiDirectory getDirectory() { return myDirectory; } public String getRelativeToProjectPath() { if (myRelativeToProjectPath == null) { final PsiDirectory directory = getDirectory(); final VirtualFile virtualFile = directory != null ? directory.getVirtualFile() : null; myRelativeToProjectPath = virtualFile != null ? ProjectUtil.calcRelativeToProjectPath(virtualFile, directory.getProject(), true, false, true) : getPresentableUrl(); } return myRelativeToProjectPath; } } @Override public JComponent getPreferredFocusedComponent(){ return myView.getComponent(); } public void fillList(PsiDirectory[] directories, @Nullable PsiDirectory defaultSelection, Project project, String postfixToShow) { fillList(directories, defaultSelection, project, postfixToShow, null); } public void fillList(PsiDirectory[] directories, @Nullable PsiDirectory defaultSelection, Project project, Map<PsiDirectory,String> postfixes) { fillList(directories, defaultSelection, project, null, postfixes); } private void fillList(PsiDirectory[] directories, @Nullable PsiDirectory defaultSelection, Project project, String postfixToShow, Map<PsiDirectory,String> postfixes) { if (myView.getItemsSize() > 0){ myView.clearItems(); } if (defaultSelection == null) { defaultSelection = getDefaultSelection(directories, project); if (defaultSelection == null && directories.length > 0) { defaultSelection = directories[0]; } } int selectionIndex = -1; for(int i = 0; i < directories.length; i++){ PsiDirectory directory = directories[i]; if (directory.equals(defaultSelection)) { selectionIndex = i; break; } } if (selectionIndex < 0 && directories.length == 1) { selectionIndex = 0; } if (selectionIndex < 0) { // find source root corresponding to defaultSelection final PsiManager manager = PsiManager.getInstance(project); VirtualFile[] sourceRoots = ProjectRootManager.getInstance(project).getContentSourceRoots(); for (VirtualFile sourceRoot : sourceRoots) { if (sourceRoot.isDirectory()) { PsiDirectory directory = manager.findDirectory(sourceRoot); if (directory != null && isParent(defaultSelection, directory)) { defaultSelection = directory; break; } } } } int existingIdx = 0; for(int i = 0; i < directories.length; i++){ PsiDirectory directory = directories[i]; final String postfixForDirectory; if (postfixes == null) { postfixForDirectory = postfixToShow; } else { postfixForDirectory = postfixes.get(directory); } final ItemWrapper itemWrapper = new ItemWrapper(directory, postfixForDirectory); myItems.add(itemWrapper); if (myFilterExisting) { if (selectionIndex == i) selectionIndex = -1; if (postfixForDirectory != null && directory.getVirtualFile().findFileByRelativePath(StringUtil.trimStart(postfixForDirectory, File.separator)) == null) { if (isParent(directory, defaultSelection)) { myDefaultSelection = directory; } continue; } } myView.addItem(itemWrapper); if (selectionIndex < 0 && isParent(directory, defaultSelection)) { selectionIndex = existingIdx; } existingIdx++; } buildFragments(); myView.listFilled(); if (myView.getItemsSize() > 0) { if (selectionIndex != -1) { myView.selectItemByIndex(selectionIndex); } else { myView.selectItemByIndex(0); } } else { myView.clearSelection(); } enableButtons(); myView.getComponent().repaint(); } @Nullable private static PsiDirectory getDefaultSelection(PsiDirectory[] directories, Project project) { final String defaultSelectionPath = PropertiesComponent.getInstance(project).getValue(DEFAULT_SELECTION); if (defaultSelectionPath != null) { final VirtualFile directoryByDefault = LocalFileSystem.getInstance().findFileByPath(defaultSelectionPath); if (directoryByDefault != null) { final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(directoryByDefault); return directory != null && ArrayUtil.find(directories, directory) > -1 ? directory : null; } } return null; } private static boolean isParent(PsiDirectory directory, PsiDirectory parentCandidate) { while (directory != null) { if (directory.equals(parentCandidate)) return true; directory = directory.getParentDirectory(); } return false; } private void enableButtons() { setOKActionEnabled(myView.getSelectedItem() != null); } @Nullable public PsiDirectory getSelectedDirectory() { if (mySelection != null) { final PsiFile file = mySelection.getContainingFile(); if (file != null){ return file.getContainingDirectory(); } } ItemWrapper wrapper = myView.getSelectedItem(); if (wrapper == null) return null; return wrapper.myDirectory; } public static class PathFragment { private final String myText; private final boolean myCommon; public PathFragment(String text, boolean isCommon) { myText = text; myCommon = isCommon; } public String getText() { return myText; } public boolean isCommon() { return myCommon; } } private class FilterExistentAction extends ToggleAction { FilterExistentAction() { super(RefactoringBundle.message("directory.chooser.hide.non.existent.checkBox.text"), UIUtil.removeMnemonic(RefactoringBundle.message("directory.chooser.hide.non.existent.checkBox.text")), AllIcons.General.Filter); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myFilterExisting; } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myFilterExisting = state; final ItemWrapper selectedItem = myView.getSelectedItem(); PsiDirectory directory = selectedItem != null ? selectedItem.getDirectory() : null; if (directory == null && myDefaultSelection != null) { directory = myDefaultSelection; } myView.clearItems(); int idx = 0; int selectionId = -1; for (ItemWrapper item : myItems) { if (myFilterExisting) { if (item.myPostfix != null && item.getDirectory().getVirtualFile().findFileByRelativePath(StringUtil.trimStart(item.myPostfix, File.separator)) == null) { continue; } } if (item.getDirectory() == directory) { selectionId = idx; } idx++; myView.addItem(item); } buildFragments(); myView.listFilled(); if (selectionId < 0) { myView.clearSelection(); if (myView.getItemsSize() > 0) { myView.selectItemByIndex(0); } } else { myView.selectItemByIndex(selectionId); } enableButtons(); myView.getComponent().repaint(); } } }
msebire/intellij-community
platform/lang-impl/src/com/intellij/ide/util/DirectoryChooser.java
Java
apache-2.0
20,814
/** * Get more info at : www.jrebirth.org . * Copyright JRebirth.org © 2011-2015 * Contact : [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.jrebirth.af.core.wave.checker; import org.jrebirth.af.api.wave.Wave; import org.jrebirth.af.api.wave.contract.WaveData; import org.jrebirth.af.core.wave.WaveItemBase; /** * The class <strong>ClassWaveChecker</strong> will check if the provided type is assignable from the wave data defined. * * @param <I> the generic type of the object stored into the WaveData * * @author Sébastien Bordes */ public class ClassWaveChecker<I extends Object> extends AbstractWaveChecker<I, Class<I>> { /** * Default Constructor to call the super one. * * @param waveItem the wave item * @param matchingValue the matching value */ public ClassWaveChecker(final WaveItemBase<I> waveItem, final Class<I> matchingValue) { super(waveItem, matchingValue); } /** * {@inheritDoc} */ @Override public Boolean call(final Wave wave) { final WaveData<I> waveData = wave.getData(getWaveItem()); final I currentValue = waveData == null ? null : waveData.value(); return getMatchingValue() != null && getMatchingValue().isAssignableFrom(currentValue.getClass()); } }
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/wave/checker/ClassWaveChecker.java
Java
apache-2.0
1,902
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.activiti.cdi.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.enterprise.util.Nonbinding; import javax.interceptor.InterceptorBinding; import org.activiti.cdi.BusinessProcess; /** * Annotation signaling that a task is to be completed after the annotated * method returns. Requires that the current unit of work (conversation * or request) is associated with a task. This has the same effect as * calling {@link BusinessProcess#completeTask()}. * * <p /> * Example: after this method returns, the current task is completed * <pre> * {@code @CompleteTask} * public void respond(String response, Message message) { * message.setResponse(response); * } * </pre> * If the annotated method throws an exception, the task is not completed. * * @see BusinessProcess#startTask(String) * @see BusinessProcess#completeTask() * * @author Daniel Meyer */ @InterceptorBinding @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.TYPE }) public @interface CompleteTask { /** * Specifies whether the current conversation should be ended. */ @Nonbinding boolean endConversation() default false; }
adbrucker/SecureBPMN
runtime/src/modules/activiti-cdi/src/main/java/org/activiti/cdi/annotation/CompleteTask.java
Java
apache-2.0
1,861
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with [email protected] * </p> */ package com.telefonica.euro_iaas.sdc.util; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import com.telefonica.euro_iaas.sdc.model.Task; /** * TaskNotificator rest implementation. * * @author Sergio Arroyo */ public class TaskNotificatorImpl implements TaskNotificator { private Client client; /** * {@inheritDoc} */ @Override public void notify(String url, Task task) { WebTarget webResource = client.target(url); webResource.request(MediaType.APPLICATION_XML).post(Entity.xml(task)); } /** * @param client * the client to set */ public void setClient(Client client) { this.client = client; } }
telefonicaid/fiware-sdc
core/src/main/java/com/telefonica/euro_iaas/sdc/util/TaskNotificatorImpl.java
Java
apache-2.0
1,643