repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
istio/istio.io | archive/v1.9/zh/docs/setup/kubernetes/prepare/platform-setup/azure/index.html | 418 | <!doctype html><html lang=en><head><title>Redirecting…</title><link rel=canonical href=/v1.9/zh/docs/setup/platform-setup/azure/><meta name=robots content="noindex"><meta charset=utf-8><meta http-equiv=refresh content="0; url=/v1.9/zh/docs/setup/platform-setup/azure/"></head><body><h1>Redirecting…</h1><a href=/v1.9/zh/docs/setup/platform-setup/azure/>Click here if you are not redirected.</a></body></html> | apache-2.0 |
redox/OrientDB | core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorOr.java | 2880 | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.sql.operator;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
/**
* OR operator.
*
* @author Luca Garulli
*
*/
public class OQueryOperatorOr extends OQueryOperator {
public OQueryOperatorOr() {
super("OR", 3, false);
}
@Override
public Object evaluateRecord(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
if (iLeft == null)
return false;
return (Boolean) iLeft || (Boolean) iRight;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
if (iLeft == null || iRight == null)
return OIndexReuseType.NO_INDEX;
return OIndexReuseType.INDEX_UNION;
}
@Override
public ORID getBeginRidRange(final Object iLeft,final Object iRight) {
final ORID leftRange;
final ORID rightRange;
if(iLeft instanceof OSQLFilterCondition)
leftRange = ((OSQLFilterCondition) iLeft).getBeginRidRange();
else
leftRange = null;
if(iRight instanceof OSQLFilterCondition)
rightRange = ((OSQLFilterCondition) iRight).getBeginRidRange();
else
rightRange = null;
if(leftRange == null || rightRange == null)
return null;
else
return leftRange.compareTo(rightRange) <= 0 ? leftRange : rightRange;
}
@Override
public ORID getEndRidRange(final Object iLeft,final Object iRight) {
final ORID leftRange;
final ORID rightRange;
if(iLeft instanceof OSQLFilterCondition)
leftRange = ((OSQLFilterCondition) iLeft).getEndRidRange();
else
leftRange = null;
if(iRight instanceof OSQLFilterCondition)
rightRange = ((OSQLFilterCondition) iRight).getEndRidRange();
else
rightRange = null;
if(leftRange == null || rightRange == null)
return null;
else
return leftRange.compareTo(rightRange) >= 0 ? leftRange : rightRange;
}
}
| apache-2.0 |
paulgallagher75/activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlUsingCoreTest.java | 32136 | /*
* 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.management;
import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl;
import org.apache.activemq.artemis.api.core.management.Parameter;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import java.util.Map;
public class ActiveMQServerControlUsingCoreTest extends ActiveMQServerControlTest {
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
private static String[] toStringArray(final Object[] res) {
String[] names = new String[res.length];
for (int i = 0; i < res.length; i++) {
names[i] = res[i].toString();
}
return names;
}
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
// ActiveMQServerControlTest overrides --------------------------
// the core messaging proxy doesn't work when the server is stopped so we cant run these 2 tests
@Override
public void testScaleDownWithOutConnector() throws Exception {
}
@Override
public void testScaleDownWithConnector() throws Exception {
}
@Override
protected ActiveMQServerControl createManagementControl() throws Exception {
return new ActiveMQServerControl() {
@Override
public void updateDuplicateIdCache(String address, Object[] ids) {
}
@Override
public void scaleDown(String connector) throws Exception {
throw new UnsupportedOperationException();
}
private final CoreMessagingProxy proxy = new CoreMessagingProxy(addServerLocator(createInVMNonHALocator()), ResourceNames.CORE_SERVER);
@Override
public boolean isSharedStore() {
return (Boolean) proxy.retrieveAttributeValue("sharedStore");
}
@Override
public boolean closeConnectionsForAddress(final String ipAddress) throws Exception {
return (Boolean) proxy.invokeOperation("closeConnectionsForAddress", ipAddress);
}
@Override
public boolean closeConsumerConnectionsForAddress(final String address) throws Exception {
return (Boolean) proxy.invokeOperation("closeConsumerConnectionsForAddress", address);
}
@Override
public boolean closeConnectionsForUser(final String userName) throws Exception {
return (Boolean) proxy.invokeOperation("closeConnectionsForUser", userName);
}
@Override
public boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception {
return (Boolean) proxy.invokeOperation("commitPreparedTransaction", transactionAsBase64);
}
@Override
public void createQueue(final String address, final String name) throws Exception {
proxy.invokeOperation("createQueue", address, name);
}
@Override
public void createQueue(final String address,
final String name,
final String filter,
final boolean durable) throws Exception {
proxy.invokeOperation("createQueue", address, name, filter, durable);
}
@Override
public void createQueue(final String address, final String name, final boolean durable) throws Exception {
proxy.invokeOperation("createQueue", address, name, durable);
}
@Override
public void deployQueue(final String address,
final String name,
final String filter,
final boolean durable) throws Exception {
proxy.invokeOperation("deployQueue", address, name, filter, durable);
}
@Override
public void deployQueue(final String address, final String name, final String filterString) throws Exception {
proxy.invokeOperation("deployQueue", address, name);
}
@Override
public void destroyQueue(final String name) throws Exception {
proxy.invokeOperation("destroyQueue", name);
}
@Override
public void destroyQueue(final String name, final boolean removeConsumers) throws Exception {
proxy.invokeOperation("destroyQueue", name, removeConsumers);
}
@Override
public void disableMessageCounters() throws Exception {
proxy.invokeOperation("disableMessageCounters");
}
@Override
public void enableMessageCounters() throws Exception {
proxy.invokeOperation("enableMessageCounters");
}
@Override
public String getBindingsDirectory() {
return (String) proxy.retrieveAttributeValue("bindingsDirectory");
}
@Override
public int getConnectionCount() {
return (Integer) proxy.retrieveAttributeValue("connectionCount", Integer.class);
}
@Override
public long getTotalConnectionCount() {
return (Long) proxy.retrieveAttributeValue("totalConnectionCount", Long.class);
}
@Override
public long getTotalMessageCount() {
return (Long) proxy.retrieveAttributeValue("totalMessageCount", Long.class);
}
@Override
public long getTotalMessagesAdded() {
return (Long) proxy.retrieveAttributeValue("totalMessagesAdded", Long.class);
}
@Override
public long getTotalMessagesAcknowledged() {
return (Long) proxy.retrieveAttributeValue("totalMessagesAcknowledged", Long.class);
}
@Override
public long getTotalConsumerCount() {
return (Long) proxy.retrieveAttributeValue("totalConsumerCount", Long.class);
}
@Override
public long getConnectionTTLOverride() {
return (Long) proxy.retrieveAttributeValue("connectionTTLOverride", Long.class);
}
@Override
public Object[] getConnectors() throws Exception {
return (Object[]) proxy.retrieveAttributeValue("connectors");
}
@Override
public String getConnectorsAsJSON() throws Exception {
return (String) proxy.retrieveAttributeValue("connectorsAsJSON");
}
@Override
public String[] getAddressNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("addressNames"));
}
@Override
public String[] getQueueNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("queueNames", String.class));
}
@Override
public String getUptime() {
return null;
}
@Override
public long getUptimeMillis() {
return 0;
}
@Override
public boolean isReplicaSync() {
return false;
}
@Override
public int getIDCacheSize() {
return (Integer) proxy.retrieveAttributeValue("IDCacheSize", Integer.class);
}
public String[] getInterceptorClassNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("incomingInterceptorClassNames"));
}
@Override
public String[] getIncomingInterceptorClassNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("incomingInterceptorClassNames"));
}
@Override
public String[] getOutgoingInterceptorClassNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("outgoingInterceptorClassNames"));
}
@Override
public String getJournalDirectory() {
return (String) proxy.retrieveAttributeValue("journalDirectory");
}
@Override
public int getJournalFileSize() {
return (Integer) proxy.retrieveAttributeValue("journalFileSize", Integer.class);
}
@Override
public int getJournalMaxIO() {
return (Integer) proxy.retrieveAttributeValue("journalMaxIO", Integer.class);
}
@Override
public int getJournalMinFiles() {
return (Integer) proxy.retrieveAttributeValue("journalMinFiles", Integer.class);
}
@Override
public String getJournalType() {
return (String) proxy.retrieveAttributeValue("journalType");
}
@Override
public String getLargeMessagesDirectory() {
return (String) proxy.retrieveAttributeValue("largeMessagesDirectory");
}
@Override
public String getManagementAddress() {
return (String) proxy.retrieveAttributeValue("managementAddress");
}
@Override
public String getManagementNotificationAddress() {
return (String) proxy.retrieveAttributeValue("managementNotificationAddress");
}
@Override
public int getMessageCounterMaxDayCount() {
return (Integer) proxy.retrieveAttributeValue("messageCounterMaxDayCount", Integer.class);
}
@Override
public long getMessageCounterSamplePeriod() {
return (Long) proxy.retrieveAttributeValue("messageCounterSamplePeriod", Long.class);
}
@Override
public long getMessageExpiryScanPeriod() {
return (Long) proxy.retrieveAttributeValue("messageExpiryScanPeriod", Long.class);
}
@Override
public long getMessageExpiryThreadPriority() {
return (Long) proxy.retrieveAttributeValue("messageExpiryThreadPriority", Long.class);
}
@Override
public String getPagingDirectory() {
return (String) proxy.retrieveAttributeValue("pagingDirectory");
}
@Override
public int getScheduledThreadPoolMaxSize() {
return (Integer) proxy.retrieveAttributeValue("scheduledThreadPoolMaxSize", Integer.class);
}
@Override
public int getThreadPoolMaxSize() {
return (Integer) proxy.retrieveAttributeValue("threadPoolMaxSize", Integer.class);
}
@Override
public long getSecurityInvalidationInterval() {
return (Long) proxy.retrieveAttributeValue("securityInvalidationInterval", Long.class);
}
@Override
public long getTransactionTimeout() {
return (Long) proxy.retrieveAttributeValue("transactionTimeout", Long.class);
}
@Override
public long getTransactionTimeoutScanPeriod() {
return (Long) proxy.retrieveAttributeValue("transactionTimeoutScanPeriod", Long.class);
}
@Override
public String getVersion() {
return proxy.retrieveAttributeValue("version").toString();
}
@Override
public boolean isBackup() {
return (Boolean) proxy.retrieveAttributeValue("backup");
}
@Override
public boolean isClustered() {
return (Boolean) proxy.retrieveAttributeValue("clustered");
}
@Override
public boolean isCreateBindingsDir() {
return (Boolean) proxy.retrieveAttributeValue("createBindingsDir");
}
@Override
public boolean isCreateJournalDir() {
return (Boolean) proxy.retrieveAttributeValue("createJournalDir");
}
@Override
public boolean isJournalSyncNonTransactional() {
return (Boolean) proxy.retrieveAttributeValue("journalSyncNonTransactional");
}
@Override
public boolean isJournalSyncTransactional() {
return (Boolean) proxy.retrieveAttributeValue("journalSyncTransactional");
}
@Override
public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown) throws Exception {
proxy.invokeOperation("setFailoverOnServerShutdown", failoverOnServerShutdown);
}
@Override
public boolean isFailoverOnServerShutdown() {
return (Boolean) proxy.retrieveAttributeValue("failoverOnServerShutdown");
}
public void setScaleDown(boolean scaleDown) throws Exception {
proxy.invokeOperation("setEnabled", scaleDown);
}
public boolean isScaleDown() {
return (Boolean) proxy.retrieveAttributeValue("scaleDown");
}
@Override
public boolean isMessageCounterEnabled() {
return (Boolean) proxy.retrieveAttributeValue("messageCounterEnabled");
}
@Override
public boolean isPersistDeliveryCountBeforeDelivery() {
return (Boolean) proxy.retrieveAttributeValue("persistDeliveryCountBeforeDelivery");
}
@Override
public boolean isAsyncConnectionExecutionEnabled() {
return (Boolean) proxy.retrieveAttributeValue("asyncConnectionExecutionEnabled");
}
@Override
public boolean isPersistIDCache() {
return (Boolean) proxy.retrieveAttributeValue("persistIDCache");
}
@Override
public boolean isSecurityEnabled() {
return (Boolean) proxy.retrieveAttributeValue("securityEnabled");
}
@Override
public boolean isStarted() {
return (Boolean) proxy.retrieveAttributeValue("started");
}
@Override
public boolean isWildcardRoutingEnabled() {
return (Boolean) proxy.retrieveAttributeValue("wildcardRoutingEnabled");
}
@Override
public String[] listConnectionIDs() throws Exception {
return (String[]) proxy.invokeOperation("listConnectionIDs");
}
@Override
public String[] listPreparedTransactions() throws Exception {
return (String[]) proxy.invokeOperation("listPreparedTransactions");
}
@Override
public String listPreparedTransactionDetailsAsJSON() throws Exception {
return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsJSON");
}
@Override
public String listPreparedTransactionDetailsAsHTML() throws Exception {
return (String) proxy.invokeOperation("listPreparedTransactionDetailsAsHTML");
}
@Override
public String[] listHeuristicCommittedTransactions() throws Exception {
return (String[]) proxy.invokeOperation("listHeuristicCommittedTransactions");
}
@Override
public String[] listHeuristicRolledBackTransactions() throws Exception {
return (String[]) proxy.invokeOperation("listHeuristicRolledBackTransactions");
}
@Override
public String[] listRemoteAddresses() throws Exception {
return (String[]) proxy.invokeOperation("listRemoteAddresses");
}
@Override
public String[] listRemoteAddresses(final String ipAddress) throws Exception {
return (String[]) proxy.invokeOperation("listRemoteAddresses", ipAddress);
}
@Override
public String[] listSessions(final String connectionID) throws Exception {
return (String[]) proxy.invokeOperation("listSessions", connectionID);
}
@Override
public void resetAllMessageCounterHistories() throws Exception {
proxy.invokeOperation("resetAllMessageCounterHistories");
}
@Override
public void resetAllMessageCounters() throws Exception {
proxy.invokeOperation("resetAllMessageCounters");
}
@Override
public boolean rollbackPreparedTransaction(final String transactionAsBase64) throws Exception {
return (Boolean) proxy.invokeOperation("rollbackPreparedTransaction", transactionAsBase64);
}
@Override
public void sendQueueInfoToQueue(final String queueName, final String address) throws Exception {
proxy.invokeOperation("sendQueueInfoToQueue", queueName, address);
}
@Override
public void setMessageCounterMaxDayCount(final int count) throws Exception {
proxy.invokeOperation("setMessageCounterMaxDayCount", count);
}
@Override
public void setMessageCounterSamplePeriod(final long newPeriod) throws Exception {
proxy.invokeOperation("setMessageCounterSamplePeriod", newPeriod);
}
@Override
public int getJournalBufferSize() {
return (Integer) proxy.retrieveAttributeValue("JournalBufferSize", Integer.class);
}
@Override
public int getJournalBufferTimeout() {
return (Integer) proxy.retrieveAttributeValue("JournalBufferTimeout", Integer.class);
}
@Override
public int getJournalCompactMinFiles() {
return (Integer) proxy.retrieveAttributeValue("JournalCompactMinFiles", Integer.class);
}
@Override
public int getJournalCompactPercentage() {
return (Integer) proxy.retrieveAttributeValue("JournalCompactPercentage", Integer.class);
}
@Override
public boolean isPersistenceEnabled() {
return (Boolean) proxy.retrieveAttributeValue("PersistenceEnabled");
}
@Override
public int getDiskScanPeriod() {
return (Integer) proxy.retrieveAttributeValue("DiskScanPeriod", Integer.class);
}
@Override
public int getMaxDiskUsage() {
return (Integer) proxy.retrieveAttributeValue("MaxDiskUsage", Integer.class);
}
@Override
public long getGlobalMaxSize() {
return (Long) proxy.retrieveAttributeValue("GlobalMaxSize", Long.class);
}
@Override
public void addSecuritySettings(String addressMatch,
String sendRoles,
String consumeRoles,
String createDurableQueueRoles,
String deleteDurableQueueRoles,
String createNonDurableQueueRoles,
String deleteNonDurableQueueRoles,
String manageRoles) throws Exception {
proxy.invokeOperation("addSecuritySettings", addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles);
}
@Override
public void addSecuritySettings(String addressMatch,
String sendRoles,
String consumeRoles,
String createDurableQueueRoles,
String deleteDurableQueueRoles,
String createNonDurableQueueRoles,
String deleteNonDurableQueueRoles,
String manageRoles,
String browseRoles) throws Exception {
proxy.invokeOperation("addSecuritySettings", addressMatch, sendRoles, consumeRoles, createDurableQueueRoles, deleteDurableQueueRoles, createNonDurableQueueRoles, deleteNonDurableQueueRoles, manageRoles, browseRoles);
}
@Override
public void removeSecuritySettings(String addressMatch) throws Exception {
proxy.invokeOperation("removeSecuritySettings", addressMatch);
}
@Override
public Object[] getRoles(String addressMatch) throws Exception {
return (Object[]) proxy.invokeOperation("getRoles", addressMatch);
}
@Override
public String getRolesAsJSON(String addressMatch) throws Exception {
return (String) proxy.invokeOperation("getRolesAsJSON", addressMatch);
}
@Override
public void addAddressSettings(@Parameter(desc = "an address match", name = "addressMatch") String addressMatch,
@Parameter(desc = "the dead letter address setting", name = "DLA") String DLA,
@Parameter(desc = "the expiry address setting", name = "expiryAddress") String expiryAddress,
@Parameter(desc = "the expiry delay setting", name = "expiryDelay") long expiryDelay,
@Parameter(desc = "are any queues created for this address a last value queue", name = "lastValueQueue") boolean lastValueQueue,
@Parameter(desc = "the delivery attempts", name = "deliveryAttempts") int deliveryAttempts,
@Parameter(desc = "the max size in bytes", name = "maxSizeBytes") long maxSizeBytes,
@Parameter(desc = "the page size in bytes", name = "pageSizeBytes") int pageSizeBytes,
@Parameter(desc = "the max number of pages in the soft memory cache", name = "pageMaxCacheSize") int pageMaxCacheSize,
@Parameter(desc = "the redelivery delay", name = "redeliveryDelay") long redeliveryDelay,
@Parameter(desc = "the redelivery delay multiplier", name = "redeliveryMultiplier") double redeliveryMultiplier,
@Parameter(desc = "the maximum redelivery delay", name = "maxRedeliveryDelay") long maxRedeliveryDelay,
@Parameter(desc = "the redistribution delay", name = "redistributionDelay") long redistributionDelay,
@Parameter(desc = "do we send to the DLA when there is no where to route the message", name = "sendToDLAOnNoRoute") boolean sendToDLAOnNoRoute,
@Parameter(desc = "the policy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy,
@Parameter(desc = "when a consumer falls below this threshold in terms of messages consumed per second it will be considered 'slow'", name = "slowConsumerThreshold") long slowConsumerThreshold,
@Parameter(desc = "how often (in seconds) to check for slow consumers", name = "slowConsumerCheckPeriod") long slowConsumerCheckPeriod,
@Parameter(desc = "the policy to use when a slow consumer is detected", name = "slowConsumerPolicy") String slowConsumerPolicy,
@Parameter(desc = "allow queues to be created automatically", name = "autoCreateJmsQueues") boolean autoCreateJmsQueues,
@Parameter(desc = "allow auto-created queues to be deleted automatically", name = "autoDeleteJmsQueues") boolean autoDeleteJmsQueues,
@Parameter(desc = "allow topics to be created automatically", name = "autoCreateJmsTopics") boolean autoCreateJmsTopics,
@Parameter(desc = "allow auto-created topics to be deleted automatically", name = "autoDeleteJmsTopics") boolean autoDeleteJmsTopics) throws Exception {
proxy.invokeOperation("addAddressSettings", addressMatch, DLA, expiryAddress, expiryDelay, lastValueQueue, deliveryAttempts, maxSizeBytes, pageSizeBytes, pageMaxCacheSize, redeliveryDelay, redeliveryMultiplier, maxRedeliveryDelay, redistributionDelay, sendToDLAOnNoRoute, addressFullMessagePolicy, slowConsumerThreshold, slowConsumerCheckPeriod, slowConsumerPolicy, autoCreateJmsQueues, autoDeleteJmsQueues, autoCreateJmsTopics, autoDeleteJmsTopics);
}
@Override
public void removeAddressSettings(String addressMatch) throws Exception {
proxy.invokeOperation("removeAddressSettings", addressMatch);
}
@Override
public void createDivert(String name,
String routingName,
String address,
String forwardingAddress,
boolean exclusive,
String filterString,
String transformerClassName) throws Exception {
proxy.invokeOperation("createDivert", name, routingName, address, forwardingAddress, exclusive, filterString, transformerClassName);
}
@Override
public void destroyDivert(String name) throws Exception {
proxy.invokeOperation("destroyDivert", name);
}
@Override
public String[] getBridgeNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("bridgeNames"));
}
@Override
public void destroyBridge(String name) throws Exception {
proxy.invokeOperation("destroyBridge", name);
}
@Override
public void createConnectorService(String name, String factoryClass, Map<String, Object> parameters) throws Exception {
proxy.invokeOperation("createConnectorService", name, factoryClass, parameters);
}
@Override
public void destroyConnectorService(String name) throws Exception {
proxy.invokeOperation("destroyConnectorService", name);
}
@Override
public String[] getConnectorServices() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("connectorServices"));
}
@Override
public void forceFailover() throws Exception {
proxy.invokeOperation("forceFailover");
}
public String getLiveConnectorName() throws Exception {
return (String) proxy.retrieveAttributeValue("liveConnectorName");
}
@Override
public String getAddressSettingsAsJSON(String addressMatch) throws Exception {
return (String) proxy.invokeOperation("getAddressSettingsAsJSON", addressMatch);
}
@Override
public String[] getDivertNames() {
return ActiveMQServerControlUsingCoreTest.toStringArray((Object[]) proxy.retrieveAttributeValue("divertNames"));
}
@Override
public void createBridge(String name,
String queueName,
String forwardingAddress,
String filterString,
String transformerClassName,
long retryInterval,
double retryIntervalMultiplier,
int initialConnectAttempts,
int reconnectAttempts,
boolean useDuplicateDetection,
int confirmationWindowSize,
int producerWindowSize,
long clientFailureCheckPeriod,
String connectorNames,
boolean useDiscovery,
boolean ha,
String user,
String password) throws Exception {
proxy.invokeOperation("createBridge", name, queueName, forwardingAddress, filterString, transformerClassName, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, producerWindowSize, clientFailureCheckPeriod, connectorNames, useDiscovery, ha, user, password);
}
@Override
public void createBridge(String name,
String queueName,
String forwardingAddress,
String filterString,
String transformerClassName,
long retryInterval,
double retryIntervalMultiplier,
int initialConnectAttempts,
int reconnectAttempts,
boolean useDuplicateDetection,
int confirmationWindowSize,
long clientFailureCheckPeriod,
String connectorNames,
boolean useDiscovery,
boolean ha,
String user,
String password) throws Exception {
proxy.invokeOperation("createBridge", name, queueName, forwardingAddress, filterString, transformerClassName, retryInterval, retryIntervalMultiplier, initialConnectAttempts, reconnectAttempts, useDuplicateDetection, confirmationWindowSize, clientFailureCheckPeriod, connectorNames, useDiscovery, ha, user, password);
}
@Override
public String listProducersInfoAsJSON() throws Exception {
return (String) proxy.invokeOperation("listProducersInfoAsJSON");
}
@Override
public String listConsumersAsJSON(String connectionID) throws Exception {
return (String) proxy.invokeOperation("listConsumersAsJSON", connectionID);
}
@Override
public String listAllConsumersAsJSON() throws Exception {
return (String) proxy.invokeOperation("listAllConsumersAsJSON");
}
@Override
public String listConnectionsAsJSON() throws Exception {
return (String) proxy.invokeOperation("listConnectionsAsJSON");
}
@Override
public String listSessionsAsJSON(@Parameter(desc = "a connection ID", name = "connectionID") String connectionID) throws Exception {
return (String) proxy.invokeOperation("listSessionsAsJSON", connectionID);
}
};
}
@Override
public boolean usingCore() {
return true;
}
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| apache-2.0 |
jackylk/incubator-carbondata | integration/spark/src/main/spark2.3/org/apache/carbondata/spark/adapter/CarbonToSparkAdapter.scala | 1137 | /*
* 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.carbondata.spark.adapter
import scala.collection.mutable.ArrayBuffer
import org.apache.spark.sql.execution.datasources.{FilePartition, PartitionedFile}
object CarbonToSparkAdapter {
def createFilePartition(index: Int, files: ArrayBuffer[PartitionedFile]) = {
FilePartition(index, files.toArray.toSeq)
}
}
| apache-2.0 |
aiyanbo/guava | guava-tests/test/com/google/common/base/CharsetsTest.java | 2382 | /*
* Copyright (C) 2007 The Guava 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 com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import junit.framework.TestCase;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* Unit test for {@link Charsets}.
*
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
public class CharsetsTest extends TestCase {
@GwtIncompatible // Non-UTF-8 Charset
public void testUsAscii() {
assertEquals(Charset.forName("US-ASCII"), Charsets.US_ASCII);
}
@GwtIncompatible // Non-UTF-8 Charset
public void testIso88591() {
assertEquals(Charset.forName("ISO-8859-1"), Charsets.ISO_8859_1);
}
public void testUtf8() {
assertEquals(Charset.forName("UTF-8"), Charsets.UTF_8);
}
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16be() {
assertEquals(Charset.forName("UTF-16BE"), Charsets.UTF_16BE);
}
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16le() {
assertEquals(Charset.forName("UTF-16LE"), Charsets.UTF_16LE);
}
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16() {
assertEquals(Charset.forName("UTF-16"), Charsets.UTF_16);
}
@GwtIncompatible // Non-UTF-8 Charset
public void testWhyUsAsciiIsDangerous() {
byte[] b1 = "朝日新聞".getBytes(Charsets.US_ASCII);
byte[] b2 = "聞朝日新".getBytes(Charsets.US_ASCII);
byte[] b3 = "????".getBytes(Charsets.US_ASCII);
byte[] b4 = "ニュース".getBytes(Charsets.US_ASCII);
byte[] b5 = "スューー".getBytes(Charsets.US_ASCII);
// Assert they are all equal (using the transitive property)
assertTrue(Arrays.equals(b1, b2));
assertTrue(Arrays.equals(b2, b3));
assertTrue(Arrays.equals(b3, b4));
assertTrue(Arrays.equals(b4, b5));
}
}
| apache-2.0 |
rafd123/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/Model/DeleteInterconnectRequest.cs | 1636 | /*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// Container for the parameters to the DeleteInterconnect operation.
/// Deletes the specified interconnect.
/// </summary>
public partial class DeleteInterconnectRequest : AmazonDirectConnectRequest
{
private string _interconnectId;
/// <summary>
/// Gets and sets the property InterconnectId.
/// </summary>
public string InterconnectId
{
get { return this._interconnectId; }
set { this._interconnectId = value; }
}
// Check to see if InterconnectId property is set
internal bool IsSetInterconnectId()
{
return this._interconnectId != null;
}
}
} | apache-2.0 |
yahoo/athenz | core/zts/src/test/java/com/yahoo/athenz/zts/HostServicesTest.java | 1478 | /*
* Copyright 2016 Yahoo 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.yahoo.athenz.zts;
import static org.testng.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
@SuppressWarnings({"EqualsWithItself", "EqualsBetweenInconvertibleTypes"})
public class HostServicesTest {
@Test
public void testHostService() {
HostServices hs = new HostServices();
HostServices hs2 = new HostServices();
List<String> nl = new ArrayList<>();
nl.add("sample.service1");
// set
hs.setNames(nl);
hs.setHost("sample.com");
hs2.setHost("sample.com");
// getter assertion
assertEquals(hs.getHost(), "sample.com");
assertEquals(hs.getNames(), nl);
assertEquals(hs, hs);
assertNotEquals(hs2, hs);
hs2.setHost(null);
assertNotEquals(hs2, hs);
assertNotEquals("", hs);
}
}
| apache-2.0 |
bravo-zhang/spark | sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala | 111856 | /*
* 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.spark.sql.catalyst.expressions
import java.util.{Comparator, TimeZone}
import scala.collection.mutable
import scala.reflect.ClassTag
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.{TypeCheckResult, TypeCoercion}
import org.apache.spark.sql.catalyst.expressions.ArraySortLike.NullOrder
import org.apache.spark.sql.catalyst.expressions.codegen._
import org.apache.spark.sql.catalyst.expressions.codegen.Block._
import org.apache.spark.sql.catalyst.util._
import org.apache.spark.sql.catalyst.util.DateTimeUtils._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.Platform
import org.apache.spark.unsafe.array.ByteArrayMethods
import org.apache.spark.unsafe.array.ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH
import org.apache.spark.unsafe.types.{ByteArray, UTF8String}
import org.apache.spark.unsafe.types.CalendarInterval
import org.apache.spark.util.collection.OpenHashSet
/**
* Base trait for [[BinaryExpression]]s with two arrays of the same element type and implicit
* casting.
*/
trait BinaryArrayExpressionWithImplicitCast extends BinaryExpression
with ImplicitCastInputTypes {
@transient protected lazy val elementType: DataType =
inputTypes.head.asInstanceOf[ArrayType].elementType
override def inputTypes: Seq[AbstractDataType] = {
(left.dataType, right.dataType) match {
case (ArrayType(e1, hasNull1), ArrayType(e2, hasNull2)) =>
TypeCoercion.findTightestCommonType(e1, e2) match {
case Some(dt) => Seq(ArrayType(dt, hasNull1), ArrayType(dt, hasNull2))
case _ => Seq.empty
}
case _ => Seq.empty
}
}
override def checkInputDataTypes(): TypeCheckResult = {
(left.dataType, right.dataType) match {
case (ArrayType(e1, _), ArrayType(e2, _)) if e1.sameType(e2) =>
TypeCheckResult.TypeCheckSuccess
case _ => TypeCheckResult.TypeCheckFailure(s"input to function $prettyName should have " +
s"been two ${ArrayType.simpleString}s with same element type, but it's " +
s"[${left.dataType.simpleString}, ${right.dataType.simpleString}]")
}
}
}
/**
* Given an array or map, returns total number of elements in it.
*/
@ExpressionDescription(
usage = """
_FUNC_(expr) - Returns the size of an array or a map.
The function returns -1 if its input is null and spark.sql.legacy.sizeOfNull is set to true.
If spark.sql.legacy.sizeOfNull is set to false, the function returns null for null input.
By default, the spark.sql.legacy.sizeOfNull parameter is set to true.
""",
examples = """
Examples:
> SELECT _FUNC_(array('b', 'd', 'c', 'a'));
4
> SELECT _FUNC_(map('a', 1, 'b', 2));
2
> SELECT _FUNC_(NULL);
-1
""")
case class Size(
child: Expression,
legacySizeOfNull: Boolean)
extends UnaryExpression with ExpectsInputTypes {
def this(child: Expression) =
this(
child,
legacySizeOfNull = SQLConf.get.getConf(SQLConf.LEGACY_SIZE_OF_NULL))
override def dataType: DataType = IntegerType
override def inputTypes: Seq[AbstractDataType] = Seq(TypeCollection(ArrayType, MapType))
override def nullable: Boolean = if (legacySizeOfNull) false else super.nullable
override def eval(input: InternalRow): Any = {
val value = child.eval(input)
if (value == null) {
if (legacySizeOfNull) -1 else null
} else child.dataType match {
case _: ArrayType => value.asInstanceOf[ArrayData].numElements()
case _: MapType => value.asInstanceOf[MapData].numElements()
case other => throw new UnsupportedOperationException(
s"The size function doesn't support the operand type ${other.getClass.getCanonicalName}")
}
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
if (legacySizeOfNull) {
val childGen = child.genCode(ctx)
ev.copy(code = code"""
boolean ${ev.isNull} = false;
${childGen.code}
${CodeGenerator.javaType(dataType)} ${ev.value} = ${childGen.isNull} ? -1 :
(${childGen.value}).numElements();""", isNull = FalseLiteral)
} else {
defineCodeGen(ctx, ev, c => s"($c).numElements()")
}
}
}
/**
* Returns an unordered array containing the keys of the map.
*/
@ExpressionDescription(
usage = "_FUNC_(map) - Returns an unordered array containing the keys of the map.",
examples = """
Examples:
> SELECT _FUNC_(map(1, 'a', 2, 'b'));
[1,2]
""")
case class MapKeys(child: Expression)
extends UnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(MapType)
override def dataType: DataType = ArrayType(child.dataType.asInstanceOf[MapType].keyType)
override def nullSafeEval(map: Any): Any = {
map.asInstanceOf[MapData].keyArray()
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => s"${ev.value} = ($c).keyArray();")
}
override def prettyName: String = "map_keys"
}
@ExpressionDescription(
usage = """
_FUNC_(a1, a2, ...) - Returns a merged array of structs in which the N-th struct contains all
N-th values of input arrays.
""",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3), array(2, 3, 4));
[[1, 2], [2, 3], [3, 4]]
> SELECT _FUNC_(array(1, 2), array(2, 3), array(3, 4));
[[1, 2, 3], [2, 3, 4]]
""",
since = "2.4.0")
case class ArraysZip(children: Seq[Expression]) extends Expression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq.fill(children.length)(ArrayType)
override def dataType: DataType = ArrayType(mountSchema)
override def nullable: Boolean = children.exists(_.nullable)
private lazy val arrayTypes = children.map(_.dataType.asInstanceOf[ArrayType])
private lazy val arrayElementTypes = arrayTypes.map(_.elementType)
@transient private lazy val mountSchema: StructType = {
val fields = children.zip(arrayElementTypes).zipWithIndex.map {
case ((expr: NamedExpression, elementType), _) =>
StructField(expr.name, elementType, nullable = true)
case ((_, elementType), idx) =>
StructField(idx.toString, elementType, nullable = true)
}
StructType(fields)
}
@transient lazy val numberOfArrays: Int = children.length
@transient lazy val genericArrayData = classOf[GenericArrayData].getName
def emptyInputGenCode(ev: ExprCode): ExprCode = {
ev.copy(code"""
|${CodeGenerator.javaType(dataType)} ${ev.value} = new $genericArrayData(new Object[0]);
|boolean ${ev.isNull} = false;
""".stripMargin)
}
def nonEmptyInputGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val genericInternalRow = classOf[GenericInternalRow].getName
val arrVals = ctx.freshName("arrVals")
val biggestCardinality = ctx.freshName("biggestCardinality")
val currentRow = ctx.freshName("currentRow")
val j = ctx.freshName("j")
val i = ctx.freshName("i")
val args = ctx.freshName("args")
val evals = children.map(_.genCode(ctx))
val getValuesAndCardinalities = evals.zipWithIndex.map { case (eval, index) =>
s"""
|if ($biggestCardinality != -1) {
| ${eval.code}
| if (!${eval.isNull}) {
| $arrVals[$index] = ${eval.value};
| $biggestCardinality = Math.max($biggestCardinality, ${eval.value}.numElements());
| } else {
| $biggestCardinality = -1;
| }
|}
""".stripMargin
}
val splittedGetValuesAndCardinalities = ctx.splitExpressionsWithCurrentInputs(
expressions = getValuesAndCardinalities,
funcName = "getValuesAndCardinalities",
returnType = "int",
makeSplitFunction = body =>
s"""
|$body
|return $biggestCardinality;
""".stripMargin,
foldFunctions = _.map(funcCall => s"$biggestCardinality = $funcCall;").mkString("\n"),
extraArguments =
("ArrayData[]", arrVals) ::
("int", biggestCardinality) :: Nil)
val getValueForType = arrayElementTypes.zipWithIndex.map { case (eleType, idx) =>
val g = CodeGenerator.getValue(s"$arrVals[$idx]", eleType, i)
s"""
|if ($i < $arrVals[$idx].numElements() && !$arrVals[$idx].isNullAt($i)) {
| $currentRow[$idx] = $g;
|} else {
| $currentRow[$idx] = null;
|}
""".stripMargin
}
val getValueForTypeSplitted = ctx.splitExpressions(
expressions = getValueForType,
funcName = "extractValue",
arguments =
("int", i) ::
("Object[]", currentRow) ::
("ArrayData[]", arrVals) :: Nil)
val initVariables = s"""
|ArrayData[] $arrVals = new ArrayData[$numberOfArrays];
|int $biggestCardinality = 0;
|${CodeGenerator.javaType(dataType)} ${ev.value} = null;
""".stripMargin
ev.copy(code"""
|$initVariables
|$splittedGetValuesAndCardinalities
|boolean ${ev.isNull} = $biggestCardinality == -1;
|if (!${ev.isNull}) {
| Object[] $args = new Object[$biggestCardinality];
| for (int $i = 0; $i < $biggestCardinality; $i ++) {
| Object[] $currentRow = new Object[$numberOfArrays];
| $getValueForTypeSplitted
| $args[$i] = new $genericInternalRow($currentRow);
| }
| ${ev.value} = new $genericArrayData($args);
|}
""".stripMargin)
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
if (numberOfArrays == 0) {
emptyInputGenCode(ev)
} else {
nonEmptyInputGenCode(ctx, ev)
}
}
override def eval(input: InternalRow): Any = {
val inputArrays = children.map(_.eval(input).asInstanceOf[ArrayData])
if (inputArrays.contains(null)) {
null
} else {
val biggestCardinality = if (inputArrays.isEmpty) {
0
} else {
inputArrays.map(_.numElements()).max
}
val result = new Array[InternalRow](biggestCardinality)
val zippedArrs: Seq[(ArrayData, Int)] = inputArrays.zipWithIndex
for (i <- 0 until biggestCardinality) {
val currentLayer: Seq[Object] = zippedArrs.map { case (arr, index) =>
if (i < arr.numElements() && !arr.isNullAt(i)) {
arr.get(i, arrayElementTypes(index))
} else {
null
}
}
result(i) = InternalRow.apply(currentLayer: _*)
}
new GenericArrayData(result)
}
}
override def prettyName: String = "arrays_zip"
}
/**
* Returns an unordered array containing the values of the map.
*/
@ExpressionDescription(
usage = "_FUNC_(map) - Returns an unordered array containing the values of the map.",
examples = """
Examples:
> SELECT _FUNC_(map(1, 'a', 2, 'b'));
["a","b"]
""")
case class MapValues(child: Expression)
extends UnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(MapType)
override def dataType: DataType = ArrayType(child.dataType.asInstanceOf[MapType].valueType)
override def nullSafeEval(map: Any): Any = {
map.asInstanceOf[MapData].valueArray()
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => s"${ev.value} = ($c).valueArray();")
}
override def prettyName: String = "map_values"
}
/**
* Returns an unordered array of all entries in the given map.
*/
@ExpressionDescription(
usage = "_FUNC_(map) - Returns an unordered array of all entries in the given map.",
examples = """
Examples:
> SELECT _FUNC_(map(1, 'a', 2, 'b'));
[(1,"a"),(2,"b")]
""",
since = "2.4.0")
case class MapEntries(child: Expression) extends UnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(MapType)
lazy val childDataType: MapType = child.dataType.asInstanceOf[MapType]
override def dataType: DataType = {
ArrayType(
StructType(
StructField("key", childDataType.keyType, false) ::
StructField("value", childDataType.valueType, childDataType.valueContainsNull) ::
Nil),
false)
}
override protected def nullSafeEval(input: Any): Any = {
val childMap = input.asInstanceOf[MapData]
val keys = childMap.keyArray()
val values = childMap.valueArray()
val length = childMap.numElements()
val resultData = new Array[AnyRef](length)
var i = 0;
while (i < length) {
val key = keys.get(i, childDataType.keyType)
val value = values.get(i, childDataType.valueType)
val row = new GenericInternalRow(Array[Any](key, value))
resultData.update(i, row)
i += 1
}
new GenericArrayData(resultData)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => {
val numElements = ctx.freshName("numElements")
val keys = ctx.freshName("keys")
val values = ctx.freshName("values")
val isKeyPrimitive = CodeGenerator.isPrimitiveType(childDataType.keyType)
val isValuePrimitive = CodeGenerator.isPrimitiveType(childDataType.valueType)
val code = if (isKeyPrimitive && isValuePrimitive) {
genCodeForPrimitiveElements(ctx, keys, values, ev.value, numElements)
} else {
genCodeForAnyElements(ctx, keys, values, ev.value, numElements)
}
s"""
|final int $numElements = $c.numElements();
|final ArrayData $keys = $c.keyArray();
|final ArrayData $values = $c.valueArray();
|$code
""".stripMargin
})
}
private def getKey(varName: String) = CodeGenerator.getValue(varName, childDataType.keyType, "z")
private def getValue(varName: String) = {
CodeGenerator.getValue(varName, childDataType.valueType, "z")
}
private def genCodeForPrimitiveElements(
ctx: CodegenContext,
keys: String,
values: String,
arrayData: String,
numElements: String): String = {
val unsafeRow = ctx.freshName("unsafeRow")
val unsafeArrayData = ctx.freshName("unsafeArrayData")
val structsOffset = ctx.freshName("structsOffset")
val calculateHeader = "UnsafeArrayData.calculateHeaderPortionInBytes"
val baseOffset = Platform.BYTE_ARRAY_OFFSET
val wordSize = UnsafeRow.WORD_SIZE
val structSize = UnsafeRow.calculateBitSetWidthInBytes(2) + wordSize * 2
val structSizeAsLong = structSize + "L"
val keyTypeName = CodeGenerator.primitiveTypeName(childDataType.keyType)
val valueTypeName = CodeGenerator.primitiveTypeName(childDataType.keyType)
val valueAssignment = s"$unsafeRow.set$valueTypeName(1, ${getValue(values)});"
val valueAssignmentChecked = if (childDataType.valueContainsNull) {
s"""
|if ($values.isNullAt(z)) {
| $unsafeRow.setNullAt(1);
|} else {
| $valueAssignment
|}
""".stripMargin
} else {
valueAssignment
}
val assignmentLoop = (byteArray: String) =>
s"""
|final int $structsOffset = $calculateHeader($numElements) + $numElements * $wordSize;
|UnsafeRow $unsafeRow = new UnsafeRow(2);
|for (int z = 0; z < $numElements; z++) {
| long offset = $structsOffset + z * $structSizeAsLong;
| $unsafeArrayData.setLong(z, (offset << 32) + $structSizeAsLong);
| $unsafeRow.pointTo($byteArray, $baseOffset + offset, $structSize);
| $unsafeRow.set$keyTypeName(0, ${getKey(keys)});
| $valueAssignmentChecked
|}
|$arrayData = $unsafeArrayData;
""".stripMargin
ctx.createUnsafeArrayWithFallback(
unsafeArrayData,
numElements,
structSize + wordSize,
assignmentLoop,
genCodeForAnyElements(ctx, keys, values, arrayData, numElements))
}
private def genCodeForAnyElements(
ctx: CodegenContext,
keys: String,
values: String,
arrayData: String,
numElements: String): String = {
val genericArrayClass = classOf[GenericArrayData].getName
val rowClass = classOf[GenericInternalRow].getName
val data = ctx.freshName("internalRowArray")
val isValuePrimitive = CodeGenerator.isPrimitiveType(childDataType.valueType)
val getValueWithCheck = if (childDataType.valueContainsNull && isValuePrimitive) {
s"$values.isNullAt(z) ? null : (Object)${getValue(values)}"
} else {
getValue(values)
}
s"""
|final Object[] $data = new Object[$numElements];
|for (int z = 0; z < $numElements; z++) {
| $data[z] = new $rowClass(new Object[]{${getKey(keys)}, $getValueWithCheck});
|}
|$arrayData = new $genericArrayClass($data);
""".stripMargin
}
override def prettyName: String = "map_entries"
}
/**
* Returns a map created from the given array of entries.
*/
@ExpressionDescription(
usage = "_FUNC_(arrayOfEntries) - Returns a map created from the given array of entries.",
examples = """
Examples:
> SELECT _FUNC_(array(struct(1, 'a'), struct(2, 'b')));
{1:"a",2:"b"}
""",
since = "2.4.0")
case class MapFromEntries(child: Expression) extends UnaryExpression {
@transient
private lazy val dataTypeDetails: Option[(MapType, Boolean, Boolean)] = child.dataType match {
case ArrayType(
StructType(Array(
StructField(_, keyType, keyNullable, _),
StructField(_, valueType, valueNullable, _))),
containsNull) => Some((MapType(keyType, valueType, valueNullable), keyNullable, containsNull))
case _ => None
}
private def nullEntries: Boolean = dataTypeDetails.get._3
override def nullable: Boolean = child.nullable || nullEntries
override def dataType: MapType = dataTypeDetails.get._1
override def checkInputDataTypes(): TypeCheckResult = dataTypeDetails match {
case Some(_) => TypeCheckResult.TypeCheckSuccess
case None => TypeCheckResult.TypeCheckFailure(s"'${child.sql}' is of " +
s"${child.dataType.simpleString} type. $prettyName accepts only arrays of pair structs.")
}
override protected def nullSafeEval(input: Any): Any = {
val arrayData = input.asInstanceOf[ArrayData]
val numEntries = arrayData.numElements()
var i = 0
if(nullEntries) {
while (i < numEntries) {
if (arrayData.isNullAt(i)) return null
i += 1
}
}
val keyArray = new Array[AnyRef](numEntries)
val valueArray = new Array[AnyRef](numEntries)
i = 0
while (i < numEntries) {
val entry = arrayData.getStruct(i, 2)
val key = entry.get(0, dataType.keyType)
if (key == null) {
throw new RuntimeException("The first field from a struct (key) can't be null.")
}
keyArray.update(i, key)
val value = entry.get(1, dataType.valueType)
valueArray.update(i, value)
i += 1
}
ArrayBasedMapData(keyArray, valueArray)
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => {
val numEntries = ctx.freshName("numEntries")
val isKeyPrimitive = CodeGenerator.isPrimitiveType(dataType.keyType)
val isValuePrimitive = CodeGenerator.isPrimitiveType(dataType.valueType)
val code = if (isKeyPrimitive && isValuePrimitive) {
genCodeForPrimitiveElements(ctx, c, ev.value, numEntries)
} else {
genCodeForAnyElements(ctx, c, ev.value, numEntries)
}
ctx.nullArrayElementsSaveExec(nullEntries, ev.isNull, c) {
s"""
|final int $numEntries = $c.numElements();
|$code
""".stripMargin
}
})
}
private def genCodeForAssignmentLoop(
ctx: CodegenContext,
childVariable: String,
mapData: String,
numEntries: String,
keyAssignment: (String, String) => String,
valueAssignment: (String, String) => String): String = {
val entry = ctx.freshName("entry")
val i = ctx.freshName("idx")
val nullKeyCheck = if (dataTypeDetails.get._2) {
s"""
|if ($entry.isNullAt(0)) {
| throw new RuntimeException("The first field from a struct (key) can't be null.");
|}
""".stripMargin
} else {
""
}
s"""
|for (int $i = 0; $i < $numEntries; $i++) {
| InternalRow $entry = $childVariable.getStruct($i, 2);
| $nullKeyCheck
| ${keyAssignment(CodeGenerator.getValue(entry, dataType.keyType, "0"), i)}
| ${valueAssignment(entry, i)}
|}
""".stripMargin
}
private def genCodeForPrimitiveElements(
ctx: CodegenContext,
childVariable: String,
mapData: String,
numEntries: String): String = {
val byteArraySize = ctx.freshName("byteArraySize")
val keySectionSize = ctx.freshName("keySectionSize")
val valueSectionSize = ctx.freshName("valueSectionSize")
val data = ctx.freshName("byteArray")
val unsafeMapData = ctx.freshName("unsafeMapData")
val keyArrayData = ctx.freshName("keyArrayData")
val valueArrayData = ctx.freshName("valueArrayData")
val baseOffset = Platform.BYTE_ARRAY_OFFSET
val keySize = dataType.keyType.defaultSize
val valueSize = dataType.valueType.defaultSize
val kByteSize = s"UnsafeArrayData.calculateSizeOfUnderlyingByteArray($numEntries, $keySize)"
val vByteSize = s"UnsafeArrayData.calculateSizeOfUnderlyingByteArray($numEntries, $valueSize)"
val keyTypeName = CodeGenerator.primitiveTypeName(dataType.keyType)
val valueTypeName = CodeGenerator.primitiveTypeName(dataType.valueType)
val keyAssignment = (key: String, idx: String) => s"$keyArrayData.set$keyTypeName($idx, $key);"
val valueAssignment = (entry: String, idx: String) => {
val value = CodeGenerator.getValue(entry, dataType.valueType, "1")
val valueNullUnsafeAssignment = s"$valueArrayData.set$valueTypeName($idx, $value);"
if (dataType.valueContainsNull) {
s"""
|if ($entry.isNullAt(1)) {
| $valueArrayData.setNullAt($idx);
|} else {
| $valueNullUnsafeAssignment
|}
""".stripMargin
} else {
valueNullUnsafeAssignment
}
}
val assignmentLoop = genCodeForAssignmentLoop(
ctx,
childVariable,
mapData,
numEntries,
keyAssignment,
valueAssignment
)
s"""
|final long $keySectionSize = $kByteSize;
|final long $valueSectionSize = $vByteSize;
|final long $byteArraySize = 8 + $keySectionSize + $valueSectionSize;
|if ($byteArraySize > ${ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH}) {
| ${genCodeForAnyElements(ctx, childVariable, mapData, numEntries)}
|} else {
| final byte[] $data = new byte[(int)$byteArraySize];
| UnsafeMapData $unsafeMapData = new UnsafeMapData();
| Platform.putLong($data, $baseOffset, $keySectionSize);
| Platform.putLong($data, ${baseOffset + 8}, $numEntries);
| Platform.putLong($data, ${baseOffset + 8} + $keySectionSize, $numEntries);
| $unsafeMapData.pointTo($data, $baseOffset, (int)$byteArraySize);
| ArrayData $keyArrayData = $unsafeMapData.keyArray();
| ArrayData $valueArrayData = $unsafeMapData.valueArray();
| $assignmentLoop
| $mapData = $unsafeMapData;
|}
""".stripMargin
}
private def genCodeForAnyElements(
ctx: CodegenContext,
childVariable: String,
mapData: String,
numEntries: String): String = {
val keys = ctx.freshName("keys")
val values = ctx.freshName("values")
val mapDataClass = classOf[ArrayBasedMapData].getName()
val isValuePrimitive = CodeGenerator.isPrimitiveType(dataType.valueType)
val valueAssignment = (entry: String, idx: String) => {
val value = CodeGenerator.getValue(entry, dataType.valueType, "1")
if (dataType.valueContainsNull && isValuePrimitive) {
s"$values[$idx] = $entry.isNullAt(1) ? null : (Object)$value;"
} else {
s"$values[$idx] = $value;"
}
}
val keyAssignment = (key: String, idx: String) => s"$keys[$idx] = $key;"
val assignmentLoop = genCodeForAssignmentLoop(
ctx,
childVariable,
mapData,
numEntries,
keyAssignment,
valueAssignment)
s"""
|final Object[] $keys = new Object[$numEntries];
|final Object[] $values = new Object[$numEntries];
|$assignmentLoop
|$mapData = $mapDataClass.apply($keys, $values);
""".stripMargin
}
override def prettyName: String = "map_from_entries"
}
/**
* Common base class for [[SortArray]] and [[ArraySort]].
*/
trait ArraySortLike extends ExpectsInputTypes {
protected def arrayExpression: Expression
protected def nullOrder: NullOrder
@transient
private lazy val lt: Comparator[Any] = {
val ordering = arrayExpression.dataType match {
case _ @ ArrayType(n: AtomicType, _) => n.ordering.asInstanceOf[Ordering[Any]]
case _ @ ArrayType(a: ArrayType, _) => a.interpretedOrdering.asInstanceOf[Ordering[Any]]
case _ @ ArrayType(s: StructType, _) => s.interpretedOrdering.asInstanceOf[Ordering[Any]]
}
new Comparator[Any]() {
override def compare(o1: Any, o2: Any): Int = {
if (o1 == null && o2 == null) {
0
} else if (o1 == null) {
nullOrder
} else if (o2 == null) {
-nullOrder
} else {
ordering.compare(o1, o2)
}
}
}
}
@transient
private lazy val gt: Comparator[Any] = {
val ordering = arrayExpression.dataType match {
case _ @ ArrayType(n: AtomicType, _) => n.ordering.asInstanceOf[Ordering[Any]]
case _ @ ArrayType(a: ArrayType, _) => a.interpretedOrdering.asInstanceOf[Ordering[Any]]
case _ @ ArrayType(s: StructType, _) => s.interpretedOrdering.asInstanceOf[Ordering[Any]]
}
new Comparator[Any]() {
override def compare(o1: Any, o2: Any): Int = {
if (o1 == null && o2 == null) {
0
} else if (o1 == null) {
-nullOrder
} else if (o2 == null) {
nullOrder
} else {
-ordering.compare(o1, o2)
}
}
}
}
def elementType: DataType = arrayExpression.dataType.asInstanceOf[ArrayType].elementType
def containsNull: Boolean = arrayExpression.dataType.asInstanceOf[ArrayType].containsNull
def sortEval(array: Any, ascending: Boolean): Any = {
val data = array.asInstanceOf[ArrayData].toArray[AnyRef](elementType)
if (elementType != NullType) {
java.util.Arrays.sort(data, if (ascending) lt else gt)
}
new GenericArrayData(data.asInstanceOf[Array[Any]])
}
def sortCodegen(ctx: CodegenContext, ev: ExprCode, base: String, order: String): String = {
val arrayData = classOf[ArrayData].getName
val genericArrayData = classOf[GenericArrayData].getName
val unsafeArrayData = classOf[UnsafeArrayData].getName
val array = ctx.freshName("array")
val c = ctx.freshName("c")
if (elementType == NullType) {
s"${ev.value} = $base.copy();"
} else {
val elementTypeTerm = ctx.addReferenceObj("elementTypeTerm", elementType)
val sortOrder = ctx.freshName("sortOrder")
val o1 = ctx.freshName("o1")
val o2 = ctx.freshName("o2")
val jt = CodeGenerator.javaType(elementType)
val comp = if (CodeGenerator.isPrimitiveType(elementType)) {
val bt = CodeGenerator.boxedType(elementType)
val v1 = ctx.freshName("v1")
val v2 = ctx.freshName("v2")
s"""
|$jt $v1 = (($bt) $o1).${jt}Value();
|$jt $v2 = (($bt) $o2).${jt}Value();
|int $c = ${ctx.genComp(elementType, v1, v2)};
""".stripMargin
} else {
s"int $c = ${ctx.genComp(elementType, s"(($jt) $o1)", s"(($jt) $o2)")};"
}
val nonNullPrimitiveAscendingSort =
if (CodeGenerator.isPrimitiveType(elementType) && !containsNull) {
val javaType = CodeGenerator.javaType(elementType)
val primitiveTypeName = CodeGenerator.primitiveTypeName(elementType)
s"""
|if ($order) {
| $javaType[] $array = $base.to${primitiveTypeName}Array();
| java.util.Arrays.sort($array);
| ${ev.value} = $unsafeArrayData.fromPrimitiveArray($array);
|} else
""".stripMargin
} else {
""
}
s"""
|$nonNullPrimitiveAscendingSort
|{
| Object[] $array = $base.toObjectArray($elementTypeTerm);
| final int $sortOrder = $order ? 1 : -1;
| java.util.Arrays.sort($array, new java.util.Comparator() {
| @Override public int compare(Object $o1, Object $o2) {
| if ($o1 == null && $o2 == null) {
| return 0;
| } else if ($o1 == null) {
| return $sortOrder * $nullOrder;
| } else if ($o2 == null) {
| return -$sortOrder * $nullOrder;
| }
| $comp
| return $sortOrder * $c;
| }
| });
| ${ev.value} = new $genericArrayData($array);
|}
""".stripMargin
}
}
}
object ArraySortLike {
type NullOrder = Int
// Least: place null element at the first of the array for ascending order
// Greatest: place null element at the end of the array for ascending order
object NullOrder {
val Least: NullOrder = -1
val Greatest: NullOrder = 1
}
}
/**
* Sorts the input array in ascending / descending order according to the natural ordering of
* the array elements and returns it.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = """
_FUNC_(array[, ascendingOrder]) - Sorts the input array in ascending or descending order
according to the natural ordering of the array elements. Null elements will be placed
at the beginning of the returned array in ascending order or at the end of the returned
array in descending order.
""",
examples = """
Examples:
> SELECT _FUNC_(array('b', 'd', null, 'c', 'a'), true);
[null,"a","b","c","d"]
""")
// scalastyle:on line.size.limit
case class SortArray(base: Expression, ascendingOrder: Expression)
extends BinaryExpression with ArraySortLike {
def this(e: Expression) = this(e, Literal(true))
override def left: Expression = base
override def right: Expression = ascendingOrder
override def dataType: DataType = base.dataType
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType, BooleanType)
override def arrayExpression: Expression = base
override def nullOrder: NullOrder = NullOrder.Least
override def checkInputDataTypes(): TypeCheckResult = base.dataType match {
case ArrayType(dt, _) if RowOrdering.isOrderable(dt) =>
ascendingOrder match {
case Literal(_: Boolean, BooleanType) =>
TypeCheckResult.TypeCheckSuccess
case _ =>
TypeCheckResult.TypeCheckFailure(
"Sort order in second argument requires a boolean literal.")
}
case ArrayType(dt, _) =>
val dtSimple = dt.simpleString
TypeCheckResult.TypeCheckFailure(
s"$prettyName does not support sorting array of type $dtSimple which is not orderable")
case _ =>
TypeCheckResult.TypeCheckFailure(s"$prettyName only supports array input.")
}
override def nullSafeEval(array: Any, ascending: Any): Any = {
sortEval(array, ascending.asInstanceOf[Boolean])
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (b, order) => sortCodegen(ctx, ev, b, order))
}
override def prettyName: String = "sort_array"
}
/**
* Sorts the input array in ascending order according to the natural ordering of
* the array elements and returns it.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = """
_FUNC_(array) - Sorts the input array in ascending order. The elements of the input array must
be orderable. Null elements will be placed at the end of the returned array.
""",
examples = """
Examples:
> SELECT _FUNC_(array('b', 'd', null, 'c', 'a'));
["a","b","c","d",null]
""",
since = "2.4.0")
// scalastyle:on line.size.limit
case class ArraySort(child: Expression) extends UnaryExpression with ArraySortLike {
override def dataType: DataType = child.dataType
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType)
override def arrayExpression: Expression = child
override def nullOrder: NullOrder = NullOrder.Greatest
override def checkInputDataTypes(): TypeCheckResult = child.dataType match {
case ArrayType(dt, _) if RowOrdering.isOrderable(dt) =>
TypeCheckResult.TypeCheckSuccess
case ArrayType(dt, _) =>
val dtSimple = dt.simpleString
TypeCheckResult.TypeCheckFailure(
s"$prettyName does not support sorting array of type $dtSimple which is not orderable")
case _ =>
TypeCheckResult.TypeCheckFailure(s"$prettyName only supports array input.")
}
override def nullSafeEval(array: Any): Any = {
sortEval(array, true)
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => sortCodegen(ctx, ev, c, "true"))
}
override def prettyName: String = "array_sort"
}
/**
* Returns a reversed string or an array with reverse order of elements.
*/
@ExpressionDescription(
usage = "_FUNC_(array) - Returns a reversed string or an array with reverse order of elements.",
examples = """
Examples:
> SELECT _FUNC_('Spark SQL');
LQS krapS
> SELECT _FUNC_(array(2, 1, 4, 3));
[3, 4, 1, 2]
""",
since = "1.5.0",
note = "Reverse logic for arrays is available since 2.4.0."
)
case class Reverse(child: Expression) extends UnaryExpression with ImplicitCastInputTypes {
// Input types are utilized by type coercion in ImplicitTypeCasts.
override def inputTypes: Seq[AbstractDataType] = Seq(TypeCollection(StringType, ArrayType))
override def dataType: DataType = child.dataType
lazy val elementType: DataType = dataType.asInstanceOf[ArrayType].elementType
override def nullSafeEval(input: Any): Any = input match {
case a: ArrayData => new GenericArrayData(a.toObjectArray(elementType).reverse)
case s: UTF8String => s.reverse()
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => dataType match {
case _: StringType => stringCodeGen(ev, c)
case _: ArrayType => arrayCodeGen(ctx, ev, c)
})
}
private def stringCodeGen(ev: ExprCode, childName: String): String = {
s"${ev.value} = ($childName).reverse();"
}
private def arrayCodeGen(ctx: CodegenContext, ev: ExprCode, childName: String): String = {
val length = ctx.freshName("length")
val javaElementType = CodeGenerator.javaType(elementType)
val isPrimitiveType = CodeGenerator.isPrimitiveType(elementType)
val initialization = if (isPrimitiveType) {
s"$childName.copy()"
} else {
s"new ${classOf[GenericArrayData].getName()}(new Object[$length])"
}
val numberOfIterations = if (isPrimitiveType) s"$length / 2" else length
val swapAssigments = if (isPrimitiveType) {
val setFunc = "set" + CodeGenerator.primitiveTypeName(elementType)
val getCall = (index: String) => CodeGenerator.getValue(ev.value, elementType, index)
s"""|boolean isNullAtK = ${ev.value}.isNullAt(k);
|boolean isNullAtL = ${ev.value}.isNullAt(l);
|if(!isNullAtK) {
| $javaElementType el = ${getCall("k")};
| if(!isNullAtL) {
| ${ev.value}.$setFunc(k, ${getCall("l")});
| } else {
| ${ev.value}.setNullAt(k);
| }
| ${ev.value}.$setFunc(l, el);
|} else if (!isNullAtL) {
| ${ev.value}.$setFunc(k, ${getCall("l")});
| ${ev.value}.setNullAt(l);
|}""".stripMargin
} else {
s"${ev.value}.update(k, ${CodeGenerator.getValue(childName, elementType, "l")});"
}
s"""
|final int $length = $childName.numElements();
|${ev.value} = $initialization;
|for(int k = 0; k < $numberOfIterations; k++) {
| int l = $length - k - 1;
| $swapAssigments
|}
""".stripMargin
}
override def prettyName: String = "reverse"
}
/**
* Checks if the array (left) has the element (right)
*/
@ExpressionDescription(
usage = "_FUNC_(array, value) - Returns true if the array contains the value.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3), 2);
true
""")
case class ArrayContains(left: Expression, right: Expression)
extends BinaryExpression with ImplicitCastInputTypes {
override def dataType: DataType = BooleanType
@transient private lazy val ordering: Ordering[Any] =
TypeUtils.getInterpretedOrdering(right.dataType)
override def inputTypes: Seq[AbstractDataType] = right.dataType match {
case NullType => Seq.empty
case _ => left.dataType match {
case n @ ArrayType(element, _) => Seq(n, element)
case _ => Seq.empty
}
}
override def checkInputDataTypes(): TypeCheckResult = {
if (right.dataType == NullType) {
TypeCheckResult.TypeCheckFailure("Null typed values cannot be used as arguments")
} else if (!left.dataType.isInstanceOf[ArrayType]
|| left.dataType.asInstanceOf[ArrayType].elementType != right.dataType) {
TypeCheckResult.TypeCheckFailure(
"Arguments must be an array followed by a value of same type as the array members")
} else {
TypeUtils.checkForOrderingExpr(right.dataType, s"function $prettyName")
}
}
override def nullable: Boolean = {
left.nullable || right.nullable || left.dataType.asInstanceOf[ArrayType].containsNull
}
override def nullSafeEval(arr: Any, value: Any): Any = {
var hasNull = false
arr.asInstanceOf[ArrayData].foreach(right.dataType, (i, v) =>
if (v == null) {
hasNull = true
} else if (ordering.equiv(v, value)) {
return true
}
)
if (hasNull) {
null
} else {
false
}
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (arr, value) => {
val i = ctx.freshName("i")
val getValue = CodeGenerator.getValue(arr, right.dataType, i)
s"""
for (int $i = 0; $i < $arr.numElements(); $i ++) {
if ($arr.isNullAt($i)) {
${ev.isNull} = true;
} else if (${ctx.genEqual(right.dataType, value, getValue)}) {
${ev.isNull} = false;
${ev.value} = true;
break;
}
}
"""
})
}
override def prettyName: String = "array_contains"
}
/**
* Checks if the two arrays contain at least one common element.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(a1, a2) - Returns true if a1 contains at least a non-null element present also in a2. If the arrays have no common element and they are both non-empty and either of them contains a null element null is returned, false otherwise.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3), array(3, 4, 5));
true
""", since = "2.4.0")
// scalastyle:off line.size.limit
case class ArraysOverlap(left: Expression, right: Expression)
extends BinaryArrayExpressionWithImplicitCast {
override def checkInputDataTypes(): TypeCheckResult = super.checkInputDataTypes() match {
case TypeCheckResult.TypeCheckSuccess =>
TypeUtils.checkForOrderingExpr(elementType, s"function $prettyName")
case failure => failure
}
@transient private lazy val ordering: Ordering[Any] =
TypeUtils.getInterpretedOrdering(elementType)
@transient private lazy val elementTypeSupportEquals = elementType match {
case BinaryType => false
case _: AtomicType => true
case _ => false
}
@transient private lazy val doEvaluation = if (elementTypeSupportEquals) {
fastEval _
} else {
bruteForceEval _
}
override def dataType: DataType = BooleanType
override def nullable: Boolean = {
left.nullable || right.nullable || left.dataType.asInstanceOf[ArrayType].containsNull ||
right.dataType.asInstanceOf[ArrayType].containsNull
}
override def nullSafeEval(a1: Any, a2: Any): Any = {
doEvaluation(a1.asInstanceOf[ArrayData], a2.asInstanceOf[ArrayData])
}
/**
* A fast implementation which puts all the elements from the smaller array in a set
* and then performs a lookup on it for each element of the bigger one.
* This eval mode works only for data types which implements properly the equals method.
*/
private def fastEval(arr1: ArrayData, arr2: ArrayData): Any = {
var hasNull = false
val (bigger, smaller) = if (arr1.numElements() > arr2.numElements()) {
(arr1, arr2)
} else {
(arr2, arr1)
}
if (smaller.numElements() > 0) {
val smallestSet = new mutable.HashSet[Any]
smaller.foreach(elementType, (_, v) =>
if (v == null) {
hasNull = true
} else {
smallestSet += v
})
bigger.foreach(elementType, (_, v1) =>
if (v1 == null) {
hasNull = true
} else if (smallestSet.contains(v1)) {
return true
}
)
}
if (hasNull) {
null
} else {
false
}
}
/**
* A slower evaluation which performs a nested loop and supports all the data types.
*/
private def bruteForceEval(arr1: ArrayData, arr2: ArrayData): Any = {
var hasNull = false
if (arr1.numElements() > 0 && arr2.numElements() > 0) {
arr1.foreach(elementType, (_, v1) =>
if (v1 == null) {
hasNull = true
} else {
arr2.foreach(elementType, (_, v2) =>
if (v2 == null) {
hasNull = true
} else if (ordering.equiv(v1, v2)) {
return true
}
)
})
}
if (hasNull) {
null
} else {
false
}
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (a1, a2) => {
val smaller = ctx.freshName("smallerArray")
val bigger = ctx.freshName("biggerArray")
val comparisonCode = if (elementTypeSupportEquals) {
fastCodegen(ctx, ev, smaller, bigger)
} else {
bruteForceCodegen(ctx, ev, smaller, bigger)
}
s"""
|ArrayData $smaller;
|ArrayData $bigger;
|if ($a1.numElements() > $a2.numElements()) {
| $bigger = $a1;
| $smaller = $a2;
|} else {
| $smaller = $a1;
| $bigger = $a2;
|}
|if ($smaller.numElements() > 0) {
| $comparisonCode
|}
""".stripMargin
})
}
/**
* Code generation for a fast implementation which puts all the elements from the smaller array
* in a set and then performs a lookup on it for each element of the bigger one.
* It works only for data types which implements properly the equals method.
*/
private def fastCodegen(ctx: CodegenContext, ev: ExprCode, smaller: String, bigger: String): String = {
val i = ctx.freshName("i")
val getFromSmaller = CodeGenerator.getValue(smaller, elementType, i)
val getFromBigger = CodeGenerator.getValue(bigger, elementType, i)
val javaElementClass = CodeGenerator.boxedType(elementType)
val javaSet = classOf[java.util.HashSet[_]].getName
val set = ctx.freshName("set")
val addToSetFromSmallerCode = nullSafeElementCodegen(
smaller, i, s"$set.add($getFromSmaller);", s"${ev.isNull} = true;")
val elementIsInSetCode = nullSafeElementCodegen(
bigger,
i,
s"""
|if ($set.contains($getFromBigger)) {
| ${ev.isNull} = false;
| ${ev.value} = true;
| break;
|}
""".stripMargin,
s"${ev.isNull} = true;")
s"""
|$javaSet<$javaElementClass> $set = new $javaSet<$javaElementClass>();
|for (int $i = 0; $i < $smaller.numElements(); $i ++) {
| $addToSetFromSmallerCode
|}
|for (int $i = 0; $i < $bigger.numElements(); $i ++) {
| $elementIsInSetCode
|}
""".stripMargin
}
/**
* Code generation for a slower evaluation which performs a nested loop and supports all the data types.
*/
private def bruteForceCodegen(ctx: CodegenContext, ev: ExprCode, smaller: String, bigger: String): String = {
val i = ctx.freshName("i")
val j = ctx.freshName("j")
val getFromSmaller = CodeGenerator.getValue(smaller, elementType, j)
val getFromBigger = CodeGenerator.getValue(bigger, elementType, i)
val compareValues = nullSafeElementCodegen(
smaller,
j,
s"""
|if (${ctx.genEqual(elementType, getFromSmaller, getFromBigger)}) {
| ${ev.isNull} = false;
| ${ev.value} = true;
|}
""".stripMargin,
s"${ev.isNull} = true;")
val isInSmaller = nullSafeElementCodegen(
bigger,
i,
s"""
|for (int $j = 0; $j < $smaller.numElements() && !${ev.value}; $j ++) {
| $compareValues
|}
""".stripMargin,
s"${ev.isNull} = true;")
s"""
|for (int $i = 0; $i < $bigger.numElements() && !${ev.value}; $i ++) {
| $isInSmaller
|}
""".stripMargin
}
def nullSafeElementCodegen(
arrayVar: String,
index: String,
code: String,
isNullCode: String): String = {
if (inputTypes.exists(_.asInstanceOf[ArrayType].containsNull)) {
s"""
|if ($arrayVar.isNullAt($index)) {
| $isNullCode
|} else {
| $code
|}
""".stripMargin
} else {
code
}
}
override def prettyName: String = "arrays_overlap"
}
/**
* Slices an array according to the requested start index and length
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(x, start, length) - Subsets array x starting from index start (or starting from the end if start is negative) with the specified length.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3, 4), 2, 2);
[2,3]
> SELECT _FUNC_(array(1, 2, 3, 4), -2, 2);
[3,4]
""", since = "2.4.0")
// scalastyle:on line.size.limit
case class Slice(x: Expression, start: Expression, length: Expression)
extends TernaryExpression with ImplicitCastInputTypes {
override def dataType: DataType = x.dataType
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType, IntegerType, IntegerType)
override def children: Seq[Expression] = Seq(x, start, length)
lazy val elementType: DataType = x.dataType.asInstanceOf[ArrayType].elementType
override def nullSafeEval(xVal: Any, startVal: Any, lengthVal: Any): Any = {
val startInt = startVal.asInstanceOf[Int]
val lengthInt = lengthVal.asInstanceOf[Int]
val arr = xVal.asInstanceOf[ArrayData]
val startIndex = if (startInt == 0) {
throw new RuntimeException(
s"Unexpected value for start in function $prettyName: SQL array indices start at 1.")
} else if (startInt < 0) {
startInt + arr.numElements()
} else {
startInt - 1
}
if (lengthInt < 0) {
throw new RuntimeException(s"Unexpected value for length in function $prettyName: " +
"length must be greater than or equal to 0.")
}
// startIndex can be negative if start is negative and its absolute value is greater than the
// number of elements in the array
if (startIndex < 0 || startIndex >= arr.numElements()) {
return new GenericArrayData(Array.empty[AnyRef])
}
val data = arr.toSeq[AnyRef](elementType)
new GenericArrayData(data.slice(startIndex, startIndex + lengthInt))
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (x, start, length) => {
val startIdx = ctx.freshName("startIdx")
val resLength = ctx.freshName("resLength")
val defaultIntValue = CodeGenerator.defaultValue(CodeGenerator.JAVA_INT, false)
s"""
|${CodeGenerator.JAVA_INT} $startIdx = $defaultIntValue;
|${CodeGenerator.JAVA_INT} $resLength = $defaultIntValue;
|if ($start == 0) {
| throw new RuntimeException("Unexpected value for start in function $prettyName: "
| + "SQL array indices start at 1.");
|} else if ($start < 0) {
| $startIdx = $start + $x.numElements();
|} else {
| // arrays in SQL are 1-based instead of 0-based
| $startIdx = $start - 1;
|}
|if ($length < 0) {
| throw new RuntimeException("Unexpected value for length in function $prettyName: "
| + "length must be greater than or equal to 0.");
|} else if ($length > $x.numElements() - $startIdx) {
| $resLength = $x.numElements() - $startIdx;
|} else {
| $resLength = $length;
|}
|${genCodeForResult(ctx, ev, x, startIdx, resLength)}
""".stripMargin
})
}
def genCodeForResult(
ctx: CodegenContext,
ev: ExprCode,
inputArray: String,
startIdx: String,
resLength: String): String = {
val values = ctx.freshName("values")
val i = ctx.freshName("i")
val getValue = CodeGenerator.getValue(inputArray, elementType, s"$i + $startIdx")
if (!CodeGenerator.isPrimitiveType(elementType)) {
val arrayClass = classOf[GenericArrayData].getName
s"""
|Object[] $values;
|if ($startIdx < 0 || $startIdx >= $inputArray.numElements()) {
| $values = new Object[0];
|} else {
| $values = new Object[$resLength];
| for (int $i = 0; $i < $resLength; $i ++) {
| $values[$i] = $getValue;
| }
|}
|${ev.value} = new $arrayClass($values);
""".stripMargin
} else {
val primitiveValueTypeName = CodeGenerator.primitiveTypeName(elementType)
s"""
|if ($startIdx < 0 || $startIdx >= $inputArray.numElements()) {
| $resLength = 0;
|}
|${ctx.createUnsafeArray(values, resLength, elementType, s" $prettyName failed.")}
|for (int $i = 0; $i < $resLength; $i ++) {
| if ($inputArray.isNullAt($i + $startIdx)) {
| $values.setNullAt($i);
| } else {
| $values.set$primitiveValueTypeName($i, $getValue);
| }
|}
|${ev.value} = $values;
""".stripMargin
}
}
}
/**
* Creates a String containing all the elements of the input array separated by the delimiter.
*/
@ExpressionDescription(
usage = """
_FUNC_(array, delimiter[, nullReplacement]) - Concatenates the elements of the given array
using the delimiter and an optional string to replace nulls. If no value is set for
nullReplacement, any null value is filtered.""",
examples = """
Examples:
> SELECT _FUNC_(array('hello', 'world'), ' ');
hello world
> SELECT _FUNC_(array('hello', null ,'world'), ' ');
hello world
> SELECT _FUNC_(array('hello', null ,'world'), ' ', ',');
hello , world
""", since = "2.4.0")
case class ArrayJoin(
array: Expression,
delimiter: Expression,
nullReplacement: Option[Expression]) extends Expression with ExpectsInputTypes {
def this(array: Expression, delimiter: Expression) = this(array, delimiter, None)
def this(array: Expression, delimiter: Expression, nullReplacement: Expression) =
this(array, delimiter, Some(nullReplacement))
override def inputTypes: Seq[AbstractDataType] = if (nullReplacement.isDefined) {
Seq(ArrayType(StringType), StringType, StringType)
} else {
Seq(ArrayType(StringType), StringType)
}
override def children: Seq[Expression] = if (nullReplacement.isDefined) {
Seq(array, delimiter, nullReplacement.get)
} else {
Seq(array, delimiter)
}
override def nullable: Boolean = children.exists(_.nullable)
override def foldable: Boolean = children.forall(_.foldable)
override def eval(input: InternalRow): Any = {
val arrayEval = array.eval(input)
if (arrayEval == null) return null
val delimiterEval = delimiter.eval(input)
if (delimiterEval == null) return null
val nullReplacementEval = nullReplacement.map(_.eval(input))
if (nullReplacementEval.contains(null)) return null
val buffer = new UTF8StringBuilder()
var firstItem = true
val nullHandling = nullReplacementEval match {
case Some(rep) => (prependDelimiter: Boolean) => {
if (!prependDelimiter) {
buffer.append(delimiterEval.asInstanceOf[UTF8String])
}
buffer.append(rep.asInstanceOf[UTF8String])
true
}
case None => (_: Boolean) => false
}
arrayEval.asInstanceOf[ArrayData].foreach(StringType, (_, item) => {
if (item == null) {
if (nullHandling(firstItem)) {
firstItem = false
}
} else {
if (!firstItem) {
buffer.append(delimiterEval.asInstanceOf[UTF8String])
}
buffer.append(item.asInstanceOf[UTF8String])
firstItem = false
}
})
buffer.build()
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val code = nullReplacement match {
case Some(replacement) =>
val replacementGen = replacement.genCode(ctx)
val nullHandling = (buffer: String, delimiter: String, firstItem: String) => {
s"""
|if (!$firstItem) {
| $buffer.append($delimiter);
|}
|$buffer.append(${replacementGen.value});
|$firstItem = false;
""".stripMargin
}
val execCode = if (replacement.nullable) {
ctx.nullSafeExec(replacement.nullable, replacementGen.isNull) {
genCodeForArrayAndDelimiter(ctx, ev, nullHandling)
}
} else {
genCodeForArrayAndDelimiter(ctx, ev, nullHandling)
}
s"""
|${replacementGen.code}
|$execCode
""".stripMargin
case None => genCodeForArrayAndDelimiter(ctx, ev,
(_: String, _: String, _: String) => "// nulls are ignored")
}
if (nullable) {
ev.copy(
code"""
|boolean ${ev.isNull} = true;
|UTF8String ${ev.value} = null;
|$code
""".stripMargin)
} else {
ev.copy(
code"""
|UTF8String ${ev.value} = null;
|$code
""".stripMargin, FalseLiteral)
}
}
private def genCodeForArrayAndDelimiter(
ctx: CodegenContext,
ev: ExprCode,
nullEval: (String, String, String) => String): String = {
val arrayGen = array.genCode(ctx)
val delimiterGen = delimiter.genCode(ctx)
val buffer = ctx.freshName("buffer")
val bufferClass = classOf[UTF8StringBuilder].getName
val i = ctx.freshName("i")
val firstItem = ctx.freshName("firstItem")
val resultCode =
s"""
|$bufferClass $buffer = new $bufferClass();
|boolean $firstItem = true;
|for (int $i = 0; $i < ${arrayGen.value}.numElements(); $i ++) {
| if (${arrayGen.value}.isNullAt($i)) {
| ${nullEval(buffer, delimiterGen.value, firstItem)}
| } else {
| if (!$firstItem) {
| $buffer.append(${delimiterGen.value});
| }
| $buffer.append(${CodeGenerator.getValue(arrayGen.value, StringType, i)});
| $firstItem = false;
| }
|}
|${ev.value} = $buffer.build();""".stripMargin
if (array.nullable || delimiter.nullable) {
arrayGen.code + ctx.nullSafeExec(array.nullable, arrayGen.isNull) {
delimiterGen.code + ctx.nullSafeExec(delimiter.nullable, delimiterGen.isNull) {
s"""
|${ev.isNull} = false;
|$resultCode""".stripMargin
}
}
} else {
s"""
|${arrayGen.code}
|${delimiterGen.code}
|$resultCode""".stripMargin
}
}
override def dataType: DataType = StringType
override def prettyName: String = "array_join"
}
/**
* Returns the minimum value in the array.
*/
@ExpressionDescription(
usage = "_FUNC_(array) - Returns the minimum value in the array. NULL elements are skipped.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 20, null, 3));
1
""", since = "2.4.0")
case class ArrayMin(child: Expression) extends UnaryExpression with ImplicitCastInputTypes {
override def nullable: Boolean = true
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType)
private lazy val ordering = TypeUtils.getInterpretedOrdering(dataType)
override def checkInputDataTypes(): TypeCheckResult = {
val typeCheckResult = super.checkInputDataTypes()
if (typeCheckResult.isSuccess) {
TypeUtils.checkForOrderingExpr(dataType, s"function $prettyName")
} else {
typeCheckResult
}
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val childGen = child.genCode(ctx)
val javaType = CodeGenerator.javaType(dataType)
val i = ctx.freshName("i")
val item = ExprCode(EmptyBlock,
isNull = JavaCode.isNullExpression(s"${childGen.value}.isNullAt($i)"),
value = JavaCode.expression(CodeGenerator.getValue(childGen.value, dataType, i), dataType))
ev.copy(code =
code"""
|${childGen.code}
|boolean ${ev.isNull} = true;
|$javaType ${ev.value} = ${CodeGenerator.defaultValue(dataType)};
|if (!${childGen.isNull}) {
| for (int $i = 0; $i < ${childGen.value}.numElements(); $i ++) {
| ${ctx.reassignIfSmaller(dataType, ev, item)}
| }
|}
""".stripMargin)
}
override protected def nullSafeEval(input: Any): Any = {
var min: Any = null
input.asInstanceOf[ArrayData].foreach(dataType, (_, item) =>
if (item != null && (min == null || ordering.lt(item, min))) {
min = item
}
)
min
}
override def dataType: DataType = child.dataType match {
case ArrayType(dt, _) => dt
case _ => throw new IllegalStateException(s"$prettyName accepts only arrays.")
}
override def prettyName: String = "array_min"
}
/**
* Returns the maximum value in the array.
*/
@ExpressionDescription(
usage = "_FUNC_(array) - Returns the maximum value in the array. NULL elements are skipped.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 20, null, 3));
20
""", since = "2.4.0")
case class ArrayMax(child: Expression) extends UnaryExpression with ImplicitCastInputTypes {
override def nullable: Boolean = true
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType)
private lazy val ordering = TypeUtils.getInterpretedOrdering(dataType)
override def checkInputDataTypes(): TypeCheckResult = {
val typeCheckResult = super.checkInputDataTypes()
if (typeCheckResult.isSuccess) {
TypeUtils.checkForOrderingExpr(dataType, s"function $prettyName")
} else {
typeCheckResult
}
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val childGen = child.genCode(ctx)
val javaType = CodeGenerator.javaType(dataType)
val i = ctx.freshName("i")
val item = ExprCode(EmptyBlock,
isNull = JavaCode.isNullExpression(s"${childGen.value}.isNullAt($i)"),
value = JavaCode.expression(CodeGenerator.getValue(childGen.value, dataType, i), dataType))
ev.copy(code =
code"""
|${childGen.code}
|boolean ${ev.isNull} = true;
|$javaType ${ev.value} = ${CodeGenerator.defaultValue(dataType)};
|if (!${childGen.isNull}) {
| for (int $i = 0; $i < ${childGen.value}.numElements(); $i ++) {
| ${ctx.reassignIfGreater(dataType, ev, item)}
| }
|}
""".stripMargin)
}
override protected def nullSafeEval(input: Any): Any = {
var max: Any = null
input.asInstanceOf[ArrayData].foreach(dataType, (_, item) =>
if (item != null && (max == null || ordering.gt(item, max))) {
max = item
}
)
max
}
override def dataType: DataType = child.dataType match {
case ArrayType(dt, _) => dt
case _ => throw new IllegalStateException(s"$prettyName accepts only arrays.")
}
override def prettyName: String = "array_max"
}
/**
* Returns the position of the first occurrence of element in the given array as long.
* Returns 0 if the given value could not be found in the array. Returns null if either of
* the arguments are null
*
* NOTE: that this is not zero based, but 1-based index. The first element in the array has
* index 1.
*/
@ExpressionDescription(
usage = """
_FUNC_(array, element) - Returns the (1-based) index of the first element of the array as long.
""",
examples = """
Examples:
> SELECT _FUNC_(array(3, 2, 1), 1);
3
""",
since = "2.4.0")
case class ArrayPosition(left: Expression, right: Expression)
extends BinaryExpression with ImplicitCastInputTypes {
@transient private lazy val ordering: Ordering[Any] =
TypeUtils.getInterpretedOrdering(right.dataType)
override def dataType: DataType = LongType
override def inputTypes: Seq[AbstractDataType] = {
val elementType = left.dataType match {
case t: ArrayType => t.elementType
case _ => AnyDataType
}
Seq(ArrayType, elementType)
}
override def checkInputDataTypes(): TypeCheckResult = {
super.checkInputDataTypes() match {
case f: TypeCheckResult.TypeCheckFailure => f
case TypeCheckResult.TypeCheckSuccess =>
TypeUtils.checkForOrderingExpr(right.dataType, s"function $prettyName")
}
}
override def nullSafeEval(arr: Any, value: Any): Any = {
arr.asInstanceOf[ArrayData].foreach(right.dataType, (i, v) =>
if (v != null && ordering.equiv(v, value)) {
return (i + 1).toLong
}
)
0L
}
override def prettyName: String = "array_position"
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (arr, value) => {
val pos = ctx.freshName("arrayPosition")
val i = ctx.freshName("i")
val getValue = CodeGenerator.getValue(arr, right.dataType, i)
s"""
|int $pos = 0;
|for (int $i = 0; $i < $arr.numElements(); $i ++) {
| if (!$arr.isNullAt($i) && ${ctx.genEqual(right.dataType, value, getValue)}) {
| $pos = $i + 1;
| break;
| }
|}
|${ev.value} = (long) $pos;
""".stripMargin
})
}
}
/**
* Returns the value of index `right` in Array `left` or the value for key `right` in Map `left`.
*/
@ExpressionDescription(
usage = """
_FUNC_(array, index) - Returns element of array at given (1-based) index. If index < 0,
accesses elements from the last to the first. Returns NULL if the index exceeds the length
of the array.
_FUNC_(map, key) - Returns value for given key, or NULL if the key is not contained in the map
""",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3), 2);
2
> SELECT _FUNC_(map(1, 'a', 2, 'b'), 2);
"b"
""",
since = "2.4.0")
case class ElementAt(left: Expression, right: Expression) extends GetMapValueUtil {
@transient private lazy val ordering: Ordering[Any] =
TypeUtils.getInterpretedOrdering(left.dataType.asInstanceOf[MapType].keyType)
override def dataType: DataType = left.dataType match {
case ArrayType(elementType, _) => elementType
case MapType(_, valueType, _) => valueType
}
override def inputTypes: Seq[AbstractDataType] = {
Seq(TypeCollection(ArrayType, MapType),
left.dataType match {
case _: ArrayType => IntegerType
case _: MapType => left.dataType.asInstanceOf[MapType].keyType
case _ => AnyDataType // no match for a wrong 'left' expression type
}
)
}
override def checkInputDataTypes(): TypeCheckResult = {
super.checkInputDataTypes() match {
case f: TypeCheckResult.TypeCheckFailure => f
case TypeCheckResult.TypeCheckSuccess if left.dataType.isInstanceOf[MapType] =>
TypeUtils.checkForOrderingExpr(
left.dataType.asInstanceOf[MapType].keyType, s"function $prettyName")
case TypeCheckResult.TypeCheckSuccess => TypeCheckResult.TypeCheckSuccess
}
}
override def nullable: Boolean = true
override def nullSafeEval(value: Any, ordinal: Any): Any = {
left.dataType match {
case _: ArrayType =>
val array = value.asInstanceOf[ArrayData]
val index = ordinal.asInstanceOf[Int]
if (array.numElements() < math.abs(index)) {
null
} else {
val idx = if (index == 0) {
throw new ArrayIndexOutOfBoundsException("SQL array indices start at 1")
} else if (index > 0) {
index - 1
} else {
array.numElements() + index
}
if (left.dataType.asInstanceOf[ArrayType].containsNull && array.isNullAt(idx)) {
null
} else {
array.get(idx, dataType)
}
}
case _: MapType =>
getValueEval(value, ordinal, left.dataType.asInstanceOf[MapType].keyType, ordering)
}
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
left.dataType match {
case _: ArrayType =>
nullSafeCodeGen(ctx, ev, (eval1, eval2) => {
val index = ctx.freshName("elementAtIndex")
val nullCheck = if (left.dataType.asInstanceOf[ArrayType].containsNull) {
s"""
|if ($eval1.isNullAt($index)) {
| ${ev.isNull} = true;
|} else
""".stripMargin
} else {
""
}
s"""
|int $index = (int) $eval2;
|if ($eval1.numElements() < Math.abs($index)) {
| ${ev.isNull} = true;
|} else {
| if ($index == 0) {
| throw new ArrayIndexOutOfBoundsException("SQL array indices start at 1");
| } else if ($index > 0) {
| $index--;
| } else {
| $index += $eval1.numElements();
| }
| $nullCheck
| {
| ${ev.value} = ${CodeGenerator.getValue(eval1, dataType, index)};
| }
|}
""".stripMargin
})
case _: MapType =>
doGetValueGenCode(ctx, ev, left.dataType.asInstanceOf[MapType])
}
}
override def prettyName: String = "element_at"
}
/**
* Concatenates multiple input columns together into a single column.
* The function works with strings, binary and compatible array columns.
*/
@ExpressionDescription(
usage = "_FUNC_(col1, col2, ..., colN) - Returns the concatenation of col1, col2, ..., colN.",
examples = """
Examples:
> SELECT _FUNC_('Spark', 'SQL');
SparkSQL
> SELECT _FUNC_(array(1, 2, 3), array(4, 5), array(6));
| [1,2,3,4,5,6]
""")
case class Concat(children: Seq[Expression]) extends Expression {
private val MAX_ARRAY_LENGTH: Int = ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH
val allowedTypes = Seq(StringType, BinaryType, ArrayType)
override def checkInputDataTypes(): TypeCheckResult = {
if (children.isEmpty) {
TypeCheckResult.TypeCheckSuccess
} else {
val childTypes = children.map(_.dataType)
if (childTypes.exists(tpe => !allowedTypes.exists(_.acceptsType(tpe)))) {
return TypeCheckResult.TypeCheckFailure(
s"input to function $prettyName should have been ${StringType.simpleString}," +
s" ${BinaryType.simpleString} or ${ArrayType.simpleString}, but it's " +
childTypes.map(_.simpleString).mkString("[", ", ", "]"))
}
TypeUtils.checkForSameTypeInputExpr(childTypes, s"function $prettyName")
}
}
override def dataType: DataType = children.map(_.dataType).headOption.getOrElse(StringType)
lazy val javaType: String = CodeGenerator.javaType(dataType)
override def nullable: Boolean = children.exists(_.nullable)
override def foldable: Boolean = children.forall(_.foldable)
override def eval(input: InternalRow): Any = dataType match {
case BinaryType =>
val inputs = children.map(_.eval(input).asInstanceOf[Array[Byte]])
ByteArray.concat(inputs: _*)
case StringType =>
val inputs = children.map(_.eval(input).asInstanceOf[UTF8String])
UTF8String.concat(inputs : _*)
case ArrayType(elementType, _) =>
val inputs = children.toStream.map(_.eval(input))
if (inputs.contains(null)) {
null
} else {
val arrayData = inputs.map(_.asInstanceOf[ArrayData])
val numberOfElements = arrayData.foldLeft(0L)((sum, ad) => sum + ad.numElements())
if (numberOfElements > MAX_ARRAY_LENGTH) {
throw new RuntimeException(s"Unsuccessful try to concat arrays with $numberOfElements" +
s" elements due to exceeding the array size limit $MAX_ARRAY_LENGTH.")
}
val finalData = new Array[AnyRef](numberOfElements.toInt)
var position = 0
for(ad <- arrayData) {
val arr = ad.toObjectArray(elementType)
Array.copy(arr, 0, finalData, position, arr.length)
position += arr.length
}
new GenericArrayData(finalData)
}
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val evals = children.map(_.genCode(ctx))
val args = ctx.freshName("args")
val inputs = evals.zipWithIndex.map { case (eval, index) =>
s"""
${eval.code}
if (!${eval.isNull}) {
$args[$index] = ${eval.value};
}
"""
}
val (concatenator, initCode) = dataType match {
case BinaryType =>
(classOf[ByteArray].getName, s"byte[][] $args = new byte[${evals.length}][];")
case StringType =>
("UTF8String", s"UTF8String[] $args = new UTF8String[${evals.length}];")
case ArrayType(elementType, _) =>
val arrayConcatClass = if (CodeGenerator.isPrimitiveType(elementType)) {
genCodeForPrimitiveArrays(ctx, elementType)
} else {
genCodeForNonPrimitiveArrays(ctx, elementType)
}
(arrayConcatClass, s"ArrayData[] $args = new ArrayData[${evals.length}];")
}
val codes = ctx.splitExpressionsWithCurrentInputs(
expressions = inputs,
funcName = "valueConcat",
extraArguments = (s"$javaType[]", args) :: Nil)
ev.copy(code"""
$initCode
$codes
$javaType ${ev.value} = $concatenator.concat($args);
boolean ${ev.isNull} = ${ev.value} == null;
""")
}
private def genCodeForNumberOfElements(ctx: CodegenContext) : (String, String) = {
val numElements = ctx.freshName("numElements")
val code = s"""
|long $numElements = 0L;
|for (int z = 0; z < ${children.length}; z++) {
| $numElements += args[z].numElements();
|}
|if ($numElements > $MAX_ARRAY_LENGTH) {
| throw new RuntimeException("Unsuccessful try to concat arrays with " + $numElements +
| " elements due to exceeding the array size limit $MAX_ARRAY_LENGTH.");
|}
""".stripMargin
(code, numElements)
}
private def nullArgumentProtection() : String = {
if (nullable) {
s"""
|for (int z = 0; z < ${children.length}; z++) {
| if (args[z] == null) return null;
|}
""".stripMargin
} else {
""
}
}
private def genCodeForPrimitiveArrays(ctx: CodegenContext, elementType: DataType): String = {
val counter = ctx.freshName("counter")
val arrayData = ctx.freshName("arrayData")
val (numElemCode, numElemName) = genCodeForNumberOfElements(ctx)
val primitiveValueTypeName = CodeGenerator.primitiveTypeName(elementType)
s"""
|new Object() {
| public ArrayData concat($javaType[] args) {
| ${nullArgumentProtection()}
| $numElemCode
| ${ctx.createUnsafeArray(arrayData, numElemName, elementType, s" $prettyName failed.")}
| int $counter = 0;
| for (int y = 0; y < ${children.length}; y++) {
| for (int z = 0; z < args[y].numElements(); z++) {
| if (args[y].isNullAt(z)) {
| $arrayData.setNullAt($counter);
| } else {
| $arrayData.set$primitiveValueTypeName(
| $counter,
| ${CodeGenerator.getValue(s"args[y]", elementType, "z")}
| );
| }
| $counter++;
| }
| }
| return $arrayData;
| }
|}""".stripMargin.stripPrefix("\n")
}
private def genCodeForNonPrimitiveArrays(ctx: CodegenContext, elementType: DataType): String = {
val genericArrayClass = classOf[GenericArrayData].getName
val arrayData = ctx.freshName("arrayObjects")
val counter = ctx.freshName("counter")
val (numElemCode, numElemName) = genCodeForNumberOfElements(ctx)
s"""
|new Object() {
| public ArrayData concat($javaType[] args) {
| ${nullArgumentProtection()}
| $numElemCode
| Object[] $arrayData = new Object[(int)$numElemName];
| int $counter = 0;
| for (int y = 0; y < ${children.length}; y++) {
| for (int z = 0; z < args[y].numElements(); z++) {
| $arrayData[$counter] = ${CodeGenerator.getValue(s"args[y]", elementType, "z")};
| $counter++;
| }
| }
| return new $genericArrayClass($arrayData);
| }
|}""".stripMargin.stripPrefix("\n")
}
override def toString: String = s"concat(${children.mkString(", ")})"
override def sql: String = s"concat(${children.map(_.sql).mkString(", ")})"
}
/**
* Transforms an array of arrays into a single array.
*/
@ExpressionDescription(
usage = "_FUNC_(arrayOfArrays) - Transforms an array of arrays into a single array.",
examples = """
Examples:
> SELECT _FUNC_(array(array(1, 2), array(3, 4));
[1,2,3,4]
""",
since = "2.4.0")
case class Flatten(child: Expression) extends UnaryExpression {
private val MAX_ARRAY_LENGTH = ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH
private lazy val childDataType: ArrayType = child.dataType.asInstanceOf[ArrayType]
override def nullable: Boolean = child.nullable || childDataType.containsNull
override def dataType: DataType = childDataType.elementType
lazy val elementType: DataType = dataType.asInstanceOf[ArrayType].elementType
override def checkInputDataTypes(): TypeCheckResult = child.dataType match {
case ArrayType(_: ArrayType, _) =>
TypeCheckResult.TypeCheckSuccess
case _ =>
TypeCheckResult.TypeCheckFailure(
s"The argument should be an array of arrays, " +
s"but '${child.sql}' is of ${child.dataType.simpleString} type."
)
}
override def nullSafeEval(child: Any): Any = {
val elements = child.asInstanceOf[ArrayData].toObjectArray(dataType)
if (elements.contains(null)) {
null
} else {
val arrayData = elements.map(_.asInstanceOf[ArrayData])
val numberOfElements = arrayData.foldLeft(0L)((sum, e) => sum + e.numElements())
if (numberOfElements > MAX_ARRAY_LENGTH) {
throw new RuntimeException("Unsuccessful try to flatten an array of arrays with " +
s"$numberOfElements elements due to exceeding the array size limit $MAX_ARRAY_LENGTH.")
}
val flattenedData = new Array(numberOfElements.toInt)
var position = 0
for (ad <- arrayData) {
val arr = ad.toObjectArray(elementType)
Array.copy(arr, 0, flattenedData, position, arr.length)
position += arr.length
}
new GenericArrayData(flattenedData)
}
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, c => {
val code = if (CodeGenerator.isPrimitiveType(elementType)) {
genCodeForFlattenOfPrimitiveElements(ctx, c, ev.value)
} else {
genCodeForFlattenOfNonPrimitiveElements(ctx, c, ev.value)
}
ctx.nullArrayElementsSaveExec(childDataType.containsNull, ev.isNull, c)(code)
})
}
private def genCodeForNumberOfElements(
ctx: CodegenContext,
childVariableName: String) : (String, String) = {
val variableName = ctx.freshName("numElements")
val code = s"""
|long $variableName = 0;
|for (int z = 0; z < $childVariableName.numElements(); z++) {
| $variableName += $childVariableName.getArray(z).numElements();
|}
|if ($variableName > $MAX_ARRAY_LENGTH) {
| throw new RuntimeException("Unsuccessful try to flatten an array of arrays with " +
| $variableName + " elements due to exceeding the array size limit $MAX_ARRAY_LENGTH.");
|}
""".stripMargin
(code, variableName)
}
private def genCodeForFlattenOfPrimitiveElements(
ctx: CodegenContext,
childVariableName: String,
arrayDataName: String): String = {
val counter = ctx.freshName("counter")
val tempArrayDataName = ctx.freshName("tempArrayData")
val (numElemCode, numElemName) = genCodeForNumberOfElements(ctx, childVariableName)
val primitiveValueTypeName = CodeGenerator.primitiveTypeName(elementType)
s"""
|$numElemCode
|${ctx.createUnsafeArray(tempArrayDataName, numElemName, elementType, s" $prettyName failed.")}
|int $counter = 0;
|for (int k = 0; k < $childVariableName.numElements(); k++) {
| ArrayData arr = $childVariableName.getArray(k);
| for (int l = 0; l < arr.numElements(); l++) {
| if (arr.isNullAt(l)) {
| $tempArrayDataName.setNullAt($counter);
| } else {
| $tempArrayDataName.set$primitiveValueTypeName(
| $counter,
| ${CodeGenerator.getValue("arr", elementType, "l")}
| );
| }
| $counter++;
| }
|}
|$arrayDataName = $tempArrayDataName;
""".stripMargin
}
private def genCodeForFlattenOfNonPrimitiveElements(
ctx: CodegenContext,
childVariableName: String,
arrayDataName: String): String = {
val genericArrayClass = classOf[GenericArrayData].getName
val arrayName = ctx.freshName("arrayObject")
val counter = ctx.freshName("counter")
val (numElemCode, numElemName) = genCodeForNumberOfElements(ctx, childVariableName)
s"""
|$numElemCode
|Object[] $arrayName = new Object[(int)$numElemName];
|int $counter = 0;
|for (int k = 0; k < $childVariableName.numElements(); k++) {
| ArrayData arr = $childVariableName.getArray(k);
| for (int l = 0; l < arr.numElements(); l++) {
| $arrayName[$counter] = ${CodeGenerator.getValue("arr", elementType, "l")};
| $counter++;
| }
|}
|$arrayDataName = new $genericArrayClass($arrayName);
""".stripMargin
}
override def prettyName: String = "flatten"
}
@ExpressionDescription(
usage = """
_FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
incrementing by step. The type of the returned elements is the same as the type of argument
expressions.
Supported types are: byte, short, integer, long, date, timestamp.
The start and stop expressions must resolve to the same type.
If start and stop expressions resolve to the 'date' or 'timestamp' type
then the step expression must resolve to the 'interval' type, otherwise to the same type
as the start and stop expressions.
""",
arguments = """
Arguments:
* start - an expression. The start of the range.
* stop - an expression. The end the range (inclusive).
* step - an optional expression. The step of the range.
By default step is 1 if start is less than or equal to stop, otherwise -1.
For the temporal sequences it's 1 day and -1 day respectively.
If start is greater than stop then the step must be negative, and vice versa.
""",
examples = """
Examples:
> SELECT _FUNC_(1, 5);
[1, 2, 3, 4, 5]
> SELECT _FUNC_(5, 1);
[5, 4, 3, 2, 1]
> SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
[2018-01-01, 2018-02-01, 2018-03-01]
""",
since = "2.4.0"
)
case class Sequence(
start: Expression,
stop: Expression,
stepOpt: Option[Expression],
timeZoneId: Option[String] = None)
extends Expression
with TimeZoneAwareExpression {
import Sequence._
def this(start: Expression, stop: Expression) =
this(start, stop, None, None)
def this(start: Expression, stop: Expression, step: Expression) =
this(start, stop, Some(step), None)
override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
copy(timeZoneId = Some(timeZoneId))
override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
override def foldable: Boolean = children.forall(_.foldable)
override def nullable: Boolean = children.exists(_.nullable)
override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
override def checkInputDataTypes(): TypeCheckResult = {
val startType = start.dataType
def stepType = stepOpt.get.dataType
val typesCorrect =
startType.sameType(stop.dataType) &&
(startType match {
case TimestampType | DateType =>
stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
case _: IntegralType =>
stepOpt.isEmpty || stepType.sameType(startType)
case _ => false
})
if (typesCorrect) {
TypeCheckResult.TypeCheckSuccess
} else {
TypeCheckResult.TypeCheckFailure(
s"$prettyName only supports integral, timestamp or date types")
}
}
def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
def castChildrenTo(widerType: DataType): Expression = Sequence(
Cast(start, widerType),
Cast(stop, widerType),
stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
timeZoneId)
private lazy val impl: SequenceImpl = dataType.elementType match {
case iType: IntegralType =>
type T = iType.InternalType
val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
new IntegralSequenceImpl(iType)(ct, iType.integral)
case TimestampType =>
new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
case DateType =>
new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
}
override def eval(input: InternalRow): Any = {
val startVal = start.eval(input)
if (startVal == null) return null
val stopVal = stop.eval(input)
if (stopVal == null) return null
val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
if (stepVal == null) return null
ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
}
override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val startGen = start.genCode(ctx)
val stopGen = stop.genCode(ctx)
val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
impl.defaultStep.genCode(ctx, startGen, stopGen))
val resultType = CodeGenerator.javaType(dataType)
val resultCode = {
val arr = ctx.freshName("arr")
val arrElemType = CodeGenerator.javaType(dataType.elementType)
s"""
|final $arrElemType[] $arr = null;
|${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
|${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
""".stripMargin
}
if (nullable) {
val nullSafeEval =
startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
s"""
|${ev.isNull} = false;
|$resultCode
""".stripMargin
}
}
}
ev.copy(code =
code"""
|boolean ${ev.isNull} = true;
|$resultType ${ev.value} = null;
|$nullSafeEval
""".stripMargin)
} else {
ev.copy(code =
code"""
|${startGen.code}
|${stopGen.code}
|${stepGen.code}
|$resultType ${ev.value} = null;
|$resultCode
""".stripMargin,
isNull = FalseLiteral)
}
}
}
object Sequence {
private type LessThanOrEqualFn = (Any, Any) => Boolean
private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
private val negativeOne = UnaryMinus(Literal(one)).eval()
def apply(start: Any, stop: Any): Any = {
if (lteq(start, stop)) one else negativeOne
}
def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
ExprCode.forNonNullValue(JavaCode.expression(
s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
stepType))
}
}
private trait SequenceImpl {
def eval(start: Any, stop: Any, step: Any): Any
def genCode(
ctx: CodegenContext,
start: String,
stop: String,
step: String,
arr: String,
elemType: String): String
val defaultStep: DefaultStep
}
private class IntegralSequenceImpl[T: ClassTag]
(elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
override val defaultStep: DefaultStep = new DefaultStep(
(elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
elemType,
num.one)
override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
import num._
val start = input1.asInstanceOf[T]
val stop = input2.asInstanceOf[T]
val step = input3.asInstanceOf[T]
var i: Int = getSequenceLength(start, stop, step)
val arr = new Array[T](i)
while (i > 0) {
i -= 1
arr(i) = start + step * num.fromInt(i)
}
arr
}
override def genCode(
ctx: CodegenContext,
start: String,
stop: String,
step: String,
arr: String,
elemType: String): String = {
val i = ctx.freshName("i")
s"""
|${genSequenceLengthCode(ctx, start, stop, step, i)}
|$arr = new $elemType[$i];
|while ($i > 0) {
| $i--;
| $arr[$i] = ($elemType) ($start + $step * $i);
|}
""".stripMargin
}
}
private class TemporalSequenceImpl[T: ClassTag]
(dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
(implicit num: Integral[T]) extends SequenceImpl {
override val defaultStep: DefaultStep = new DefaultStep(
(dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
CalendarIntervalType,
new CalendarInterval(0, MICROS_PER_DAY))
private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
val start = input1.asInstanceOf[T]
val stop = input2.asInstanceOf[T]
val step = input3.asInstanceOf[CalendarInterval]
val stepMonths = step.months
val stepMicros = step.microseconds
if (stepMonths == 0) {
backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
} else {
// To estimate the resulted array length we need to make assumptions
// about a month length in microseconds
val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
val startMicros: Long = num.toLong(start) * scale
val stopMicros: Long = num.toLong(stop) * scale
val maxEstimatedArrayLength =
getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
val stepSign = if (stopMicros > startMicros) +1 else -1
val exclusiveItem = stopMicros + stepSign
val arr = new Array[T](maxEstimatedArrayLength)
var t = startMicros
var i = 0
while (t < exclusiveItem ^ stepSign < 0) {
arr(i) = fromLong(t / scale)
t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
i += 1
}
// truncate array to the correct length
if (arr.length == i) arr else arr.slice(0, i)
}
}
override def genCode(
ctx: CodegenContext,
start: String,
stop: String,
step: String,
arr: String,
elemType: String): String = {
val stepMonths = ctx.freshName("stepMonths")
val stepMicros = ctx.freshName("stepMicros")
val stepScaled = ctx.freshName("stepScaled")
val intervalInMicros = ctx.freshName("intervalInMicros")
val startMicros = ctx.freshName("startMicros")
val stopMicros = ctx.freshName("stopMicros")
val arrLength = ctx.freshName("arrLength")
val stepSign = ctx.freshName("stepSign")
val exclusiveItem = ctx.freshName("exclusiveItem")
val t = ctx.freshName("t")
val i = ctx.freshName("i")
val genTimeZone = ctx.addReferenceObj("timeZone", timeZone, classOf[TimeZone].getName)
val sequenceLengthCode =
s"""
|final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
|${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
""".stripMargin
val timestampAddIntervalCode =
s"""
|$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
| $t, $stepMonths, $stepMicros, $genTimeZone);
""".stripMargin
s"""
|final int $stepMonths = $step.months;
|final long $stepMicros = $step.microseconds;
|
|if ($stepMonths == 0) {
| final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
| ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
|
|} else {
| final long $startMicros = $start * ${scale}L;
| final long $stopMicros = $stop * ${scale}L;
|
| $sequenceLengthCode
|
| final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
| final long $exclusiveItem = $stopMicros + $stepSign;
|
| $arr = new $elemType[$arrLength];
| long $t = $startMicros;
| int $i = 0;
|
| while ($t < $exclusiveItem ^ $stepSign < 0) {
| $arr[$i] = ($elemType) ($t / ${scale}L);
| $timestampAddIntervalCode
| $i += 1;
| }
|
| if ($arr.length > $i) {
| $arr = java.util.Arrays.copyOf($arr, $i);
| }
|}
""".stripMargin
}
}
private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
import num._
require(
(step > num.zero && start <= stop)
|| (step < num.zero && start >= stop)
|| (step == num.zero && start == stop),
s"Illegal sequence boundaries: $start to $stop by $step")
val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
require(
len <= MAX_ROUNDED_ARRAY_LENGTH,
s"Too long sequence: $len. Should be <= $MAX_ROUNDED_ARRAY_LENGTH")
len.toInt
}
private def genSequenceLengthCode(
ctx: CodegenContext,
start: String,
stop: String,
step: String,
len: String): String = {
val longLen = ctx.freshName("longLen")
s"""
|if (!(($step > 0 && $start <= $stop) ||
| ($step < 0 && $start >= $stop) ||
| ($step == 0 && $start == $stop))) {
| throw new IllegalArgumentException(
| "Illegal sequence boundaries: " + $start + " to " + $stop + " by " + $step);
|}
|long $longLen = $stop == $start ? 1L : 1L + ((long) $stop - $start) / $step;
|if ($longLen > $MAX_ROUNDED_ARRAY_LENGTH) {
| throw new IllegalArgumentException(
| "Too long sequence: " + $longLen + ". Should be <= $MAX_ROUNDED_ARRAY_LENGTH");
|}
|int $len = (int) $longLen;
""".stripMargin
}
}
/**
* Returns the array containing the given input value (left) count (right) times.
*/
@ExpressionDescription(
usage = "_FUNC_(element, count) - Returns the array containing element count times.",
examples = """
Examples:
> SELECT _FUNC_('123', 2);
['123', '123']
""",
since = "2.4.0")
case class ArrayRepeat(left: Expression, right: Expression)
extends BinaryExpression with ExpectsInputTypes {
private val MAX_ARRAY_LENGTH = ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH
override def dataType: ArrayType = ArrayType(left.dataType, left.nullable)
override def inputTypes: Seq[AbstractDataType] = Seq(AnyDataType, IntegerType)
override def nullable: Boolean = right.nullable
override def eval(input: InternalRow): Any = {
val count = right.eval(input)
if (count == null) {
null
} else {
if (count.asInstanceOf[Int] > MAX_ARRAY_LENGTH) {
throw new RuntimeException(s"Unsuccessful try to create array with $count elements " +
s"due to exceeding the array size limit $MAX_ARRAY_LENGTH.");
}
val element = left.eval(input)
new GenericArrayData(Array.fill(count.asInstanceOf[Int])(element))
}
}
override def prettyName: String = "array_repeat"
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val leftGen = left.genCode(ctx)
val rightGen = right.genCode(ctx)
val element = leftGen.value
val count = rightGen.value
val et = dataType.elementType
val coreLogic = if (CodeGenerator.isPrimitiveType(et)) {
genCodeForPrimitiveElement(ctx, et, element, count, leftGen.isNull, ev.value)
} else {
genCodeForNonPrimitiveElement(ctx, element, count, leftGen.isNull, ev.value)
}
val resultCode = nullElementsProtection(ev, rightGen.isNull, coreLogic)
ev.copy(code =
code"""
|boolean ${ev.isNull} = false;
|${leftGen.code}
|${rightGen.code}
|${CodeGenerator.javaType(dataType)} ${ev.value} =
| ${CodeGenerator.defaultValue(dataType)};
|$resultCode
""".stripMargin)
}
private def nullElementsProtection(
ev: ExprCode,
rightIsNull: String,
coreLogic: String): String = {
if (nullable) {
s"""
|if ($rightIsNull) {
| ${ev.isNull} = true;
|} else {
| ${coreLogic}
|}
""".stripMargin
} else {
coreLogic
}
}
private def genCodeForNumberOfElements(ctx: CodegenContext, count: String): (String, String) = {
val numElements = ctx.freshName("numElements")
val numElementsCode =
s"""
|int $numElements = 0;
|if ($count > 0) {
| $numElements = $count;
|}
|if ($numElements > $MAX_ARRAY_LENGTH) {
| throw new RuntimeException("Unsuccessful try to create array with " + $numElements +
| " elements due to exceeding the array size limit $MAX_ARRAY_LENGTH.");
|}
""".stripMargin
(numElements, numElementsCode)
}
private def genCodeForPrimitiveElement(
ctx: CodegenContext,
elementType: DataType,
element: String,
count: String,
leftIsNull: String,
arrayDataName: String): String = {
val tempArrayDataName = ctx.freshName("tempArrayData")
val primitiveValueTypeName = CodeGenerator.primitiveTypeName(elementType)
val errorMessage = s" $prettyName failed."
val (numElemName, numElemCode) = genCodeForNumberOfElements(ctx, count)
s"""
|$numElemCode
|${ctx.createUnsafeArray(tempArrayDataName, numElemName, elementType, errorMessage)}
|if (!$leftIsNull) {
| for (int k = 0; k < $tempArrayDataName.numElements(); k++) {
| $tempArrayDataName.set$primitiveValueTypeName(k, $element);
| }
|} else {
| for (int k = 0; k < $tempArrayDataName.numElements(); k++) {
| $tempArrayDataName.setNullAt(k);
| }
|}
|$arrayDataName = $tempArrayDataName;
""".stripMargin
}
private def genCodeForNonPrimitiveElement(
ctx: CodegenContext,
element: String,
count: String,
leftIsNull: String,
arrayDataName: String): String = {
val genericArrayClass = classOf[GenericArrayData].getName
val arrayName = ctx.freshName("arrayObject")
val (numElemName, numElemCode) = genCodeForNumberOfElements(ctx, count)
s"""
|$numElemCode
|Object[] $arrayName = new Object[(int)$numElemName];
|if (!$leftIsNull) {
| for (int k = 0; k < $numElemName; k++) {
| $arrayName[k] = $element;
| }
|}
|$arrayDataName = new $genericArrayClass($arrayName);
""".stripMargin
}
}
/**
* Remove all elements that equal to element from the given array
*/
@ExpressionDescription(
usage = "_FUNC_(array, element) - Remove all elements that equal to element from array.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3, null, 3), 3);
[1,2,null]
""", since = "2.4.0")
case class ArrayRemove(left: Expression, right: Expression)
extends BinaryExpression with ImplicitCastInputTypes {
override def dataType: DataType = left.dataType
override def inputTypes: Seq[AbstractDataType] = {
val elementType = left.dataType match {
case t: ArrayType => t.elementType
case _ => AnyDataType
}
Seq(ArrayType, elementType)
}
lazy val elementType: DataType = left.dataType.asInstanceOf[ArrayType].elementType
@transient private lazy val ordering: Ordering[Any] =
TypeUtils.getInterpretedOrdering(right.dataType)
override def checkInputDataTypes(): TypeCheckResult = {
super.checkInputDataTypes() match {
case f: TypeCheckResult.TypeCheckFailure => f
case TypeCheckResult.TypeCheckSuccess =>
TypeUtils.checkForOrderingExpr(right.dataType, s"function $prettyName")
}
}
override def nullSafeEval(arr: Any, value: Any): Any = {
val newArray = new Array[Any](arr.asInstanceOf[ArrayData].numElements())
var pos = 0
arr.asInstanceOf[ArrayData].foreach(right.dataType, (i, v) =>
if (v == null || !ordering.equiv(v, value)) {
newArray(pos) = v
pos += 1
}
)
new GenericArrayData(newArray.slice(0, pos))
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (arr, value) => {
val numsToRemove = ctx.freshName("numsToRemove")
val newArraySize = ctx.freshName("newArraySize")
val i = ctx.freshName("i")
val getValue = CodeGenerator.getValue(arr, elementType, i)
val isEqual = ctx.genEqual(elementType, value, getValue)
s"""
|int $numsToRemove = 0;
|for (int $i = 0; $i < $arr.numElements(); $i ++) {
| if (!$arr.isNullAt($i) && $isEqual) {
| $numsToRemove = $numsToRemove + 1;
| }
|}
|int $newArraySize = $arr.numElements() - $numsToRemove;
|${genCodeForResult(ctx, ev, arr, value, newArraySize)}
""".stripMargin
})
}
def genCodeForResult(
ctx: CodegenContext,
ev: ExprCode,
inputArray: String,
value: String,
newArraySize: String): String = {
val values = ctx.freshName("values")
val i = ctx.freshName("i")
val pos = ctx.freshName("pos")
val getValue = CodeGenerator.getValue(inputArray, elementType, i)
val isEqual = ctx.genEqual(elementType, value, getValue)
if (!CodeGenerator.isPrimitiveType(elementType)) {
val arrayClass = classOf[GenericArrayData].getName
s"""
|int $pos = 0;
|Object[] $values = new Object[$newArraySize];
|for (int $i = 0; $i < $inputArray.numElements(); $i ++) {
| if ($inputArray.isNullAt($i)) {
| $values[$pos] = null;
| $pos = $pos + 1;
| }
| else {
| if (!($isEqual)) {
| $values[$pos] = $getValue;
| $pos = $pos + 1;
| }
| }
|}
|${ev.value} = new $arrayClass($values);
""".stripMargin
} else {
val primitiveValueTypeName = CodeGenerator.primitiveTypeName(elementType)
s"""
|${ctx.createUnsafeArray(values, newArraySize, elementType, s" $prettyName failed.")}
|int $pos = 0;
|for (int $i = 0; $i < $inputArray.numElements(); $i ++) {
| if ($inputArray.isNullAt($i)) {
| $values.setNullAt($pos);
| $pos = $pos + 1;
| }
| else {
| if (!($isEqual)) {
| $values.set$primitiveValueTypeName($pos, $getValue);
| $pos = $pos + 1;
| }
| }
|}
|${ev.value} = $values;
""".stripMargin
}
}
override def prettyName: String = "array_remove"
}
/**
* Removes duplicate values from the array.
*/
@ExpressionDescription(
usage = "_FUNC_(array) - Removes duplicate values from the array.",
examples = """
Examples:
> SELECT _FUNC_(array(1, 2, 3, null, 3));
[1,2,3,null]
""", since = "2.4.0")
case class ArrayDistinct(child: Expression)
extends UnaryExpression with ExpectsInputTypes {
override def inputTypes: Seq[AbstractDataType] = Seq(ArrayType)
override def dataType: DataType = child.dataType
@transient lazy val elementType: DataType = dataType.asInstanceOf[ArrayType].elementType
@transient private lazy val ordering: Ordering[Any] =
TypeUtils.getInterpretedOrdering(elementType)
override def checkInputDataTypes(): TypeCheckResult = {
super.checkInputDataTypes() match {
case f: TypeCheckResult.TypeCheckFailure => f
case TypeCheckResult.TypeCheckSuccess =>
TypeUtils.checkForOrderingExpr(elementType, s"function $prettyName")
}
}
@transient private lazy val elementTypeSupportEquals = elementType match {
case BinaryType => false
case _: AtomicType => true
case _ => false
}
override def nullSafeEval(array: Any): Any = {
val data = array.asInstanceOf[ArrayData].toArray[AnyRef](elementType)
if (elementTypeSupportEquals) {
new GenericArrayData(data.distinct.asInstanceOf[Array[Any]])
} else {
var foundNullElement = false
var pos = 0
for (i <- 0 until data.length) {
if (data(i) == null) {
if (!foundNullElement) {
foundNullElement = true
pos = pos + 1
}
} else {
var j = 0
var done = false
while (j <= i && !done) {
if (data(j) != null && ordering.equiv(data(j), data(i))) {
done = true
}
j = j + 1
}
if (i == j - 1) {
pos = pos + 1
}
}
}
new GenericArrayData(data.slice(0, pos))
}
}
override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
nullSafeCodeGen(ctx, ev, (array) => {
val i = ctx.freshName("i")
val j = ctx.freshName("j")
val sizeOfDistinctArray = ctx.freshName("sizeOfDistinctArray")
val getValue1 = CodeGenerator.getValue(array, elementType, i)
val getValue2 = CodeGenerator.getValue(array, elementType, j)
val foundNullElement = ctx.freshName("foundNullElement")
val openHashSet = classOf[OpenHashSet[_]].getName
val hs = ctx.freshName("hs")
val classTag = s"scala.reflect.ClassTag$$.MODULE$$.Object()"
if (elementTypeSupportEquals) {
s"""
|int $sizeOfDistinctArray = 0;
|boolean $foundNullElement = false;
|$openHashSet $hs = new $openHashSet($classTag);
|for (int $i = 0; $i < $array.numElements(); $i ++) {
| if ($array.isNullAt($i)) {
| $foundNullElement = true;
| } else {
| $hs.add($getValue1);
| }
|}
|$sizeOfDistinctArray = $hs.size() + ($foundNullElement ? 1 : 0);
|${genCodeForResult(ctx, ev, array, sizeOfDistinctArray)}
""".stripMargin
} else {
s"""
|int $sizeOfDistinctArray = 0;
|boolean $foundNullElement = false;
|for (int $i = 0; $i < $array.numElements(); $i ++) {
| if ($array.isNullAt($i)) {
| if (!($foundNullElement)) {
| $sizeOfDistinctArray = $sizeOfDistinctArray + 1;
| $foundNullElement = true;
| }
| } else {
| int $j;
| for ($j = 0; $j < $i; $j ++) {
| if (!$array.isNullAt($j) && ${ctx.genEqual(elementType, getValue1, getValue2)}) {
| break;
| }
| }
| if ($i == $j) {
| $sizeOfDistinctArray = $sizeOfDistinctArray + 1;
| }
| }
|}
|
|${genCodeForResult(ctx, ev, array, sizeOfDistinctArray)}
""".stripMargin
}
})
}
private def setNull(
isPrimitive: Boolean,
foundNullElement: String,
distinctArray: String,
pos: String): String = {
val setNullValue =
if (!isPrimitive) {
s"$distinctArray[$pos] = null";
} else {
s"$distinctArray.setNullAt($pos)";
}
s"""
|if (!($foundNullElement)) {
| $setNullValue;
| $pos = $pos + 1;
| $foundNullElement = true;
|}
""".stripMargin
}
private def setNotNullValue(isPrimitive: Boolean,
distinctArray: String,
pos: String,
getValue1: String,
primitiveValueTypeName: String): String = {
if (!isPrimitive) {
s"$distinctArray[$pos] = $getValue1";
} else {
s"$distinctArray.set$primitiveValueTypeName($pos, $getValue1)";
}
}
private def setValueForFastEval(
isPrimitive: Boolean,
hs: String,
distinctArray: String,
pos: String,
getValue1: String,
primitiveValueTypeName: String): String = {
val setValue = setNotNullValue(isPrimitive,
distinctArray, pos, getValue1, primitiveValueTypeName)
s"""
|if (!($hs.contains($getValue1))) {
| $hs.add($getValue1);
| $setValue;
| $pos = $pos + 1;
|}
""".stripMargin
}
private def setValueForBruteForceEval(
isPrimitive: Boolean,
i: String,
j: String,
inputArray: String,
distinctArray: String,
pos: String,
getValue1: String,
isEqual: String,
primitiveValueTypeName: String): String = {
val setValue = setNotNullValue(isPrimitive,
distinctArray, pos, getValue1, primitiveValueTypeName)
s"""
|int $j;
|for ($j = 0; $j < $i; $j ++) {
| if (!$inputArray.isNullAt($j) && $isEqual) {
| break;
| }
|}
|if ($i == $j) {
| $setValue;
| $pos = $pos + 1;
|}
""".stripMargin
}
def genCodeForResult(
ctx: CodegenContext,
ev: ExprCode,
inputArray: String,
size: String): String = {
val distinctArray = ctx.freshName("distinctArray")
val i = ctx.freshName("i")
val j = ctx.freshName("j")
val pos = ctx.freshName("pos")
val getValue1 = CodeGenerator.getValue(inputArray, elementType, i)
val getValue2 = CodeGenerator.getValue(inputArray, elementType, j)
val isEqual = ctx.genEqual(elementType, getValue1, getValue2)
val foundNullElement = ctx.freshName("foundNullElement")
val hs = ctx.freshName("hs")
val openHashSet = classOf[OpenHashSet[_]].getName
if (!CodeGenerator.isPrimitiveType(elementType)) {
val arrayClass = classOf[GenericArrayData].getName
val classTag = s"scala.reflect.ClassTag$$.MODULE$$.Object()"
val setNullForNonPrimitive =
setNull(false, foundNullElement, distinctArray, pos)
if (elementTypeSupportEquals) {
val setValueForFast = setValueForFastEval(false, hs, distinctArray, pos, getValue1, "")
s"""
|int $pos = 0;
|Object[] $distinctArray = new Object[$size];
|boolean $foundNullElement = false;
|$openHashSet $hs = new $openHashSet($classTag);
|for (int $i = 0; $i < $inputArray.numElements(); $i ++) {
| if ($inputArray.isNullAt($i)) {
| $setNullForNonPrimitive;
| } else {
| $setValueForFast;
| }
|}
|${ev.value} = new $arrayClass($distinctArray);
""".stripMargin
} else {
val setValueForBruteForce = setValueForBruteForceEval(
false, i, j, inputArray, distinctArray, pos, getValue1, isEqual, "")
s"""
|int $pos = 0;
|Object[] $distinctArray = new Object[$size];
|boolean $foundNullElement = false;
|for (int $i = 0; $i < $inputArray.numElements(); $i ++) {
| if ($inputArray.isNullAt($i)) {
| $setNullForNonPrimitive;
| } else {
| $setValueForBruteForce;
| }
|}
|${ev.value} = new $arrayClass($distinctArray);
""".stripMargin
}
} else {
val primitiveValueTypeName = CodeGenerator.primitiveTypeName(elementType)
val setNullForPrimitive = setNull(true, foundNullElement, distinctArray, pos)
val classTag = s"scala.reflect.ClassTag$$.MODULE$$.$primitiveValueTypeName()"
val setValueForFast =
setValueForFastEval(true, hs, distinctArray, pos, getValue1, primitiveValueTypeName)
s"""
|${ctx.createUnsafeArray(distinctArray, size, elementType, s" $prettyName failed.")}
|int $pos = 0;
|boolean $foundNullElement = false;
|$openHashSet $hs = new $openHashSet($classTag);
|for (int $i = 0; $i < $inputArray.numElements(); $i ++) {
| if ($inputArray.isNullAt($i)) {
| $setNullForPrimitive;
| } else {
| $setValueForFast;
| }
|}
|${ev.value} = $distinctArray;
""".stripMargin
}
}
override def prettyName: String = "array_distinct"
}
| apache-2.0 |
awslabs/aws-sdk-cpp | aws-cpp-sdk-s3control/include/aws/s3control/model/AsyncErrorDetails.h | 7062 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/s3control/S3Control_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace S3Control
{
namespace Model
{
/**
* <p>Error details for the failed asynchronous operation.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/s3control-2018-08-20/AsyncErrorDetails">AWS
* API Reference</a></p>
*/
class AWS_S3CONTROL_API AsyncErrorDetails
{
public:
AsyncErrorDetails();
AsyncErrorDetails(const Aws::Utils::Xml::XmlNode& xmlNode);
AsyncErrorDetails& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline const Aws::String& GetCode() const{ return m_code; }
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline bool CodeHasBeenSet() const { return m_codeHasBeenSet; }
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline void SetCode(const Aws::String& value) { m_codeHasBeenSet = true; m_code = value; }
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline void SetCode(Aws::String&& value) { m_codeHasBeenSet = true; m_code = std::move(value); }
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline void SetCode(const char* value) { m_codeHasBeenSet = true; m_code.assign(value); }
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline AsyncErrorDetails& WithCode(const Aws::String& value) { SetCode(value); return *this;}
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline AsyncErrorDetails& WithCode(Aws::String&& value) { SetCode(std::move(value)); return *this;}
/**
* <p>A string that uniquely identifies the error condition.</p>
*/
inline AsyncErrorDetails& WithCode(const char* value) { SetCode(value); return *this;}
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline const Aws::String& GetMessage() const{ return m_message; }
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline AsyncErrorDetails& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline AsyncErrorDetails& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}
/**
* <p>A generic descritpion of the error condition in English.</p>
*/
inline AsyncErrorDetails& WithMessage(const char* value) { SetMessage(value); return *this;}
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline const Aws::String& GetResource() const{ return m_resource; }
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline bool ResourceHasBeenSet() const { return m_resourceHasBeenSet; }
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline void SetResource(const Aws::String& value) { m_resourceHasBeenSet = true; m_resource = value; }
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline void SetResource(Aws::String&& value) { m_resourceHasBeenSet = true; m_resource = std::move(value); }
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline void SetResource(const char* value) { m_resourceHasBeenSet = true; m_resource.assign(value); }
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline AsyncErrorDetails& WithResource(const Aws::String& value) { SetResource(value); return *this;}
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline AsyncErrorDetails& WithResource(Aws::String&& value) { SetResource(std::move(value)); return *this;}
/**
* <p>The identifier of the resource associated with the error.</p>
*/
inline AsyncErrorDetails& WithResource(const char* value) { SetResource(value); return *this;}
/**
* <p>The ID of the request associated with the error.</p>
*/
inline const Aws::String& GetRequestId() const{ return m_requestId; }
/**
* <p>The ID of the request associated with the error.</p>
*/
inline bool RequestIdHasBeenSet() const { return m_requestIdHasBeenSet; }
/**
* <p>The ID of the request associated with the error.</p>
*/
inline void SetRequestId(const Aws::String& value) { m_requestIdHasBeenSet = true; m_requestId = value; }
/**
* <p>The ID of the request associated with the error.</p>
*/
inline void SetRequestId(Aws::String&& value) { m_requestIdHasBeenSet = true; m_requestId = std::move(value); }
/**
* <p>The ID of the request associated with the error.</p>
*/
inline void SetRequestId(const char* value) { m_requestIdHasBeenSet = true; m_requestId.assign(value); }
/**
* <p>The ID of the request associated with the error.</p>
*/
inline AsyncErrorDetails& WithRequestId(const Aws::String& value) { SetRequestId(value); return *this;}
/**
* <p>The ID of the request associated with the error.</p>
*/
inline AsyncErrorDetails& WithRequestId(Aws::String&& value) { SetRequestId(std::move(value)); return *this;}
/**
* <p>The ID of the request associated with the error.</p>
*/
inline AsyncErrorDetails& WithRequestId(const char* value) { SetRequestId(value); return *this;}
private:
Aws::String m_code;
bool m_codeHasBeenSet;
Aws::String m_message;
bool m_messageHasBeenSet;
Aws::String m_resource;
bool m_resourceHasBeenSet;
Aws::String m_requestId;
bool m_requestIdHasBeenSet;
};
} // namespace Model
} // namespace S3Control
} // namespace Aws
| apache-2.0 |
mdamt/PdfBox-Android | library/src/main/java/org/apache/pdfbox/pdmodel/graphics/PDPostScriptXObject.java | 535 | package org.apache.pdfbox.pdmodel.graphics;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.common.PDStream;
/**
* A PostScript XObject.
* Conforming readers may not be able to interpret the PostScript fragments.
*
* @author John Hewson
*/
public class PDPostScriptXObject extends PDXObject
{
/**
* Creates a PostScript XObject.
* @param stream The XObject stream
*/
public PDPostScriptXObject(PDStream stream)
{
super(stream, COSName.PS);
}
}
| apache-2.0 |
apache/libcloud | libcloud/test/compute/test_hostvirtual.py | 8559 | # 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.
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.compute.drivers.hostvirtual import HostVirtualNodeDriver
from libcloud.compute.types import NodeState
from libcloud.compute.base import NodeAuthPassword
from libcloud.test import MockHttp
from libcloud.test.file_fixtures import ComputeFileFixtures
from libcloud.test.secrets import HOSTVIRTUAL_PARAMS
class HostVirtualTest(unittest.TestCase):
def setUp(self):
HostVirtualNodeDriver.connectionCls.conn_class = HostVirtualMockHttp
self.driver = HostVirtualNodeDriver(*HOSTVIRTUAL_PARAMS)
def test_list_nodes(self):
nodes = self.driver.list_nodes()
self.assertEqual(len(nodes), 4)
self.assertEqual(len(nodes[0].public_ips), 1)
self.assertEqual(len(nodes[1].public_ips), 1)
self.assertEqual(len(nodes[0].private_ips), 0)
self.assertEqual(len(nodes[1].private_ips), 0)
self.assertTrue("208.111.39.118" in nodes[1].public_ips)
self.assertTrue("208.111.45.250" in nodes[0].public_ips)
self.assertEqual(nodes[3].state, NodeState.RUNNING)
self.assertEqual(nodes[1].state, NodeState.TERMINATED)
def test_list_sizes(self):
sizes = self.driver.list_sizes()
self.assertEqual(len(sizes), 14)
self.assertEqual(sizes[0].id, "31")
self.assertEqual(sizes[4].id, "71")
self.assertEqual(sizes[2].ram, "512MB")
self.assertEqual(sizes[2].disk, "20GB")
self.assertEqual(sizes[3].bandwidth, "600GB")
self.assertEqual(sizes[1].price, "15.00")
def test_list_images(self):
images = self.driver.list_images()
self.assertEqual(len(images), 8)
self.assertEqual(images[0].id, "1739")
self.assertEqual(images[0].name, "Gentoo 2012 (0619) i386")
def test_list_locations(self):
locations = self.driver.list_locations()
self.assertEqual(locations[0].id, "3")
self.assertEqual(locations[0].name, "SJC - San Jose, CA")
self.assertEqual(locations[1].id, "13")
self.assertEqual(locations[1].name, "IAD - Reston, VA")
def test_reboot_node(self):
node = self.driver.list_nodes()[0]
self.assertTrue(self.driver.reboot_node(node))
def test_ex_get_node(self):
node = self.driver.ex_get_node(node_id="62291")
self.assertEqual(node.id, "62291")
self.assertEqual(node.name, "server1.vr-cluster.org")
self.assertEqual(node.state, NodeState.TERMINATED)
self.assertTrue("208.111.45.250" in node.public_ips)
def test_ex_list_packages(self):
pkgs = self.driver.ex_list_packages()
self.assertEqual(len(pkgs), 3)
self.assertEqual(pkgs[1]["mbpkgid"], "176018")
self.assertEqual(pkgs[2]["package_status"], "Suspended")
def test_ex_order_package(self):
sizes = self.driver.list_sizes()
pkg = self.driver.ex_order_package(sizes[0])
self.assertEqual(pkg["id"], "62291")
def test_ex_cancel_package(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_cancel_package(node)
self.assertEqual(result["status"], "success")
def test_ex_unlink_package(self):
node = self.driver.list_nodes()[0]
result = self.driver.ex_unlink_package(node)
self.assertEqual(result["status"], "success")
def test_ex_stop_node(self):
node = self.driver.list_nodes()[0]
self.assertTrue(self.driver.ex_stop_node(node))
def test_ex_start_node(self):
node = self.driver.list_nodes()[0]
self.assertTrue(self.driver.ex_start_node(node))
def test_destroy_node(self):
node = self.driver.list_nodes()[0]
self.assertTrue(self.driver.destroy_node(node))
def test_ex_delete_node(self):
node = self.driver.list_nodes()[0]
self.assertTrue(self.driver.ex_delete_node(node))
def test_create_node(self):
auth = NodeAuthPassword("vr!@#hosted#@!")
size = self.driver.list_sizes()[0]
image = self.driver.list_images()[0]
node = self.driver.create_node(
name="test.com", image=image, size=size, auth=auth
)
self.assertEqual("62291", node.id)
self.assertEqual("server1.vr-cluster.org", node.name)
def test_ex_provision_node(self):
node = self.driver.list_nodes()[0]
auth = NodeAuthPassword("vr!@#hosted#@!")
self.assertTrue(self.driver.ex_provision_node(node=node, auth=auth))
def test_create_node_in_location(self):
auth = NodeAuthPassword("vr!@#hosted#@!")
size = self.driver.list_sizes()[0]
image = self.driver.list_images()[0]
location = self.driver.list_locations()[1]
node = self.driver.create_node(
name="test.com", image=image, size=size, auth=auth, location=location
)
self.assertEqual("62291", node.id)
self.assertEqual("server1.vr-cluster.org", node.name)
class HostVirtualMockHttp(MockHttp):
fixtures = ComputeFileFixtures("hostvirtual")
def _cloud_servers(self, method, url, body, headers):
body = self.fixtures.load("list_nodes.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_server(self, method, url, body, headers):
body = self.fixtures.load("get_node.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_packages(self, method, url, body, headers):
body = self.fixtures.load("list_packages.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_sizes(self, method, url, body, headers):
body = self.fixtures.load("list_sizes.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_images(self, method, url, body, headers):
body = self.fixtures.load("list_images.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_locations(self, method, url, body, headers):
body = self.fixtures.load("list_locations.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_server_delete(self, method, url, body, headers):
body = self.fixtures.load("cancel_package.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_server_reboot(self, method, url, body, headers):
body = self.fixtures.load("node_reboot.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_server_shutdown(self, method, url, body, headers):
body = self.fixtures.load("node_stop.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_server_start(self, method, url, body, headers):
body = self.fixtures.load("node_start.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_server_build(self, method, url, body, headers):
body = self.fixtures.load("order_package.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_buy(self, method, url, body, headers):
body = self.fixtures.load("order_package.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_cancel(self, method, url, body, headers):
body = self.fixtures.load("cancel_package.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _cloud_unlink(self, method, url, body, headers):
body = self.fixtures.load("unlink_package.json")
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
if __name__ == "__main__":
sys.exit(unittest.main())
# vim:autoindent tabstop=4 shiftwidth=4 expandtab softtabstop=4 filetype=python
| apache-2.0 |
luci/recipes-py | recipe_modules/cq/tests/mode_of_run.py | 825 | # Copyright 2021 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
PYTHON_VERSION_COMPATIBILITY = 'PY2+3'
DEPS = [
'cq',
'properties',
'step',
]
def RunSteps(api):
api.step('show properties', [])
api.step.active_result.presentation.logs['result'] = [
'mode: %s' % (api.cq.run_mode,),
]
def GenTests(api):
yield api.test('dry') + api.cq(run_mode=api.cq.DRY_RUN)
yield api.test('quick-dry') + api.cq(run_mode=api.cq.QUICK_DRY_RUN)
yield api.test('full') + api.cq(run_mode=api.cq.FULL_RUN)
yield api.test('legacy-full') + api.properties(**{
'$recipe_engine/cq': {'dry_run': False},
})
yield api.test('legacy-dry') + api.properties(**{
'$recipe_engine/cq': {'dry_run': True},
})
| apache-2.0 |
tgraf/cilium | pkg/addressing/ip.go | 4261 | // Copyright 2016-2017 Authors of Cilium
//
// 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 addressing
import (
"encoding/json"
"fmt"
"net"
)
type CiliumIP interface {
IPNet(ones int) *net.IPNet
EndpointPrefix() *net.IPNet
IP() net.IP
String() string
IsIPv6() bool
GetFamilyString() string
IsSet() bool
}
type CiliumIPv6 []byte
// NewCiliumIPv6 returns a IPv6 if the given `address` is an IPv6 address.
func NewCiliumIPv6(address string) (CiliumIPv6, error) {
ip, _, err := net.ParseCIDR(address)
if err != nil {
ip = net.ParseIP(address)
if ip == nil {
return nil, fmt.Errorf("Invalid IPv6 address: %s", address)
}
}
// As result of ParseIP, ip is either a valid IPv6 or IPv4 address. net.IP
// represents both versions on 16 bytes, so a more reliable way to tell
// IPv4 and IPv6 apart is to see if it fits 4 bytes
ip4 := ip.To4()
if ip4 != nil {
return nil, fmt.Errorf("Not an IPv6 address: %s", address)
}
return DeriveCiliumIPv6(ip.To16()), nil
}
func DeriveCiliumIPv6(src net.IP) CiliumIPv6 {
ip := make(CiliumIPv6, 16)
copy(ip, src.To16())
return ip
}
// IsSet returns true if the IP is set
func (ip CiliumIPv6) IsSet() bool {
return ip.String() != ""
}
func (ip CiliumIPv6) IsIPv6() bool {
return true
}
func (ip CiliumIPv6) IPNet(ones int) *net.IPNet {
return &net.IPNet{
IP: ip.IP(),
Mask: net.CIDRMask(ones, 128),
}
}
func (ip CiliumIPv6) EndpointPrefix() *net.IPNet {
return ip.IPNet(128)
}
func (ip CiliumIPv6) IP() net.IP {
return net.IP(ip)
}
func (ip CiliumIPv6) String() string {
if ip == nil {
return ""
}
return net.IP(ip).String()
}
func (ip CiliumIPv6) MarshalJSON() ([]byte, error) {
return json.Marshal(net.IP(ip))
}
func (ip *CiliumIPv6) UnmarshalJSON(b []byte) error {
if len(b) < len(`""`) {
return fmt.Errorf("Invalid CiliumIPv6 '%s'", string(b))
}
str := string(b[1 : len(b)-1])
if str == "" {
return nil
}
c, err := NewCiliumIPv6(str)
if err != nil {
return fmt.Errorf("Invalid CiliumIPv6 '%s': %s", str, err)
}
*ip = c
return nil
}
type CiliumIPv4 []byte
func NewCiliumIPv4(address string) (CiliumIPv4, error) {
ip, _, err := net.ParseCIDR(address)
if err != nil {
ip = net.ParseIP(address)
if ip == nil {
return nil, fmt.Errorf("Invalid IPv4 address: %s", address)
}
}
ip4 := ip.To4()
if ip4 == nil {
return nil, fmt.Errorf("Not an IPv4 address")
}
return DeriveCiliumIPv4(ip4), nil
}
func DeriveCiliumIPv4(src net.IP) CiliumIPv4 {
ip := make(CiliumIPv4, 4)
copy(ip, src.To4())
return ip
}
// IsSet returns true if the IP is set
func (ip CiliumIPv4) IsSet() bool {
return ip.String() != ""
}
func (ip CiliumIPv4) IsIPv6() bool {
return false
}
func (ip CiliumIPv4) IPNet(ones int) *net.IPNet {
return &net.IPNet{
IP: net.IP(ip),
Mask: net.CIDRMask(ones, 32),
}
}
func (ip CiliumIPv4) EndpointPrefix() *net.IPNet {
return ip.IPNet(32)
}
func (ip CiliumIPv4) IP() net.IP {
return net.IP(ip)
}
func (ip CiliumIPv4) String() string {
if ip == nil {
return ""
}
return net.IP(ip).String()
}
func (ip CiliumIPv4) MarshalJSON() ([]byte, error) {
return json.Marshal(net.IP(ip))
}
func (ip *CiliumIPv4) UnmarshalJSON(b []byte) error {
if len(b) < len(`""`) {
return fmt.Errorf("Invalid CiliumIPv4 '%s'", string(b))
}
str := string(b[1 : len(b)-1])
if str == "" {
return nil
}
c, err := NewCiliumIPv4(str)
if err != nil {
return fmt.Errorf("Invalid CiliumIPv4 '%s': %s", str, err)
}
*ip = c
return nil
}
// GetFamilyString returns the address family of ip as a string.
func (ip CiliumIPv4) GetFamilyString() string {
return "IPv4"
}
// GetFamilyString returns the address family of ip as a string.
func (ip CiliumIPv6) GetFamilyString() string {
return "IPv6"
}
| apache-2.0 |
bbossgroups/bbossgroups-3.5 | bboss-core/src/org/frameworkset/spi/assemble/Context.java | 2300 | /*
* Copyright 2008 biaoping.yin
*
* 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.frameworkset.spi.assemble;
import org.frameworkset.spi.assemble.BeanAccembleHelper.LoopObject;
/**
*
*
* <p>Title: Context.java</p>
*
* <p>Description:
* This context is used to defend loopioc.
* 依赖注入的上下文信息,
* 如果注入类与被注入类之间存在循环注入的情况,则系统自动报错,是否存在循环注入
* 是通过上下文信息来判断的
*
*
*
*
* </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>bboss workgroup</p>
* @Date Aug 14, 2008 4:37:33 PM
* @author biaoping.yin,尹标平
* @version 1.0
*/
public class Context {
Context parent;
String refid;
/**
* 保存应用的
*/
private Object currentObj;
boolean isroot = false;
public Context(String refid)
{
isroot = true;
this.refid = refid;
}
public Context(Context parent,String refid)
{
this.parent = parent;
this.refid = refid;
}
public boolean isLoopIOC(String refid_,LoopObject lo)
{
if(refid_.equals(this.refid))
{
lo.setObj(currentObj);
return true;
}
if(this.isroot)
{
return false;
}
else if(parent != null)
{
return parent.isLoopIOC(refid_,lo);
}
return false;
}
public String toString()
{
StringBuilder ret = new StringBuilder();
if(this.isroot)
{
ret.append(refid);
}
else
{
ret.append(parent)
.append(">")
.append(refid);
}
return ret.toString();
}
public Object getCurrentObj() {
return currentObj;
}
public Object setCurrentObj(Object currentObj) {
this.currentObj = currentObj;
return currentObj;
}
}
| apache-2.0 |
benjaminbollen/eris-db | manager/burrow-mint/evm/stack.go | 2847 | // Copyright 2017 Monax Industries 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vm
import (
"fmt"
"github.com/hyperledger/burrow/common/math/integral"
"github.com/hyperledger/burrow/common/sanity"
. "github.com/hyperledger/burrow/word256"
)
// Not goroutine safe
type Stack struct {
data []Word256
ptr int
gas *int64
err *error
}
func NewStack(capacity int, gas *int64, err *error) *Stack {
return &Stack{
data: make([]Word256, capacity),
ptr: 0,
gas: gas,
err: err,
}
}
func (st *Stack) useGas(gasToUse int64) {
if *st.gas > gasToUse {
*st.gas -= gasToUse
} else {
st.setErr(ErrInsufficientGas)
}
}
func (st *Stack) setErr(err error) {
if *st.err == nil {
*st.err = err
}
}
func (st *Stack) Push(d Word256) {
st.useGas(GasStackOp)
if st.ptr == cap(st.data) {
st.setErr(ErrDataStackOverflow)
return
}
st.data[st.ptr] = d
st.ptr++
}
// currently only called after Sha3
func (st *Stack) PushBytes(bz []byte) {
if len(bz) != 32 {
sanity.PanicSanity("Invalid bytes size: expected 32")
}
st.Push(LeftPadWord256(bz))
}
func (st *Stack) Push64(i int64) {
st.Push(Int64ToWord256(i))
}
func (st *Stack) Pop() Word256 {
st.useGas(GasStackOp)
if st.ptr == 0 {
st.setErr(ErrDataStackUnderflow)
return Zero256
}
st.ptr--
return st.data[st.ptr]
}
func (st *Stack) PopBytes() []byte {
return st.Pop().Bytes()
}
func (st *Stack) Pop64() int64 {
d := st.Pop()
return Int64FromWord256(d)
}
func (st *Stack) Len() int {
return st.ptr
}
func (st *Stack) Swap(n int) {
st.useGas(GasStackOp)
if st.ptr < n {
st.setErr(ErrDataStackUnderflow)
return
}
st.data[st.ptr-n], st.data[st.ptr-1] = st.data[st.ptr-1], st.data[st.ptr-n]
return
}
func (st *Stack) Dup(n int) {
st.useGas(GasStackOp)
if st.ptr < n {
st.setErr(ErrDataStackUnderflow)
return
}
st.Push(st.data[st.ptr-n])
return
}
// Not an opcode, costs no gas.
func (st *Stack) Peek() Word256 {
if st.ptr == 0 {
st.setErr(ErrDataStackUnderflow)
return Zero256
}
return st.data[st.ptr-1]
}
func (st *Stack) Print(n int) {
fmt.Println("### stack ###")
if st.ptr > 0 {
nn := integral.MinInt(n, st.ptr)
for j, i := 0, st.ptr-1; i > st.ptr-1-nn; i-- {
fmt.Printf("%-3d %X\n", j, st.data[i])
j += 1
}
} else {
fmt.Println("-- empty --")
}
fmt.Println("#############")
}
| apache-2.0 |
apache/incubator-systemml | src/test/java/org/apache/sysds/test/functions/compress/instructionsSpark/CompressedSparkInstructionsTestSparse.java | 1032 | /*
* 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.sysds.test.functions.compress.instructionsSpark;
public class CompressedSparkInstructionsTestSparse extends CompressedSparkInstructionsTest {
@Override
public double getDensity() {
return 0.1;
}
}
| apache-2.0 |
sozoStudio/sozoStudio.github.io | FoguangTemple_web/node_modules/utf-8-validate/build/Makefile | 13362 | # We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
LINK ?= $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_objc = CXX($(TOOLSET)) $@
cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
quiet_cmd_objcxx = CXX($(TOOLSET)) $@
cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
# Commands for precompiled header files.
quiet_cmd_pch_c = CXX($(TOOLSET)) $@
cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_pch_m = CXX($(TOOLSET)) $@
cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
# gyp-mac-tool is written next to the root Makefile by gyp.
# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
# already.
quiet_cmd_mac_tool = MACTOOL $(4) $<
cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
quiet_cmd_infoplist = INFOPLIST $@
cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = LIBTOOL-STATIC $@
cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 2,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,validation.target.mk)))),)
include validation.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/alfance/websites/Foguang_ionic/www/node_modules/utf-8-validate/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/alfance/.node-gyp/5.0.0/include/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/alfance/.node-gyp/5.0.0" "-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/Users/alfance/websites/Foguang_ionic/www/node_modules/utf-8-validate" binding.gyp
Makefile: $(srcdir)/../../../../../.node-gyp/5.0.0/include/node/common.gypi $(srcdir)/../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif
| apache-2.0 |
rsimha-amp/amphtml | extensions/amp-iframely/0.1/test/test-amp-iframely.js | 12110 | /**
* Copyright 2021 The AMP HTML Authors. 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.
*/
import '../amp-iframely';
describes.realWin(
'amp-iframely',
{
amp: {
extensions: ['amp-iframely'],
},
},
(env) => {
let win, doc;
const TestID = 'pHBVuFj';
const paramsID = {
'data-id': TestID,
'width': '10',
'height': '10',
'layout': 'responsive',
};
const url = 'https//some.url/';
const key = 'some-StRiNg-of-more-then-16';
const paramsKU = {
'data-key': key,
'data-url': url,
'layout': 'responsive',
'width': '100',
'height': '100',
};
beforeEach(() => {
win = env.win;
doc = win.document;
});
function renderIframely(params) {
const iframely = doc.createElement('amp-iframely');
for (const param in params) {
iframely.setAttribute(param, params[param]);
}
doc.body.appendChild(iframely);
return iframely.buildInternal().then(() => {
iframely.layoutCallback();
return iframely;
});
}
function testIframe(iframe, id) {
expect(iframe).to.not.be.null;
expect(iframe.src).to.equal('https://cdn.iframe.ly/' + id + '?amp=1');
expect(iframe.className).to.match(/i-amphtml-fill-content/);
}
it('renders', () => {
return renderIframely(paramsID).then((iframely) => {
testIframe(iframely.querySelector('iframe'), TestID);
});
});
it('does not render without required attributes', () => {
return allowConsoleError(() => {
return renderIframely({
'layout': 'fill',
}).should.eventually.be.rejectedWith(/<amp-iframely> requires either/);
});
});
it('not renders with only URL parameter', () => {
return allowConsoleError(() => {
return renderIframely({
'data-url': 'https//some.url/',
'layout': 'fixed',
}).should.eventually.be.rejectedWith(
/Iframely data-key must also be set/
);
});
});
it('not renders with only KEY parameter', () => {
return allowConsoleError(() => {
return renderIframely({
'data-key': 'some-StRiNg/',
'layout': 'fixed',
}).should.eventually.be.rejectedWith(
/<amp-iframely> requires either "data-id" /
);
});
});
it('rejects with both data-url AND data-id parameters specified', () => {
const params = {
'data-id': TestID,
'data-key': 'some-StRiNg/',
'data-url': 'https//some.url/',
'layout': 'fill',
};
return allowConsoleError(() => {
return renderIframely(params).should.eventually.be.rejectedWith(
/Only one way of setting either data-id or/
);
});
});
it('builds url for key-url pair properly', () => {
return renderIframely(paramsKU).then((iframely) => {
const iframe = iframely.querySelector('iframe');
expect(iframe).to.not.be.null;
expect(iframe.src).to.equal(
`https://cdn.iframe.ly/api/iframe?url=${encodeURIComponent(
url
)}&key=${key}&=1`
);
expect(iframe.className).to.match(/i-amphtml-fill-content/);
});
});
it('renders iframe properly', () => {
return renderIframely(paramsID).then((iframely) => {
const iframe = iframely.querySelector('iframe');
testIframe(iframe, TestID);
expect(iframe.tagName).to.equal('IFRAME');
expect(iframe.className).to.match(/i-amphtml-fill-content/);
// Border render cleared
expect(iframe.getAttribute('style')).to.equal('border: 0px;');
});
});
it('renders image placeholder', () => {
return renderIframely(paramsID).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(image).to.have.class('i-amphtml-fill-content');
expect(image.getAttribute('loading')).to.equal('lazy');
});
});
it('renders image placeholder with proper URL for ID version', () => {
return renderIframely(paramsID).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(image.getAttribute('src')).to.equal(
`https://cdn.iframe.ly/${TestID}/thumbnail?amp=1`
);
});
});
it('renders image placeholder with proper URL for Key-URL version', () => {
return renderIframely(paramsKU).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(image.getAttribute('src')).to.equal(
`https://cdn.iframe.ly/api/thumbnail?url=${encodeURIComponent(
url
)}&key=${key}&=1`
);
});
});
it('does not render iframe and image placeholder with wrong domain', () => {
const domain = 'mydomain.com';
const properDomain = 'cdn.iframe.ly';
const data = {
'data-id': TestID,
'data-domain': domain,
'width': '100',
'height': '100',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(image.getAttribute('src')).to.equal(
`https://${properDomain}/${TestID}/thumbnail?amp=1`
);
const iframe = iframely.querySelector('iframe');
expect(iframe.src).to.equal(`https://${properDomain}/${TestID}?amp=1`);
});
});
it('renders iframe and image placeholder with proper domain', () => {
const domain = 'iframe.ly';
const data = {
'data-id': TestID,
'data-domain': domain,
'width': '100',
'height': '100',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(image.getAttribute('src')).to.equal(
`https://${domain}/${TestID}/thumbnail?amp=1`
);
const iframe = iframely.querySelector('iframe');
expect(iframe.src).to.equal(`https://${domain}/${TestID}?amp=1`);
});
});
it('renders placeholder with data-img key set', () => {
const data = {
'data-id': TestID,
'data-img': '',
'layout': 'fill',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('does not render placeholder with resizable key set and responsive layout', () => {
const data = {
'data-id': TestID,
'resizable': '',
'height': '100',
'width': '100',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('render placeholder with data-img and resizeable', () => {
const data = {
'data-id': TestID,
'resizable': '',
'data-img': '',
'height': '100',
'width': '100',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('does not render placeholder with fixed layout', () => {
const data = {
'data-id': TestID,
'height': '100',
'width': '100',
'layout': 'fixed',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('does not render placeholder with fixed layout and resizable', () => {
const data = {
'data-id': TestID,
'height': '100',
'width': '100',
'resizable': '',
'layout': 'fixed',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('render placeholder with data-img responsive layout and resizable params', () => {
const data = {
'data-id': TestID,
'height': '100',
'width': '100',
'data-img': '',
'resizable': '',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('render placeholder with data-img fixed layout and resizable params', () => {
const data = {
'data-id': TestID,
'height': '100',
'width': '100',
'data-img': '',
'layout': 'fixed',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.not.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('does not render placeholder with fixed-height layout and resizable params', () => {
const data = {
'data-id': TestID,
'height': '166',
'layout': 'fixed-height',
'resizable': '',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('does not render placeholder with resizable param set and layout===responsive', () => {
const data = {
'data-id': TestID,
'height': '100',
'width': '100',
'resizable': '',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
expect(image).to.be.null;
expect(iframely.querySelector('iframe')).to.not.be.null;
});
});
it('does not render with invalid key length', () => {
const data = {
'data-url': 'https://some-url.com',
'height': '100',
'width': '100',
'data-key': '',
'layout': 'fixed',
};
return allowConsoleError(() => {
return renderIframely(data).should.eventually.be.rejectedWith(
/Iframely data-key must also be set when you specify data-url parameter/
);
});
});
it('render iframe options properly', () => {
const data = {
'data-id': TestID,
'height': '100',
'width': '100',
'data-optionOne': 'value',
'data-option-two': 'value',
'data-img': 'something',
'layout': 'responsive',
};
return renderIframely(data).then((iframely) => {
const image = iframely.querySelector('img');
const iframe = iframely.querySelector('iframe');
expect(image).to.not.be.null;
expect(iframe).to.not.be.null;
expect(iframe.src.includes('&optionone=value&optionTwo=value')).to.be
.true;
});
});
}
);
| apache-2.0 |
incodehq/isis | core/viewer-wicket-ui/src/main/java/org/apache/isis/viewer/wicket/ui/errors/ExceptionModel.java | 6578 | /*
* 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.isis.viewer.wicket.ui.errors;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.isis.applib.NonRecoverableException;
import org.apache.isis.applib.services.error.ErrorReportingService;
import org.apache.isis.applib.services.error.Ticket;
import org.apache.isis.core.metamodel.spec.feature.ObjectMember;
import org.apache.isis.viewer.wicket.model.models.ModelAbstract;
public class ExceptionModel extends ModelAbstract<List<StackTraceDetail>> {
private static final long serialVersionUID = 1L;
private static final String MAIN_MESSAGE_IF_NOT_RECOGNIZED = "Sorry, an unexpected error occurred.";
private List<StackTraceDetail> stackTraceDetailList;
private List<List<StackTraceDetail>> stackTraceDetailLists;
private boolean recognized;
private boolean authorizationCause;
private final String mainMessage;
public static ExceptionModel create(String recognizedMessageIfAny, Exception ex) {
return new ExceptionModel(recognizedMessageIfAny, ex);
}
/**
* Three cases: authorization exception, else recognized, else or not recognized.
* @param recognizedMessageIfAny
* @param ex
*/
private ExceptionModel(String recognizedMessageIfAny, Exception ex) {
final ObjectMember.AuthorizationException authorizationException = causalChainOf(ex, ObjectMember.AuthorizationException.class);
if(authorizationException != null) {
this.authorizationCause = true;
this.mainMessage = authorizationException.getMessage();
} else {
this.authorizationCause = false;
if(recognizedMessageIfAny != null) {
this.recognized = true;
this.mainMessage = recognizedMessageIfAny;
} else {
this.recognized =false;
// see if we can find a NonRecoverableException in the stack trace
Iterable<NonRecoverableException> appEx = Iterables.filter(Throwables.getCausalChain(ex), NonRecoverableException.class);
Iterator<NonRecoverableException> iterator = appEx.iterator();
NonRecoverableException nonRecoverableException = iterator.hasNext() ? iterator.next() : null;
this.mainMessage = nonRecoverableException != null? nonRecoverableException.getMessage() : MAIN_MESSAGE_IF_NOT_RECOGNIZED;
}
}
stackTraceDetailList = asStackTrace(ex);
stackTraceDetailLists = asStackTraces(ex);
}
@Override
protected List<StackTraceDetail> load() {
return stackTraceDetailList;
}
private static <T extends Exception> T causalChainOf(Exception ex, Class<T> exType) {
final List<Throwable> causalChain = Throwables.getCausalChain(ex);
for (Throwable cause : causalChain) {
if(exType.isAssignableFrom(cause.getClass())) {
return (T)cause;
}
}
return null;
}
@Override
public void setObject(List<StackTraceDetail> stackTraceDetail) {
if(stackTraceDetail == null) {
return;
}
this.stackTraceDetailList = stackTraceDetail;
}
private Ticket ticket;
public Ticket getTicket() {
return ticket;
}
/**
* Optionally called if an {@link ErrorReportingService} has been configured and returns a <tt>non-null</tt> ticket
* to represent the fact that the error has been recorded.
*/
public void setTicket(final Ticket ticket) {
this.ticket = ticket;
}
public boolean isRecognized() {
return recognized;
}
public String getMainMessage() {
return mainMessage;
}
/**
* Whether this was an authorization exception (so UI can suppress information, eg stack trace).
*/
public boolean isAuthorizationException() {
return authorizationCause;
}
public List<StackTraceDetail> getStackTrace() {
return stackTraceDetailList;
}
public List<List<StackTraceDetail>> getStackTraces() {
return stackTraceDetailLists;
}
private static List<StackTraceDetail> asStackTrace(Throwable ex) {
List<StackTraceDetail> stackTrace = Lists.newArrayList();
List<Throwable> causalChain = Throwables.getCausalChain(ex);
boolean firstTime = true;
for(Throwable cause: causalChain) {
if(!firstTime) {
stackTrace.add(StackTraceDetail.spacer());
stackTrace.add(StackTraceDetail.causedBy());
stackTrace.add(StackTraceDetail.spacer());
} else {
firstTime = false;
}
append(cause, stackTrace);
}
return stackTrace;
}
private static List<List<StackTraceDetail>> asStackTraces(Throwable ex) {
List<List<StackTraceDetail>> stackTraces = Lists.newArrayList();
List<Throwable> causalChain = Throwables.getCausalChain(ex);
boolean firstTime = true;
for(Throwable cause: causalChain) {
List<StackTraceDetail> stackTrace = Lists.newArrayList();
append(cause, stackTrace);
stackTraces.add(stackTrace);
}
return stackTraces;
}
private static void append(final Throwable cause, final List<StackTraceDetail> stackTrace) {
stackTrace.add(StackTraceDetail.exceptionClassName(cause));
stackTrace.add(StackTraceDetail.exceptionMessage(cause));
for (StackTraceElement el : cause.getStackTrace()) {
stackTrace.add(StackTraceDetail.element(el));
}
}
}
| apache-2.0 |
AzureAutomationTeam/azure-powershell | src/ResourceManager/Compute/Commands.Compute/Generated/Snapshot/SnapshotUpdateMethod.cs | 4375 | //
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsData.Update, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Snapshot", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSSnapshot))]
public partial class UpdateAzureRmSnapshot : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.SnapshotName, VerbsData.Update))
{
string resourceGroupName = this.ResourceGroupName;
string snapshotName = this.SnapshotName;
SnapshotUpdate snapshotupdate = new SnapshotUpdate();
ComputeAutomationAutoMapperProfile.Mapper.Map<PSSnapshotUpdate, SnapshotUpdate>(this.SnapshotUpdate, snapshotupdate);
Snapshot snapshot = new Snapshot();
ComputeAutomationAutoMapperProfile.Mapper.Map<PSSnapshot, Snapshot>(this.Snapshot, snapshot);
var result = (this.SnapshotUpdate == null)
? SnapshotsClient.CreateOrUpdate(resourceGroupName, snapshotName, snapshot)
: SnapshotsClient.Update(resourceGroupName, snapshotName, snapshotupdate);
var psObject = new PSSnapshot();
ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshot>(result, psObject);
WriteObject(psObject);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceNameCompleter("Microsoft.Compute/snapshots", "ResourceGroupName")]
[Alias("Name")]
public string SnapshotName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 3,
Mandatory = true,
ValueFromPipeline = true)]
public PSSnapshotUpdate SnapshotUpdate { get; set; }
[Parameter(
ParameterSetName = "FriendMethod",
Position = 4,
Mandatory = true,
ValueFromPipelineByPropertyName = false,
ValueFromPipeline = true)]
[AllowNull]
public PSSnapshot Snapshot { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
}
}
| apache-2.0 |
queria/my-tempest | tempest/api/compute/servers/test_attach_interfaces.py | 6514 | # Copyright 2013 IBM Corp.
# 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.
from tempest.api.compute import base
from tempest import config
from tempest import exceptions
from tempest import test
import time
CONF = config.CONF
class AttachInterfacesTestJSON(base.BaseV2ComputeTest):
@classmethod
def resource_setup(cls):
if not CONF.service_available.neutron:
raise cls.skipException("Neutron is required")
if not CONF.compute_feature_enabled.interface_attach:
raise cls.skipException("Interface attachment is not available.")
# This test class requires network and subnet
cls.set_network_resources(network=True, subnet=True)
super(AttachInterfacesTestJSON, cls).resource_setup()
cls.client = cls.os.interfaces_client
def _check_interface(self, iface, port_id=None, network_id=None,
fixed_ip=None):
self.assertIn('port_state', iface)
if port_id:
self.assertEqual(iface['port_id'], port_id)
if network_id:
self.assertEqual(iface['net_id'], network_id)
if fixed_ip:
self.assertEqual(iface['fixed_ips'][0]['ip_address'], fixed_ip)
def _create_server_get_interfaces(self):
resp, server = self.create_test_server(wait_until='ACTIVE')
resp, ifs = self.client.list_interfaces(server['id'])
self.assertEqual(200, resp.status)
resp, body = self.client.wait_for_interface_status(
server['id'], ifs[0]['port_id'], 'ACTIVE')
ifs[0]['port_state'] = body['port_state']
return server, ifs
def _test_create_interface(self, server):
resp, iface = self.client.create_interface(server['id'])
self.assertEqual(200, resp.status)
resp, iface = self.client.wait_for_interface_status(
server['id'], iface['port_id'], 'ACTIVE')
self._check_interface(iface)
return iface
def _test_create_interface_by_network_id(self, server, ifs):
network_id = ifs[0]['net_id']
resp, iface = self.client.create_interface(server['id'],
network_id=network_id)
self.assertEqual(200, resp.status)
resp, iface = self.client.wait_for_interface_status(
server['id'], iface['port_id'], 'ACTIVE')
self._check_interface(iface, network_id=network_id)
return iface
def _test_show_interface(self, server, ifs):
iface = ifs[0]
resp, _iface = self.client.show_interface(server['id'],
iface['port_id'])
self.assertEqual(200, resp.status)
self.assertEqual(iface, _iface)
def _test_delete_interface(self, server, ifs):
# NOTE(danms): delete not the first or last, but one in the middle
iface = ifs[1]
resp, _ = self.client.delete_interface(server['id'], iface['port_id'])
self.assertEqual(202, resp.status)
_ifs = self.client.list_interfaces(server['id'])[1]
start = int(time.time())
while len(ifs) == len(_ifs):
time.sleep(self.build_interval)
_ifs = self.client.list_interfaces(server['id'])[1]
timed_out = int(time.time()) - start >= self.build_timeout
if len(ifs) == len(_ifs) and timed_out:
message = ('Failed to delete interface within '
'the required time: %s sec.' % self.build_timeout)
raise exceptions.TimeoutException(message)
self.assertNotIn(iface['port_id'], [i['port_id'] for i in _ifs])
return _ifs
def _compare_iface_list(self, list1, list2):
# NOTE(danms): port_state will likely have changed, so just
# confirm the port_ids are the same at least
list1 = [x['port_id'] for x in list1]
list2 = [x['port_id'] for x in list2]
self.assertEqual(sorted(list1), sorted(list2))
@test.attr(type='smoke')
@test.services('network')
def test_create_list_show_delete_interfaces(self):
server, ifs = self._create_server_get_interfaces()
interface_count = len(ifs)
self.assertTrue(interface_count > 0)
self._check_interface(ifs[0])
iface = self._test_create_interface(server)
ifs.append(iface)
iface = self._test_create_interface_by_network_id(server, ifs)
ifs.append(iface)
resp, _ifs = self.client.list_interfaces(server['id'])
self._compare_iface_list(ifs, _ifs)
self._test_show_interface(server, ifs)
_ifs = self._test_delete_interface(server, ifs)
self.assertEqual(len(ifs) - 1, len(_ifs))
@test.attr(type='smoke')
@test.services('network')
def test_add_remove_fixed_ip(self):
# Add and Remove the fixed IP to server.
server, ifs = self._create_server_get_interfaces()
interface_count = len(ifs)
self.assertTrue(interface_count > 0)
self._check_interface(ifs[0])
network_id = ifs[0]['net_id']
resp, body = self.client.add_fixed_ip(server['id'],
network_id)
self.assertEqual(202, resp.status)
# Remove the fixed IP from server.
server_resp, server_detail = self.os.servers_client.get_server(
server['id'])
# Get the Fixed IP from server.
fixed_ip = None
for ip_set in server_detail['addresses']:
for ip in server_detail['addresses'][ip_set]:
if ip['OS-EXT-IPS:type'] == 'fixed':
fixed_ip = ip['addr']
break
if fixed_ip is not None:
break
resp, body = self.client.remove_fixed_ip(server['id'],
fixed_ip)
self.assertEqual(202, resp.status)
class AttachInterfacesTestXML(AttachInterfacesTestJSON):
_interface = 'xml'
| apache-2.0 |
elasticfence/kaae | public/pages/watcher_wizard/services/wizard_helper/wizard_helper.js | 414 | import { get } from 'lodash';
class WizardHelper {
constructor() {}
isScheduleModeEvery(scheduleString) {
return !!scheduleString.match(/every\s(\d+)\s(seconds|minutes|hours|days|months|years)/);
}
isWizardWatcher(watcher) {
return get(watcher, 'wizard.chart_query_params');
}
getUniqueTagId(name, uuid) {
return name + '_' + uuid.replace(/-/g, '');
}
}
export default WizardHelper;
| apache-2.0 |
jrnz/hadoop | docs/api/org/apache/hadoop/io/class-use/SequenceFile.Sorter.html | 6014 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Wed Oct 03 05:15:38 UTC 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.io.SequenceFile.Sorter (Hadoop 1.0.4 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-03">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.io.SequenceFile.Sorter (Hadoop 1.0.4 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/io/SequenceFile.Sorter.html" title="class in org.apache.hadoop.io"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/io//class-useSequenceFile.Sorter.html" target="_top"><B>FRAMES</B></A>
<A HREF="SequenceFile.Sorter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.io.SequenceFile.Sorter</B></H2>
</CENTER>
No usage of org.apache.hadoop.io.SequenceFile.Sorter
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/io/SequenceFile.Sorter.html" title="class in org.apache.hadoop.io"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/io//class-useSequenceFile.Sorter.html" target="_top"><B>FRAMES</B></A>
<A HREF="SequenceFile.Sorter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| apache-2.0 |
kylebyerly-hp/grommet | src/js/components/icons/base/DocumentConfig.js | 1979 | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-document-config`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-config');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4.99787498,8.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L16,23 M18,1 L18,6 L23,6 M9,14 L9,11 M9,20 C10.6568542,20 12,18.6568542 12,17 C12,15.3431458 10.6568542,14 9,14 C7.34314575,14 6,15.3431458 6,17 C6,18.6568542 7.34314575,20 9,20 Z M9,23 L9,20 M12,17 L15,17 M3,17 L6,17 M5,13 L7,15 M11,19 L13,21 M13,13 L11,15 M7,19 L5,21"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'DocumentConfig';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
| apache-2.0 |
aclissold/uMobile-iOS-app | uMobile/Config.h | 1002 | //
// Config.h
// uMobile
//
// Connects to the umobile-global-config webapp to respond to server-side configuration settings.
//
// Created by Andrew Clissold on 9/30/14.
// Copyright (c) 2014 uMobile. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Config : NSObject<UIAlertViewDelegate>
@property (nonatomic, getter=isAvailable) BOOL available;
@property (nonatomic, getter=isUpgradeRecommended) BOOL upgradeRecommended;
@property (nonatomic, getter=isUpgradeRequired) BOOL upgradeRequired;
// To help determine if ErrorViewController should be presented.
@property (nonatomic, getter=hasUnrecoverableError) BOOL unrecoverableError;
@property (nonatomic, strong) NSArray *disabledPortlets;
@property (nonatomic, strong) NSArray *disabledFolders;
+ (instancetype)sharedConfig;
typedef void (^completion)(void); // crash-course on working with blocks: http://goo.gl/jJzNLr
- (void)checkWithCompletion:(completion)completion;
- (void)showUpgradeRecommendedAlert;
@end
| apache-2.0 |
DavBfr/FreeRDP | winpr/libwinpr/crt/string.c | 9571 | /**
* WinPR: Windows Portable Runtime
* String Manipulation (CRT)
*
* Copyright 2012 Marc-Andre Moreau <[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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <errno.h>
#include <stdio.h>
#include <ctype.h>
#include <wctype.h>
#include <wchar.h>
#include <winpr/crt.h>
#include <winpr/endian.h>
/* String Manipulation (CRT): http://msdn.microsoft.com/en-us/library/f0151s4x.aspx */
#include "../log.h"
#define TAG WINPR_TAG("crt")
#ifndef _WIN32
char* _strdup(const char* strSource)
{
char* strDestination;
if (strSource == NULL)
return NULL;
strDestination = strdup(strSource);
if (strDestination == NULL)
WLog_ERR(TAG, "strdup");
return strDestination;
}
WCHAR* _wcsdup(const WCHAR* strSource)
{
size_t len = _wcslen(strSource);
WCHAR* strDestination;
strDestination = calloc(len + 1, sizeof(WCHAR));
if (strDestination != NULL)
memcpy(strDestination, strSource, len * sizeof(WCHAR));
if (strDestination == NULL)
WLog_ERR(TAG, "wcsdup");
return strDestination;
}
int _stricmp(const char* string1, const char* string2)
{
return strcasecmp(string1, string2);
}
int _strnicmp(const char* string1, const char* string2, size_t count)
{
return strncasecmp(string1, string2, count);
}
/* _wcscmp -> wcscmp */
int _wcscmp(const WCHAR* string1, const WCHAR* string2)
{
WCHAR value1, value2;
while (*string1 && (*string1 == *string2))
{
string1++;
string2++;
}
Data_Read_UINT16(string1, value1);
Data_Read_UINT16(string2, value2);
return value1 - value2;
}
/* _wcslen -> wcslen */
size_t _wcslen(const WCHAR* str)
{
const WCHAR* p = (const WCHAR*)str;
if (!p)
return 0;
while (*p)
p++;
return (size_t)(p - str);
}
/* _wcsnlen -> wcsnlen */
size_t _wcsnlen(const WCHAR* str, size_t max)
{
size_t x;
if (!str)
return 0;
for (x = 0; x < max; x++)
{
if (str[x] == 0)
return x;
}
return x;
}
/* _wcschr -> wcschr */
WCHAR* _wcschr(const WCHAR* str, WCHAR c)
{
const WCHAR* p = (const WCHAR*)str;
WCHAR value;
Data_Write_UINT16(&value, c);
while (*p && (*p != value))
p++;
return ((*p == value) ? (WCHAR*)p : NULL);
}
/* _wcsrchr -> wcsrchr */
WCHAR* _wcsrchr(const WCHAR* str, WCHAR c)
{
const WCHAR* p;
WCHAR ch;
if (!str)
return NULL;
for (p = (const WCHAR*)0; (ch = *str); str++)
if (ch == c)
p = (const WCHAR*)str;
return (WCHAR*)p;
}
char* strtok_s(char* strToken, const char* strDelimit, char** context)
{
return strtok_r(strToken, strDelimit, context);
}
WCHAR* wcstok_s(WCHAR* strToken, const WCHAR* strDelimit, WCHAR** context)
{
WCHAR* nextToken;
WCHAR value;
if (!strToken)
strToken = *context;
Data_Read_UINT16(strToken, value);
while (*strToken && _wcschr(strDelimit, value))
{
strToken++;
Data_Read_UINT16(strToken, value);
}
if (!*strToken)
return NULL;
nextToken = strToken++;
Data_Read_UINT16(strToken, value);
while (*strToken && !(_wcschr(strDelimit, value)))
{
strToken++;
Data_Read_UINT16(strToken, value);
}
if (*strToken)
*strToken++ = 0;
*context = strToken;
return nextToken;
}
#endif
#if !defined(_WIN32) || defined(_UWP)
/* Windows API Sets - api-ms-win-core-string-l2-1-0.dll
* http://msdn.microsoft.com/en-us/library/hh802935/
*/
#include "casing.c"
LPSTR CharUpperA(LPSTR lpsz)
{
size_t i;
size_t length;
if (!lpsz)
return NULL;
length = strlen(lpsz);
if (length < 1)
return (LPSTR)NULL;
if (length == 1)
{
char c = *lpsz;
if ((c >= 'a') && (c <= 'z'))
c = c - 'a' + 'A';
*lpsz = c;
return lpsz;
}
for (i = 0; i < length; i++)
{
if ((lpsz[i] >= 'a') && (lpsz[i] <= 'z'))
lpsz[i] = lpsz[i] - 'a' + 'A';
}
return lpsz;
}
LPWSTR CharUpperW(LPWSTR lpsz)
{
size_t i;
size_t length;
if (!lpsz)
return NULL;
length = _wcslen(lpsz);
if (length < 1)
return (LPWSTR)NULL;
if (length == 1)
{
WCHAR c = *lpsz;
if ((c >= L'a') && (c <= L'z'))
c = c - L'a' + L'A';
*lpsz = c;
return lpsz;
}
for (i = 0; i < length; i++)
{
if ((lpsz[i] >= L'a') && (lpsz[i] <= L'z'))
lpsz[i] = lpsz[i] - L'a' + L'A';
}
return lpsz;
}
DWORD CharUpperBuffA(LPSTR lpsz, DWORD cchLength)
{
DWORD i;
if (cchLength < 1)
return 0;
for (i = 0; i < cchLength; i++)
{
if ((lpsz[i] >= 'a') && (lpsz[i] <= 'z'))
lpsz[i] = lpsz[i] - 'a' + 'A';
}
return cchLength;
}
DWORD CharUpperBuffW(LPWSTR lpsz, DWORD cchLength)
{
DWORD i;
WCHAR value;
for (i = 0; i < cchLength; i++)
{
Data_Read_UINT16(&lpsz[i], value);
value = WINPR_TOUPPERW(value);
Data_Write_UINT16(&lpsz[i], value);
}
return cchLength;
}
LPSTR CharLowerA(LPSTR lpsz)
{
size_t i;
size_t length;
if (!lpsz)
return (LPSTR)NULL;
length = strlen(lpsz);
if (length < 1)
return (LPSTR)NULL;
if (length == 1)
{
char c = *lpsz;
if ((c >= 'A') && (c <= 'Z'))
c = c - 'A' + 'a';
*lpsz = c;
return lpsz;
}
for (i = 0; i < length; i++)
{
if ((lpsz[i] >= 'A') && (lpsz[i] <= 'Z'))
lpsz[i] = lpsz[i] - 'A' + 'a';
}
return lpsz;
}
LPWSTR CharLowerW(LPWSTR lpsz)
{
CharLowerBuffW(lpsz, _wcslen(lpsz));
return lpsz;
}
DWORD CharLowerBuffA(LPSTR lpsz, DWORD cchLength)
{
DWORD i;
if (cchLength < 1)
return 0;
for (i = 0; i < cchLength; i++)
{
if ((lpsz[i] >= 'A') && (lpsz[i] <= 'Z'))
lpsz[i] = lpsz[i] - 'A' + 'a';
}
return cchLength;
}
DWORD CharLowerBuffW(LPWSTR lpsz, DWORD cchLength)
{
DWORD i;
WCHAR value;
for (i = 0; i < cchLength; i++)
{
Data_Read_UINT16(&lpsz[i], value);
value = WINPR_TOLOWERW(value);
Data_Write_UINT16(&lpsz[i], value);
}
return cchLength;
}
BOOL IsCharAlphaA(CHAR ch)
{
if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')))
return 1;
else
return 0;
}
BOOL IsCharAlphaW(WCHAR ch)
{
if (((ch >= L'a') && (ch <= L'z')) || ((ch >= L'A') && (ch <= L'Z')))
return 1;
else
return 0;
}
BOOL IsCharAlphaNumericA(CHAR ch)
{
if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) ||
((ch >= '0') && (ch <= '9')))
return 1;
else
return 0;
}
BOOL IsCharAlphaNumericW(WCHAR ch)
{
if (((ch >= L'a') && (ch <= L'z')) || ((ch >= L'A') && (ch <= L'Z')) ||
((ch >= L'0') && (ch <= L'9')))
return 1;
else
return 0;
}
BOOL IsCharUpperA(CHAR ch)
{
if ((ch >= 'A') && (ch <= 'Z'))
return 1;
else
return 0;
}
BOOL IsCharUpperW(WCHAR ch)
{
if ((ch >= L'A') && (ch <= L'Z'))
return 1;
else
return 0;
}
BOOL IsCharLowerA(CHAR ch)
{
if ((ch >= 'a') && (ch <= 'z'))
return 1;
else
return 0;
}
BOOL IsCharLowerW(WCHAR ch)
{
if ((ch >= L'a') && (ch <= L'z'))
return 1;
else
return 0;
}
int lstrlenA(LPCSTR lpString)
{
return (int)strlen(lpString);
}
int lstrlenW(LPCWSTR lpString)
{
LPCWSTR p;
if (!lpString)
return 0;
p = (LPCWSTR)lpString;
while (*p)
p++;
return (int)(p - lpString);
}
int lstrcmpA(LPCSTR lpString1, LPCSTR lpString2)
{
return strcmp(lpString1, lpString2);
}
int lstrcmpW(LPCWSTR lpString1, LPCWSTR lpString2)
{
WCHAR value1, value2;
while (*lpString1 && (*lpString1 == *lpString2))
{
lpString1++;
lpString2++;
}
Data_Read_UINT16(lpString1, value1);
Data_Read_UINT16(lpString2, value2);
return value1 - value2;
}
#endif
int ConvertLineEndingToLF(char* str, int size)
{
int status;
char* end;
char* pInput;
char* pOutput;
end = &str[size];
pInput = pOutput = str;
while (pInput < end)
{
if ((pInput[0] == '\r') && (pInput[1] == '\n'))
{
*pOutput++ = '\n';
pInput += 2;
}
else
{
*pOutput++ = *pInput++;
}
}
status = (int)(pOutput - str);
return status;
}
char* ConvertLineEndingToCRLF(const char* str, int* size)
{
int count;
char* newStr;
char* pOutput;
const char* end;
const char* pInput;
end = &str[*size];
count = 0;
pInput = str;
while (pInput < end)
{
if (*pInput == '\n')
count++;
pInput++;
}
newStr = (char*)malloc(*size + (count * 2) + 1);
if (!newStr)
return NULL;
pInput = str;
pOutput = newStr;
while (pInput < end)
{
if ((*pInput == '\n') && ((pInput > str) && (pInput[-1] != '\r')))
{
*pOutput++ = '\r';
*pOutput++ = '\n';
}
else
{
*pOutput++ = *pInput;
}
pInput++;
}
*size = (int)(pOutput - newStr);
return newStr;
}
char* StrSep(char** stringp, const char* delim)
{
char* start = *stringp;
char* p;
p = (start != NULL) ? strpbrk(start, delim) : NULL;
if (!p)
*stringp = NULL;
else
{
*p = '\0';
*stringp = p + 1;
}
return start;
}
INT64 GetLine(char** lineptr, size_t* size, FILE* stream)
{
#if defined(_WIN32)
char c;
char* n;
size_t step = 32;
size_t used = 0;
if (!lineptr || !size)
{
errno = EINVAL;
return -1;
}
do
{
if (used + 2 >= *size)
{
*size += step;
n = realloc(*lineptr, *size);
if (!n)
{
return -1;
}
*lineptr = n;
}
c = fgetc(stream);
if (c != EOF)
(*lineptr)[used++] = c;
} while ((c != '\n') && (c != '\r') && (c != EOF));
(*lineptr)[used] = '\0';
return used;
#elif !defined(ANDROID) && !defined(IOS)
return getline(lineptr, size, stream);
#else
return -1;
#endif
}
| apache-2.0 |
kawamon/hue | desktop/core/ext-py/django_opentracing-1.1.0/django_opentracing/middleware.py | 3646 | from django.conf import settings
from django.utils.module_loading import import_string
from .tracing import DjangoTracing
from .tracing import initialize_global_tracer
try:
# Django >= 1.10
from django.utils.deprecation import MiddlewareMixin
except ImportError:
# Not required for Django <= 1.9, see:
# https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware
MiddlewareMixin = object
class OpenTracingMiddleware(MiddlewareMixin):
'''
__init__() is only called once, no arguments, when the Web server
responds to the first request
'''
def __init__(self, get_response=None):
'''
TODO: ANSWER Qs
- Is it better to place all tracing info in the settings file,
or to require a tracing.py file with configurations?
- Also, better to have try/catch with empty tracer or just fail
fast if there's no tracer specified
'''
self._init_tracing()
self._tracing = settings.OPENTRACING_TRACING
self.get_response = get_response
def _init_tracing(self):
if getattr(settings, 'OPENTRACING_TRACER', None) is not None:
# Backwards compatibility.
tracing = settings.OPENTRACING_TRACER
elif getattr(settings, 'OPENTRACING_TRACING', None) is not None:
tracing = settings.OPENTRACING_TRACING
elif getattr(settings, 'OPENTRACING_TRACER_CALLABLE',
None) is not None:
tracer_callable = settings.OPENTRACING_TRACER_CALLABLE
tracer_parameters = getattr(settings,
'OPENTRACING_TRACER_PARAMETERS',
{})
if not callable(tracer_callable):
tracer_callable = import_string(tracer_callable)
tracer = tracer_callable(**tracer_parameters)
tracing = DjangoTracing(tracer)
else:
# Rely on the global Tracer.
tracing = DjangoTracing()
# trace_all defaults to True when used as middleware.
tracing._trace_all = getattr(settings, 'OPENTRACING_TRACE_ALL', True)
# set the start_span_cb hook, if any.
tracing._start_span_cb = getattr(settings, 'OPENTRACING_START_SPAN_CB',
None)
# Normalize the tracing field in settings, including the old field.
settings.OPENTRACING_TRACING = tracing
settings.OPENTRACING_TRACER = tracing
# Potentially set the global Tracer (unless we rely on it already).
if getattr(settings, 'OPENTRACING_SET_GLOBAL_TRACER', False):
initialize_global_tracer(tracing)
def process_view(self, request, view_func, view_args, view_kwargs):
# determine whether this middleware should be applied
# NOTE: if tracing is on but not tracing all requests, then the tracing
# occurs through decorator functions rather than middleware
if not self._tracing._trace_all:
return None
if hasattr(settings, 'OPENTRACING_TRACED_ATTRIBUTES'):
traced_attributes = getattr(settings,
'OPENTRACING_TRACED_ATTRIBUTES')
else:
traced_attributes = []
self._tracing._apply_tracing(request, view_func, traced_attributes)
def process_exception(self, request, exception):
self._tracing._finish_tracing(request, error=exception)
def process_response(self, request, response):
self._tracing._finish_tracing(request, response=response)
return response
| apache-2.0 |
jt70471/aws-sdk-cpp | aws-cpp-sdk-appstream/source/model/CreateFleetRequest.cpp | 3638 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appstream/model/CreateFleetRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::AppStream::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateFleetRequest::CreateFleetRequest() :
m_nameHasBeenSet(false),
m_imageNameHasBeenSet(false),
m_imageArnHasBeenSet(false),
m_instanceTypeHasBeenSet(false),
m_fleetType(FleetType::NOT_SET),
m_fleetTypeHasBeenSet(false),
m_computeCapacityHasBeenSet(false),
m_vpcConfigHasBeenSet(false),
m_maxUserDurationInSeconds(0),
m_maxUserDurationInSecondsHasBeenSet(false),
m_disconnectTimeoutInSeconds(0),
m_disconnectTimeoutInSecondsHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_displayNameHasBeenSet(false),
m_enableDefaultInternetAccess(false),
m_enableDefaultInternetAccessHasBeenSet(false),
m_domainJoinInfoHasBeenSet(false),
m_tagsHasBeenSet(false),
m_idleDisconnectTimeoutInSeconds(0),
m_idleDisconnectTimeoutInSecondsHasBeenSet(false),
m_iamRoleArnHasBeenSet(false),
m_streamView(StreamView::NOT_SET),
m_streamViewHasBeenSet(false)
{
}
Aws::String CreateFleetRequest::SerializePayload() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_imageNameHasBeenSet)
{
payload.WithString("ImageName", m_imageName);
}
if(m_imageArnHasBeenSet)
{
payload.WithString("ImageArn", m_imageArn);
}
if(m_instanceTypeHasBeenSet)
{
payload.WithString("InstanceType", m_instanceType);
}
if(m_fleetTypeHasBeenSet)
{
payload.WithString("FleetType", FleetTypeMapper::GetNameForFleetType(m_fleetType));
}
if(m_computeCapacityHasBeenSet)
{
payload.WithObject("ComputeCapacity", m_computeCapacity.Jsonize());
}
if(m_vpcConfigHasBeenSet)
{
payload.WithObject("VpcConfig", m_vpcConfig.Jsonize());
}
if(m_maxUserDurationInSecondsHasBeenSet)
{
payload.WithInteger("MaxUserDurationInSeconds", m_maxUserDurationInSeconds);
}
if(m_disconnectTimeoutInSecondsHasBeenSet)
{
payload.WithInteger("DisconnectTimeoutInSeconds", m_disconnectTimeoutInSeconds);
}
if(m_descriptionHasBeenSet)
{
payload.WithString("Description", m_description);
}
if(m_displayNameHasBeenSet)
{
payload.WithString("DisplayName", m_displayName);
}
if(m_enableDefaultInternetAccessHasBeenSet)
{
payload.WithBool("EnableDefaultInternetAccess", m_enableDefaultInternetAccess);
}
if(m_domainJoinInfoHasBeenSet)
{
payload.WithObject("DomainJoinInfo", m_domainJoinInfo.Jsonize());
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("Tags", std::move(tagsJsonMap));
}
if(m_idleDisconnectTimeoutInSecondsHasBeenSet)
{
payload.WithInteger("IdleDisconnectTimeoutInSeconds", m_idleDisconnectTimeoutInSeconds);
}
if(m_iamRoleArnHasBeenSet)
{
payload.WithString("IamRoleArn", m_iamRoleArn);
}
if(m_streamViewHasBeenSet)
{
payload.WithString("StreamView", StreamViewMapper::GetNameForStreamView(m_streamView));
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection CreateFleetRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "PhotonAdminProxyService.CreateFleet"));
return headers;
}
| apache-2.0 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/font/FontItemBase.java | 6279 | /**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* 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.resource.font;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import org.jrebirth.af.api.resource.builder.VariantResourceBuilder;
import org.jrebirth.af.api.resource.font.FontExtension;
import org.jrebirth.af.api.resource.font.FontItem;
import org.jrebirth.af.api.resource.font.FontName;
import org.jrebirth.af.api.resource.font.FontParams;
import org.jrebirth.af.core.resource.ResourceBuilders;
/**
* The interface <strong>FontItemReal</strong> used to provided convenient shortcuts for initializing a {@link Font}.
*
* @author Sébastien Bordes
*/
public interface FontItemBase extends FontItem {
/**
* {@inheritDoc}
*/
@Override
default VariantResourceBuilder<FontItem, FontParams, Font, Double> builder() {
return ResourceBuilders.FONT_BUILDER;
}
/**
* The interface <strong>Real</strong> provides shortcuts method used to build and register a {@link RealFont}.
*/
interface Real extends FontItemBase {
/**
* Build and register a {@link RealFont} {@link FontParams}.
*
* @param name the name of the font
* @param size the size of the font
* @param extension the font extension
*/
default void real(final FontName name, final double size, final FontExtension extension) {
set(new RealFont(name, size, extension));
}
/**
* Build and register a {@link RealFont} {@link FontParams}.
*
* @param name the name of the font
* @param size the size of the font
*/
default void real(final FontName name, final double size) {
set(new RealFont(name, size));
}
}
/**
* The interface <strong>Family</strong> provides shortcuts method used to build and register a {@link FamilyFont}.
*/
interface Family extends FontItemBase {
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param extension the font extension
*/
default void family(final String family, final double size, final FontExtension extension) {
set(new FamilyFont(family, size, extension));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param weight the font weight {@link FontWeight}
* @param extension the font extension
*/
default void family(final String family, final double size, final FontWeight weight, final FontExtension extension) {
set(new FamilyFont(family, size, extension, weight));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param extension the font extension
* @param posture the font posture {@link FontPosture}
*/
default void family(final String family, final double size, final FontExtension extension, final FontPosture posture) {
set(new FamilyFont(family, size, extension, posture));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param extension the font extension
* @param weight the font weight {@link FontWeight}
* @param posture the font posture {@link FontPosture}
*/
default void family(final String family, final double size, final FontExtension extension, final FontWeight weight, final FontPosture posture) {
set(new FamilyFont(family, size, extension, weight, posture));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
*/
default void family(final String family, final double size) {
set(new FamilyFont(family, size));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param weight the font weight {@link FontWeight}
*/
default void family(final String family, final double size, final FontWeight weight) {
set(new FamilyFont(family, size, weight));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param posture the font posture {@link FontPosture}
*/
default void family(final String family, final double size, final FontPosture posture) {
set(new FamilyFont(family, size, posture));
}
/**
* Build and register a {@link FamilyFont} {@link FontParams}.
*
* @param family the font family
* @param size the font size
* @param weight the font weight {@link FontWeight}
* @param posture the font posture {@link FontPosture}
*/
default void family(final String family, final double size, final FontWeight weight, final FontPosture posture) {
set(new FamilyFont(family, size, weight, posture));
}
}
}
| apache-2.0 |
yarish/tinylog | tinylog/src/main/java/org/pmw/tinylog/Tokenizer.java | 21096 | /*
* Copyright 2012 Martin Winandy
*
* 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.pmw.tinylog;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.pmw.tinylog.writers.LogEntryValue;
/**
* Converts a format pattern for log entries to a list of tokens.
*
* @see Logger#setLoggingFormat(String)
*/
final class Tokenizer {
private static final String DEFAULT_DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String NEW_LINE = EnvironmentHelper.getNewLine();
private static final Pattern NEW_LINE_REPLACER = Pattern.compile("\r\n|\\\\r\\\\n|\n|\\\\n|\r|\\\\r");
private static final String TAB = "\t";
private static final Pattern TAB_REPLACER = Pattern.compile("\t|\\\\t");
private final Locale locale;
private final int maxStackTraceElements;
private int index;
/**
* @param locale
* Locale for formatting
* @param maxStackTraceElements
* Limit of stack traces for exceptions
*/
Tokenizer(final Locale locale, final int maxStackTraceElements) {
this.locale = locale;
this.maxStackTraceElements = maxStackTraceElements;
}
/**
* Parse a format pattern.
*
* @param formatPattern
* Format pattern for log entries
*
* @return List of tokens
*/
List<Token> parse(final String formatPattern) {
List<Token> tokens = new ArrayList<>();
index = 0;
while (index < formatPattern.length()) {
char c = formatPattern.charAt(index);
int start = index;
while (c != '{' && c != '}') {
++index;
if (index >= formatPattern.length()) {
tokens.add(getPlainTextToken(formatPattern.substring(start, index)));
return tokens;
}
c = formatPattern.charAt(index);
}
if (index > start) {
tokens.add(getPlainTextToken(formatPattern.substring(start, index)));
}
if (c == '{') {
Token token = parsePartly(formatPattern);
if (token != null) {
tokens.add(token);
}
} else if (c == '}') {
InternalLogger.warn("Opening curly brace is missing for: \"{}\"", formatPattern.substring(0, index + 1));
++index;
}
}
return tokens;
}
private Token parsePartly(final String formatPattern) {
List<Token> tokens = new ArrayList<>();
int[] options = new int[] { 0 /* minimum size */, 0 /* indent */};
int offset = index;
++index;
while (index < formatPattern.length()) {
char c = formatPattern.charAt(index);
int start = index;
while (c != '{' && c != '|' && c != '}') {
++index;
if (index >= formatPattern.length()) {
InternalLogger.warn("Closing curly brace is missing for: \"{}\"", formatPattern.substring(offset, index));
tokens.add(getToken(formatPattern.substring(start, index)));
return combine(tokens, options);
}
c = formatPattern.charAt(index);
}
if (index > start) {
if (c == '{') {
tokens.add(getPlainTextToken(formatPattern.substring(start, index)));
} else {
tokens.add(getToken(formatPattern.substring(start, index)));
}
}
if (c == '{') {
Token token = parsePartly(formatPattern);
if (token != null) {
tokens.add(token);
}
} else if (c == '|') {
++index;
start = index;
while (c != '{' && c != '}') {
++index;
if (index >= formatPattern.length()) {
InternalLogger.warn("Closing curly brace is missing for: \"{}\"", formatPattern.substring(offset, index));
options = parseOptions(formatPattern.substring(start));
return combine(tokens, options);
}
c = formatPattern.charAt(index);
}
if (index > start) {
options = parseOptions(formatPattern.substring(start, index));
}
} else if (c == '}') {
++index;
return combine(tokens, options);
}
}
InternalLogger.warn("Closing curly brace is missing for: \"{}\"", formatPattern.substring(offset, index));
return combine(tokens, options);
}
private Token getToken(final String text) {
if (text.equals("date")) {
return new DateToken(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT_PATTERN, locale));
} else if (text.startsWith("date:")) {
String dateFormatPattern = text.substring(5, text.length());
try {
return new DateToken(DateTimeFormatter.ofPattern(dateFormatPattern, locale));
} catch (IllegalArgumentException ex) {
InternalLogger.error(ex, "\"{}\" is an invalid date format pattern", dateFormatPattern);
return new DateToken(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT_PATTERN, locale));
}
} else if ("pid".equals(text)) {
return new PlainTextToken(EnvironmentHelper.getProcessId());
} else if (text.startsWith("pid:")) {
InternalLogger.warn("\"{pid}\" does not support parameters");
return new PlainTextToken(EnvironmentHelper.getProcessId().toString());
} else if ("thread".equals(text)) {
return new ThreadNameToken();
} else if (text.startsWith("thread:")) {
InternalLogger.warn("\"{thread}\" does not support parameters");
return new ThreadNameToken();
} else if ("thread_id".equals(text)) {
return new ThreadIdToken();
} else if (text.startsWith("thread_id:")) {
InternalLogger.warn("\"{thread_id}\" does not support parameters");
return new ThreadIdToken();
} else if ("class".equals(text)) {
return new ClassToken();
} else if (text.startsWith("class:")) {
InternalLogger.warn("\"{class}\" does not support parameters");
return new ClassToken();
} else if ("class_name".equals(text)) {
return new ClassNameToken();
} else if (text.startsWith("class_name:")) {
InternalLogger.warn("\"{class_name}\" does not support parameters");
return new ClassNameToken();
} else if ("package".equals(text)) {
return new PackageToken();
} else if (text.startsWith("package:")) {
InternalLogger.warn("\"{package}\" does not support parameters");
return new PackageToken();
} else if ("method".equals(text)) {
return new MethodToken();
} else if (text.startsWith("method:")) {
InternalLogger.warn("\"{method}\" does not support parameters");
return new MethodToken();
} else if ("file".equals(text)) {
return new FileToken();
} else if (text.startsWith("file:")) {
InternalLogger.warn("\"{file}\" does not support parameters");
return new FileToken();
} else if ("line".equals(text)) {
return new LineToken();
} else if (text.startsWith("line:")) {
InternalLogger.warn("\"{line}\" does not support parameters");
return new LineToken();
} else if ("level".equals(text)) {
return new LevelToken();
} else if (text.startsWith("level:")) {
InternalLogger.warn("\"{level}\" does not support parameters");
return new LevelToken();
} else if ("message".equals(text)) {
return new MessageToken(maxStackTraceElements);
} else if (text.startsWith("message:")) {
InternalLogger.warn("\"{message}\" does not support parameters");
return new MessageToken(maxStackTraceElements);
} else {
return getPlainTextToken(text);
}
}
private static Token getPlainTextToken(final String text) {
String plainText = NEW_LINE_REPLACER.matcher(text).replaceAll(NEW_LINE);
plainText = TAB_REPLACER.matcher(plainText).replaceAll(TAB);
return new PlainTextToken(plainText);
}
private static int[] parseOptions(final String text) {
int minSize = 0;
int indent = 0;
int index = 0;
while (index < text.length()) {
char c = text.charAt(index);
while (c == ',') {
++index;
if (index >= text.length()) {
return new int[] { minSize, indent };
}
c = text.charAt(index);
}
int start = index;
while (c != ',') {
++index;
if (index >= text.length()) {
break;
}
c = text.charAt(index);
}
if (index > start) {
String parameter = text.substring(start, index);
int splitter = parameter.indexOf('=');
if (splitter == -1) {
parameter = parameter.trim();
if ("min-size".equals(parameter)) {
InternalLogger.warn("No value set for \"min-size\"");
} else if ("indent".equals(parameter)) {
InternalLogger.warn("No value set for \"indent\"");
} else {
InternalLogger.warn("Unknown option \"{}\"", parameter);
}
} else {
String key = parameter.substring(0, splitter).trim();
String value = parameter.substring(splitter + 1).trim();
if ("min-size".equals(key)) {
if (value.length() == 0) {
InternalLogger.warn("No value set for \"min-size\"");
} else {
try {
minSize = parsePositiveInt(value);
} catch (NumberFormatException ex) {
InternalLogger.warn("\"{}\" is an invalid number for \"min-size\"", value);
}
}
} else if ("indent".equals(key)) {
if (value.length() == 0) {
InternalLogger.warn("No value set for \"indent\"");
} else {
try {
indent = parsePositiveInt(value);
} catch (NumberFormatException ex) {
InternalLogger.warn("\"{}\" is an invalid number for \"indent\"", value);
}
}
} else {
InternalLogger.warn("Unknown option \"{}\"", key);
}
}
}
}
return new int[] { minSize, indent };
}
private static int parsePositiveInt(final String value) throws NumberFormatException {
int number = Integer.parseInt(value);
if (number >= 0) {
return number;
} else {
throw new NumberFormatException();
}
}
private static Token combine(final List<Token> tokens, final int[] options) {
int minSize = options[0];
int indent = options[1];
if (tokens.isEmpty()) {
return null;
} else if (tokens.size() == 1) {
if (indent > 0) {
return new IndentToken(tokens.get(0), indent);
} else if (minSize > 0) {
return new MinSizeToken(tokens.get(0), minSize);
} else {
return tokens.get(0);
}
} else {
if (indent > 0) {
return new IndentToken(new BundlerToken(tokens), indent);
} else if (minSize > 0) {
return new MinSizeToken(new BundlerToken(tokens), minSize);
} else {
return new BundlerToken(tokens);
}
}
}
private static final class BundlerToken implements Token {
private final List<Token> tokens;
private BundlerToken(final List<Token> tokens) {
this.tokens = tokens;
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
Collection<LogEntryValue> values = EnumSet.noneOf(LogEntryValue.class);
for (Token token : tokens) {
values.addAll(token.getRequiredLogEntryValues());
}
return values;
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
for (Token token : tokens) {
token.render(logEntry, builder);
}
}
}
private static final class MinSizeToken implements Token {
private final Token token;
private final int minSize;
private MinSizeToken(final Token token, final int minSize) {
this.token = token;
this.minSize = minSize;
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return token.getRequiredLogEntryValues();
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
int offset = builder.length();
token.render(logEntry, builder);
int size = builder.length() - offset;
if (size < minSize) {
char[] spaces = new char[minSize - size];
Arrays.fill(spaces, ' ');
builder.append(spaces);
}
}
}
private static final class IndentToken implements Token {
private final Token token;
private final char[] spaces;
private IndentToken(final Token token, final int indent) {
this.token = token;
this.spaces = new char[indent];
Arrays.fill(spaces, ' ');
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return token.getRequiredLogEntryValues();
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
if (builder.length() == 0 || builder.charAt(builder.length() - 1) == '\n' || builder.charAt(builder.length() - 1) == '\r') {
builder.append(spaces);
}
StringBuilder subBuilder = new StringBuilder(1024);
token.render(logEntry, subBuilder);
int head = 0;
for (int i = head; i < subBuilder.length(); ++i) {
char c = subBuilder.charAt(i);
if (c == '\n') {
builder.append(subBuilder, head, i + 1);
builder.append(spaces);
head = i + 1;
} else if (c == '\r') {
if (i + 1 < subBuilder.length() && subBuilder.charAt(i + 1) == '\n') {
++i;
}
builder.append(subBuilder, head, i + 1);
builder.append(spaces);
head = i + 1;
} else if (head == i && (c == ' ' || c == '\t')) {
++head;
}
}
if (head < subBuilder.length()) {
builder.append(subBuilder, head, subBuilder.length());
}
}
}
private static final class DateToken implements Token {
private final DateTimeFormatter formatter;
private DateToken(final DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.DATE);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(formatter.format(logEntry.getDate()));
}
}
private static final class ThreadNameToken implements Token {
private ThreadNameToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.THREAD);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getThread().getName());
}
};
private static final class ThreadIdToken implements Token {
public ThreadIdToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.THREAD);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getThread().getId());
}
}
private static final class ClassToken implements Token {
public ClassToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.CLASS);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getClassName());
}
}
private static final class ClassNameToken implements Token {
public ClassNameToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.CLASS);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
String fullyQualifiedClassName = logEntry.getClassName();
int dotIndex = fullyQualifiedClassName.lastIndexOf('.');
if (dotIndex < 0) {
builder.append(fullyQualifiedClassName);
} else {
builder.append(fullyQualifiedClassName.substring(dotIndex + 1));
}
}
}
private static final class PackageToken implements Token {
private PackageToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.CLASS);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
String fullyQualifiedClassName = logEntry.getClassName();
int dotIndex = fullyQualifiedClassName.lastIndexOf('.');
if (dotIndex != -1) {
builder.append(fullyQualifiedClassName.substring(0, dotIndex));
}
}
}
private static final class MethodToken implements Token {
private MethodToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.METHOD);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getMethodName());
}
}
private static final class FileToken implements Token {
private FileToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.FILE);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getFilename());
}
}
private static final class LineToken implements Token {
private LineToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.LINE);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getLineNumber());
}
}
private static final class LevelToken implements Token {
private LevelToken() {
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.LEVEL);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(logEntry.getLevel());
}
}
private static final class MessageToken implements Token {
private static final String NEW_LINE = EnvironmentHelper.getNewLine();
private final int maxStackTraceElements;
private MessageToken(final int maxStackTraceElements) {
this.maxStackTraceElements = maxStackTraceElements;
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.singletonList(LogEntryValue.MESSAGE);
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
String message = logEntry.getMessage();
if (message != null) {
builder.append(message);
}
Throwable exception = logEntry.getException();
if (exception != null) {
if (message != null) {
builder.append(": ");
}
formatException(builder, exception, maxStackTraceElements);
}
}
private static void formatException(final StringBuilder builder, final Throwable exception, final int maxStackTraceElements) {
if (maxStackTraceElements == 0) {
builder.append(exception.getClass().getName());
String exceptionMessage = exception.getMessage();
if (exceptionMessage != null) {
builder.append(": ");
builder.append(exceptionMessage);
}
} else {
formatExceptionWithStackTrace(builder, exception, maxStackTraceElements);
}
}
private static void formatExceptionWithStackTrace(final StringBuilder builder, final Throwable exception, final int countStackTraceElements) {
builder.append(exception.getClass().getName());
String message = exception.getMessage();
if (message != null) {
builder.append(": ");
builder.append(message);
}
StackTraceElement[] stackTrace = exception.getStackTrace();
int length = Math.min(stackTrace.length, Math.max(1, countStackTraceElements));
for (int i = 0; i < length; ++i) {
builder.append(NEW_LINE);
builder.append('\t');
builder.append("at ");
builder.append(stackTrace[i]);
}
if (stackTrace.length > length) {
builder.append(NEW_LINE);
builder.append('\t');
builder.append("...");
} else {
Throwable cause = exception.getCause();
if (cause != null) {
builder.append(NEW_LINE);
builder.append("Caused by: ");
formatExceptionWithStackTrace(builder, cause, countStackTraceElements - length);
}
}
}
}
private static final class PlainTextToken implements Token {
private final String text;
private PlainTextToken(final String text) {
this.text = text;
}
@Override
public Collection<LogEntryValue> getRequiredLogEntryValues() {
return Collections.emptyList();
}
@Override
public void render(final LogEntry logEntry, final StringBuilder builder) {
builder.append(text);
}
}
}
| apache-2.0 |
SummerBatch/SummerBatch | Summer.Batch.Extra/Ebcdic/IEbcdicReaderMapper.cs | 1853 | //
// Copyright 2015 Blu Age Corporation - Plano, Texas
//
// 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.
using System.Collections.Generic;
using Summer.Batch.Extra.Copybook;
namespace Summer.Batch.Extra.Ebcdic
{
/// <summary>
/// An EbcdicReaderMapper maps a list of fields, corresponding to an EBCDIC
/// record, to a business object.
/// </summary>
/// <typeparam name="TT"> </typeparam>
public interface IEbcdicReaderMapper<out TT>
{
/// <summary>
/// Converts the content of a list of values into a business object.
/// </summary>
/// <param name="values">the list of values to map</param>
/// <param name="itemCount">the record line number, starting at 0.</param>
/// <returns>The mapped object</returns>
TT Map(IList<object> values, int itemCount);
/// <summary>
/// Sets the record format map to use for mapping
/// </summary>
RecordFormatMap RecordFormatMap { set; }
/// <summary>
/// Sets the date parser
/// </summary>
IDateParser DateParser { set; }
/// <summary>
/// The getter for the distinguished pattern.
/// </summary>
string DistinguishedPattern { get; }
}
} | apache-2.0 |
kierarad/gocd | config/config-api/src/main/java/com/thoughtworks/go/config/registry/NoPluginsInstalled.java | 1001 | /*
* Copyright 2019 ThoughtWorks, 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.thoughtworks.go.config.registry;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.go.plugins.PluginExtensions;
import org.springframework.stereotype.Component;
@Component
public class NoPluginsInstalled implements PluginExtensions {
@Override
public List<ConfigurationExtension> configTagImplementations() {
return new ArrayList<>();
}
}
| apache-2.0 |
workflowproducts/envelope | src/app/developer_g/greyspots-1.1.1/documentation/doc-library/css-test-1.html | 4608 | <!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, minimal-ui" />
<title>CSS test</title>
<script src="/js/greyspots.js" type="text/javascript"></script>
<link href="/css/greyspots.css" type="text/css" rel="stylesheet" />
<script>
function windowSizeHandler() {
if (window.innerWidth <= 768 && !document.getElementById('child-3').style.height) {
document.getElementById('child-3').style.height =
(document.getElementById('child-1').offsetHeight + document.getElementById('child-2').offsetHeight) + 'px';
} else if (window.innerWidth > 768 && document.getElementById('child-3').style.height) {
document.getElementById('child-3').style.height = '';
}
}
function addToChild(strChildNumber) {
document.getElementById('child-' + strChildNumber).innerHTML += '<div>test</div>';
windowSizeHandler();
}
function takeFromChild(strChildNumber) {
document.getElementById('child-' + strChildNumber).removeChild(
document.getElementById('child-' + strChildNumber).children[
document.getElementById('child-' + strChildNumber).children.length - 1]);
windowSizeHandler();
}
window.addEventListener('resize', windowSizeHandler);
window.addEventListener('load', windowSizeHandler);
</script>
<style>
#parent {
position: relative;
background-color: #FF0000; /* red */
}
#child-1 {
width: 50%;
height: auto;
background-color: #00FF00; /* green */
}
#child-2 {
width: 50%;
height: auto;
background-color: #00FFFF; /* cyan*/
}
#child-3 {
position: absolute;
left: 50%;
top: 0;
width: 50%;
height: 100%;
background-color: #0000FF; /* blue */
}
#child-4 {
background-color: #FFFF00; /* yellow */
}
/* reflow CSS */
@media only screen and (max-width: 768px) {
#child-1,
#child-2 {
width: auto;
}
#child-3 {
position: static;
left: auto;
top: auto;
width: auto;
}
}
</style>
</head>
<body>
<gs-page>
<gs-header>
<h3>CSS test</h3>
<gs-button onclick="addToChild('1')">Green Element Taller</gs-button>
<gs-button onclick="takeFromChild('1')">Green Element Shorter</gs-button>
<br />
<gs-button onclick="addToChild('2')">Cyan Element Taller</gs-button>
<gs-button onclick="takeFromChild('2')">Cyan Element Shorter</gs-button>
</gs-header>
<gs-body padded>
<div id="parent">
<div id="child-1">
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
<div id="child-2">
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
<br />
<div id="child-3" flex-vertical flex-fill>
<gs-text></gs-text>
<br />
<div id="child-4" flex></div>
</div>
</div>
</gs-body>
</gs-page>
</body>
</html> | apache-2.0 |
sankarh/hive | standalone-metastore/metastore-common/src/gen/thrift/gen-php/metastore/GetProjectionsSpec.php | 5244 | <?php
namespace metastore;
/**
* Autogenerated by Thrift Compiler (0.14.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
class GetProjectionsSpec
{
static public $isValidate = false;
static public $_TSPEC = array(
1 => array(
'var' => 'fieldList',
'isRequired' => false,
'type' => TType::LST,
'etype' => TType::STRING,
'elem' => array(
'type' => TType::STRING,
),
),
2 => array(
'var' => 'includeParamKeyPattern',
'isRequired' => false,
'type' => TType::STRING,
),
3 => array(
'var' => 'excludeParamKeyPattern',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string[]
*/
public $fieldList = null;
/**
* @var string
*/
public $includeParamKeyPattern = null;
/**
* @var string
*/
public $excludeParamKeyPattern = null;
public function __construct($vals = null)
{
if (is_array($vals)) {
if (isset($vals['fieldList'])) {
$this->fieldList = $vals['fieldList'];
}
if (isset($vals['includeParamKeyPattern'])) {
$this->includeParamKeyPattern = $vals['includeParamKeyPattern'];
}
if (isset($vals['excludeParamKeyPattern'])) {
$this->excludeParamKeyPattern = $vals['excludeParamKeyPattern'];
}
}
}
public function getName()
{
return 'GetProjectionsSpec';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true) {
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid) {
case 1:
if ($ftype == TType::LST) {
$this->fieldList = array();
$_size935 = 0;
$_etype938 = 0;
$xfer += $input->readListBegin($_etype938, $_size935);
for ($_i939 = 0; $_i939 < $_size935; ++$_i939) {
$elem940 = null;
$xfer += $input->readString($elem940);
$this->fieldList []= $elem940;
}
$xfer += $input->readListEnd();
} else {
$xfer += $input->skip($ftype);
}
break;
case 2:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->includeParamKeyPattern);
} else {
$xfer += $input->skip($ftype);
}
break;
case 3:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->excludeParamKeyPattern);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output)
{
$xfer = 0;
$xfer += $output->writeStructBegin('GetProjectionsSpec');
if ($this->fieldList !== null) {
if (!is_array($this->fieldList)) {
throw new TProtocolException('Bad type in structure.', TProtocolException::INVALID_DATA);
}
$xfer += $output->writeFieldBegin('fieldList', TType::LST, 1);
$output->writeListBegin(TType::STRING, count($this->fieldList));
foreach ($this->fieldList as $iter941) {
$xfer += $output->writeString($iter941);
}
$output->writeListEnd();
$xfer += $output->writeFieldEnd();
}
if ($this->includeParamKeyPattern !== null) {
$xfer += $output->writeFieldBegin('includeParamKeyPattern', TType::STRING, 2);
$xfer += $output->writeString($this->includeParamKeyPattern);
$xfer += $output->writeFieldEnd();
}
if ($this->excludeParamKeyPattern !== null) {
$xfer += $output->writeFieldBegin('excludeParamKeyPattern', TType::STRING, 3);
$xfer += $output->writeString($this->excludeParamKeyPattern);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
| apache-2.0 |
saeta/penguin | docs/parallel/docsets/PenguinParallel.docset/Contents/Resources/Documents/Protocols/ConditionVariableProtocol.html | 15780 | <!DOCTYPE html>
<html lang="en">
<head>
<title>ConditionVariableProtocol Protocol Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset="utf-8">
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
<script src="../js/lunr.min.js" defer></script>
<script src="../js/typeahead.jquery.js" defer></script>
<script src="../js/jazzy.search.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Protocol/ConditionVariableProtocol" class="dashAnchor"></a>
<a title="ConditionVariableProtocol Protocol Reference"></a>
<header class="header">
<p class="header-col header-col--primary">
<a class="header-link" href="../index.html">
PenguinParallel Docs
</a>
(95% documented)
</p>
<p class="header-col--secondary">
<form role="search" action="../search.json">
<input type="text" placeholder="Search documentation" data-typeahead>
</form>
</p>
<p class="header-col header-col--secondary">
<a class="header-link" href="https://github.com/saeta/penguin">
<img class="header-icon" src="../img/gh.png"/>
View on GitHub
</a>
</p>
</header>
<p class="breadcrumbs">
<a class="breadcrumb" href="../index.html">PenguinParallel Reference</a>
<img class="carat" src="../img/carat.png" />
ConditionVariableProtocol Protocol Reference
</p>
<div class="content-wrapper">
<nav class="navigation">
<ul class="nav-groups">
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Parallel.html">Parallel</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/Array.html">Array</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Other%20Classes.html">Other Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/NonBlockingThreadPool.html">NonBlockingThreadPool</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/NonblockingCondition.html">NonblockingCondition</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Other%20Enums.html">Other Enumerations</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/ComputeThreadPools.html">ComputeThreadPools</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Other%20Protocols.html">Other Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ComputeThreadPool.html">ComputeThreadPool</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ConcurrencyPlatform.html">ConcurrencyPlatform</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ConditionMutexProtocol.html">ConditionMutexProtocol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ConditionVariableProtocol.html">ConditionVariableProtocol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/MutexProtocol.html">MutexProtocol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/RawThreadLocalStorage.html">RawThreadLocalStorage</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ThreadProtocol.html">ThreadProtocol</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Other%20Structs.html">Other Structures</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/InlineComputeThreadPool.html">InlineComputeThreadPool</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/PosixThreadLocalStorage.html">PosixThreadLocalStorage</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/PosixThreadLocalStorage.html#/s:15PenguinParallel21RawThreadLocalStorageP3KeyQa">– Key</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/TypedThreadLocalStorage.html">TypedThreadLocalStorage</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/TypedThreadLocalStorage/Key.html">– Key</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section class="section">
<div class="section-content top-matter">
<h1>ConditionVariableProtocol</h1>
<div class="declaration">
<div class="language">
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">protocol</span> <span class="kt">ConditionVariableProtocol</span></code></pre>
</div>
</div>
<p>A condition variable.</p>
<p>Only perform operations on <code>self</code> when holding the mutex associated with <code>self</code>.</p>
<div class="slightly-smaller">
<a href="https://github.com/saeta/penguin/tree/main/Sources/PenguinParallel/ConcurrencyPlatform.swift#L118-L140">Show on GitHub</a>
</div>
</div>
</section>
<section class="section">
<div class="section-content">
<div class="task-group">
<ul class="item-container">
<li class="item">
<div>
<code>
<a name="/s:15PenguinParallel25ConditionVariableProtocolP5MutexQa"></a>
<a name="//apple_ref/swift/Alias/Mutex" class="dashAnchor"></a>
<a class="token" href="#/s:15PenguinParallel25ConditionVariableProtocolP5MutexQa">Mutex</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The mutex type associated with this condition variable.</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">associatedtype</span> <span class="kt">Mutex</span> <span class="p">:</span> <span class="kt"><a href="../Protocols/MutexProtocol.html">MutexProtocol</a></span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/saeta/penguin/tree/main/Sources/PenguinParallel/ConcurrencyPlatform.swift#L120">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:15PenguinParallel25ConditionVariableProtocolPxycfc"></a>
<a name="//apple_ref/swift/Method/init()" class="dashAnchor"></a>
<a class="token" href="#/s:15PenguinParallel25ConditionVariableProtocolPxycfc">init()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Initializes <code>self</code>.</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="nf">init</span><span class="p">()</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/saeta/penguin/tree/main/Sources/PenguinParallel/ConcurrencyPlatform.swift#L123">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:15PenguinParallel25ConditionVariableProtocolP4waityy5MutexQzF"></a>
<a name="//apple_ref/swift/Method/wait(_:)" class="dashAnchor"></a>
<a class="token" href="#/s:15PenguinParallel25ConditionVariableProtocolP4waityy5MutexQzF">wait(_:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Wait until signaled, releasing <code>lock</code> while waiting.</p>
<div class="aside aside-precondition">
<p class="aside-title">Precondition</p>
<code>lock</code> is locked.
</div><div class="aside aside-postcondition">
<p class="aside-title">Postcondition</p>
<code>lock</code> is locked.
</div>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">func</span> <span class="nf">wait</span><span class="p">(</span><span class="n">_</span> <span class="nv">lock</span><span class="p">:</span> <span class="kt"><a href="../Protocols/ConditionVariableProtocol.html#/s:15PenguinParallel25ConditionVariableProtocolP5MutexQa">Mutex</a></span><span class="p">)</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/saeta/penguin/tree/main/Sources/PenguinParallel/ConcurrencyPlatform.swift#L129">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:15PenguinParallel25ConditionVariableProtocolP6signalyyF"></a>
<a name="//apple_ref/swift/Method/signal()" class="dashAnchor"></a>
<a class="token" href="#/s:15PenguinParallel25ConditionVariableProtocolP6signalyyF">signal()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Wake up one waiter.</p>
<div class="aside aside-precondition">
<p class="aside-title">Precondition</p>
the <code>lock</code> associated with <code>self</code> is locked.
</div>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">func</span> <span class="nf">signal</span><span class="p">()</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/saeta/penguin/tree/main/Sources/PenguinParallel/ConcurrencyPlatform.swift#L134">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:15PenguinParallel25ConditionVariableProtocolP9broadcastyyF"></a>
<a name="//apple_ref/swift/Method/broadcast()" class="dashAnchor"></a>
<a class="token" href="#/s:15PenguinParallel25ConditionVariableProtocolP9broadcastyyF">broadcast()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Wake up all waiters.</p>
<div class="aside aside-precondition">
<p class="aside-title">Precondition</p>
the <code>lock</code> associated with <code>self</code> is locked.
</div>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">func</span> <span class="nf">broadcast</span><span class="p">()</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/saeta/penguin/tree/main/Sources/PenguinParallel/ConcurrencyPlatform.swift#L139">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
</div>
</section>
</article>
</div>
<section class="footer">
<p>© 2020 <a class="link" href="https://github.com/saeta" target="_blank" rel="external">Brennan Saeta <a href="mailto:[email protected]">[email protected]</a></a>. All rights reserved. (Last updated: 2020-12-07)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.6</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</body>
</div>
</html>
| apache-2.0 |
missedone/testng | src/main/java/org/testng/TestNGAntTask.java | 32705 | package org.testng;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.ExecuteWatchdog;
import org.apache.tools.ant.taskdefs.LogOutputStream;
import org.apache.tools.ant.taskdefs.PumpStreamHandler;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PropertySet;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.types.selectors.FilenameSelector;
import org.testng.collections.Lists;
import org.testng.internal.ExitCode;
import org.testng.internal.Utils;
import org.testng.log4testng.Logger;
import org.testng.reporters.VerboseReporter;
import static java.lang.Boolean.TRUE;
import static org.testng.internal.Utils.isStringNotBlank;
/**
* TestNG settings:
*
* <ul>
* <li>classfileset (inner)
* <li>classfilesetref (attribute)
* <li>xmlfileset (inner)
* <li>xmlfilesetref (attribute)
* <li>enableAssert (attribute)
* <li>excludedGroups (attribute)
* <li>groups (attribute)
* <li>junit (attribute)
* <li>listener (attribute)
* <li>outputdir (attribute)
* <li>parallel (attribute)
* <li>reporter (attribute)
* <li>sourcedir (attribute)
* <li>sourcedirref (attribute)
* <li>suitename (attribute)
* <li>suiterunnerclass (attribute)
* <li>target (attribute)
* <li>testjar (attribute)
* <li>testname (attribute)
* <li>threadcount (attribute)
* <li>dataproviderthreadcount (attribute)
* <li>verbose (attribute)
* <li>testrunfactory (attribute)
* <li>configFailurepolicy (attribute)
* <li>randomizeSuites (attribute)
* <li>methodselectors (attribute)
* </ul>
*
* Ant settings:
*
* <ul>
* <li>classpath (inner)
* <li>classpathref (attribute)
* <li>jvm (attribute)
* <li>workingDir (attribute)
* <li>env (inner)
* <li>sysproperty (inner)
* <li>propertyset (inner)
* <li>jvmarg (inner)
* <li>timeout (attribute)
* <li>haltonfailure (attribute)
* <li>onHaltTarget (attribute)
* <li>failureProperty (attribute)
* <li>haltonFSP (attribute)
* <li>FSPproperty (attribute)
* <li>haltonskipped (attribute)
* <li>skippedProperty (attribute)
* <li>testRunnerFactory (attribute)
* </ul>
*
* Debug information:
*
* <ul>
* <li>dumpCommand (boolean)
* <li>dumpEnv (boolean)
* <li>dumpSys (boolean)
* </ul>
*
* @author <a href="mailto:[email protected]">Alexandru Popescu</a>
* @author Cedric Beust
* @author Lukas Jungmann
*/
public class TestNGAntTask extends Task {
protected CommandlineJava m_javaCommand;
protected List<ResourceCollection> m_xmlFilesets = Lists.newArrayList();
protected List<ResourceCollection> m_classFilesets = Lists.newArrayList();
protected File m_outputDir;
protected File m_testjar;
protected File m_workingDir;
private Integer m_timeout;
private List<String> m_listeners = Lists.newArrayList();
private List<String> m_methodselectors = Lists.newArrayList();
private String m_objectFactory;
protected String m_testRunnerFactory;
private boolean m_delegateCommandSystemProperties = false;
protected Environment m_environment = new Environment();
/** The suite runner name (defaults to TestNG.class.getName(). */
protected String m_mainClass = TestNG.class.getName();
/**
* True if the temporary file created by the Ant Task for command line parameters to TestNG should
* be preserved after execution.
*/
protected boolean m_dump;
private boolean m_dumpEnv;
private boolean m_dumpSys;
protected boolean m_assertEnabled = true;
protected boolean m_haltOnFailure;
protected String m_onHaltTarget;
protected String m_failurePropertyName;
protected boolean m_haltOnSkipped;
protected String m_skippedPropertyName;
protected boolean m_haltOnFSP;
protected String m_fspPropertyName;
protected String m_includedGroups;
protected String m_excludedGroups;
protected String m_parallelMode;
protected String m_threadCount;
protected String m_dataproviderthreadCount;
protected String m_configFailurePolicy;
protected Boolean m_randomizeSuites;
public String m_useDefaultListeners;
private String m_suiteName = "Ant suite";
private String m_testName = "Ant test";
private Boolean m_skipFailedInvocationCounts;
private String m_methods;
private Mode mode = Mode.testng;
public enum Mode {
// lower-case to better look in build scripts
testng,
junit,
mixed
}
private static final Logger LOGGER = Logger.getLogger(TestNGAntTask.class);
/** The list of report listeners added via <reporter> sub-element of the Ant task */
private List<ReporterConfig> reporterConfigs = Lists.newArrayList();
private String m_testNames = "";
public void setParallel(String parallel) {
m_parallelMode = parallel;
}
public void setThreadCount(String threadCount) {
m_threadCount = threadCount;
}
public void setDataProviderThreadCount(String dataproviderthreadCount) {
m_dataproviderthreadCount = dataproviderthreadCount;
}
public void setUseDefaultListeners(String f) {
m_useDefaultListeners = f;
}
// Ant task settings
public void setHaltonfailure(boolean value) {
m_haltOnFailure = value;
}
public void setOnHaltTarget(String targetName) {
m_onHaltTarget = targetName;
}
public void setFailureProperty(String propertyName) {
m_failurePropertyName = propertyName;
}
public void setHaltonskipped(boolean value) {
m_haltOnSkipped = value;
}
public void setSkippedProperty(String propertyName) {
m_skippedPropertyName = propertyName;
}
public void setHaltonFSP(boolean value) {
m_haltOnFSP = value;
}
public void setFSPProperty(String propertyName) {
m_fspPropertyName = propertyName;
}
public void setDelegateCommandSystemProperties(boolean value) {
m_delegateCommandSystemProperties = value;
}
/**
* Sets the flag to log the command line. When verbose is set to true the command line parameters
* are stored in a temporary file stored in the user's default temporary file directory. The file
* created is prefixed with "testng".
*/
public void setDumpCommand(boolean verbose) {
m_dump = verbose;
}
/**
* Sets the flag to write on <code>System.out</code> the Ant Environment properties.
*
* @param verbose <tt>true</tt> for printing
*/
public void setDumpEnv(boolean verbose) {
m_dumpEnv = verbose;
}
/**
* Sets te flag to write on <code>System.out</code> the system properties.
*
* @param verbose <tt>true</tt> for dumping the info
*/
public void setDumpSys(boolean verbose) {
m_dumpSys = verbose;
}
public void setEnableAssert(boolean flag) {
m_assertEnabled = flag;
}
/**
* The directory to invoke the VM in.
*
* @param workingDir the directory to invoke the JVM from.
*/
public void setWorkingDir(File workingDir) {
m_workingDir = workingDir;
}
/**
* Sets a particular JVM to be used. Default is 'java' and is solved by <code>Runtime.exec()
* </code>.
*
* @param jvm the new jvm
*/
public void setJvm(String jvm) {
getJavaCommand().setVm(jvm);
}
/**
* Set the timeout value (in milliseconds).
*
* <p>If the tests are running for more than this value, the tests will be canceled.
*
* @param value the maximum time (in milliseconds) allowed before declaring the test as
* 'timed-out'
*/
public void setTimeout(Integer value) {
m_timeout = value;
}
public Commandline.Argument createJvmarg() {
return getJavaCommand().createVmArgument();
}
public void addSysproperty(Environment.Variable sysp) {
getJavaCommand().addSysproperty(sysp);
}
/** Adds an environment variable; used when forking. */
public void addEnv(Environment.Variable var) {
m_environment.addVariable(var);
}
/**
* Adds path to classpath used for tests.
*
* @return reference to the classpath in the embedded java command line
*/
public Path createClasspath() {
return getJavaCommand().createClasspath(getProject()).createPath();
}
/**
* Adds a path to the bootclasspath.
*
* @return reference to the bootclasspath in the embedded java command line
*/
public Path createBootclasspath() {
return getJavaCommand().createBootclasspath(getProject()).createPath();
}
/**
* Set the classpath to be used when running the Java class
*
* @param s an Ant Path object containing the classpath.
*/
public void setClasspath(Path s) {
createClasspath().append(s);
}
/**
* Classpath to use, by reference.
*
* @param r a reference to an existing classpath
*/
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
public void addXmlfileset(FileSet fs) {
m_xmlFilesets.add(fs);
}
public void setXmlfilesetRef(Reference ref) {
m_xmlFilesets.add(createResourceCollection(ref));
}
public void addClassfileset(FileSet fs) {
m_classFilesets.add(appendClassSelector(fs));
}
public void setClassfilesetRef(Reference ref) {
m_classFilesets.add(createResourceCollection(ref));
}
public void setTestNames(String testNames) {
m_testNames = testNames;
}
/**
* Sets the suite runner class to invoke
*
* @param s the name of the suite runner class
*/
public void setSuiteRunnerClass(String s) {
m_mainClass = s;
}
/**
* Sets the suite name
*
* @param s the name of the suite
*/
public void setSuiteName(String s) {
m_suiteName = s;
}
/**
* Sets the test name
*
* @param s the name of the test
*/
public void setTestName(String s) {
m_testName = s;
}
// TestNG settings
public void setJUnit(boolean value) {
mode = value ? Mode.junit : Mode.testng;
}
// TestNG settings
public void setMode(Mode mode) {
this.mode = mode;
}
/**
* Sets the test output directory
*
* @param dir the name of directory
*/
public void setOutputDir(File dir) {
m_outputDir = dir;
}
/**
* Sets the test jar
*
* @param s the name of test jar
*/
public void setTestJar(File s) {
m_testjar = s;
}
public void setGroups(String groups) {
m_includedGroups = groups;
}
public void setExcludedGroups(String groups) {
m_excludedGroups = groups;
}
private Integer m_verbose = null;
private Integer m_suiteThreadPoolSize;
private String m_xmlPathInJar;
public void setVerbose(Integer verbose) {
m_verbose = verbose;
}
public void setReporter(String listener) {
m_listeners.add(listener);
}
public void setObjectFactory(String className) {
m_objectFactory = className;
}
public void setTestRunnerFactory(String testRunnerFactory) {
m_testRunnerFactory = testRunnerFactory;
}
public void setSuiteThreadPoolSize(Integer n) {
m_suiteThreadPoolSize = n;
}
/** @deprecated Use "listeners" */
@Deprecated
public void setListener(String listener) {
m_listeners.add(listener);
}
public void setListeners(String listeners) {
StringTokenizer st = new StringTokenizer(listeners, " ,");
while (st.hasMoreTokens()) {
m_listeners.add(st.nextToken());
}
}
public void setMethodSelectors(String methodSelectors) {
StringTokenizer st = new StringTokenizer(methodSelectors, " ,");
while (st.hasMoreTokens()) {
m_methodselectors.add(st.nextToken());
}
}
public void setConfigFailurePolicy(String failurePolicy) {
m_configFailurePolicy = failurePolicy;
}
public void setRandomizeSuites(Boolean randomizeSuites) {
m_randomizeSuites = randomizeSuites;
}
public void setMethods(String methods) {
m_methods = methods;
}
/**
* Launches TestNG in a new JVM.
*
* <p>{@inheritDoc}
*/
@Override
public void execute() throws BuildException {
validateOptions();
CommandlineJava cmd = getJavaCommand();
cmd.setClassname(m_mainClass);
if (m_assertEnabled) {
cmd.createVmArgument().setValue("-ea");
}
if (m_delegateCommandSystemProperties) {
delegateCommandSystemProperties();
}
List<String> argv = createArguments();
String fileName = "";
FileWriter fw = null;
BufferedWriter bw = null;
try {
File f = File.createTempFile("testng", "");
fileName = f.getAbsolutePath();
// If the user asked to see the command, preserve the file
if (!m_dump) {
f.deleteOnExit();
}
fw = new FileWriter(f);
bw = new BufferedWriter(fw);
for (String arg : argv) {
bw.write(arg);
bw.newLine();
}
bw.flush();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
printDebugInfo(fileName);
createClasspath().setLocation(findJar());
cmd.createArgument().setValue("@" + fileName);
ExecuteWatchdog watchdog = createWatchdog();
boolean wasKilled = false;
int exitValue = executeAsForked(cmd, watchdog);
if (null != watchdog) {
wasKilled = watchdog.killedProcess();
}
actOnResult(exitValue, wasKilled);
}
protected List<String> createArguments() {
List<String> argv = Lists.newArrayList();
addBooleanIfTrue(argv, CommandLineArgs.JUNIT, mode == Mode.junit);
addBooleanIfTrue(argv, CommandLineArgs.MIXED, mode == Mode.mixed);
addBooleanIfTrue(
argv, CommandLineArgs.SKIP_FAILED_INVOCATION_COUNTS, m_skipFailedInvocationCounts);
addIntegerIfNotNull(argv, CommandLineArgs.LOG, m_verbose);
addDefaultListeners(argv);
addOutputDir(argv);
addFileIfFile(argv, CommandLineArgs.TEST_JAR, m_testjar);
addStringIfNotBlank(argv, CommandLineArgs.GROUPS, m_includedGroups);
addStringIfNotBlank(argv, CommandLineArgs.EXCLUDED_GROUPS, m_excludedGroups);
addFilesOfRCollection(argv, CommandLineArgs.TEST_CLASS, m_classFilesets);
addListOfStringIfNotEmpty(argv, CommandLineArgs.LISTENER, m_listeners);
addListOfStringIfNotEmpty(argv, CommandLineArgs.METHOD_SELECTORS, m_methodselectors);
addStringIfNotNull(argv, CommandLineArgs.OBJECT_FACTORY, m_objectFactory);
addStringIfNotNull(argv, CommandLineArgs.TEST_RUNNER_FACTORY, m_testRunnerFactory);
addStringIfNotNull(argv, CommandLineArgs.PARALLEL, m_parallelMode);
addStringIfNotNull(argv, CommandLineArgs.CONFIG_FAILURE_POLICY, m_configFailurePolicy);
addBooleanIfTrue(argv, CommandLineArgs.RANDOMIZE_SUITES, m_randomizeSuites);
addStringIfNotNull(argv, CommandLineArgs.THREAD_COUNT, m_threadCount);
addStringIfNotNull(argv, CommandLineArgs.DATA_PROVIDER_THREAD_COUNT, m_dataproviderthreadCount);
addStringIfNotBlank(argv, CommandLineArgs.SUITE_NAME, m_suiteName);
addStringIfNotBlank(argv, CommandLineArgs.TEST_NAME, m_testName);
addStringIfNotBlank(argv, CommandLineArgs.TEST_NAMES, m_testNames);
addStringIfNotBlank(argv, CommandLineArgs.METHODS, m_methods);
addReporterConfigs(argv);
addIntegerIfNotNull(argv, CommandLineArgs.SUITE_THREAD_POOL_SIZE, m_suiteThreadPoolSize);
addStringIfNotNull(argv, CommandLineArgs.XML_PATH_IN_JAR, m_xmlPathInJar);
addXmlFiles(argv);
return argv;
}
private void addDefaultListeners(List<String> argv) {
if (m_useDefaultListeners != null) {
String useDefaultListeners = "false";
if ("yes".equalsIgnoreCase(m_useDefaultListeners)
|| "true".equalsIgnoreCase(m_useDefaultListeners)) {
useDefaultListeners = "true";
}
argv.add(CommandLineArgs.USE_DEFAULT_LISTENERS);
argv.add(useDefaultListeners);
}
}
private void addOutputDir(List<String> argv) {
if (null != m_outputDir) {
if (!m_outputDir.exists()) {
m_outputDir.mkdirs();
}
if (m_outputDir.isDirectory()) {
argv.add(CommandLineArgs.OUTPUT_DIRECTORY);
argv.add(m_outputDir.getAbsolutePath());
} else {
throw new BuildException("Output directory is not a directory: " + m_outputDir);
}
}
}
private void addReporterConfigs(List<String> argv) {
for (ReporterConfig reporterConfig : reporterConfigs) {
argv.add(CommandLineArgs.REPORTER);
argv.add(reporterConfig.serialize());
}
}
private void addFilesOfRCollection(
List<String> argv, String name, List<ResourceCollection> resources) {
addArgumentsIfNotEmpty(argv, name, getFiles(resources), ",");
}
private void addListOfStringIfNotEmpty(List<String> argv, String name, List<String> arguments) {
addArgumentsIfNotEmpty(argv, name, arguments, ";");
}
private void addArgumentsIfNotEmpty(
List<String> argv, String name, List<String> arguments, String separator) {
if (arguments != null && !arguments.isEmpty()) {
argv.add(name);
String value = Utils.join(arguments, separator);
argv.add(value);
}
}
private void addFileIfFile(List<String> argv, String name, File file) {
if ((null != file) && file.isFile()) {
argv.add(name);
argv.add(file.getAbsolutePath());
}
}
private void addBooleanIfTrue(List<String> argv, String name, Boolean value) {
if (TRUE.equals(value)) {
argv.add(name);
}
}
private void addIntegerIfNotNull(List<String> argv, String name, Integer value) {
if (value != null) {
argv.add(name);
argv.add(value.toString());
}
}
private void addStringIfNotNull(List<String> argv, String name, String value) {
if (value != null) {
argv.add(name);
argv.add(value);
}
}
private void addStringIfNotBlank(List<String> argv, String name, String value) {
if (isStringNotBlank(value)) {
argv.add(name);
argv.add(value);
}
}
private void addXmlFiles(List<String> argv) {
for (String file : getSuiteFileNames()) {
argv.add(file);
}
}
/** @return the list of the XML file names. This method can be overridden by subclasses. */
protected List<String> getSuiteFileNames() {
List<String> result = Lists.newArrayList();
for (String file : getFiles(m_xmlFilesets)) {
result.add(file);
}
return result;
}
private void delegateCommandSystemProperties() {
// Iterate over command-line args and pass them through as sysproperty
// exclude any built-in properties that start with "ant."
for (Object propKey : getProject().getUserProperties().keySet()) {
String propName = (String) propKey;
String propVal = getProject().getUserProperty(propName);
if (propName.startsWith("ant.")) {
log("Excluding ant property: " + propName + ": " + propVal, Project.MSG_DEBUG);
} else {
log("Including user property: " + propName + ": " + propVal, Project.MSG_DEBUG);
Environment.Variable var = new Environment.Variable();
var.setKey(propName);
var.setValue(propVal);
addSysproperty(var);
}
}
}
private void printDebugInfo(String fileName) {
if (m_dumpSys) {
debug("* SYSTEM PROPERTIES *");
Properties props = System.getProperties();
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
debug(key + ": " + props.getProperty(key));
}
debug("");
}
if (m_dumpEnv) {
String[] vars = m_environment.getVariables();
if (null != vars && vars.length > 0) {
debug("* ENVIRONMENT *");
for (String v : vars) {
debug(v);
}
debug("");
}
}
if (m_dump) {
dumpCommand(fileName);
}
}
private void debug(String message) {
log("[TestNGAntTask] " + message, Project.MSG_DEBUG);
}
protected void actOnResult(int exitValue, boolean wasKilled) {
if (exitValue == -1) {
executeHaltTarget(exitValue);
throw new BuildException("an error occurred when running TestNG tests");
}
if ((exitValue & ExitCode.HAS_NO_TEST) == ExitCode.HAS_NO_TEST) {
if (m_haltOnFailure) {
executeHaltTarget(exitValue);
throw new BuildException("No tests were run");
} else {
if (null != m_failurePropertyName) {
getProject().setNewProperty(m_failurePropertyName, "true");
}
log("TestNG haven't found any tests to be run", Project.MSG_DEBUG);
}
}
boolean failed = (ExitCode.hasFailure(exitValue)) || wasKilled;
if (failed) {
final String msg = wasKilled ? "The tests timed out and were killed." : "The tests failed.";
if (m_haltOnFailure) {
executeHaltTarget(exitValue);
throw new BuildException(msg);
} else {
if (null != m_failurePropertyName) {
getProject().setNewProperty(m_failurePropertyName, "true");
}
log(msg, Project.MSG_INFO);
}
}
if (ExitCode.hasSkipped(exitValue)) {
if (m_haltOnSkipped) {
executeHaltTarget(exitValue);
throw new BuildException("There are TestNG SKIPPED tests");
} else {
if (null != m_skippedPropertyName) {
getProject().setNewProperty(m_skippedPropertyName, "true");
}
log("There are TestNG SKIPPED tests", Project.MSG_DEBUG);
}
}
if (ExitCode.hasFailureWithinSuccessPercentage(exitValue)) {
if (m_haltOnFSP) {
executeHaltTarget(exitValue);
throw new BuildException("There are TestNG FAILED WITHIN SUCCESS PERCENTAGE tests");
} else {
if (null != m_fspPropertyName) {
getProject().setNewProperty(m_fspPropertyName, "true");
}
log("There are TestNG FAILED WITHIN SUCCESS PERCENTAGE tests", Project.MSG_DEBUG);
}
}
}
/** Executes the target, if any, that user designates executing before failing the test */
private void executeHaltTarget(int exitValue) {
if (m_onHaltTarget != null) {
if (m_outputDir != null) {
getProject().setProperty("testng.outputdir", m_outputDir.getAbsolutePath());
}
getProject().setProperty("testng.returncode", String.valueOf(exitValue));
Target t = getProject().getTargets().get(m_onHaltTarget);
if (t != null) {
t.execute();
}
}
}
/**
* Executes the command line as a new process.
*
* @param cmd the command to execute
* @param watchdog - A {@link ExecuteWatchdog} object.
* @return the exit status of the subprocess or INVALID.
*/
protected int executeAsForked(CommandlineJava cmd, ExecuteWatchdog watchdog) {
Execute execute =
new Execute(
new TestNGLogSH(
this, Project.MSG_INFO, Project.MSG_WARN, (m_verbose == null || m_verbose < 5)),
watchdog);
execute.setCommandline(cmd.getCommandline());
execute.setAntRun(getProject());
if (m_workingDir != null) {
if (m_workingDir.exists() && m_workingDir.isDirectory()) {
execute.setWorkingDirectory(m_workingDir);
} else {
log("Ignoring invalid working directory : " + m_workingDir, Project.MSG_WARN);
}
}
String[] environment = m_environment.getVariables();
if (null != environment) {
for (String envEntry : environment) {
log("Setting environment variable: " + envEntry, Project.MSG_VERBOSE);
}
}
execute.setEnvironment(environment);
log(cmd.describeCommand(), Project.MSG_VERBOSE);
int retVal;
try {
retVal = execute.execute();
} catch (IOException e) {
throw new BuildException("Process fork failed.", e, getLocation());
}
return retVal;
}
/** Creates or returns the already created <CODE>CommandlineJava</CODE>. */
protected CommandlineJava getJavaCommand() {
if (null == m_javaCommand) {
m_javaCommand = new CommandlineJava();
}
return m_javaCommand;
}
/**
* @return <tt>null</tt> if there is no timeout value, otherwise the watchdog instance.
* @throws BuildException under unspecified circumstances
* @since Ant 1.2
*/
protected ExecuteWatchdog createWatchdog() /*throws BuildException*/ {
if (m_timeout == null) {
return null;
}
return new ExecuteWatchdog(m_timeout.longValue());
}
protected void validateOptions() throws BuildException {
int suiteCount = getSuiteFileNames().size();
if (suiteCount == 0
&& m_classFilesets.size() == 0
&& Utils.isStringEmpty(m_methods)
&& ((null == m_testjar) || !m_testjar.isFile())) {
throw new BuildException("No suites, classes, methods or jar file was specified.");
}
if ((null != m_includedGroups) && (m_classFilesets.size() == 0 && suiteCount == 0)) {
throw new BuildException("No class filesets or xml file sets specified while using groups");
}
if (m_onHaltTarget != null) {
if (!getProject().getTargets().containsKey(m_onHaltTarget)) {
throw new BuildException("Target " + m_onHaltTarget + " not found in this project");
}
}
}
private ResourceCollection createResourceCollection(Reference ref) {
Object o = ref.getReferencedObject();
if (!(o instanceof ResourceCollection)) {
throw new BuildException("Only File based ResourceCollections are supported.");
}
ResourceCollection rc = (ResourceCollection) o;
if (!rc.isFilesystemOnly()) {
throw new BuildException("Only ResourceCollections from local file system are supported.");
}
return rc;
}
private FileSet appendClassSelector(FileSet fs) {
FilenameSelector selector = new FilenameSelector();
selector.setName("**/*.class");
selector.setProject(getProject());
fs.appendSelector(selector);
return fs;
}
private File findJar() {
Class thisClass = getClass();
String resource = thisClass.getName().replace('.', '/') + ".class";
URL url = thisClass.getClassLoader().getResource(resource);
if (null != url) {
String u = url.toString();
if (u.startsWith("jar:file:")) {
int pling = u.indexOf("!");
String jarName = u.substring(4, pling);
return new File(fromURI(jarName));
} else if (u.startsWith("file:")) {
int tail = u.indexOf(resource);
String dirName = u.substring(0, tail);
return new File(fromURI(dirName));
}
}
return null;
}
private String fromURI(String uri) {
URL url = null;
try {
url = new URL(uri);
} catch (MalformedURLException murle) {
// Gobble exceptions and do nothing.
}
if ((null == url) || !("file".equals(url.getProtocol()))) {
throw new IllegalArgumentException("Can only handle valid file: URIs");
}
StringBuilder buf = new StringBuilder(url.getHost());
if (buf.length() > 0) {
buf.insert(0, File.separatorChar).insert(0, File.separatorChar);
}
String file = url.getFile();
int queryPos = file.indexOf('?');
buf.append((queryPos < 0) ? file : file.substring(0, queryPos));
uri = buf.toString().replace('/', File.separatorChar);
if ((File.pathSeparatorChar == ';')
&& uri.startsWith("\\")
&& (uri.length() > 2)
&& Character.isLetter(uri.charAt(1))
&& (uri.lastIndexOf(':') > -1)) {
uri = uri.substring(1);
}
StringBuilder sb = new StringBuilder();
CharacterIterator iter = new StringCharacterIterator(uri);
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
if (c == '%') {
char c1 = iter.next();
if (c1 != CharacterIterator.DONE) {
int i1 = Character.digit(c1, 16);
char c2 = iter.next();
if (c2 != CharacterIterator.DONE) {
int i2 = Character.digit(c2, 16);
sb.append((char) ((i1 << 4) + i2));
}
}
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* Returns the list of files corresponding to the resource collection
*
* @param resources - A list of {@link ResourceCollection}
* @return the list of files corresponding to the resource collection
* @throws BuildException
*/
private List<String> getFiles(List<ResourceCollection> resources) throws BuildException {
List<String> files = Lists.newArrayList();
for (ResourceCollection rc : resources) {
for (Resource o : rc) {
if (o instanceof FileResource) {
FileResource fr = ((FileResource) o);
if (fr.isDirectory()) {
throw new BuildException("Directory based FileResources are not supported.");
}
if (!fr.isExists()) {
log("'" + fr.toLongString() + "' does not exist", Project.MSG_VERBOSE);
}
files.add(fr.getFile().getAbsolutePath());
} else {
log("Unsupported Resource type: " + o.toString(), Project.MSG_VERBOSE);
}
}
}
return files;
}
private void dumpCommand(String fileName) {
log("TESTNG PASSED @" + fileName + " WHICH CONTAINS:", Project.MSG_INFO);
readAndPrintFile(fileName);
}
private void readAndPrintFile(String fileName) {
try {
Files.readAllLines(Paths.get(fileName)).forEach(line -> log(" " + line, Project.MSG_INFO));
} catch (IOException ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
public void addConfiguredReporter(ReporterConfig reporterConfig) {
reporterConfigs.add(reporterConfig);
}
public void setSkipFailedInvocationCounts(boolean skip) {
m_skipFailedInvocationCounts = skip;
}
public void setXmlPathInJar(String path) {
m_xmlPathInJar = path;
}
/**
* Add the referenced property set as system properties for the TestNG JVM.
*
* @param sysPropertySet A PropertySet of system properties.
*/
public void addConfiguredPropertySet(PropertySet sysPropertySet) {
Properties properties = sysPropertySet.getProperties();
log(
properties.keySet().size() + " properties found in nested propertyset",
Project.MSG_VERBOSE);
for (Object propKeyObj : properties.keySet()) {
String propKey = (String) propKeyObj;
Environment.Variable sysProp = new Environment.Variable();
sysProp.setKey(propKey);
if (properties.get(propKey) instanceof String) {
String propVal = (String) properties.get(propKey);
sysProp.setValue(propVal);
getJavaCommand().addSysproperty(sysProp);
log("Added system property " + propKey + " with value " + propVal, Project.MSG_VERBOSE);
} else {
log("Ignoring non-String property " + propKey, Project.MSG_WARN);
}
}
}
@Override
protected void handleOutput(String output) {
if (output.startsWith(VerboseReporter.LISTENER_PREFIX)) {
// send everything from VerboseReporter to verbose level unless log level is > 4
log(output, m_verbose < 5 ? Project.MSG_VERBOSE : Project.MSG_INFO);
} else {
super.handleOutput(output);
}
}
private static class TestNGLogOS extends LogOutputStream {
private Task task;
private boolean verbose;
public TestNGLogOS(Task task, int level, boolean verbose) {
super(task, level);
this.task = task;
this.verbose = verbose;
}
@Override
protected void processLine(String line, int level) {
if (line.startsWith(VerboseReporter.LISTENER_PREFIX)) {
task.log(line, verbose ? Project.MSG_VERBOSE : Project.MSG_INFO);
} else {
super.processLine(line, level);
}
}
}
protected static class TestNGLogSH extends PumpStreamHandler {
public TestNGLogSH(Task task, int outlevel, int errlevel, boolean verbose) {
super(new TestNGLogOS(task, outlevel, verbose), new LogOutputStream(task, errlevel));
}
}
}
| apache-2.0 |
google/google-ctf | third_party/edk2/MdePkg/Include/Protocol/Ebc.h | 10355 | /** @file
Describes the protocol interface to the EBC interpreter.
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __EFI_EBC_PROTOCOL_H__
#define __EFI_EBC_PROTOCOL_H__
#define EFI_EBC_INTERPRETER_PROTOCOL_GUID \
{ \
0x13AC6DD1, 0x73D0, 0x11D4, {0xB0, 0x6B, 0x00, 0xAA, 0x00, 0xBD, 0x6D, 0xE7 } \
}
//
// Define OPCODES
//
#define OPCODE_BREAK 0x00
#define OPCODE_JMP 0x01
#define OPCODE_JMP8 0x02
#define OPCODE_CALL 0x03
#define OPCODE_RET 0x04
#define OPCODE_CMPEQ 0x05
#define OPCODE_CMPLTE 0x06
#define OPCODE_CMPGTE 0x07
#define OPCODE_CMPULTE 0x08
#define OPCODE_CMPUGTE 0x09
#define OPCODE_NOT 0x0A
#define OPCODE_NEG 0x0B
#define OPCODE_ADD 0x0C
#define OPCODE_SUB 0x0D
#define OPCODE_MUL 0x0E
#define OPCODE_MULU 0x0F
#define OPCODE_DIV 0x10
#define OPCODE_DIVU 0x11
#define OPCODE_MOD 0x12
#define OPCODE_MODU 0x13
#define OPCODE_AND 0x14
#define OPCODE_OR 0x15
#define OPCODE_XOR 0x16
#define OPCODE_SHL 0x17
#define OPCODE_SHR 0x18
#define OPCODE_ASHR 0x19
#define OPCODE_EXTNDB 0x1A
#define OPCODE_EXTNDW 0x1B
#define OPCODE_EXTNDD 0x1C
#define OPCODE_MOVBW 0x1D
#define OPCODE_MOVWW 0x1E
#define OPCODE_MOVDW 0x1F
#define OPCODE_MOVQW 0x20
#define OPCODE_MOVBD 0x21
#define OPCODE_MOVWD 0x22
#define OPCODE_MOVDD 0x23
#define OPCODE_MOVQD 0x24
#define OPCODE_MOVSNW 0x25 // Move signed natural with word index
#define OPCODE_MOVSND 0x26 // Move signed natural with dword index
//
// #define OPCODE_27 0x27
//
#define OPCODE_MOVQQ 0x28 // Does this go away?
#define OPCODE_LOADSP 0x29
#define OPCODE_STORESP 0x2A
#define OPCODE_PUSH 0x2B
#define OPCODE_POP 0x2C
#define OPCODE_CMPIEQ 0x2D
#define OPCODE_CMPILTE 0x2E
#define OPCODE_CMPIGTE 0x2F
#define OPCODE_CMPIULTE 0x30
#define OPCODE_CMPIUGTE 0x31
#define OPCODE_MOVNW 0x32
#define OPCODE_MOVND 0x33
//
// #define OPCODE_34 0x34
//
#define OPCODE_PUSHN 0x35
#define OPCODE_POPN 0x36
#define OPCODE_MOVI 0x37
#define OPCODE_MOVIN 0x38
#define OPCODE_MOVREL 0x39
//
// Bit masks for opcode encodings
//
#define OPCODE_M_OPCODE 0x3F // bits of interest for first level decode
#define OPCODE_M_IMMDATA 0x80
#define OPCODE_M_IMMDATA64 0x40
#define OPCODE_M_64BIT 0x40 // for CMP
#define OPCODE_M_RELADDR 0x10 // for CALL instruction
#define OPCODE_M_CMPI32_DATA 0x80 // for CMPI
#define OPCODE_M_CMPI64 0x40 // for CMPI 32 or 64 bit comparison
#define OPERAND_M_MOVIN_N 0x80
#define OPERAND_M_CMPI_INDEX 0x10
//
// Masks for instructions that encode presence of indexes for operand1 and/or
// operand2.
//
#define OPCODE_M_IMMED_OP1 0x80
#define OPCODE_M_IMMED_OP2 0x40
//
// Bit masks for operand encodings
//
#define OPERAND_M_INDIRECT1 0x08
#define OPERAND_M_INDIRECT2 0x80
#define OPERAND_M_OP1 0x07
#define OPERAND_M_OP2 0x70
//
// Masks for data manipulation instructions
//
#define DATAMANIP_M_64 0x40 // 64-bit width operation
#define DATAMANIP_M_IMMDATA 0x80
//
// For MOV instructions, need a mask for the opcode when immediate
// data applies to R2.
//
#define OPCODE_M_IMMED_OP2 0x40
//
// The MOVI/MOVIn instructions use bit 6 of operands byte to indicate
// if an index is present. Then bits 4 and 5 are used to indicate the width
// of the move.
//
#define MOVI_M_IMMDATA 0x40
#define MOVI_M_DATAWIDTH 0xC0
#define MOVI_DATAWIDTH16 0x40
#define MOVI_DATAWIDTH32 0x80
#define MOVI_DATAWIDTH64 0xC0
#define MOVI_M_MOVEWIDTH 0x30
#define MOVI_MOVEWIDTH8 0x00
#define MOVI_MOVEWIDTH16 0x10
#define MOVI_MOVEWIDTH32 0x20
#define MOVI_MOVEWIDTH64 0x30
//
// Masks for CALL instruction encodings
//
#define OPERAND_M_RELATIVE_ADDR 0x10
#define OPERAND_M_NATIVE_CALL 0x20
//
// Masks for decoding push/pop instructions
//
#define PUSHPOP_M_IMMDATA 0x80 // opcode bit indicating immediate data
#define PUSHPOP_M_64 0x40 // opcode bit indicating 64-bit operation
//
// Mask for operand of JMP instruction
//
#define JMP_M_RELATIVE 0x10
#define JMP_M_CONDITIONAL 0x80
#define JMP_M_CS 0x40
//
// Macros to determine if a given operand is indirect
//
#define OPERAND1_INDIRECT(op) ((op) & OPERAND_M_INDIRECT1)
#define OPERAND2_INDIRECT(op) ((op) & OPERAND_M_INDIRECT2)
//
// Macros to extract the operands from second byte of instructions
//
#define OPERAND1_REGNUM(op) ((op) & OPERAND_M_OP1)
#define OPERAND2_REGNUM(op) (((op) & OPERAND_M_OP2) >> 4)
#define OPERAND1_CHAR(op) ('0' + OPERAND1_REGNUM (op))
#define OPERAND2_CHAR(op) ('0' + OPERAND2_REGNUM (op))
//
// Condition masks usually for byte 1 encodings of code
//
#define CONDITION_M_CONDITIONAL 0x80
#define CONDITION_M_CS 0x40
///
/// Protocol Guid Name defined in spec.
///
#define EFI_EBC_PROTOCOL_GUID EFI_EBC_INTERPRETER_PROTOCOL_GUID
///
/// Define for forward reference.
///
typedef struct _EFI_EBC_PROTOCOL EFI_EBC_PROTOCOL;
/**
Creates a thunk for an EBC entry point, returning the address of the thunk.
A PE32+ EBC image, like any other PE32+ image, contains an optional header that specifies the
entry point for image execution. However, for EBC images, this is the entry point of EBC
instructions, so is not directly executable by the native processor. Therefore, when an EBC image is
loaded, the loader must call this service to get a pointer to native code (thunk) that can be executed,
which will invoke the interpreter to begin execution at the original EBC entry point.
@param This A pointer to the EFI_EBC_PROTOCOL instance.
@param ImageHandle Handle of image for which the thunk is being created.
@param EbcEntryPoint Address of the actual EBC entry point or protocol service the thunk should call.
@param Thunk Returned pointer to a thunk created.
@retval EFI_SUCCESS The function completed successfully.
@retval EFI_INVALID_PARAMETER Image entry point is not 2-byte aligned.
@retval EFI_OUT_OF_RESOURCES Memory could not be allocated for the thunk.
**/
typedef
EFI_STATUS
(EFIAPI *EFI_EBC_CREATE_THUNK)(
IN EFI_EBC_PROTOCOL *This,
IN EFI_HANDLE ImageHandle,
IN VOID *EbcEntryPoint,
OUT VOID **Thunk
);
/**
Called prior to unloading an EBC image from memory.
This function is called after an EBC image has exited, but before the image is actually unloaded. It
is intended to provide the interpreter with the opportunity to perform any cleanup that may be
necessary as a result of loading and executing the image.
@param This A pointer to the EFI_EBC_PROTOCOL instance.
@param ImageHandle Image handle of the EBC image that is being unloaded from memory.
@retval EFI_SUCCESS The function completed successfully.
@retval EFI_INVALID_PARAMETER Image handle is not recognized as belonging
to an EBC image that has been executed.
**/
typedef
EFI_STATUS
(EFIAPI *EFI_EBC_UNLOAD_IMAGE)(
IN EFI_EBC_PROTOCOL *This,
IN EFI_HANDLE ImageHandle
);
/**
This is the prototype for the Flush callback routine. A pointer to a routine
of this type is passed to the EBC EFI_EBC_REGISTER_ICACHE_FLUSH protocol service.
@param Start The beginning physical address to flush from the processor's instruction cache.
@param Length The number of bytes to flush from the processor's instruction cache.
@retval EFI_SUCCESS The function completed successfully.
**/
typedef
EFI_STATUS
(EFIAPI *EBC_ICACHE_FLUSH)(
IN EFI_PHYSICAL_ADDRESS Start,
IN UINT64 Length
);
/**
Registers a callback function that the EBC interpreter calls to flush
the processor instruction cache following creation of thunks.
@param This A pointer to the EFI_EBC_PROTOCOL instance.
@param Flush Pointer to a function of type EBC_ICACH_FLUSH.
@retval EFI_SUCCESS The function completed successfully.
**/
typedef
EFI_STATUS
(EFIAPI *EFI_EBC_REGISTER_ICACHE_FLUSH)(
IN EFI_EBC_PROTOCOL *This,
IN EBC_ICACHE_FLUSH Flush
);
/**
Called to get the version of the interpreter.
This function is called to get the version of the loaded EBC interpreter. The value and format of the
returned version is identical to that returned by the EBC BREAK 1 instruction.
@param This A pointer to the EFI_EBC_PROTOCOL instance.
@param Version Pointer to where to store the returned version of the interpreter.
@retval EFI_SUCCESS The function completed successfully.
@retval EFI_INVALID_PARAMETER Version pointer is NULL.
**/
typedef
EFI_STATUS
(EFIAPI *EFI_EBC_GET_VERSION)(
IN EFI_EBC_PROTOCOL *This,
IN OUT UINT64 *Version
);
///
/// The EFI EBC protocol provides services to load and execute EBC images, which will typically be
/// loaded into option ROMs. The image loader will load the EBC image, perform standard relocations,
/// and invoke the CreateThunk() service to create a thunk for the EBC image's entry point. The
/// image can then be run using the standard EFI start image services.
///
struct _EFI_EBC_PROTOCOL {
EFI_EBC_CREATE_THUNK CreateThunk;
EFI_EBC_UNLOAD_IMAGE UnloadImage;
EFI_EBC_REGISTER_ICACHE_FLUSH RegisterICacheFlush;
EFI_EBC_GET_VERSION GetVersion;
};
//
// Extern the global EBC protocol GUID
//
extern EFI_GUID gEfiEbcProtocolGuid;
#endif
| apache-2.0 |
nagavallia/geomesa | geomesa-index-api/src/main/scala/org/locationtech/geomesa/index/strategies/AttributeFilterStrategy.scala | 4279 | /***********************************************************************
* Copyright (c) 2013-2016 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
*************************************************************************/
package org.locationtech.geomesa.index.strategies
import org.locationtech.geomesa.filter._
import org.locationtech.geomesa.filter.visitor.FilterExtractingVisitor
import org.locationtech.geomesa.index.api.{FilterStrategy, GeoMesaFeatureIndex, WrappedFeature}
import org.locationtech.geomesa.index.geotools.GeoMesaDataStore
import org.locationtech.geomesa.utils.stats.Cardinality
import org.opengis.feature.simple.SimpleFeatureType
import org.opengis.filter._
import org.opengis.filter.expression.{Expression, PropertyName}
import org.opengis.filter.temporal.{After, Before, During, TEquals}
trait AttributeFilterStrategy[DS <: GeoMesaDataStore[DS, F, W], F <: WrappedFeature, W]
extends GeoMesaFeatureIndex[DS, F, W] {
override def getFilterStrategy(sft: SimpleFeatureType, filter: Filter): Seq[FilterStrategy[DS, F, W]] = {
import org.locationtech.geomesa.index.strategies.AttributeFilterStrategy.attributeCheck
import org.locationtech.geomesa.utils.geotools.RichAttributeDescriptors.RichAttributeDescriptor
val attributes = FilterHelper.propertyNames(filter, sft)
val indexedAttributes = attributes.filter(a => Option(sft.getDescriptor(a)).exists(_.isIndexed))
indexedAttributes.flatMap { attribute =>
val (primary, secondary) = FilterExtractingVisitor(filter, attribute, sft, attributeCheck(sft))
if (primary.isDefined) {
Seq(FilterStrategy(this, primary, secondary))
} else {
Seq.empty
}
}
}
/**
* Static cost - 100
*
* high cardinality: / 10
* low cardinality: Long.MaxValue
*
* Compare with id lookups at 1, z2/z3 at 200-401
*/
override def getCost(sft: SimpleFeatureType,
ds: Option[DS],
filter: FilterStrategy[DS, F, W],
transform: Option[SimpleFeatureType]): Long = {
import org.locationtech.geomesa.utils.geotools.RichAttributeDescriptors.RichAttributeDescriptor
filter.primary match {
case None => Long.MaxValue
case Some(f) =>
lazy val cost = ds.flatMap(_.stats.getCount(sft, f, exact = false)).getOrElse(AttributeFilterStrategy.StaticCost)
// if there is a filter, we know it has a valid property name
val attribute = FilterHelper.propertyNames(f, sft).head
sft.getDescriptor(attribute).getCardinality() match {
case Cardinality.HIGH => cost / 10 // prioritize attributes marked high-cardinality
case Cardinality.UNKNOWN => cost
case Cardinality.LOW => Long.MaxValue
}
}
}
}
object AttributeFilterStrategy {
val StaticCost = 100L
/**
* Checks for attribute filters that we can satisfy using the attribute index strategy
*
* @param filter filter to evaluate
* @return true if we can process it as an attribute query
*/
def attributeCheck(sft: SimpleFeatureType)(filter: Filter): Boolean = {
filter match {
case _: And | _: Or => true // note: implies further processing of children
case _: PropertyIsEqualTo => true
case _: PropertyIsBetween => true
case _: PropertyIsGreaterThan | _: PropertyIsLessThan => true
case _: PropertyIsGreaterThanOrEqualTo | _: PropertyIsLessThanOrEqualTo => true
case _: During | _: Before | _: After | _: TEquals => true
case _: PropertyIsNull => true // we need this to be able to handle 'not null'
case f: PropertyIsLike => isStringProperty(sft, f.getExpression) && likeEligible(f)
case f: Not => f.getFilter.isInstanceOf[PropertyIsNull]
case _ => false
}
}
def isStringProperty(sft: SimpleFeatureType, e: Expression): Boolean = e match {
case p: PropertyName => Option(sft.getDescriptor(p.getPropertyName)).exists(_.getType.getBinding == classOf[String])
case _ => false
}
}
| apache-2.0 |
naveenhooda2000/elasticsearch | core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java | 121631 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.translog;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.Term;
import org.apache.lucene.mockfile.FilterFileChannel;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LineFileDocs;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.FileSystemUtils;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.common.util.concurrent.ReleasableLock;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.Engine.Operation.Origin;
import org.elasticsearch.index.mapper.ParseContext.Document;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SeqNoFieldMapper;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.UidFieldMapper;
import org.elasticsearch.index.seqno.LocalCheckpointTracker;
import org.elasticsearch.index.seqno.LocalCheckpointTrackerTests;
import org.elasticsearch.index.seqno.SequenceNumbersService;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.translog.Translog.Location;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomLongBetween;
import static org.elasticsearch.common.util.BigArrays.NON_RECYCLING_INSTANCE;
import static org.elasticsearch.index.translog.TranslogDeletionPolicyTests.createTranslogDeletionPolicy;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
@LuceneTestCase.SuppressFileSystems("ExtrasFS")
public class TranslogTests extends ESTestCase {
protected final ShardId shardId = new ShardId("index", "_na_", 1);
protected Translog translog;
private AtomicLong globalCheckpoint;
protected Path translogDir;
@Override
protected void afterIfSuccessful() throws Exception {
super.afterIfSuccessful();
if (translog.isOpen()) {
if (translog.currentFileGeneration() > 1) {
markCurrentGenAsCommitted(translog);
translog.trimUnreferencedReaders();
assertFileDeleted(translog, translog.currentFileGeneration() - 1);
}
translog.close();
}
assertFileIsPresent(translog, translog.currentFileGeneration());
IOUtils.rm(translog.location()); // delete all the locations
}
protected Translog createTranslog(TranslogConfig config, String translogUUID) throws IOException {
return new Translog(config, translogUUID, createTranslogDeletionPolicy(config.getIndexSettings()),
() -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
}
private void markCurrentGenAsCommitted(Translog translog) throws IOException {
commit(translog, translog.currentFileGeneration());
}
private void rollAndCommit(Translog translog) throws IOException {
translog.rollGeneration();
commit(translog, translog.currentFileGeneration());
}
private void commit(Translog translog, long genToCommit) throws IOException {
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
deletionPolicy.setMinTranslogGenerationForRecovery(genToCommit);
long minGenRequired = deletionPolicy.minTranslogGenRequired(translog.getReaders(), translog.getCurrent());
translog.trimUnreferencedReaders();
assertThat(minGenRequired, equalTo(translog.getMinFileGeneration()));
assertFilePresences(translog);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
// if a previous test failed we clean up things here
translogDir = createTempDir();
translog = create(translogDir);
}
@Override
@After
public void tearDown() throws Exception {
try {
assertEquals("there are still open views", 0, translog.getDeletionPolicy().pendingViewsCount());
translog.close();
} finally {
super.tearDown();
}
}
private Translog create(Path path) throws IOException {
globalCheckpoint = new AtomicLong(SequenceNumbersService.UNASSIGNED_SEQ_NO);
final TranslogConfig translogConfig = getTranslogConfig(path);
final TranslogDeletionPolicy deletionPolicy = createTranslogDeletionPolicy(translogConfig.getIndexSettings());
return new Translog(translogConfig, null, deletionPolicy, () -> globalCheckpoint.get());
}
private TranslogConfig getTranslogConfig(final Path path) {
final Settings settings = Settings
.builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, org.elasticsearch.Version.CURRENT)
// only randomize between nog age retention and a long one, so failures will have a chance of reproducing
.put(IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING.getKey(), randomBoolean() ? "-1ms" : "1h")
.put(IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING.getKey(), randomIntBetween(-1, 2048) + "b")
.build();
return getTranslogConfig(path, settings);
}
private TranslogConfig getTranslogConfig(final Path path, final Settings settings) {
final ByteSizeValue bufferSize;
if (randomBoolean()) {
bufferSize = TranslogConfig.DEFAULT_BUFFER_SIZE;
} else {
bufferSize = new ByteSizeValue(10 + randomInt(128 * 1024), ByteSizeUnit.BYTES);
}
final IndexSettings indexSettings =
IndexSettingsModule.newIndexSettings(shardId.getIndex(), settings);
return new TranslogConfig(shardId, path, indexSettings, NON_RECYCLING_INSTANCE, bufferSize);
}
private void addToTranslogAndList(Translog translog, ArrayList<Translog.Operation> list, Translog.Operation op) throws IOException {
list.add(op);
translog.add(op);
}
public void testIdParsingFromFile() {
long id = randomIntBetween(0, Integer.MAX_VALUE);
Path file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + id + ".tlog");
assertThat(Translog.parseIdFromFileName(file), equalTo(id));
id = randomIntBetween(0, Integer.MAX_VALUE);
file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + id);
try {
Translog.parseIdFromFileName(file);
fail("invalid pattern");
} catch (IllegalArgumentException ex) {
// all good
}
file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + id + ".recovering");
try {
Translog.parseIdFromFileName(file);
fail("invalid pattern");
} catch (IllegalArgumentException ex) {
// all good
}
file = translogDir.resolve(Translog.TRANSLOG_FILE_PREFIX + randomNonTranslogPatternString(1, 10) + id);
try {
Translog.parseIdFromFileName(file);
fail("invalid pattern");
} catch (IllegalArgumentException ex) {
// all good
}
file = translogDir.resolve(randomNonTranslogPatternString(1, Translog.TRANSLOG_FILE_PREFIX.length() - 1));
try {
Translog.parseIdFromFileName(file);
fail("invalid pattern");
} catch (IllegalArgumentException ex) {
// all good
}
}
private String randomNonTranslogPatternString(int min, int max) {
String string;
boolean validPathString;
do {
validPathString = false;
string = randomRealisticUnicodeOfCodepointLength(randomIntBetween(min, max));
try {
final Path resolved = translogDir.resolve(string);
// some strings (like '/' , '..') do not refer to a file, which we this method should return
validPathString = resolved.getFileName() != null;
} catch (InvalidPathException ex) {
// some FS don't like our random file names -- let's just skip these random choices
}
} while (Translog.PARSE_STRICT_ID_PATTERN.matcher(string).matches() || validPathString == false);
return string;
}
public void testSimpleOperations() throws IOException {
ArrayList<Translog.Operation> ops = new ArrayList<>();
Translog.Snapshot snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.size(0));
addToTranslogAndList(translog, ops, new Translog.Index("test", "1", 0, new byte[]{1}));
snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.equalsTo(ops));
assertThat(snapshot.totalOperations(), equalTo(ops.size()));
addToTranslogAndList(translog, ops, new Translog.Delete("test", "2", 1, newUid("2")));
snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.equalsTo(ops));
assertThat(snapshot.totalOperations(), equalTo(ops.size()));
final long seqNo = randomNonNegativeLong();
final long primaryTerm = randomNonNegativeLong();
final String reason = randomAlphaOfLength(16);
addToTranslogAndList(translog, ops, new Translog.NoOp(seqNo, primaryTerm, reason));
snapshot = translog.newSnapshot();
Translog.Index index = (Translog.Index) snapshot.next();
assertNotNull(index);
assertThat(BytesReference.toBytes(index.source()), equalTo(new byte[]{1}));
Translog.Delete delete = (Translog.Delete) snapshot.next();
assertNotNull(delete);
assertThat(delete.uid(), equalTo(newUid("2")));
Translog.NoOp noOp = (Translog.NoOp) snapshot.next();
assertNotNull(noOp);
assertThat(noOp.seqNo(), equalTo(seqNo));
assertThat(noOp.primaryTerm(), equalTo(primaryTerm));
assertThat(noOp.reason(), equalTo(reason));
assertNull(snapshot.next());
long firstId = translog.currentFileGeneration();
translog.rollGeneration();
assertThat(translog.currentFileGeneration(), Matchers.not(equalTo(firstId)));
snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.equalsTo(ops));
assertThat(snapshot.totalOperations(), equalTo(ops.size()));
markCurrentGenAsCommitted(translog);
snapshot = translog.newSnapshot(firstId + 1);
assertThat(snapshot, SnapshotMatchers.size(0));
assertThat(snapshot.totalOperations(), equalTo(0));
}
protected TranslogStats stats() throws IOException {
// force flushing and updating of stats
translog.sync();
TranslogStats stats = translog.stats();
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
StreamInput in = out.bytes().streamInput();
stats = new TranslogStats();
stats.readFrom(in);
}
return stats;
}
public void testStats() throws IOException {
// self control cleaning for test
translog.getDeletionPolicy().setRetentionSizeInBytes(1024 * 1024);
translog.getDeletionPolicy().setRetentionAgeInMillis(3600 * 1000);
final long firstOperationPosition = translog.getFirstOperationPosition();
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(0));
}
assertThat((int) firstOperationPosition, greaterThan(CodecUtil.headerLength(TranslogWriter.TRANSLOG_CODEC)));
translog.add(new Translog.Index("test", "1", 0, new byte[]{1}));
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(1));
assertThat(stats.getTranslogSizeInBytes(), equalTo(97L));
assertThat(stats.getUncommittedOperations(), equalTo(1));
assertThat(stats.getUncommittedSizeInBytes(), equalTo(97L));
}
translog.add(new Translog.Delete("test", "2", 1, newUid("2")));
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(2));
assertThat(stats.getTranslogSizeInBytes(), equalTo(146L));
assertThat(stats.getUncommittedOperations(), equalTo(2));
assertThat(stats.getUncommittedSizeInBytes(), equalTo(146L));
}
translog.add(new Translog.Delete("test", "3", 2, newUid("3")));
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(3));
assertThat(stats.getTranslogSizeInBytes(), equalTo(195L));
assertThat(stats.getUncommittedOperations(), equalTo(3));
assertThat(stats.getUncommittedSizeInBytes(), equalTo(195L));
}
translog.add(new Translog.NoOp(3, 1, randomAlphaOfLength(16)));
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(4));
assertThat(stats.getTranslogSizeInBytes(), equalTo(237L));
assertThat(stats.getUncommittedOperations(), equalTo(4));
assertThat(stats.getUncommittedSizeInBytes(), equalTo(237L));
}
final long expectedSizeInBytes = 280L;
translog.rollGeneration();
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(4));
assertThat(stats.getTranslogSizeInBytes(), equalTo(expectedSizeInBytes));
assertThat(stats.getUncommittedOperations(), equalTo(4));
assertThat(stats.getUncommittedSizeInBytes(), equalTo(expectedSizeInBytes));
}
{
final TranslogStats stats = stats();
final BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
final TranslogStats copy = new TranslogStats();
copy.readFrom(out.bytes().streamInput());
assertThat(copy.estimatedNumberOfOperations(), equalTo(4));
assertThat(copy.getTranslogSizeInBytes(), equalTo(expectedSizeInBytes));
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
builder.startObject();
copy.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
assertThat(builder.string(), equalTo("{\"translog\":{\"operations\":4,\"size_in_bytes\":" + expectedSizeInBytes
+ ",\"uncommitted_operations\":4,\"uncommitted_size_in_bytes\":" + expectedSizeInBytes + "}}"));
}
}
markCurrentGenAsCommitted(translog);
{
final TranslogStats stats = stats();
assertThat(stats.estimatedNumberOfOperations(), equalTo(4));
assertThat(stats.getTranslogSizeInBytes(), equalTo(expectedSizeInBytes));
assertThat(stats.getUncommittedOperations(), equalTo(0));
assertThat(stats.getUncommittedSizeInBytes(), equalTo(firstOperationPosition));
}
}
public void testTotalTests() {
final TranslogStats total = new TranslogStats();
final int n = randomIntBetween(0, 16);
final List<TranslogStats> statsList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
final TranslogStats stats = new TranslogStats(randomIntBetween(1, 4096), randomIntBetween(1, 1 << 20),
randomIntBetween(1, 1 << 20), randomIntBetween(1, 4096));
statsList.add(stats);
total.add(stats);
}
assertThat(
total.estimatedNumberOfOperations(),
equalTo(statsList.stream().mapToInt(TranslogStats::estimatedNumberOfOperations).sum()));
assertThat(
total.getTranslogSizeInBytes(),
equalTo(statsList.stream().mapToLong(TranslogStats::getTranslogSizeInBytes).sum()));
assertThat(
total.getUncommittedOperations(),
equalTo(statsList.stream().mapToInt(TranslogStats::getUncommittedOperations).sum()));
assertThat(
total.getUncommittedSizeInBytes(),
equalTo(statsList.stream().mapToLong(TranslogStats::getUncommittedSizeInBytes).sum()));
}
public void testNegativeNumberOfOperations() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TranslogStats(-1, 1, 1, 1));
assertThat(e, hasToString(containsString("numberOfOperations must be >= 0")));
e = expectThrows(IllegalArgumentException.class, () -> new TranslogStats(1, 1, -1, 1));
assertThat(e, hasToString(containsString("uncommittedOperations must be >= 0")));
}
public void testNegativeSizeInBytes() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TranslogStats(1, -1, 1, 1));
assertThat(e, hasToString(containsString("translogSizeInBytes must be >= 0")));
e = expectThrows(IllegalArgumentException.class, () -> new TranslogStats(1, 1, 1, -1));
assertThat(e, hasToString(containsString("uncommittedSizeInBytes must be >= 0")));
}
public void testSnapshot() throws IOException {
ArrayList<Translog.Operation> ops = new ArrayList<>();
Translog.Snapshot snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.size(0));
addToTranslogAndList(translog, ops, new Translog.Index("test", "1", 0, new byte[]{1}));
snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.equalsTo(ops));
assertThat(snapshot.totalOperations(), equalTo(1));
snapshot = translog.newSnapshot();
Translog.Snapshot snapshot1 = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.equalsTo(ops));
assertThat(snapshot.totalOperations(), equalTo(1));
assertThat(snapshot1, SnapshotMatchers.size(1));
assertThat(snapshot1.totalOperations(), equalTo(1));
}
public void testSnapshotWithNewTranslog() throws IOException {
ArrayList<Translog.Operation> ops = new ArrayList<>();
Translog.Snapshot snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.size(0));
addToTranslogAndList(translog, ops, new Translog.Index("test", "1", 0, new byte[]{1}));
Translog.Snapshot snapshot1 = translog.newSnapshot();
addToTranslogAndList(translog, ops, new Translog.Index("test", "2", 1, new byte[]{2}));
assertThat(snapshot1, SnapshotMatchers.equalsTo(ops.get(0)));
translog.rollGeneration();
addToTranslogAndList(translog, ops, new Translog.Index("test", "3", 2, new byte[]{3}));
try (Translog.View view = translog.newView()) {
Translog.Snapshot snapshot2 = translog.newSnapshot();
markCurrentGenAsCommitted(translog);
assertThat(snapshot2, SnapshotMatchers.equalsTo(ops));
assertThat(snapshot2.totalOperations(), equalTo(ops.size()));
}
}
public void testSnapshotOnClosedTranslog() throws IOException {
assertTrue(Files.exists(translogDir.resolve(Translog.getFilename(1))));
translog.add(new Translog.Index("test", "1", 0, new byte[]{1}));
translog.close();
try {
Translog.Snapshot snapshot = translog.newSnapshot();
fail("translog is closed");
} catch (AlreadyClosedException ex) {
assertEquals(ex.getMessage(), "translog is already closed");
}
}
public void assertFileIsPresent(Translog translog, long id) {
if (Files.exists(translog.location().resolve(Translog.getFilename(id)))) {
return;
}
fail(Translog.getFilename(id) + " is not present in any location: " + translog.location());
}
public void assertFileDeleted(Translog translog, long id) {
assertFalse("translog [" + id + "] still exists", Files.exists(translog.location().resolve(Translog.getFilename(id))));
}
private void assertFilePresences(Translog translog) {
for (long gen = translog.getMinFileGeneration(); gen < translog.currentFileGeneration(); gen++) {
assertFileIsPresent(translog, gen);
}
for (long gen = 1; gen < translog.getMinFileGeneration(); gen++) {
assertFileDeleted(translog, gen);
}
}
static class LocationOperation implements Comparable<LocationOperation> {
final Translog.Operation operation;
final Translog.Location location;
LocationOperation(Translog.Operation operation, Translog.Location location) {
this.operation = operation;
this.location = location;
}
@Override
public int compareTo(LocationOperation o) {
return location.compareTo(o.location);
}
}
public void testConcurrentWritesWithVaryingSize() throws Throwable {
final int opsPerThread = randomIntBetween(10, 200);
int threadCount = 2 + randomInt(5);
logger.info("testing with [{}] threads, each doing [{}] ops", threadCount, opsPerThread);
final BlockingQueue<LocationOperation> writtenOperations = new ArrayBlockingQueue<>(threadCount * opsPerThread);
Thread[] threads = new Thread[threadCount];
final Exception[] threadExceptions = new Exception[threadCount];
final AtomicLong seqNoGenerator = new AtomicLong();
final CountDownLatch downLatch = new CountDownLatch(1);
for (int i = 0; i < threadCount; i++) {
final int threadId = i;
threads[i] = new TranslogThread(translog, downLatch, opsPerThread, threadId, writtenOperations, seqNoGenerator, threadExceptions);
threads[i].setDaemon(true);
threads[i].start();
}
downLatch.countDown();
for (int i = 0; i < threadCount; i++) {
if (threadExceptions[i] != null) {
throw threadExceptions[i];
}
threads[i].join(60 * 1000);
}
List<LocationOperation> collect = new ArrayList<>(writtenOperations);
Collections.sort(collect);
Translog.Snapshot snapshot = translog.newSnapshot();
for (LocationOperation locationOperation : collect) {
Translog.Operation op = snapshot.next();
assertNotNull(op);
Translog.Operation expectedOp = locationOperation.operation;
assertEquals(expectedOp.opType(), op.opType());
switch (op.opType()) {
case INDEX:
Translog.Index indexOp = (Translog.Index) op;
Translog.Index expIndexOp = (Translog.Index) expectedOp;
assertEquals(expIndexOp.id(), indexOp.id());
assertEquals(expIndexOp.routing(), indexOp.routing());
assertEquals(expIndexOp.type(), indexOp.type());
assertEquals(expIndexOp.source(), indexOp.source());
assertEquals(expIndexOp.version(), indexOp.version());
assertEquals(expIndexOp.versionType(), indexOp.versionType());
break;
case DELETE:
Translog.Delete delOp = (Translog.Delete) op;
Translog.Delete expDelOp = (Translog.Delete) expectedOp;
assertEquals(expDelOp.uid(), delOp.uid());
assertEquals(expDelOp.version(), delOp.version());
assertEquals(expDelOp.versionType(), delOp.versionType());
break;
case NO_OP:
final Translog.NoOp noOp = (Translog.NoOp) op;
final Translog.NoOp expectedNoOp = (Translog.NoOp) expectedOp;
assertThat(noOp.seqNo(), equalTo(expectedNoOp.seqNo()));
assertThat(noOp.primaryTerm(), equalTo(expectedNoOp.primaryTerm()));
assertThat(noOp.reason(), equalTo(expectedNoOp.reason()));
break;
default:
throw new AssertionError("unsupported operation type [" + op.opType() + "]");
}
}
assertNull(snapshot.next());
}
public void testTranslogChecksums() throws Exception {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
for (int op = 0; op < translogOperations; op++) {
String ascii = randomAlphaOfLengthBetween(1, 50);
locations.add(translog.add(new Translog.Index("test", "" + op, op, ascii.getBytes("UTF-8"))));
}
translog.sync();
corruptTranslogs(translogDir);
AtomicInteger corruptionsCaught = new AtomicInteger(0);
Translog.Snapshot snapshot = translog.newSnapshot();
for (Translog.Location location : locations) {
try {
Translog.Operation next = snapshot.next();
assertNotNull(next);
} catch (TranslogCorruptedException e) {
corruptionsCaught.incrementAndGet();
}
}
expectThrows(TranslogCorruptedException.class, snapshot::next);
assertThat("at least one corruption was caused and caught", corruptionsCaught.get(), greaterThanOrEqualTo(1));
}
public void testTruncatedTranslogs() throws Exception {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
for (int op = 0; op < translogOperations; op++) {
String ascii = randomAlphaOfLengthBetween(1, 50);
locations.add(translog.add(new Translog.Index("test", "" + op, op, ascii.getBytes("UTF-8"))));
}
translog.sync();
truncateTranslogs(translogDir);
AtomicInteger truncations = new AtomicInteger(0);
Translog.Snapshot snap = translog.newSnapshot();
for (Translog.Location location : locations) {
try {
assertNotNull(snap.next());
} catch (EOFException e) {
truncations.incrementAndGet();
}
}
assertThat("at least one truncation was caused and caught", truncations.get(), greaterThanOrEqualTo(1));
}
/**
* Randomly truncate some bytes in the translog files
*/
private void truncateTranslogs(Path directory) throws Exception {
Path[] files = FileSystemUtils.files(directory, "translog-*");
for (Path file : files) {
try (FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
long prevSize = f.size();
long newSize = prevSize - randomIntBetween(1, (int) prevSize / 2);
logger.info("--> truncating {}, prev: {}, now: {}", file, prevSize, newSize);
f.truncate(newSize);
}
}
}
/**
* Randomly overwrite some bytes in the translog files
*/
private void corruptTranslogs(Path directory) throws Exception {
Path[] files = FileSystemUtils.files(directory, "translog-*");
for (Path file : files) {
logger.info("--> corrupting {}...", file);
FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
int corruptions = scaledRandomIntBetween(10, 50);
for (int i = 0; i < corruptions; i++) {
// note: with the current logic, this will sometimes be a no-op
long pos = randomIntBetween(0, (int) f.size());
ByteBuffer junk = ByteBuffer.wrap(new byte[]{randomByte()});
f.write(junk, pos);
}
f.close();
}
}
private Term newUid(ParsedDocument doc) {
return new Term("_uid", Uid.createUidAsBytes(doc.type(), doc.id()));
}
private Term newUid(String uid) {
return new Term("_uid", uid);
}
public void testVerifyTranslogIsNotDeleted() throws IOException {
assertFileIsPresent(translog, 1);
translog.add(new Translog.Index("test", "1", 0, new byte[]{1}));
Translog.Snapshot snapshot = translog.newSnapshot();
assertThat(snapshot, SnapshotMatchers.size(1));
assertFileIsPresent(translog, 1);
assertThat(snapshot.totalOperations(), equalTo(1));
translog.close();
assertFileIsPresent(translog, 1);
}
/**
* Tests that concurrent readers and writes maintain view and snapshot semantics
*/
public void testConcurrentWriteViewsAndSnapshot() throws Throwable {
final Thread[] writers = new Thread[randomIntBetween(1, 3)];
final Thread[] readers = new Thread[randomIntBetween(1, 3)];
final int flushEveryOps = randomIntBetween(5, 100);
final int maxOps = randomIntBetween(200, 1000);
final Object signalReaderSomeDataWasIndexed = new Object();
final AtomicLong idGenerator = new AtomicLong();
final CyclicBarrier barrier = new CyclicBarrier(writers.length + readers.length + 1);
// a map of all written ops and their returned location.
final Map<Translog.Operation, Translog.Location> writtenOps = ConcurrentCollections.newConcurrentMap();
// a signal for all threads to stop
final AtomicBoolean run = new AtomicBoolean(true);
final Object flushMutex = new Object();
final AtomicLong lastCommittedLocalCheckpoint = new AtomicLong(SequenceNumbersService.NO_OPS_PERFORMED);
final LocalCheckpointTracker tracker = LocalCheckpointTrackerTests.createEmptyTracker();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
// any errors on threads
final List<Exception> errors = new CopyOnWriteArrayList<>();
logger.debug("using [{}] readers. [{}] writers. flushing every ~[{}] ops.", readers.length, writers.length, flushEveryOps);
for (int i = 0; i < writers.length; i++) {
final String threadName = "writer_" + i;
final int threadId = i;
writers[i] = new Thread(new AbstractRunnable() {
@Override
public void doRun() throws BrokenBarrierException, InterruptedException, IOException {
barrier.await();
int counter = 0;
while (run.get() && idGenerator.get() < maxOps) {
long id = idGenerator.getAndIncrement();
final Translog.Operation op;
final Translog.Operation.Type type =
Translog.Operation.Type.values()[((int) (id % Translog.Operation.Type.values().length))];
switch (type) {
case CREATE:
case INDEX:
op = new Translog.Index("type", "" + id, id, new byte[]{(byte) id});
break;
case DELETE:
op = new Translog.Delete("test", Long.toString(id), id, newUid(Long.toString(id)));
break;
case NO_OP:
op = new Translog.NoOp(id, 1, Long.toString(id));
break;
default:
throw new AssertionError("unsupported operation type [" + type + "]");
}
Translog.Location location = translog.add(op);
tracker.markSeqNoAsCompleted(id);
Translog.Location existing = writtenOps.put(op, location);
if (existing != null) {
fail("duplicate op [" + op + "], old entry at " + location);
}
if (id % writers.length == threadId) {
translog.ensureSynced(location);
}
if (id % flushEveryOps == 0) {
synchronized (flushMutex) {
// we need not do this concurrently as we need to make sure that the generation
// we're committing - is still present when we're committing
long localCheckpoint = tracker.getCheckpoint() + 1;
translog.rollGeneration();
deletionPolicy.setMinTranslogGenerationForRecovery(
translog.getMinGenerationForSeqNo(localCheckpoint + 1).translogFileGeneration);
translog.trimUnreferencedReaders();
lastCommittedLocalCheckpoint.set(localCheckpoint);
}
}
if (id % 7 == 0) {
synchronized (signalReaderSomeDataWasIndexed) {
signalReaderSomeDataWasIndexed.notifyAll();
}
}
counter++;
}
logger.debug("--> [{}] done. wrote [{}] ops.", threadName, counter);
}
@Override
public void onFailure(Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("--> writer [{}] had an error", threadName), e);
errors.add(e);
}
}, threadName);
writers[i].start();
}
for (int i = 0; i < readers.length; i++) {
final String threadId = "reader_" + i;
readers[i] = new Thread(new AbstractRunnable() {
Translog.View view = null;
long committedLocalCheckpointAtView;
@Override
public void onFailure(Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("--> reader [{}] had an error", threadId), e);
errors.add(e);
try {
closeView();
} catch (IOException inner) {
inner.addSuppressed(e);
logger.error("unexpected error while closing view, after failure", inner);
}
}
void closeView() throws IOException {
if (view != null) {
view.close();
}
}
void newView() throws IOException {
closeView();
view = translog.newView();
// captures the last committed checkpoint, while holding the view, simulating
// recovery logic which captures a view and gets a lucene commit
committedLocalCheckpointAtView = lastCommittedLocalCheckpoint.get();
logger.debug("--> [{}] opened view from [{}]", threadId, view.viewGenToRelease);
}
@Override
protected void doRun() throws Exception {
barrier.await();
int iter = 0;
while (idGenerator.get() < maxOps) {
if (iter++ % 10 == 0) {
newView();
}
// captures al views that are written since the view was created (with a small caveat see bellow)
// these are what we expect the snapshot to return (and potentially some more).
Set<Translog.Operation> expectedOps = new HashSet<>(writtenOps.keySet());
expectedOps.removeIf(op -> op.seqNo() <= committedLocalCheckpointAtView);
Translog.Snapshot snapshot = view.snapshot(committedLocalCheckpointAtView + 1L);
Translog.Operation op;
while ((op = snapshot.next()) != null) {
expectedOps.remove(op);
}
if (expectedOps.isEmpty() == false) {
StringBuilder missed = new StringBuilder("missed ").append(expectedOps.size())
.append(" operations from [").append(committedLocalCheckpointAtView + 1L).append("]");
boolean failed = false;
for (Translog.Operation expectedOp : expectedOps) {
final Translog.Location loc = writtenOps.get(expectedOp);
failed = true;
missed.append("\n --> [").append(expectedOp).append("] written at ").append(loc);
}
if (failed) {
fail(missed.toString());
}
}
// slow down things a bit and spread out testing..
synchronized (signalReaderSomeDataWasIndexed) {
if (idGenerator.get() < maxOps) {
signalReaderSomeDataWasIndexed.wait();
}
}
}
closeView();
logger.debug("--> [{}] done. tested [{}] snapshots", threadId, iter);
}
}, threadId);
readers[i].start();
}
barrier.await();
logger.debug("--> waiting for threads to stop");
for (Thread thread : writers) {
thread.join();
}
logger.debug("--> waiting for readers to stop");
// force stopping, if all writers crashed
synchronized (signalReaderSomeDataWasIndexed) {
idGenerator.set(Long.MAX_VALUE);
signalReaderSomeDataWasIndexed.notifyAll();
}
for (Thread thread : readers) {
thread.join();
}
if (errors.size() > 0) {
Throwable e = errors.get(0);
for (Throwable suppress : errors.subList(1, errors.size())) {
e.addSuppressed(suppress);
}
throw e;
}
logger.info("--> test done. total ops written [{}]", writtenOps.size());
}
public void testSyncUpTo() throws IOException {
int translogOperations = randomIntBetween(10, 100);
int count = 0;
for (int op = 0; op < translogOperations; op++) {
int seqNo = ++count;
final Translog.Location location =
translog.add(new Translog.Index("test", "" + op, seqNo, Integer.toString(seqNo).getBytes(Charset.forName("UTF-8"))));
if (randomBoolean()) {
assertTrue("at least one operation pending", translog.syncNeeded());
assertTrue("this operation has not been synced", translog.ensureSynced(location));
assertFalse("the last call to ensureSycned synced all previous ops", translog.syncNeeded()); // we are the last location so everything should be synced
seqNo = ++count;
translog.add(new Translog.Index("test", "" + op, seqNo, Integer.toString(seqNo).getBytes(Charset.forName("UTF-8"))));
assertTrue("one pending operation", translog.syncNeeded());
assertFalse("this op has been synced before", translog.ensureSynced(location)); // not syncing now
assertTrue("we only synced a previous operation yet", translog.syncNeeded());
}
if (rarely()) {
rollAndCommit(translog);
assertFalse("location is from a previous translog - already synced", translog.ensureSynced(location)); // not syncing now
assertFalse("no sync needed since no operations in current translog", translog.syncNeeded());
}
if (randomBoolean()) {
translog.sync();
assertFalse("translog has been synced already", translog.ensureSynced(location));
}
}
}
public void testSyncUpToStream() throws IOException {
int iters = randomIntBetween(5, 10);
for (int i = 0; i < iters; i++) {
int translogOperations = randomIntBetween(10, 100);
int count = 0;
ArrayList<Location> locations = new ArrayList<>();
for (int op = 0; op < translogOperations; op++) {
if (rarely()) {
rollAndCommit(translog); // do this first so that there is at least one pending tlog entry
}
final Translog.Location location =
translog.add(new Translog.Index("test", "" + op, op, Integer.toString(++count).getBytes(Charset.forName("UTF-8"))));
locations.add(location);
}
Collections.shuffle(locations, random());
if (randomBoolean()) {
assertTrue("at least one operation pending", translog.syncNeeded());
assertTrue("this operation has not been synced", translog.ensureSynced(locations.stream()));
assertFalse("the last call to ensureSycned synced all previous ops", translog.syncNeeded()); // we are the last location so everything should be synced
} else if (rarely()) {
rollAndCommit(translog);
assertFalse("location is from a previous translog - already synced", translog.ensureSynced(locations.stream())); // not syncing now
assertFalse("no sync needed since no operations in current translog", translog.syncNeeded());
} else {
translog.sync();
assertFalse("translog has been synced already", translog.ensureSynced(locations.stream()));
}
for (Location location : locations) {
assertFalse("all of the locations should be synced: " + location, translog.ensureSynced(location));
}
}
}
public void testLocationComparison() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
int count = 0;
for (int op = 0; op < translogOperations; op++) {
locations.add(
translog.add(new Translog.Index("test", "" + op, op, Integer.toString(++count).getBytes(Charset.forName("UTF-8")))));
if (rarely() && translogOperations > op + 1) {
rollAndCommit(translog);
}
}
Collections.shuffle(locations, random());
Translog.Location max = locations.get(0);
for (Translog.Location location : locations) {
max = max(max, location);
}
assertEquals(max.generation, translog.currentFileGeneration());
Translog.Snapshot snap = translog.newSnapshot();
Translog.Operation next;
Translog.Operation maxOp = null;
while ((next = snap.next()) != null) {
maxOp = next;
}
assertNotNull(maxOp);
assertEquals(maxOp.getSource().source.utf8ToString(), Integer.toString(count));
}
public static Translog.Location max(Translog.Location a, Translog.Location b) {
if (a.compareTo(b) > 0) {
return a;
}
return b;
}
public void testBasicCheckpoint() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
int lastSynced = -1;
long lastSyncedGlobalCheckpoint = globalCheckpoint.get();
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
if (randomBoolean()) {
globalCheckpoint.set(globalCheckpoint.get() + randomIntBetween(1, 16));
}
if (frequently()) {
translog.sync();
lastSynced = op;
lastSyncedGlobalCheckpoint = globalCheckpoint.get();
}
}
assertEquals(translogOperations, translog.totalOperations());
translog.add(new Translog.Index(
"test", "" + translogOperations, translogOperations, Integer.toString(translogOperations).getBytes(Charset.forName("UTF-8"))));
final Checkpoint checkpoint = Checkpoint.read(translog.location().resolve(Translog.CHECKPOINT_FILE_NAME));
try (TranslogReader reader = translog.openReader(translog.location().resolve(Translog.getFilename(translog.currentFileGeneration())), checkpoint)) {
assertEquals(lastSynced + 1, reader.totalOperations());
Translog.Snapshot snapshot = reader.newSnapshot();
for (int op = 0; op < translogOperations; op++) {
if (op <= lastSynced) {
final Translog.Operation read = snapshot.next();
assertEquals(Integer.toString(op), read.getSource().source.utf8ToString());
} else {
Translog.Operation next = snapshot.next();
assertNull(next);
}
}
Translog.Operation next = snapshot.next();
assertNull(next);
}
assertEquals(translogOperations + 1, translog.totalOperations());
assertThat(checkpoint.globalCheckpoint, equalTo(lastSyncedGlobalCheckpoint));
translog.close();
}
public void testTranslogWriter() throws IOException {
final TranslogWriter writer = translog.createWriter(translog.currentFileGeneration() + 1);
final int numOps = randomIntBetween(8, 128);
byte[] bytes = new byte[4];
ByteArrayDataOutput out = new ByteArrayDataOutput(bytes);
final Set<Long> seenSeqNos = new HashSet<>();
boolean opsHaveValidSequenceNumbers = randomBoolean();
for (int i = 0; i < numOps; i++) {
out.reset(bytes);
out.writeInt(i);
long seqNo;
do {
seqNo = opsHaveValidSequenceNumbers ? randomNonNegativeLong() : SequenceNumbersService.UNASSIGNED_SEQ_NO;
opsHaveValidSequenceNumbers = opsHaveValidSequenceNumbers || !rarely();
} while (seenSeqNos.contains(seqNo));
if (seqNo != SequenceNumbersService.UNASSIGNED_SEQ_NO) {
seenSeqNos.add(seqNo);
}
writer.add(new BytesArray(bytes), seqNo);
}
writer.sync();
final BaseTranslogReader reader = randomBoolean() ? writer : translog.openReader(writer.path(), Checkpoint.read(translog.location().resolve(Translog.CHECKPOINT_FILE_NAME)));
for (int i = 0; i < numOps; i++) {
ByteBuffer buffer = ByteBuffer.allocate(4);
reader.readBytes(buffer, reader.getFirstOperationOffset() + 4 * i);
buffer.flip();
final int value = buffer.getInt();
assertEquals(i, value);
}
final long minSeqNo = seenSeqNos.stream().min(Long::compareTo).orElse(SequenceNumbersService.NO_OPS_PERFORMED);
final long maxSeqNo = seenSeqNos.stream().max(Long::compareTo).orElse(SequenceNumbersService.NO_OPS_PERFORMED);
assertThat(reader.getCheckpoint().minSeqNo, equalTo(minSeqNo));
assertThat(reader.getCheckpoint().maxSeqNo, equalTo(maxSeqNo));
out.reset(bytes);
out.writeInt(2048);
writer.add(new BytesArray(bytes), randomNonNegativeLong());
if (reader instanceof TranslogReader) {
ByteBuffer buffer = ByteBuffer.allocate(4);
try {
reader.readBytes(buffer, reader.getFirstOperationOffset() + 4 * numOps);
fail("read past EOF?");
} catch (EOFException ex) {
// expected
}
((TranslogReader) reader).close();
} else {
// live reader!
ByteBuffer buffer = ByteBuffer.allocate(4);
final long pos = reader.getFirstOperationOffset() + 4 * numOps;
reader.readBytes(buffer, pos);
buffer.flip();
final int value = buffer.getInt();
assertEquals(2048, value);
}
IOUtils.close(writer);
}
public void testCloseIntoReader() throws IOException {
try (TranslogWriter writer = translog.createWriter(translog.currentFileGeneration() + 1)) {
final int numOps = randomIntBetween(8, 128);
final byte[] bytes = new byte[4];
final ByteArrayDataOutput out = new ByteArrayDataOutput(bytes);
for (int i = 0; i < numOps; i++) {
out.reset(bytes);
out.writeInt(i);
writer.add(new BytesArray(bytes), randomNonNegativeLong());
}
writer.sync();
final Checkpoint writerCheckpoint = writer.getCheckpoint();
TranslogReader reader = writer.closeIntoReader();
try {
if (randomBoolean()) {
reader.close();
reader = translog.openReader(reader.path(), writerCheckpoint);
}
for (int i = 0; i < numOps; i++) {
final ByteBuffer buffer = ByteBuffer.allocate(4);
reader.readBytes(buffer, reader.getFirstOperationOffset() + 4 * i);
buffer.flip();
final int value = buffer.getInt();
assertEquals(i, value);
}
final Checkpoint readerCheckpoint = reader.getCheckpoint();
assertThat(readerCheckpoint, equalTo(writerCheckpoint));
} finally {
IOUtils.close(reader);
}
}
}
public void testBasicRecovery() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
Translog.TranslogGeneration translogGeneration = null;
int minUncommittedOp = -1;
final boolean commitOften = randomBoolean();
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
final boolean commit = commitOften ? frequently() : rarely();
if (commit && op < translogOperations - 1) {
rollAndCommit(translog);
minUncommittedOp = op + 1;
translogGeneration = translog.getGeneration();
}
}
translog.sync();
TranslogConfig config = translog.getConfig();
translog.close();
if (translogGeneration == null) {
translog = createTranslog(config, null);
assertEquals(0, translog.stats().estimatedNumberOfOperations());
assertEquals(1, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot();
assertNull(snapshot.next());
} else {
translog = new Translog(config, translogGeneration.translogUUID, translog.getDeletionPolicy(), () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
assertEquals("lastCommitted must be 1 less than current", translogGeneration.translogFileGeneration + 1, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot(translogGeneration.translogFileGeneration);
for (int i = minUncommittedOp; i < translogOperations; i++) {
assertEquals("expected operation" + i + " to be in the previous translog but wasn't", translog.currentFileGeneration() - 1, locations.get(i).generation);
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
assertEquals(i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
public void testRecoveryUncommitted() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
final int prepareOp = randomIntBetween(0, translogOperations - 1);
Translog.TranslogGeneration translogGeneration = null;
final boolean sync = randomBoolean();
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
if (op == prepareOp) {
translogGeneration = translog.getGeneration();
translog.rollGeneration();
assertEquals("expected this to be the first commit", 1L, translogGeneration.translogFileGeneration);
assertNotNull(translogGeneration.translogUUID);
}
}
if (sync) {
translog.sync();
}
// we intentionally don't close the tlog that is in the prepareCommit stage since we try to recovery the uncommitted
// translog here as well.
TranslogConfig config = translog.getConfig();
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
try (Translog translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertNotNull(translogGeneration);
assertEquals("lastCommitted must be 2 less than current - we never finished the commit", translogGeneration.translogFileGeneration + 2, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot();
int upTo = sync ? translogOperations : prepareOp;
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
assertEquals("payload mismatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
if (randomBoolean()) { // recover twice
try (Translog translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertNotNull(translogGeneration);
assertEquals("lastCommitted must be 3 less than current - we never finished the commit and run recovery twice", translogGeneration.translogFileGeneration + 3, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot();
int upTo = sync ? translogOperations : prepareOp;
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
assertEquals("payload mismatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
}
public void testRecoveryUncommittedFileExists() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
final int prepareOp = randomIntBetween(0, translogOperations - 1);
Translog.TranslogGeneration translogGeneration = null;
final boolean sync = randomBoolean();
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
if (op == prepareOp) {
translogGeneration = translog.getGeneration();
translog.rollGeneration();
assertEquals("expected this to be the first commit", 1L, translogGeneration.translogFileGeneration);
assertNotNull(translogGeneration.translogUUID);
}
}
if (sync) {
translog.sync();
}
// we intentionally don't close the tlog that is in the prepareCommit stage since we try to recovery the uncommitted
// translog here as well.
TranslogConfig config = translog.getConfig();
Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME);
Checkpoint read = Checkpoint.read(ckp);
Files.copy(ckp, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)));
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
try (Translog translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertNotNull(translogGeneration);
assertEquals("lastCommitted must be 2 less than current - we never finished the commit", translogGeneration.translogFileGeneration + 2, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot();
int upTo = sync ? translogOperations : prepareOp;
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
assertEquals("payload mismatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
if (randomBoolean()) { // recover twice
try (Translog translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertNotNull(translogGeneration);
assertEquals("lastCommitted must be 3 less than current - we never finished the commit and run recovery twice", translogGeneration.translogFileGeneration + 3, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot();
int upTo = sync ? translogOperations : prepareOp;
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
assertEquals("payload mismatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
}
public void testRecoveryUncommittedCorruptedCheckpoint() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = 100;
final int prepareOp = 44;
Translog.TranslogGeneration translogGeneration = null;
final boolean sync = randomBoolean();
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
if (op == prepareOp) {
translogGeneration = translog.getGeneration();
translog.rollGeneration();
assertEquals("expected this to be the first commit", 1L, translogGeneration.translogFileGeneration);
assertNotNull(translogGeneration.translogUUID);
}
}
translog.sync();
// we intentionally don't close the tlog that is in the prepareCommit stage since we try to recovery the uncommitted
// translog here as well.
TranslogConfig config = translog.getConfig();
Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME);
Checkpoint read = Checkpoint.read(ckp);
Checkpoint corrupted = Checkpoint.emptyTranslogCheckpoint(0, 0, SequenceNumbersService.UNASSIGNED_SEQ_NO, 0);
Checkpoint.write(FileChannel::open, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)), corrupted, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
try (Translog ignored = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
fail("corrupted");
} catch (IllegalStateException ex) {
assertEquals("Checkpoint file translog-2.ckp already exists but has corrupted content expected: Checkpoint{offset=3123, " +
"numOps=55, generation=2, minSeqNo=45, maxSeqNo=99, globalCheckpoint=-2, minTranslogGeneration=1} but got: Checkpoint{offset=0, numOps=0, " +
"generation=0, minSeqNo=-1, maxSeqNo=-1, globalCheckpoint=-2, minTranslogGeneration=0}", ex.getMessage());
}
Checkpoint.write(FileChannel::open, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)), read, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
try (Translog translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertNotNull(translogGeneration);
assertEquals("lastCommitted must be 2 less than current - we never finished the commit", translogGeneration.translogFileGeneration + 2, translog.currentFileGeneration());
assertFalse(translog.syncNeeded());
Translog.Snapshot snapshot = translog.newSnapshot();
int upTo = sync ? translogOperations : prepareOp;
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
assertEquals("payload mismatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
public void testSnapshotFromStreamInput() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
List<Translog.Operation> ops = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
for (int op = 0; op < translogOperations; op++) {
Translog.Index test = new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")));
ops.add(test);
}
Translog.writeOperations(out, ops);
final List<Translog.Operation> readOperations = Translog.readOperations(out.bytes().streamInput());
assertEquals(ops.size(), readOperations.size());
assertEquals(ops, readOperations);
}
public void testLocationHashCodeEquals() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
List<Translog.Location> locations2 = new ArrayList<>();
int translogOperations = randomIntBetween(10, 100);
try (Translog translog2 = create(createTempDir())) {
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
locations2.add(translog2.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
}
int iters = randomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
Translog.Location location = RandomPicks.randomFrom(random(), locations);
for (Translog.Location loc : locations) {
if (loc == location) {
assertTrue(loc.equals(location));
assertEquals(loc.hashCode(), location.hashCode());
} else {
assertFalse(loc.equals(location));
}
}
for (int j = 0; j < translogOperations; j++) {
assertTrue(locations.get(j).equals(locations2.get(j)));
assertEquals(locations.get(j).hashCode(), locations2.get(j).hashCode());
}
}
}
}
public void testOpenForeignTranslog() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int translogOperations = randomIntBetween(1, 10);
int firstUncommitted = 0;
for (int op = 0; op < translogOperations; op++) {
locations.add(translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8")))));
if (randomBoolean()) {
rollAndCommit(translog);
firstUncommitted = op + 1;
}
}
final TranslogConfig config = translog.getConfig();
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
Translog.TranslogGeneration translogGeneration = translog.getGeneration();
translog.close();
final String foreignTranslog = randomRealisticUnicodeOfCodepointLengthBetween(1,
translogGeneration.translogUUID.length());
try {
new Translog(config, foreignTranslog, createTranslogDeletionPolicy(), () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
fail("translog doesn't belong to this UUID");
} catch (TranslogCorruptedException ex) {
}
this.translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
Translog.Snapshot snapshot = this.translog.newSnapshot(translogGeneration.translogFileGeneration);
for (int i = firstUncommitted; i < translogOperations; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("" + i, next);
assertEquals(Integer.parseInt(next.getSource().source.utf8ToString()), i);
}
assertNull(snapshot.next());
}
public void testFailOnClosedWrite() throws IOException {
translog.add(new Translog.Index("test", "1", 0, Integer.toString(1).getBytes(Charset.forName("UTF-8"))));
translog.close();
try {
translog.add(new Translog.Index("test", "1", 0, Integer.toString(1).getBytes(Charset.forName("UTF-8"))));
fail("closed");
} catch (AlreadyClosedException ex) {
// all is well
}
}
public void testCloseConcurrently() throws Throwable {
final int opsPerThread = randomIntBetween(10, 200);
int threadCount = 2 + randomInt(5);
logger.info("testing with [{}] threads, each doing [{}] ops", threadCount, opsPerThread);
final BlockingQueue<LocationOperation> writtenOperations = new ArrayBlockingQueue<>(threadCount * opsPerThread);
Thread[] threads = new Thread[threadCount];
final Exception[] threadExceptions = new Exception[threadCount];
final CountDownLatch downLatch = new CountDownLatch(1);
final AtomicLong seqNoGenerator = new AtomicLong();
for (int i = 0; i < threadCount; i++) {
final int threadId = i;
threads[i] = new TranslogThread(translog, downLatch, opsPerThread, threadId, writtenOperations, seqNoGenerator, threadExceptions);
threads[i].setDaemon(true);
threads[i].start();
}
downLatch.countDown();
translog.close();
for (int i = 0; i < threadCount; i++) {
if (threadExceptions[i] != null) {
if ((threadExceptions[i] instanceof AlreadyClosedException) == false) {
throw threadExceptions[i];
}
}
threads[i].join(60 * 1000);
}
}
private static class TranslogThread extends Thread {
private final CountDownLatch downLatch;
private final int opsPerThread;
private final int threadId;
private final Collection<LocationOperation> writtenOperations;
private final Exception[] threadExceptions;
private final Translog translog;
private final AtomicLong seqNoGenerator;
TranslogThread(Translog translog, CountDownLatch downLatch, int opsPerThread, int threadId,
Collection<LocationOperation> writtenOperations, AtomicLong seqNoGenerator, Exception[] threadExceptions) {
this.translog = translog;
this.downLatch = downLatch;
this.opsPerThread = opsPerThread;
this.threadId = threadId;
this.writtenOperations = writtenOperations;
this.seqNoGenerator = seqNoGenerator;
this.threadExceptions = threadExceptions;
}
@Override
public void run() {
try {
downLatch.await();
for (int opCount = 0; opCount < opsPerThread; opCount++) {
Translog.Operation op;
final Translog.Operation.Type type = randomFrom(Translog.Operation.Type.values());
switch (type) {
case CREATE:
case INDEX:
op = new Translog.Index("test", threadId + "_" + opCount, seqNoGenerator.getAndIncrement(),
randomUnicodeOfLengthBetween(1, 20 * 1024).getBytes("UTF-8"));
break;
case DELETE:
op = new Translog.Delete(
"test", threadId + "_" + opCount,
new Term("_uid", threadId + "_" + opCount),
seqNoGenerator.getAndIncrement(),
0,
1 + randomInt(100000),
randomFrom(VersionType.values()));
break;
case NO_OP:
op = new Translog.NoOp(seqNoGenerator.getAndIncrement(), randomNonNegativeLong(), randomAlphaOfLength(16));
break;
default:
throw new AssertionError("unsupported operation type [" + type + "]");
}
Translog.Location loc = add(op);
writtenOperations.add(new LocationOperation(op, loc));
afterAdd();
}
} catch (Exception t) {
threadExceptions[threadId] = t;
}
}
protected Translog.Location add(Translog.Operation op) throws IOException {
return translog.add(op);
}
protected void afterAdd() throws IOException {
}
}
public void testFailFlush() throws IOException {
Path tempDir = createTempDir();
final FailSwitch fail = new FailSwitch();
TranslogConfig config = getTranslogConfig(tempDir);
Translog translog = getFailableTranslog(fail, config);
List<Translog.Location> locations = new ArrayList<>();
int opsSynced = 0;
boolean failed = false;
while (failed == false) {
try {
locations.add(translog.add(
new Translog.Index("test", "" + opsSynced, opsSynced, Integer.toString(opsSynced).getBytes(Charset.forName("UTF-8")))));
translog.sync();
opsSynced++;
} catch (MockDirectoryWrapper.FakeIOException ex) {
failed = true;
assertFalse(translog.isOpen());
} catch (IOException ex) {
failed = true;
assertFalse(translog.isOpen());
assertEquals("__FAKE__ no space left on device", ex.getMessage());
}
if (randomBoolean()) {
fail.failAlways();
} else {
fail.failNever();
}
}
fail.failNever();
if (randomBoolean()) {
try {
locations.add(translog.add(
new Translog.Index("test", "" + opsSynced, opsSynced, Integer.toString(opsSynced).getBytes(Charset.forName("UTF-8")))));
fail("we are already closed");
} catch (AlreadyClosedException ex) {
assertNotNull(ex.getCause());
if (ex.getCause() instanceof MockDirectoryWrapper.FakeIOException) {
assertNull(ex.getCause().getMessage());
} else {
assertEquals(ex.getCause().getMessage(), "__FAKE__ no space left on device");
}
}
}
Translog.TranslogGeneration translogGeneration = translog.getGeneration();
try {
translog.newSnapshot();
fail("already closed");
} catch (AlreadyClosedException ex) {
// all is well
assertNotNull(ex.getCause());
assertSame(translog.getTragicException(), ex.getCause());
}
try {
rollAndCommit(translog);
fail("already closed");
} catch (AlreadyClosedException ex) {
assertNotNull(ex.getCause());
assertSame(translog.getTragicException(), ex.getCause());
}
assertFalse(translog.isOpen());
translog.close(); // we are closed
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
try (Translog tlog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertEquals("lastCommitted must be 1 less than current", translogGeneration.translogFileGeneration + 1, tlog.currentFileGeneration());
assertFalse(tlog.syncNeeded());
Translog.Snapshot snapshot = tlog.newSnapshot();
assertEquals(opsSynced, snapshot.totalOperations());
for (int i = 0; i < opsSynced; i++) {
assertEquals("expected operation" + i + " to be in the previous translog but wasn't", tlog.currentFileGeneration() - 1, locations.get(i).generation);
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
assertEquals(i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
public void testTranslogOpsCountIsCorrect() throws IOException {
List<Translog.Location> locations = new ArrayList<>();
int numOps = randomIntBetween(100, 200);
LineFileDocs lineFileDocs = new LineFileDocs(random()); // writes pretty big docs so we cross buffer borders regularly
for (int opsAdded = 0; opsAdded < numOps; opsAdded++) {
locations.add(translog.add(
new Translog.Index("test", "" + opsAdded, opsAdded, lineFileDocs.nextDoc().toString().getBytes(Charset.forName("UTF-8")))));
Translog.Snapshot snapshot = this.translog.newSnapshot();
assertEquals(opsAdded + 1, snapshot.totalOperations());
for (int i = 0; i < opsAdded; i++) {
assertEquals("expected operation" + i + " to be in the current translog but wasn't", translog.currentFileGeneration(), locations.get(i).generation);
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
}
}
}
public void testTragicEventCanBeAnyException() throws IOException {
Path tempDir = createTempDir();
final FailSwitch fail = new FailSwitch();
TranslogConfig config = getTranslogConfig(tempDir);
Translog translog = getFailableTranslog(fail, config, false, true, null, createTranslogDeletionPolicy());
LineFileDocs lineFileDocs = new LineFileDocs(random()); // writes pretty big docs so we cross buffer boarders regularly
translog.add(new Translog.Index("test", "1", 0, lineFileDocs.nextDoc().toString().getBytes(Charset.forName("UTF-8"))));
fail.failAlways();
try {
Translog.Location location = translog.add(
new Translog.Index("test", "2", 1, lineFileDocs.nextDoc().toString().getBytes(Charset.forName("UTF-8"))));
if (randomBoolean()) {
translog.ensureSynced(location);
} else {
translog.sync();
}
//TODO once we have a mock FS that can simulate we can also fail on plain sync
fail("WTF");
} catch (UnknownException ex) {
// w00t
} catch (TranslogException ex) {
assertTrue(ex.getCause() instanceof UnknownException);
}
assertFalse(translog.isOpen());
assertTrue(translog.getTragicException() instanceof UnknownException);
}
public void testFatalIOExceptionsWhileWritingConcurrently() throws IOException, InterruptedException {
Path tempDir = createTempDir();
final FailSwitch fail = new FailSwitch();
TranslogConfig config = getTranslogConfig(tempDir);
Translog translog = getFailableTranslog(fail, config);
final String translogUUID = translog.getTranslogUUID();
final int threadCount = randomIntBetween(1, 5);
Thread[] threads = new Thread[threadCount];
final Exception[] threadExceptions = new Exception[threadCount];
final CountDownLatch downLatch = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(randomIntBetween(10, 100));
final AtomicLong seqNoGenerator = new AtomicLong();
List<LocationOperation> writtenOperations = Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < threadCount; i++) {
final int threadId = i;
threads[i] = new TranslogThread(translog, downLatch, 200, threadId, writtenOperations, seqNoGenerator, threadExceptions) {
@Override
protected Translog.Location add(Translog.Operation op) throws IOException {
Translog.Location add = super.add(op);
added.countDown();
return add;
}
@Override
protected void afterAdd() throws IOException {
if (randomBoolean()) {
translog.sync();
}
}
};
threads[i].setDaemon(true);
threads[i].start();
}
downLatch.countDown();
added.await();
try (Translog.View view = translog.newView()) {
// this holds a reference to the current tlog channel such that it's not closed
// if we hit a tragic event. this is important to ensure that asserts inside the Translog#add doesn't trip
// otherwise our assertions here are off by one sometimes.
fail.failAlways();
for (int i = 0; i < threadCount; i++) {
threads[i].join();
}
boolean atLeastOneFailed = false;
for (Throwable ex : threadExceptions) {
if (ex != null) {
assertTrue(ex.toString(), ex instanceof IOException || ex instanceof AlreadyClosedException);
atLeastOneFailed = true;
}
}
if (atLeastOneFailed == false) {
try {
boolean syncNeeded = translog.syncNeeded();
translog.close();
assertFalse("should have failed if sync was needed", syncNeeded);
} catch (IOException ex) {
// boom now we failed
}
}
Collections.sort(writtenOperations, (a, b) -> a.location.compareTo(b.location));
assertFalse(translog.isOpen());
final Checkpoint checkpoint = Checkpoint.read(config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME));
Iterator<LocationOperation> iterator = writtenOperations.iterator();
while (iterator.hasNext()) {
LocationOperation next = iterator.next();
if (checkpoint.offset < (next.location.translogLocation + next.location.size)) {
// drop all that haven't been synced
iterator.remove();
}
}
try (Translog tlog = new Translog(config, translogUUID, createTranslogDeletionPolicy(), () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
Translog.Snapshot snapshot = tlog.newSnapshot();
if (writtenOperations.size() != snapshot.totalOperations()) {
for (int i = 0; i < threadCount; i++) {
if (threadExceptions[i] != null) {
logger.info("Translog exception", threadExceptions[i]);
}
}
}
assertEquals(writtenOperations.size(), snapshot.totalOperations());
for (int i = 0; i < writtenOperations.size(); i++) {
assertEquals("expected operation" + i + " to be in the previous translog but wasn't", tlog.currentFileGeneration() - 1, writtenOperations.get(i).location.generation);
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
assertEquals(next, writtenOperations.get(i).operation);
}
}
}
}
/**
* Tests the situation where the node crashes after a translog gen was committed to lucene, but before the translog had the chance
* to clean up its files.
*/
public void testRecoveryFromAFutureGenerationCleansUp() throws IOException {
int translogOperations = randomIntBetween(10, 100);
for (int op = 0; op < translogOperations / 2; op++) {
translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))));
if (rarely()) {
translog.rollGeneration();
}
}
translog.rollGeneration();
long comittedGeneration = randomLongBetween(2, translog.currentFileGeneration());
for (int op = translogOperations / 2; op < translogOperations; op++) {
translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))));
if (rarely()) {
translog.rollGeneration();
}
}
// engine blows up, after committing the above generation
translog.close();
TranslogConfig config = translog.getConfig();
final TranslogDeletionPolicy deletionPolicy = new TranslogDeletionPolicy(-1, -1);
deletionPolicy.setMinTranslogGenerationForRecovery(comittedGeneration);
translog = new Translog(config, translog.getTranslogUUID(), deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
assertThat(translog.getMinFileGeneration(), equalTo(1L));
// no trimming done yet, just recovered
for (long gen = 1; gen < translog.currentFileGeneration(); gen++) {
assertFileIsPresent(translog, gen);
}
translog.trimUnreferencedReaders();
for (long gen = 1; gen < comittedGeneration; gen++) {
assertFileDeleted(translog, gen);
}
}
/**
* Tests the situation where the node crashes after a translog gen was committed to lucene, but before the translog had the chance
* to clean up its files.
*/
public void testRecoveryFromFailureOnTrimming() throws IOException {
Path tempDir = createTempDir();
final FailSwitch fail = new FailSwitch();
fail.failNever();
final TranslogConfig config = getTranslogConfig(tempDir);
final long comittedGeneration;
final String translogUUID;
try (Translog translog = getFailableTranslog(fail, config)) {
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
// disable retention so we trim things
deletionPolicy.setRetentionSizeInBytes(-1);
deletionPolicy.setRetentionAgeInMillis(-1);
translogUUID = translog.getTranslogUUID();
int translogOperations = randomIntBetween(10, 100);
for (int op = 0; op < translogOperations / 2; op++) {
translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))));
if (rarely()) {
translog.rollGeneration();
}
}
translog.rollGeneration();
comittedGeneration = randomLongBetween(2, translog.currentFileGeneration());
for (int op = translogOperations / 2; op < translogOperations; op++) {
translog.add(new Translog.Index("test", "" + op, op, Integer.toString(op).getBytes(Charset.forName("UTF-8"))));
if (rarely()) {
translog.rollGeneration();
}
}
deletionPolicy.setMinTranslogGenerationForRecovery(comittedGeneration);
fail.failRandomly();
try {
translog.trimUnreferencedReaders();
} catch (Exception e) {
// expected...
}
}
final TranslogDeletionPolicy deletionPolicy = new TranslogDeletionPolicy(-1, -1);
deletionPolicy.setMinTranslogGenerationForRecovery(comittedGeneration);
try (Translog translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
// we don't know when things broke exactly
assertThat(translog.getMinFileGeneration(), greaterThanOrEqualTo(1L));
assertThat(translog.getMinFileGeneration(), lessThanOrEqualTo(comittedGeneration));
assertFilePresences(translog);
translog.trimUnreferencedReaders();
assertThat(translog.getMinFileGeneration(), equalTo(comittedGeneration));
assertFilePresences(translog);
}
}
private Translog getFailableTranslog(FailSwitch fail, final TranslogConfig config) throws IOException {
return getFailableTranslog(fail, config, randomBoolean(), false, null, createTranslogDeletionPolicy());
}
private static class FailSwitch {
private volatile int failRate;
private volatile boolean onceFailedFailAlways = false;
public boolean fail() {
boolean fail = randomIntBetween(1, 100) <= failRate;
if (fail && onceFailedFailAlways) {
failAlways();
}
return fail;
}
public void failNever() {
failRate = 0;
}
public void failAlways() {
failRate = 100;
}
public void failRandomly() {
failRate = randomIntBetween(1, 100);
}
public void onceFailedFailAlways() {
onceFailedFailAlways = true;
}
}
private Translog getFailableTranslog(final FailSwitch fail, final TranslogConfig config, final boolean partialWrites,
final boolean throwUnknownException, String translogUUID,
final TranslogDeletionPolicy deletionPolicy) throws IOException {
return new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO) {
@Override
ChannelFactory getChannelFactory() {
final ChannelFactory factory = super.getChannelFactory();
return (file, openOption) -> {
FileChannel channel = factory.open(file, openOption);
boolean success = false;
try {
final boolean isCkpFile = file.getFileName().toString().endsWith(".ckp"); // don't do partial writes for checkpoints we rely on the fact that the bytes are written as an atomic operation
ThrowingFileChannel throwingFileChannel = new ThrowingFileChannel(fail, isCkpFile ? false : partialWrites, throwUnknownException, channel);
success = true;
return throwingFileChannel;
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(channel);
}
}
};
}
@Override
void deleteReaderFiles(TranslogReader reader) {
if (fail.fail()) {
// simulate going OOM and dieing just at the wrong moment.
throw new RuntimeException("simulated");
} else {
super.deleteReaderFiles(reader);
}
}
};
}
public static class ThrowingFileChannel extends FilterFileChannel {
private final FailSwitch fail;
private final boolean partialWrite;
private final boolean throwUnknownException;
public ThrowingFileChannel(FailSwitch fail, boolean partialWrite, boolean throwUnknownException, FileChannel delegate) throws MockDirectoryWrapper.FakeIOException {
super(delegate);
this.fail = fail;
this.partialWrite = partialWrite;
this.throwUnknownException = throwUnknownException;
if (fail.fail()) {
throw new MockDirectoryWrapper.FakeIOException();
}
}
@Override
public int read(ByteBuffer dst) throws IOException {
if (fail.fail()) {
throw new MockDirectoryWrapper.FakeIOException();
}
return super.read(dst);
}
@Override
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
if (fail.fail()) {
throw new MockDirectoryWrapper.FakeIOException();
}
return super.read(dsts, offset, length);
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int write(ByteBuffer src, long position) throws IOException {
throw new UnsupportedOperationException();
}
public int write(ByteBuffer src) throws IOException {
if (fail.fail()) {
if (partialWrite) {
if (src.hasRemaining()) {
final int pos = src.position();
final int limit = src.limit();
src.limit(randomIntBetween(pos, limit));
super.write(src);
src.limit(limit);
src.position(pos);
throw new IOException("__FAKE__ no space left on device");
}
}
if (throwUnknownException) {
throw new UnknownException();
} else {
throw new MockDirectoryWrapper.FakeIOException();
}
}
return super.write(src);
}
@Override
public void force(boolean metaData) throws IOException {
if (fail.fail()) {
throw new MockDirectoryWrapper.FakeIOException();
}
super.force(metaData);
}
@Override
public long position() throws IOException {
if (fail.fail()) {
throw new MockDirectoryWrapper.FakeIOException();
}
return super.position();
}
}
private static final class UnknownException extends RuntimeException {
}
// see https://github.com/elastic/elasticsearch/issues/15754
public void testFailWhileCreateWriteWithRecoveredTLogs() throws IOException {
Path tempDir = createTempDir();
TranslogConfig config = getTranslogConfig(tempDir);
Translog translog = createTranslog(config, null);
translog.add(new Translog.Index("test", "boom", 0, "boom".getBytes(Charset.forName("UTF-8"))));
translog.close();
try {
new Translog(config, translog.getTranslogUUID(), createTranslogDeletionPolicy(), () -> SequenceNumbersService.UNASSIGNED_SEQ_NO) {
@Override
protected TranslogWriter createWriter(long fileGeneration) throws IOException {
throw new MockDirectoryWrapper.FakeIOException();
}
};
// if we have a LeakFS here we fail if not all resources are closed
fail("should have been failed");
} catch (MockDirectoryWrapper.FakeIOException ex) {
// all is well
}
}
public void testRecoverWithUnbackedNextGen() throws IOException {
translog.add(new Translog.Index("test", "" + 0, 0, Integer.toString(0).getBytes(Charset.forName("UTF-8"))));
translog.close();
TranslogConfig config = translog.getConfig();
Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME);
Checkpoint read = Checkpoint.read(ckp);
Files.copy(ckp, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)));
Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog"));
try (Translog tlog = createTranslog(config, translog.getTranslogUUID())) {
assertFalse(tlog.syncNeeded());
Translog.Snapshot snapshot = tlog.newSnapshot();
for (int i = 0; i < 1; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
tlog.add(new Translog.Index("test", "" + 1, 1, Integer.toString(1).getBytes(Charset.forName("UTF-8"))));
}
try (Translog tlog = createTranslog(config, translog.getTranslogUUID())) {
assertFalse(tlog.syncNeeded());
Translog.Snapshot snapshot = tlog.newSnapshot();
for (int i = 0; i < 2; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
public void testRecoverWithUnbackedNextGenInIllegalState() throws IOException {
translog.add(new Translog.Index("test", "" + 0, 0, Integer.toString(0).getBytes(Charset.forName("UTF-8"))));
translog.close();
TranslogConfig config = translog.getConfig();
Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME);
Checkpoint read = Checkpoint.read(ckp);
// don't copy the new file
Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog"));
try {
Translog tlog = new Translog(config, translog.getTranslogUUID(), translog.getDeletionPolicy(), () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
fail("file already exists?");
} catch (TranslogException ex) {
// all is well
assertEquals(ex.getMessage(), "failed to create new translog file");
assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class);
}
}
public void testRecoverWithUnbackedNextGenAndFutureFile() throws IOException {
translog.add(new Translog.Index("test", "" + 0, 0, Integer.toString(0).getBytes(Charset.forName("UTF-8"))));
translog.close();
TranslogConfig config = translog.getConfig();
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
Path ckp = config.getTranslogPath().resolve(Translog.CHECKPOINT_FILE_NAME);
Checkpoint read = Checkpoint.read(ckp);
Files.copy(ckp, config.getTranslogPath().resolve(Translog.getCommitCheckpointFileName(read.generation)));
Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog"));
// we add N+1 and N+2 to ensure we only delete the N+1 file and never jump ahead and wipe without the right condition
Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 2) + ".tlog"));
try (Translog tlog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
assertFalse(tlog.syncNeeded());
Translog.Snapshot snapshot = tlog.newSnapshot();
for (int i = 0; i < 1; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
tlog.add(new Translog.Index("test", "" + 1, 1, Integer.toString(1).getBytes(Charset.forName("UTF-8"))));
}
try {
Translog tlog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
fail("file already exists?");
} catch (TranslogException ex) {
// all is well
assertEquals(ex.getMessage(), "failed to create new translog file");
assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class);
}
}
/**
* This test adds operations to the translog which might randomly throw an IOException. The only thing this test verifies is
* that we can, after we hit an exception, open and recover the translog successfully and retrieve all successfully synced operations
* from the transaction log.
*/
public void testWithRandomException() throws IOException {
final int runs = randomIntBetween(5, 10);
for (int run = 0; run < runs; run++) {
Path tempDir = createTempDir();
final FailSwitch fail = new FailSwitch();
fail.failRandomly();
TranslogConfig config = getTranslogConfig(tempDir);
final int numOps = randomIntBetween(100, 200);
long minGenForRecovery = 1;
List<String> syncedDocs = new ArrayList<>();
List<String> unsynced = new ArrayList<>();
if (randomBoolean()) {
fail.onceFailedFailAlways();
}
String generationUUID = null;
try {
boolean committing = false;
final Translog failableTLog = getFailableTranslog(fail, config, randomBoolean(), false, generationUUID, createTranslogDeletionPolicy());
try {
LineFileDocs lineFileDocs = new LineFileDocs(random()); //writes pretty big docs so we cross buffer boarders regularly
for (int opsAdded = 0; opsAdded < numOps; opsAdded++) {
String doc = lineFileDocs.nextDoc().toString();
failableTLog.add(new Translog.Index("test", "" + opsAdded, opsAdded, doc.getBytes(Charset.forName("UTF-8"))));
unsynced.add(doc);
if (randomBoolean()) {
failableTLog.sync();
syncedDocs.addAll(unsynced);
unsynced.clear();
}
if (randomFloat() < 0.1) {
failableTLog.sync(); // we have to sync here first otherwise we don't know if the sync succeeded if the commit fails
syncedDocs.addAll(unsynced);
unsynced.clear();
failableTLog.rollGeneration();
committing = true;
failableTLog.getDeletionPolicy().setMinTranslogGenerationForRecovery(failableTLog.currentFileGeneration());
failableTLog.trimUnreferencedReaders();
committing = false;
syncedDocs.clear();
}
}
// we survived all the randomness!!!
// lets close the translog and if it succeeds we are all synced again. If we don't do this we will close
// it in the finally block but miss to copy over unsynced docs to syncedDocs and fail the assertion down the road...
failableTLog.close();
syncedDocs.addAll(unsynced);
unsynced.clear();
} catch (TranslogException | MockDirectoryWrapper.FakeIOException ex) {
// fair enough
} catch (IOException ex) {
assertEquals(ex.getMessage(), "__FAKE__ no space left on device");
} catch (RuntimeException ex) {
assertEquals(ex.getMessage(), "simulated");
} finally {
Checkpoint checkpoint = Translog.readCheckpoint(config.getTranslogPath());
if (checkpoint.numOps == unsynced.size() + syncedDocs.size()) {
syncedDocs.addAll(unsynced); // failed in fsync but got fully written
unsynced.clear();
}
if (committing && checkpoint.minTranslogGeneration == checkpoint.generation) {
// we were committing and blew up in one of the syncs, but they made it through
syncedDocs.clear();
assertThat(unsynced, empty());
}
generationUUID = failableTLog.getTranslogUUID();
minGenForRecovery = failableTLog.getDeletionPolicy().getMinTranslogGenerationForRecovery();
IOUtils.closeWhileHandlingException(failableTLog);
}
} catch (TranslogException | MockDirectoryWrapper.FakeIOException ex) {
// failed - that's ok, we didn't even create it
} catch (IOException ex) {
assertEquals(ex.getMessage(), "__FAKE__ no space left on device");
}
// now randomly open this failing tlog again just to make sure we can also recover from failing during recovery
if (randomBoolean()) {
try {
TranslogDeletionPolicy deletionPolicy = createTranslogDeletionPolicy();
deletionPolicy.setMinTranslogGenerationForRecovery(minGenForRecovery);
IOUtils.close(getFailableTranslog(fail, config, randomBoolean(), false, generationUUID, deletionPolicy));
} catch (TranslogException | MockDirectoryWrapper.FakeIOException ex) {
// failed - that's ok, we didn't even create it
} catch (IOException ex) {
assertEquals(ex.getMessage(), "__FAKE__ no space left on device");
}
}
fail.failNever(); // we don't wanna fail here but we might since we write a new checkpoint and create a new tlog file
TranslogDeletionPolicy deletionPolicy = createTranslogDeletionPolicy();
deletionPolicy.setMinTranslogGenerationForRecovery(minGenForRecovery);
try (Translog translog = new Translog(config, generationUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO)) {
Translog.Snapshot snapshot = translog.newSnapshot(minGenForRecovery);
assertEquals(syncedDocs.size(), snapshot.totalOperations());
for (int i = 0; i < syncedDocs.size(); i++) {
Translog.Operation next = snapshot.next();
assertEquals(syncedDocs.get(i), next.getSource().source.utf8ToString());
assertNotNull("operation " + i + " must be non-null", next);
}
}
}
}
private Checkpoint randomCheckpoint() {
final long a = randomNonNegativeLong();
final long b = randomNonNegativeLong();
final long minSeqNo;
final long maxSeqNo;
if (a <= b) {
minSeqNo = a;
maxSeqNo = b;
} else {
minSeqNo = b;
maxSeqNo = a;
}
final long generation = randomNonNegativeLong();
return new Checkpoint(randomLong(), randomInt(), generation, minSeqNo, maxSeqNo, randomNonNegativeLong(),
randomLongBetween(1, generation));
}
public void testCheckpointOnDiskFull() throws IOException {
final Checkpoint checkpoint = randomCheckpoint();
Path tempDir = createTempDir();
Checkpoint.write(FileChannel::open, tempDir.resolve("foo.cpk"), checkpoint, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
final Checkpoint checkpoint2 = randomCheckpoint();
try {
Checkpoint.write((p, o) -> {
if (randomBoolean()) {
throw new MockDirectoryWrapper.FakeIOException();
}
FileChannel open = FileChannel.open(p, o);
FailSwitch failSwitch = new FailSwitch();
failSwitch.failNever(); // don't fail in the ctor
ThrowingFileChannel channel = new ThrowingFileChannel(failSwitch, false, false, open);
failSwitch.failAlways();
return channel;
}, tempDir.resolve("foo.cpk"), checkpoint2, StandardOpenOption.WRITE);
fail("should have failed earlier");
} catch (MockDirectoryWrapper.FakeIOException ex) {
//fine
}
Checkpoint read = Checkpoint.read(tempDir.resolve("foo.cpk"));
assertEquals(read, checkpoint);
}
/**
* Tests that closing views after the translog is fine and we can reopen the translog
*/
public void testPendingDelete() throws IOException {
translog.add(new Translog.Index("test", "1", 0, new byte[]{1}));
translog.rollGeneration();
TranslogConfig config = translog.getConfig();
final String translogUUID = translog.getTranslogUUID();
final TranslogDeletionPolicy deletionPolicy = createTranslogDeletionPolicy(config.getIndexSettings());
translog.close();
translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
translog.add(new Translog.Index("test", "2", 1, new byte[]{2}));
translog.rollGeneration();
Translog.View view = translog.newView();
translog.add(new Translog.Index("test", "3", 2, new byte[]{3}));
translog.close();
IOUtils.close(view);
translog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbersService.UNASSIGNED_SEQ_NO);
}
public static Translog.Location randomTranslogLocation() {
return new Translog.Location(randomLong(), randomLong(), randomInt());
}
public void testTranslogOpSerialization() throws Exception {
BytesReference B_1 = new BytesArray(new byte[]{1});
SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID();
assert Version.CURRENT.major <= 6 : "Using UNASSIGNED_SEQ_NO can be removed in 7.0, because 6.0+ nodes have actual sequence numbers";
long randomSeqNum = randomBoolean() ? SequenceNumbersService.UNASSIGNED_SEQ_NO : randomNonNegativeLong();
long primaryTerm = randomSeqNum == SequenceNumbersService.UNASSIGNED_SEQ_NO ? 0 : randomIntBetween(1, 16);
long randomPrimaryTerm = randomBoolean() ? 0 : randomNonNegativeLong();
seqID.seqNo.setLongValue(randomSeqNum);
seqID.seqNoDocValue.setLongValue(randomSeqNum);
seqID.primaryTerm.setLongValue(randomPrimaryTerm);
Field uidField = new Field("_uid", Uid.createUid("test", "1"), UidFieldMapper.Defaults.FIELD_TYPE);
Field versionField = new NumericDocValuesField("_version", 1);
Document document = new Document();
document.add(new TextField("value", "test", Field.Store.YES));
document.add(uidField);
document.add(versionField);
document.add(seqID.seqNo);
document.add(seqID.seqNoDocValue);
document.add(seqID.primaryTerm);
ParsedDocument doc = new ParsedDocument(versionField, seqID, "1", "type", null, Arrays.asList(document), B_1, XContentType.JSON,
null);
Engine.Index eIndex = new Engine.Index(newUid(doc), doc, randomSeqNum, randomPrimaryTerm,
1, VersionType.INTERNAL, Origin.PRIMARY, 0, 0, false);
Engine.IndexResult eIndexResult = new Engine.IndexResult(1, randomSeqNum, true);
Translog.Index index = new Translog.Index(eIndex, eIndexResult);
BytesStreamOutput out = new BytesStreamOutput();
index.writeTo(out);
StreamInput in = out.bytes().streamInput();
Translog.Index serializedIndex = new Translog.Index(in);
assertEquals(index, serializedIndex);
Engine.Delete eDelete = new Engine.Delete(doc.type(), doc.id(), newUid(doc), randomSeqNum, randomPrimaryTerm,
2, VersionType.INTERNAL, Origin.PRIMARY, 0);
Engine.DeleteResult eDeleteResult = new Engine.DeleteResult(2, randomSeqNum, true);
Translog.Delete delete = new Translog.Delete(eDelete, eDeleteResult);
out = new BytesStreamOutput();
delete.writeTo(out);
in = out.bytes().streamInput();
Translog.Delete serializedDelete = new Translog.Delete(in);
assertEquals(delete, serializedDelete);
// simulate legacy delete serialization
out = new BytesStreamOutput();
out.writeVInt(Translog.Delete.FORMAT_5_0);
out.writeString(UidFieldMapper.NAME);
out.writeString("my_type#my_id");
out.writeLong(3); // version
out.writeByte(VersionType.INTERNAL.getValue());
out.writeLong(2); // seq no
out.writeLong(0); // primary term
in = out.bytes().streamInput();
serializedDelete = new Translog.Delete(in);
assertEquals("my_type", serializedDelete.type());
assertEquals("my_id", serializedDelete.id());
}
public void testRollGeneration() throws Exception {
// make sure we keep some files around
final boolean longRetention = randomBoolean();
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
if (longRetention) {
deletionPolicy.setRetentionAgeInMillis(3600 * 1000);
} else {
deletionPolicy.setRetentionAgeInMillis(-1);
}
// we control retention via time, disable size based calculations for simplicity
deletionPolicy.setRetentionSizeInBytes(-1);
final long generation = translog.currentFileGeneration();
final int rolls = randomIntBetween(1, 16);
int totalOperations = 0;
int seqNo = 0;
for (int i = 0; i < rolls; i++) {
final int operations = randomIntBetween(1, 128);
for (int j = 0; j < operations; j++) {
translog.add(new Translog.NoOp(seqNo++, 0, "test"));
totalOperations++;
}
try (ReleasableLock ignored = translog.writeLock.acquire()) {
translog.rollGeneration();
}
assertThat(translog.currentFileGeneration(), equalTo(generation + i + 1));
assertThat(translog.totalOperations(), equalTo(totalOperations));
}
for (int i = 0; i <= rolls; i++) {
assertFileIsPresent(translog, generation + i);
}
commit(translog, generation + rolls);
assertThat(translog.currentFileGeneration(), equalTo(generation + rolls ));
assertThat(translog.uncommittedOperations(), equalTo(0));
if (longRetention) {
for (int i = 0; i <= rolls; i++) {
assertFileIsPresent(translog, generation + i);
}
deletionPolicy.setRetentionAgeInMillis(randomBoolean() ? 100 : -1);
assertBusy(() -> {
translog.trimUnreferencedReaders();
for (int i = 0; i < rolls; i++) {
assertFileDeleted(translog, generation + i);
}
});
} else {
// immediate cleanup
for (int i = 0; i < rolls; i++) {
assertFileDeleted(translog, generation + i);
}
}
assertFileIsPresent(translog, generation + rolls);
}
public void testMinGenerationForSeqNo() throws IOException {
final int operations = randomIntBetween(1, 4096);
final List<Long> shuffledSeqNos = LongStream.range(0, operations).boxed().collect(Collectors.toList());
Randomness.shuffle(shuffledSeqNos);
final List<Tuple<Long, Long>> seqNos = new ArrayList<>();
final Map<Long, Long> terms = new HashMap<>();
for (final Long seqNo : shuffledSeqNos) {
seqNos.add(Tuple.tuple(seqNo, terms.computeIfAbsent(seqNo, k -> 0L)));
Long repeatingTermSeqNo = randomFrom(seqNos.stream().map(Tuple::v1).collect(Collectors.toList()));
seqNos.add(Tuple.tuple(repeatingTermSeqNo, terms.get(repeatingTermSeqNo)));
}
for (final Tuple<Long, Long> tuple : seqNos) {
translog.add(new Translog.NoOp(tuple.v1(), tuple.v2(), "test"));
if (rarely()) {
translog.rollGeneration();
}
}
Map<Long, Set<Tuple<Long, Long>>> generations = new HashMap<>();
// one extra roll to make sure that all ops so far are available via a reader and a translog-{gen}.ckp
// file in a consistent way, in order to simplify checking code.
translog.rollGeneration();
for (long seqNo = 0; seqNo < operations; seqNo++) {
final Set<Tuple<Long, Long>> seenSeqNos = new HashSet<>();
final long generation = translog.getMinGenerationForSeqNo(seqNo).translogFileGeneration;
for (long g = generation; g < translog.currentFileGeneration(); g++) {
if (!generations.containsKey(g)) {
final Set<Tuple<Long, Long>> generationSeenSeqNos = new HashSet<>();
final Checkpoint checkpoint = Checkpoint.read(translog.location().resolve(Translog.getCommitCheckpointFileName(g)));
try (TranslogReader reader = translog.openReader(translog.location().resolve(Translog.getFilename(g)), checkpoint)) {
Translog.Snapshot snapshot = reader.newSnapshot();
Translog.Operation operation;
while ((operation = snapshot.next()) != null) {
generationSeenSeqNos.add(Tuple.tuple(operation.seqNo(), operation.primaryTerm()));
}
}
generations.put(g, generationSeenSeqNos);
}
seenSeqNos.addAll(generations.get(g));
}
final long seqNoLowerBound = seqNo;
final Set<Tuple<Long, Long>> expected = seqNos.stream().filter(t -> t.v1() >= seqNoLowerBound).collect(Collectors.toSet());
seenSeqNos.retainAll(expected);
assertThat(seenSeqNos, equalTo(expected));
}
}
public void testSimpleCommit() throws IOException {
final int operations = randomIntBetween(1, 4096);
long seqNo = 0;
for (int i = 0; i < operations; i++) {
translog.add(new Translog.NoOp(seqNo++, 0, "test'"));
if (rarely()) {
translog.rollGeneration();
}
}
final long generation =
randomIntBetween(1, Math.toIntExact(translog.currentFileGeneration()));
commit(translog, generation);
}
public void testOpenViewIsPassToDeletionPolicy() throws IOException {
final int operations = randomIntBetween(1, 4096);
final TranslogDeletionPolicy deletionPolicy = translog.getDeletionPolicy();
for (int i = 0; i < operations; i++) {
translog.add(new Translog.NoOp(i, 0, "test"));
if (rarely()) {
translog.rollGeneration();
}
if (rarely()) {
commit(translog, randomLongBetween(deletionPolicy.getMinTranslogGenerationForRecovery(), translog.currentFileGeneration()));
}
if (frequently()) {
long viewGen;
try (Translog.View view = translog.newView()) {
viewGen = view.viewGenToRelease;
assertThat(deletionPolicy.getViewCount(view.viewGenToRelease), equalTo(1L));
}
assertThat(deletionPolicy.getViewCount(viewGen), equalTo(0L));
}
}
}
}
| apache-2.0 |
aws/aws-sdk-cpp | aws-cpp-sdk-es/source/model/AutoTune.cpp | 1529 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/es/model/AutoTune.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ElasticsearchService
{
namespace Model
{
AutoTune::AutoTune() :
m_autoTuneType(AutoTuneType::NOT_SET),
m_autoTuneTypeHasBeenSet(false),
m_autoTuneDetailsHasBeenSet(false)
{
}
AutoTune::AutoTune(JsonView jsonValue) :
m_autoTuneType(AutoTuneType::NOT_SET),
m_autoTuneTypeHasBeenSet(false),
m_autoTuneDetailsHasBeenSet(false)
{
*this = jsonValue;
}
AutoTune& AutoTune::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("AutoTuneType"))
{
m_autoTuneType = AutoTuneTypeMapper::GetAutoTuneTypeForName(jsonValue.GetString("AutoTuneType"));
m_autoTuneTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("AutoTuneDetails"))
{
m_autoTuneDetails = jsonValue.GetObject("AutoTuneDetails");
m_autoTuneDetailsHasBeenSet = true;
}
return *this;
}
JsonValue AutoTune::Jsonize() const
{
JsonValue payload;
if(m_autoTuneTypeHasBeenSet)
{
payload.WithString("AutoTuneType", AutoTuneTypeMapper::GetNameForAutoTuneType(m_autoTuneType));
}
if(m_autoTuneDetailsHasBeenSet)
{
payload.WithObject("AutoTuneDetails", m_autoTuneDetails.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace ElasticsearchService
} // namespace Aws
| apache-2.0 |
xtoolkit/XMPN | Xtouch/header2.php | 8225 | <?php
/************************************************************************/
/* PHP-NUKE: Advanced Content Management System */
/* ============================================ */
/* */
/* Copyright (c) 2006 by Francisco Burzi */
/* http://phpnuke.org */
/* */
/* 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. */
/************************************************************************/
if (stristr(htmlentities($_SERVER['PHP_SELF']), "header.php")) {
Header("Location: index.php");
die();
}
$preloader = 1; //Preloader
define('NUKE_HEADER', true);
@require_once("mainfile.php");
global $db ,$prefix ,$gtset ,$admin ,$adminmail;
if ($gtset == "1") {
nextGenTap(1,0,0);
}
if(!$row = $db->sql_fetchrow($db->sql_query("SELECT * from ".$prefix."_nukesql"))){
die(header("location: upgrade.php"));
}
##################################################
# Include some common header for HTML generation #
##################################################
global $pagetitle;
if(defined("ADMIN_FILE")){
adminheader($pagetitle);
}else{
global $name, $nukeurl, $xdemailset,$xtouch,$sitecookies;
//// in this code we save current page that user is in it.
if($name != "Your_Account"){
$currentpagelink = $_SERVER['REQUEST_URI'];
$arr_nukeurl = explode("/",$nukeurl);
$arr_nukeurl = array_filter($arr_nukeurl);
foreach($arr_nukeurl as $key => $values){
if($key > 2){
unset($arr_nukeurl[$key]);
}
}
$arr_nukeurl = array_filter($arr_nukeurl);
$new_nukeurl = $arr_nukeurl[0]."//".$arr_nukeurl[2];
$currentpage = $new_nukeurl.$currentpagelink;
nuke_set_cookie("currentpage",$currentpage,time()+1800);
}
if(!function_exists('head')){
function head() {
global $slogan, $name, $sitename, $banners, $nukeurl, $Version_Num, $ab_config, $artpage, $topic, $hlpfile, $user, $hr, $theme, $cookie, $bgcolor1, $bgcolor2, $bgcolor3, $bgcolor4, $textcolor1, $textcolor2, $forumpage, $adminpage, $userpage, $pagetitle, $pagetags, $align, $preloader, $anonymous;
$ThemeSel = get_theme();
theme_lang();
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
echo "<head>\n";
echo"<title>$sitename $pagetitle</title>";
@include("includes/meta.php");
@include("includes/javascript.php");
if (file_exists("themes/$ThemeSel/images/favicon.ico")) {
echo "<link rel=\"shortcut icon\" href=\"themes/$ThemeSel/images/favicon.ico\" type=\"image/x-icon\" />\n";
}
echo "</head>\n";
if($preloader == 1){
echo "<div id=\"waitDiv\" onclick=\"this.style.visibility='hidden'\" style=\" direction:rtl; text-align:center; line-height:17px; position:fixed; z-index:1000; width:100%; height:100%; background-color:#000; color:#fff; font-size:11px; margin:0px auto;\"><div style=\"position:fixed; top:100px; left:100px \" id=\"loadingimage\" ><img src=\"images/loader.gif\" /></div></div>";
echo "<script>showWaitm('waitDiv', 1);</script>\n";
echo "</div>\n";
}
$u_agent = $_SERVER['HTTP_USER_AGENT'];
themeheader();
}
}
online();
if(isset($admin) && $admin == $_COOKIE['admin']){}else{
function xdvs($nuim){
global $prefix, $db, $dbname;
$nuim=intval($nuim);
$result = $db->sql_query("SELECT * FROM `" . $prefix . "_xdisable` WHERE `xdid` =$nuim LIMIT 0 , 1");
while ($row = $db->sql_fetchrow($result)) {
mb_internal_encoding('UTF-8');
$xdid = intval($row['xdid']);
$xdname = $row['xdname'];
$xdvalue = $row['xdvalue'];
}
return $xdvalue;
}
function xduemails($nuim){
global $prefix, $db, $dbname;
$db->sql_query("INSERT INTO `$dbname`.`" . $prefix . "_xdisable` (`xdid`, `xdname`, `xdvalue`) VALUES (NULL, 'xduemail', '$nuim');");
}
if(xdvs(1)==1){
if(isset($xdemailset)){
if (filter_var($xdemailset, FILTER_VALIDATE_EMAIL)) {
xduemails($xdemailset);
}else{
$xdemailset=0;
}
}
$xdtheme=xdvs(2);
if($xdtheme=="default"){
xdisable_theme();
}else{
@include("includes/xdisable/$xdtheme/xdtheme.php");
xdisable_theme();
}
}
}
function xtscookie($name, $cookiedata, $cookietime){
global $sitecookies;
if($cookiedata == false){
$cookietime = time()-3600;
}
$name_data = rawurlencode($name) . '=' . rawurlencode($cookiedata);
$expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
@header('Set-Cookie: '.$name_data.(($cookietime) ? '; expires='.$expire : '').'; path='.$sitecookies.'; HttpOnly', false);
}
if(isset($xtouch)){
$expire = time()+60*60*24*7;
xtscookie("xtouch-set", $xtouch, $expire);
if($_SERVER['HTTP_REFERER']==""){
Header("Location: index.php");
} else {
header('Location:' . $_SERVER['HTTP_REFERER']);
}
}
$mobile_browser = '0';
if(@preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i',
strtolower($_SERVER['HTTP_USER_AGENT']))){
$mobile_browser++;
}
if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or
((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))){
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-');
if(in_array($mobile_ua,$mobile_agents)){
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
$mobile_browser=0;
}
if($mobile_browser>0 OR $_COOKIE['xtouch-set']==1){
require_once("XMSConfig.lib.php");
$xcall1=xsitemapitemcall("radius","حالت فعال بودن ماژول تاچ");
$xcallt=xsitemapitemcall("select","پوسته ماژول تاچ");
$xcallsm=xsitemapitemcall("select","منو در Xtouch");
$xcallst=xsitemapitemcall("text","عنوان سایت در حالت موبایل");
$xcallss=xsitemapitemcall("radius","نمایش لینک دسکتاپ");
$xcallsmm=xsitemapitemcall("checkbox","فعال بودن ماژول های تاچ");
if($xcall1[1]=="radius" AND $xcall1[2]=="حالت فعال بودن ماژول تاچ" AND $xcall1[3]!==""){
if($xcall1[3]==0 OR $xcall1[3]==1){
if($xcallsmm[1]=="checkbox" AND $xcallsmm[2]=="فعال بودن ماژول های تاچ"){$xtmodules=$xcallsmm[3];}
if($xcallt[1]=="select" AND $xcallt[2]=="پوسته ماژول تاچ"){$xttheme=$xcallt[3];}
if($xcallt[3]==""){$xttheme="default";}
if($xcallsm[1]=="select" AND $xcallsm[2]=="منو در Xtouch" AND $xcallsm[3]!==""){$xtxmmenu=$xcallsm[3];}
if($xcallst[1]=="text" AND $xcallst[2]=="عنوان سایت در حالت موبایل" AND $xcallst[3]!==""){$xtstitle=$xcallst[3];}
if($xcallss[1]=="radius" AND $xcallss[2]=="نمایش لینک دسکتاپ" AND $xcallss[3]!==""){$swichers=$xcallss[3];}
if($xcallst[3]==""){$xtstitle=$sitename;}
if($xcall1[3]==1 AND is_admin($admin)){
if($xttheme=="default"){}else{include("modules/Xtouch/themes/$xttheme/xttheme.php");}
xttheme($xtstitle,$xtxmmenu,$swichers,$xtmodules);
}elseif($xcall1[3]==0){
if($xttheme=="default"){}else{include("modules/Xtouch/themes/$xttheme/xttheme.php");}
xttheme($xtstitle,$xtxmmenu,$swichers,$xtmodules);
}
}
}
}
head();
@include("includes/counter.php");
if(defined('HOME_FILE')) {
message_box();
blocks("Center");
}
}
?> | apache-2.0 |
asoft-tlt/book | app/templates/page19.html | 2449 | <div class="page" id="page19">
<div class="page-slider" style="position:absolute;top:222px;left:523px;width:417px;height:450px;padding: 4px;border: 1px solid #d7b39d;">
<div class="page-slider__container"></div>
</div>
<div class="text2col">
<div style="text-align:justify;" class="col1">
Знай, что на дверях каждой из казацких церквей бывает железная цепь, вроде той, которую налагают на шею пленникам. Мы спросили о ней и нам сказали, что всякому, кто приходит в церковь на рассвете после звона, вешают эту цепь на шею и целый день он остаётся распятым на дверном от- воре, не имея возможности шевельнуться. Это его эпитимья.<br><br>
Начиная с города Рашкова и по всей земле <span style="letter-spacing:-0.3px;word-spacing:-1px;">казаков, то есть русских, мы заметили возбу-</span><span style="letter-spacing:-0.3px;word-spacing:-1px;"> дившую наше удивление прекрасную черту.</span> Все они, за исключением немногих, умеют читать и знают порядок церковных служб. При этом священники обучают сирот, при- <span style="letter-spacing:-0.3px;word-spacing:-1px;">нимают их на попечение и не оставляют ша-</span> таться по улицам невеждами. В каждом го- <span style="letter-spacing:-0.3px;word-spacing:-1px;">роде и в каждой деревне для них выстроены</span> приёмные дома.
</div>
<div style="text-align:justify;" class="col2">
<span style="letter-spacing:-0.3px;word-spacing:-1px;">Как мы приметили, вдов и сирот в этой стра-</span><span style="letter-spacing:-0.3px;word-spacing:-1px;"> не бесчисленное множество, ибо со времени</span><span style="letter-spacing:-0.3px;word-spacing:-1px;"> появления гетмана Хмельницкого не прекра-</span> щались у них страшные войны.
</div>
</div>
</div> | apache-2.0 |
halatmit/appinventor-sources | appinventor/appengine/src/com/google/appinventor/client/wizards/ComponentImportWizard.java | 9473 | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2020 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.client.wizards;
import static com.google.appinventor.client.Ode.MESSAGES;
import com.allen_sauer.gwt.dnd.client.util.StringUtil;
import com.google.appinventor.client.Ode;
import com.google.appinventor.client.OdeAsyncCallback;
import com.google.appinventor.client.editor.simple.SimpleComponentDatabase;
import com.google.appinventor.client.editor.youngandroid.YaProjectEditor;
import com.google.appinventor.client.explorer.project.Project;
import com.google.appinventor.client.output.OdeLog;
import com.google.appinventor.common.utils.StringUtils;
import com.google.appinventor.client.utils.Uploader;
import com.google.appinventor.shared.rpc.ServerLayout;
import com.google.appinventor.shared.rpc.UploadResponse;
import com.google.appinventor.shared.rpc.component.Component;
import com.google.appinventor.shared.rpc.component.ComponentImportResponse;
import com.google.appinventor.shared.rpc.project.ProjectNode;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidAssetsFolder;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidComponentsFolder;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.Command;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import java.util.List;
public class ComponentImportWizard extends Wizard {
final static String external_components = "assets/external_comps/";
public static class ImportComponentCallback extends OdeAsyncCallback<ComponentImportResponse> {
@Override
public void onSuccess(ComponentImportResponse response) {
if (response.getStatus() == ComponentImportResponse.Status.FAILED){
Window.alert(MESSAGES.componentImportError() + "\n" + response.getMessage());
return;
}
else if (response.getStatus() != ComponentImportResponse.Status.IMPORTED &&
response.getStatus() != ComponentImportResponse.Status.UPGRADED) {
Window.alert(MESSAGES.componentImportError());
return;
}
else if (response.getStatus() == ComponentImportResponse.Status.UNKNOWN_URL) {
Window.alert(MESSAGES.componentImportUnknownURLError());
}
else if (response.getStatus() == ComponentImportResponse.Status.UPGRADED) {
StringBuilder sb = new StringBuilder(MESSAGES.componentUpgradedAlert());
for (String name : response.getComponentTypes().values()) {
sb.append("\n");
sb.append(name);
}
Window.alert(sb.toString());
}
List<ProjectNode> compNodes = response.getNodes();
long destinationProjectId = response.getProjectId();
long currentProjectId = ode.getCurrentYoungAndroidProjectId();
if (currentProjectId != destinationProjectId) {
return; // User switched project early!
}
Project project = ode.getProjectManager().getProject(destinationProjectId);
if (project == null) {
return; // Project does not exist!
}
if (response.getStatus() == ComponentImportResponse.Status.UPGRADED ||
response.getStatus() == ComponentImportResponse.Status.IMPORTED) {
YoungAndroidComponentsFolder componentsFolder = ((YoungAndroidProjectNode) project.getRootNode()).getComponentsFolder();
YaProjectEditor projectEditor = (YaProjectEditor) ode.getEditorManager().getOpenProjectEditor(destinationProjectId);
if (projectEditor == null) {
return; // Project is not open!
}
for (ProjectNode node : compNodes) {
project.addNode(componentsFolder, node);
if ((node.getName().equals("component.json") || node.getName().equals("components.json"))
&& StringUtils.countMatches(node.getFileId(), "/") == 3) {
projectEditor.addComponent(node, null);
}
}
}
}
}
private static int FROM_MY_COMPUTER_TAB = 0;
private static int URL_TAB = 1;
private static final String COMPONENT_ARCHIVE_EXTENSION = ".aix";
private static final Ode ode = Ode.getInstance();
public ComponentImportWizard() {
super(MESSAGES.componentImportWizardCaption(), true, false);
final CellTable compTable = createCompTable();
final FileUpload fileUpload = createFileUpload();
final Grid urlGrid = createUrlGrid();
final TabPanel tabPanel = new TabPanel();
tabPanel.add(fileUpload, MESSAGES.componentImportFromComputer());
tabPanel.add(urlGrid, MESSAGES.componentImportFromURL());
tabPanel.selectTab(FROM_MY_COMPUTER_TAB);
tabPanel.addStyleName("ode-Tabpanel");
VerticalPanel panel = new VerticalPanel();
panel.add(tabPanel);
addPage(panel);
getConfirmButton().setText("Import");
setPagePanelHeight(150);
setPixelSize(200, 150);
setStylePrimaryName("ode-DialogBox");
initFinishCommand(new Command() {
@Override
public void execute() {
final long projectId = ode.getCurrentYoungAndroidProjectId();
final Project project = ode.getProjectManager().getProject(projectId);
final YoungAndroidAssetsFolder assetsFolderNode =
((YoungAndroidProjectNode) project.getRootNode()).getAssetsFolder();
if (tabPanel.getTabBar().getSelectedTab() == URL_TAB) {
TextBox urlTextBox = (TextBox) urlGrid.getWidget(1, 0);
String url = urlTextBox.getText();
if (url.trim().isEmpty()) {
Window.alert(MESSAGES.noUrlError());
return;
}
ode.getComponentService().importComponentToProject(url, projectId,
assetsFolderNode.getFileId(), new ImportComponentCallback());
} else if (tabPanel.getTabBar().getSelectedTab() == FROM_MY_COMPUTER_TAB) {
if (!fileUpload.getFilename().endsWith(COMPONENT_ARCHIVE_EXTENSION)) {
Window.alert(MESSAGES.notComponentArchiveError());
return;
}
String url = GWT.getModuleBaseURL() +
ServerLayout.UPLOAD_SERVLET + "/" +
ServerLayout.UPLOAD_COMPONENT + "/" +
trimLeadingPath(fileUpload.getFilename());
Uploader.getInstance().upload(fileUpload, url,
new OdeAsyncCallback<UploadResponse>() {
@Override
public void onSuccess(UploadResponse uploadResponse) {
String toImport = uploadResponse.getInfo();
ode.getComponentService().importComponentToProject(toImport, projectId,
assetsFolderNode.getFileId(), new ImportComponentCallback());
}
});
return;
}
}
private String trimLeadingPath(String filename) {
// Strip leading path off filename.
// We need to support both Unix ('/') and Windows ('\\') separators.
return filename.substring(Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\')) + 1);
}
});
}
private CellTable createCompTable() {
final SingleSelectionModel<Component> selectionModel =
new SingleSelectionModel<Component>();
CellTable<Component> compTable = new CellTable<Component>();
compTable.setSelectionModel(selectionModel);
Column<Component, Boolean> checkColumn =
new Column<Component, Boolean>(new CheckboxCell(true, false)) {
@Override
public Boolean getValue(Component comp) {
return selectionModel.isSelected(comp);
}
};
Column<Component, String> nameColumn =
new Column<Component, String>(new TextCell()) {
@Override
public String getValue(Component comp) {
return comp.getName();
}
};
Column<Component, Number> versionColumn =
new Column<Component, Number>(new NumberCell()) {
@Override
public Number getValue(Component comp) {
return comp.getVersion();
}
};
compTable.addColumn(checkColumn);
compTable.addColumn(nameColumn, "Component");
compTable.addColumn(versionColumn, "Version");
return compTable;
}
private Grid createUrlGrid() {
TextBox urlTextBox = new TextBox();
urlTextBox.setWidth("100%");
Grid grid = new Grid(2, 1);
grid.setWidget(0, 0, new Label("Url:"));
grid.setWidget(1, 0, urlTextBox);
return grid;
}
private FileUpload createFileUpload() {
FileUpload upload = new FileUpload();
upload.setName(ServerLayout.UPLOAD_COMPONENT_ARCHIVE_FORM_ELEMENT);
upload.getElement().setAttribute("accept", COMPONENT_ARCHIVE_EXTENSION);
return upload;
}
}
| apache-2.0 |
Appudo/Appudo.github.io | static/release/dojo/NodeList-data.js | 930 | //>>built
define("dojo/NodeList-data",["./_base/kernel","./query","./_base/lang","./_base/array","./dom-attr"],function(_1,_2,_3,_4,_5){var _6=_2.NodeList;var _7={},x=0,_8="data-dojo-dataid",_9=function(_a){var _b=_5.get(_a,_8);if(!_b){_b="pid"+(x++);_5.set(_a,_8,_b);}return _b;};var _c=_1._nodeData=function(_d,_e,_f){var pid=_9(_d),r;if(!_7[pid]){_7[pid]={};}if(arguments.length==1){r=_7[pid];}if(typeof _e=="string"){if(arguments.length>2){_7[pid][_e]=_f;}else{r=_7[pid][_e];}}else{r=_3.mixin(_7[pid],_e);}return r;};var _10=_1._removeNodeData=function(_11,key){var pid=_9(_11);if(_7[pid]){if(key){delete _7[pid][key];}else{delete _7[pid];}}};_1._gcNodeData=function(){var _12=_2("["+_8+"]").map(_9);for(var i in _7){if(_4.indexOf(_12,i)<0){delete _7[i];}}};_3.extend(_6,{data:_6._adaptWithCondition(_c,function(a){return a.length===0||a.length==1&&(typeof a[0]=="string");}),removeData:_6._adaptAsForEach(_10)});return _6;}); | apache-2.0 |
xli/gocd | common/src/com/thoughtworks/go/domain/materials/AgentSubprocessExecutionContext.java | 1684 | /*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.domain.materials;
import com.thoughtworks.go.config.materials.SubprocessExecutionContext;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.util.CachedDigestUtils;
import java.util.HashMap;
import java.util.Map;
class AgentSubprocessExecutionContext implements SubprocessExecutionContext {
private AgentIdentifier agentIdentifier;
private final String workingDirectory;
AgentSubprocessExecutionContext(final AgentIdentifier agentIdentifier, String workingDirectory) {
this.agentIdentifier = agentIdentifier;
this.workingDirectory = workingDirectory;
}
public String getProcessNamespace(String fingerprint) {
return CachedDigestUtils.sha256Hex(fingerprint + agentIdentifier.getUuid() + workingDirectory);
}
@Override
public Map<String, String> getDefaultEnvironmentVariables() {
return new HashMap<>();
}
}
| apache-2.0 |
robander/dita-ot | src/test/resources/keyref_modify/exp/xhtml/index.html | 935 | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="copyright" content="(C) Copyright 2014" />
<meta name="DC.rights.owner" content="(C) Copyright 2014" />
<meta name="DC.Type" content="map" />
<meta name="DC.Format" content="XHTML" />
<link rel="stylesheet" type="text/css" href="commonltr.css" />
<title></title></head>
<body><div><ul class="map"><li class="topicref"><a href="a1.html">topic a1</a></li><li class="topicref"><a href="dita1.html">DITA1</a></li><li class="topicref"><a href="abs.html">Anti-lock Braking System</a></li><li class="topicref"><a href="c.html">topic c</a></li><li class="topicref"><a href="task.html">task</a></li></ul></div></body></html> | apache-2.0 |
wangjiegulu/RapidRouter | library/src/test/java/com/wangjie/rapidrouter/ExampleUnitTest.java | 401 | package com.wangjie.rapidrouter;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
tgroh/incubator-beam | sdks/java/core/src/test/java/org/apache/beam/sdk/coders/ListCoderTest.java | 4233 | /*
* 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.beam.sdk.coders;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.beam.sdk.testing.CoderProperties;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.util.CoderUtils;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ListCoder}. */
@RunWith(JUnit4.class)
public class ListCoderTest {
private static final Coder<List<Integer>> TEST_CODER = ListCoder.of(VarIntCoder.of());
private static final List<List<Integer>> TEST_VALUES =
Arrays.asList(
Collections.emptyList(),
Collections.singletonList(43),
Arrays.asList(1, 2, 3, 4),
new ArrayList<>(Arrays.asList(7, 6, 5)));
@Test
public void testCoderIsSerializableWithWellKnownCoderType() throws Exception {
CoderProperties.coderSerializable(ListCoder.of(GlobalWindow.Coder.INSTANCE));
}
@Test
public void testDecodeEncodeContentsInSameOrder() throws Exception {
for (List<Integer> value : TEST_VALUES) {
CoderProperties.coderDecodeEncodeContentsInSameOrder(TEST_CODER, value);
}
}
@Test
public void testEmptyList() throws Exception {
List<Integer> list = Collections.emptyList();
Coder<List<Integer>> coder = ListCoder.of(VarIntCoder.of());
CoderProperties.coderDecodeEncodeEqual(coder, list);
}
@Test
public void testCoderSerializable() throws Exception {
CoderProperties.coderSerializable(TEST_CODER);
}
/**
* Generated data to check that the wire format has not changed. To regenerate, see
* {@link org.apache.beam.sdk.coders.PrintBase64Encodings}.
*/
private static final List<String> TEST_ENCODINGS = Arrays.asList(
"AAAAAA",
"AAAAASs",
"AAAABAECAwQ",
"AAAAAwcGBQ");
@Test
public void testWireFormatEncode() throws Exception {
CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS);
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void encodeNullThrowsCoderException() throws Exception {
thrown.expect(CoderException.class);
thrown.expectMessage("cannot encode a null List");
CoderUtils.encodeToBase64(TEST_CODER, null);
}
@Test
public void testListWithNullsAndVarIntCoderThrowsException() throws Exception {
thrown.expect(CoderException.class);
thrown.expectMessage("cannot encode a null Integer");
List<Integer> list = Arrays.asList(1, 2, 3, null, 4);
Coder<List<Integer>> coder = ListCoder.of(VarIntCoder.of());
CoderProperties.coderDecodeEncodeEqual(coder, list);
}
@Test
public void testListWithNullsAndSerializableCoder() throws Exception {
List<Integer> list = Arrays.asList(1, 2, 3, null, 4);
Coder<List<Integer>> coder = ListCoder.of(SerializableCoder.of(Integer.class));
CoderProperties.coderDecodeEncodeEqual(coder, list);
}
@Test
public void testEncodedTypeDescriptor() throws Exception {
TypeDescriptor<List<Integer>> typeDescriptor = new TypeDescriptor<List<Integer>>() {};
assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(typeDescriptor));
}
}
| apache-2.0 |
nghiant2710/base-images | balena-base-images/openjdk/beaglebone-black/debian/bullseye/11-jdk/build/Dockerfile | 3854 | # AUTOGENERATED FILE
FROM balenalib/beaglebone-black-debian:bullseye-build
# A few reasons for installing distribution-provided OpenJDK:
#
# 1. Oracle. Licensing prevents us from redistributing the official JDK.
#
# 2. Compiling OpenJDK also requires the JDK to be installed, and it gets
# really hairy.
#
# For some sample build times, see Debian's buildd logs:
# https://buildd.debian.org/status/logs.php?pkg=openjdk-11
RUN apt-get update && apt-get install -y --no-install-recommends \
bzip2 \
unzip \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
# do some fancy footwork to create a JAVA_HOME that's cross-architecture-safe
RUN ln -svT "/usr/lib/jvm/java-11-openjdk-$(dpkg --print-architecture)" /docker-java-home
ENV JAVA_HOME /docker-java-home
RUN set -ex; \
\
# deal with slim variants not having man page directories (which causes "update-alternatives" to fail)
if [ ! -d /usr/share/man/man1 ]; then \
mkdir -p /usr/share/man/man1; \
fi; \
\
apt-get update; \
apt-get install -y --no-install-recommends \
openjdk-11-jdk-headless \
; \
rm -rf /var/lib/apt/lists/*; \
\
rm -vf /usr/local/bin/java; \
\
# ca-certificates-java does not work on src:openjdk-11: (https://bugs.debian.org/914424, https://bugs.debian.org/894979, https://salsa.debian.org/java-team/ca-certificates-java/commit/813b8c4973e6c4bb273d5d02f8d4e0aa0b226c50#d4b95d176f05e34cd0b718357c532dc5a6d66cd7_54_56)
keytool -importkeystore -srckeystore /etc/ssl/certs/java/cacerts -destkeystore /etc/ssl/certs/java/cacerts.jks -deststoretype JKS -srcstorepass changeit -deststorepass changeit -noprompt; \
mv /etc/ssl/certs/java/cacerts.jks /etc/ssl/certs/java/cacerts; \
/var/lib/dpkg/info/ca-certificates-java.postinst configure; \
\
# verify that "docker-java-home" returns what we expect
[ "$(readlink -f "$JAVA_HOME")" = "$(docker-java-home)" ]; \
\
# update-alternatives so that future installs of other OpenJDK versions don't change /usr/bin/java
update-alternatives --get-selections | awk -v home="$(readlink -f "$JAVA_HOME")" 'index($3, home) == 1 { $2 = "manual"; print | "update-alternatives --set-selections" }'; \
# ... and verify that it actually worked for one of the alternatives we care about
update-alternatives --query java | grep -q 'Status: manual'
# https://docs.oracle.com/javase/10/tools/jshell.htm
# https://en.wikipedia.org/wiki/JShell
CMD ["jshell"]
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v11-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | apache-2.0 |
dhermes/google-cloud-python | bigtable/google/cloud/bigtable_v2/gapic/bigtable_client_config.py | 2407 | config = {
"interfaces": {
"google.bigtable.v2.Bigtable": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 20000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 600000,
},
"streaming": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 20000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 3600000,
},
},
"methods": {
"ReadRows": {
"timeout_millis": 3600000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming",
},
"SampleRowKeys": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"MutateRow": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"MutateRows": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"CheckAndMutateRow": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"ReadModifyWriteRow": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
},
}
}
}
| apache-2.0 |
TitasNandi/Summer_Project | dkpro-similarity-master/dkpro-similarity-algorithms-core-asl/src/main/java/dkpro/similarity/algorithms/package-info.java | 937 | /*******************************************************************************
* Copyright 2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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.
******************************************************************************/
/**
* Contains components which are fundamental for all similarity measures.
*/
package dkpro.similarity.algorithms; | apache-2.0 |
google/llvm-propeller | mlir/include/mlir/ExecutionEngine/OptUtils.h | 2301 | //===- OptUtils.h - MLIR Execution Engine opt pass utilities ----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file declares the utility functions to trigger LLVM optimizations from
// MLIR Execution Engine.
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_EXECUTIONENGINE_OPTUTILS_H_
#define MLIR_EXECUTIONENGINE_OPTUTILS_H_
#include "llvm/Pass.h"
#include <functional>
#include <string>
namespace llvm {
class Module;
class Error;
class TargetMachine;
} // namespace llvm
namespace mlir {
/// Initialize LLVM passes that can be used when running MLIR code using
/// ExecutionEngine.
void initializeLLVMPasses();
/// Create a module transformer function for MLIR ExecutionEngine that runs
/// LLVM IR passes corresponding to the given speed and size optimization
/// levels (e.g. -O2 or -Os). If not null, `targetMachine` is used to
/// initialize passes that provide target-specific information to the LLVM
/// optimizer. `targetMachine` must outlive the returned std::function.
std::function<llvm::Error(llvm::Module *)>
makeOptimizingTransformer(unsigned optLevel, unsigned sizeLevel,
llvm::TargetMachine *targetMachine);
/// Create a module transformer function for MLIR ExecutionEngine that runs
/// LLVM IR passes explicitly specified, plus an optional optimization level,
/// Any optimization passes, if present, will be inserted before the pass at
/// position optPassesInsertPos. If not null, `targetMachine` is used to
/// initialize passes that provide target-specific information to the LLVM
/// optimizer. `targetMachine` must outlive the returned std::function.
std::function<llvm::Error(llvm::Module *)>
makeLLVMPassesTransformer(llvm::ArrayRef<const llvm::PassInfo *> llvmPasses,
llvm::Optional<unsigned> mbOptLevel,
llvm::TargetMachine *targetMachine,
unsigned optPassesInsertPos = 0);
} // end namespace mlir
#endif // LIR_EXECUTIONENGINE_OPTUTILS_H_
| apache-2.0 |
tduehr/cas | support/cas-server-support-consent-webflow/src/main/java/org/apereo/cas/config/CasConsentWebflowConfiguration.java | 3498 | package org.apereo.cas.config;
import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.consent.ConsentEngine;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.web.flow.CasWebflowConfigurer;
import org.apereo.cas.web.flow.CasWebflowExecutionPlan;
import org.apereo.cas.web.flow.CasWebflowExecutionPlanConfigurer;
import org.apereo.cas.web.flow.CheckConsentRequiredAction;
import org.apereo.cas.web.flow.ConfirmConsentAction;
import org.apereo.cas.web.flow.ConsentWebflowConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.execution.Action;
/**
* This is {@link CasConsentWebflowConfiguration}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
@Configuration("casConsentWebflowConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@ConditionalOnBean(name = "consentRepository")
public class CasConsentWebflowConfiguration implements CasWebflowExecutionPlanConfigurer {
@Autowired
@Qualifier("loginFlowRegistry")
private FlowDefinitionRegistry loginFlowDefinitionRegistry;
@Autowired
private FlowBuilderServices flowBuilderServices;
@Autowired
@Qualifier("authenticationServiceSelectionPlan")
private AuthenticationServiceSelectionPlan authenticationRequestServiceSelectionStrategies;
@Autowired
@Qualifier("consentEngine")
private ConsentEngine consentEngine;
@Autowired
private ApplicationContext applicationContext;
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Autowired
private CasConfigurationProperties casProperties;
@ConditionalOnMissingBean(name = "checkConsentRequiredAction")
@Bean
public Action checkConsentRequiredAction() {
return new CheckConsentRequiredAction(servicesManager,
authenticationRequestServiceSelectionStrategies, consentEngine, casProperties);
}
@ConditionalOnMissingBean(name = "confirmConsentAction")
@Bean
public Action confirmConsentAction() {
return new ConfirmConsentAction(servicesManager,
authenticationRequestServiceSelectionStrategies, consentEngine, casProperties);
}
@ConditionalOnMissingBean(name = "consentWebflowConfigurer")
@Bean
@DependsOn("defaultWebflowConfigurer")
public CasWebflowConfigurer consentWebflowConfigurer() {
return new ConsentWebflowConfigurer(flowBuilderServices, loginFlowDefinitionRegistry,
applicationContext, casProperties);
}
@Override
public void configureWebflowExecutionPlan(final CasWebflowExecutionPlan plan) {
plan.registerWebflowConfigurer(consentWebflowConfigurer());
}
}
| apache-2.0 |
lheric/GitlHEVCAnalyzer | appgitlhevcdecoder/HM-5.2/source/Lib/TLibDecoder/NALread.cpp | 5455 | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2012, ITU/ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <algorithm>
#include <ostream>
#include "NALread.h"
#include "TLibCommon/NAL.h"
#include "TLibCommon/TComBitStream.h"
using namespace std;
//! \ingroup TLibDecoder
//! \{
static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *pcBitstream)
{
unsigned zeroCount = 0;
vector<uint8_t>::iterator it_read, it_write;
UInt *auiStoredTileMarkerLocation = new UInt[MAX_MARKER_PER_NALU];
// Remove tile markers and note the bitstream location
for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++ )
{
Bool bTileMarkerFound = false;
if ( ( it_read - nalUnitBuf.begin() ) < ( nalUnitBuf.size() - 2 ) )
{
if ( (*(it_read) == 0x00) && (*(it_read+1) == 0x00) && (*(it_read+2) == 0x02) ) // tile marker detected
{
it_read += 2;
UInt uiDistance = (UInt) (it_write - nalUnitBuf.begin());
UInt uiCount = pcBitstream->getTileMarkerLocationCount();
bTileMarkerFound = true;
pcBitstream->setTileMarkerLocation( uiCount, uiDistance );
auiStoredTileMarkerLocation[uiCount] = uiDistance;
pcBitstream->setTileMarkerLocationCount( uiCount + 1 );
}
}
if (!bTileMarkerFound)
{
*it_write = *it_read;
it_write++;
}
}
nalUnitBuf.resize(it_write - nalUnitBuf.begin());
for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++)
{
if (zeroCount == 2 && *it_read == 0x03)
{
// update tile marker location
UInt uiDistance = (UInt) (it_read - nalUnitBuf.begin());
for (UInt uiIdx=0; uiIdx<pcBitstream->getTileMarkerLocationCount(); uiIdx++)
{
if (auiStoredTileMarkerLocation[ uiIdx ] >= uiDistance)
{
pcBitstream->setTileMarkerLocation( uiIdx, pcBitstream->getTileMarkerLocation( uiIdx )-1 );
}
}
it_read++;
zeroCount = 0;
}
zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0;
*it_write = *it_read;
}
nalUnitBuf.resize(it_write - nalUnitBuf.begin());
delete [] auiStoredTileMarkerLocation;
}
/**
* create a NALunit structure with given header values and storage for
* a bitstream
*/
void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
{
/* perform anti-emulation prevention */
TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
convertPayloadToRBSP(nalUnitBuf, pcBitstream);
nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
// copy the tile marker location information
nalu.m_Bitstream->setTileMarkerLocationCount( pcBitstream->getTileMarkerLocationCount() );
for (UInt uiIdx=0; uiIdx < nalu.m_Bitstream->getTileMarkerLocationCount(); uiIdx++)
{
nalu.m_Bitstream->setTileMarkerLocation( uiIdx, pcBitstream->getTileMarkerLocation(uiIdx) );
}
delete pcBitstream;
TComInputBitstream& bs = *nalu.m_Bitstream;
bool forbidden_zero_bit = bs.read(1);
assert(forbidden_zero_bit == 0);
nalu.m_RefIDC = (NalRefIdc) bs.read(2);
nalu.m_UnitType = (NalUnitType) bs.read(5);
switch (nalu.m_UnitType)
{
case NAL_UNIT_CODED_SLICE:
case NAL_UNIT_CODED_SLICE_IDR:
case NAL_UNIT_CODED_SLICE_CDR:
{
nalu.m_TemporalID = bs.read(3);
nalu.m_OutputFlag = bs.read(1);
unsigned reserved_one_4bits = bs.read(4);
assert(reserved_one_4bits == 1);
}
break;
default:
nalu.m_TemporalID = 0;
nalu.m_OutputFlag = true;
break;
}
}
//! \}
| apache-2.0 |
sdnwiselab/onos | apps/openstacknetworking/src/main/java/org/onosproject/openstacknetworking/impl/HostBasedInstancePortManager.java | 6879 | /*
* Copyright 2017-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.openstacknetworking.impl;
import com.google.common.collect.ImmutableSet;
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.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.IpAddress;
import org.onlab.packet.MacAddress;
import org.onlab.util.Tools;
import org.onosproject.event.ListenerRegistry;
import org.onosproject.net.Host;
import org.onosproject.net.HostId;
import org.onosproject.net.host.HostEvent;
import org.onosproject.net.host.HostListener;
import org.onosproject.net.host.HostService;
import org.onosproject.openstacknetworking.api.InstancePort;
import org.onosproject.openstacknetworking.api.InstancePortEvent;
import org.onosproject.openstacknetworking.api.InstancePortListener;
import org.onosproject.openstacknetworking.api.InstancePortService;
import org.slf4j.Logger;
import java.util.Set;
import java.util.stream.Collectors;
import static org.onosproject.openstacknetworking.api.InstancePortEvent.Type.OPENSTACK_INSTANCE_PORT_DETECTED;
import static org.onosproject.openstacknetworking.api.InstancePortEvent.Type.OPENSTACK_INSTANCE_PORT_UPDATED;
import static org.onosproject.openstacknetworking.api.InstancePortEvent.Type.OPENSTACK_INSTANCE_PORT_VANISHED;
import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_NETWORK_ID;
import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_PORT_ID;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provides implementation of administering and interfacing host based instance ports.
* It also provides instance port events for the hosts mapped to OpenStack VM interface.
*/
@Service
@Component(immediate = true)
public class HostBasedInstancePortManager
extends ListenerRegistry<InstancePortEvent, InstancePortListener>
implements InstancePortService {
protected final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostService hostService;
private final HostListener hostListener = new InternalHostListener();
@Activate
protected void activate() {
hostService.addListener(hostListener);
log.info("Started");
}
@Deactivate
protected void deactivate() {
hostService.removeListener(hostListener);
log.info("Stopped");
}
@Override
public InstancePort instancePort(MacAddress macAddress) {
Host host = hostService.getHost(HostId.hostId(macAddress));
if (host == null || !isValidHost(host)) {
return null;
}
return HostBasedInstancePort.of(host);
}
@Override
public InstancePort instancePort(IpAddress ipAddress, String osNetId) {
return Tools.stream(hostService.getHosts()).filter(this::isValidHost)
.map(HostBasedInstancePort::of)
.filter(instPort -> instPort.networkId().equals(osNetId))
.filter(instPort -> instPort.ipAddress().equals(ipAddress))
.findAny().orElse(null);
}
@Override
public InstancePort instancePort(String osPortId) {
return Tools.stream(hostService.getHosts()).filter(this::isValidHost)
.map(HostBasedInstancePort::of)
.filter(instPort -> instPort.portId().equals(osPortId))
.findAny().orElse(null);
}
@Override
public Set<InstancePort> instancePorts() {
Set<InstancePort> instPors = Tools.stream(hostService.getHosts())
.filter(this::isValidHost)
.map(HostBasedInstancePort::of)
.collect(Collectors.toSet());
return ImmutableSet.copyOf(instPors);
}
@Override
public Set<InstancePort> instancePorts(String osNetId) {
Set<InstancePort> instPors = Tools.stream(hostService.getHosts())
.filter(this::isValidHost)
.map(HostBasedInstancePort::of)
.filter(instPort -> instPort.networkId().equals(osNetId))
.collect(Collectors.toSet());
return ImmutableSet.copyOf(instPors);
}
private boolean isValidHost(Host host) {
return !host.ipAddresses().isEmpty() &&
host.annotations().value(ANNOTATION_NETWORK_ID) != null &&
host.annotations().value(ANNOTATION_PORT_ID) != null;
}
private class InternalHostListener implements HostListener {
@Override
public boolean isRelevant(HostEvent event) {
Host host = event.subject();
if (!isValidHost(host)) {
log.debug("Invalid host detected, ignore it {}", host);
return false;
}
return true;
}
@Override
public void event(HostEvent event) {
InstancePort instPort = HostBasedInstancePort.of(event.subject());
InstancePortEvent instPortEvent;
switch (event.type()) {
case HOST_UPDATED:
instPortEvent = new InstancePortEvent(
OPENSTACK_INSTANCE_PORT_UPDATED,
instPort);
log.debug("Instance port is updated: {}", instPort);
process(instPortEvent);
break;
case HOST_ADDED:
instPortEvent = new InstancePortEvent(
OPENSTACK_INSTANCE_PORT_DETECTED,
instPort);
log.debug("Instance port is detected: {}", instPort);
process(instPortEvent);
break;
case HOST_REMOVED:
instPortEvent = new InstancePortEvent(
OPENSTACK_INSTANCE_PORT_VANISHED,
instPort);
log.debug("Instance port is disabled: {}", instPort);
process(instPortEvent);
break;
default:
break;
}
}
}
}
| apache-2.0 |
Clayton7510/RuleBook | rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/runner/test/rulebooks/SampleRuleWithoutRuleAnnotation.java | 176 | package com.deliveredtechnologies.rulebook.runner.test.rulebooks;
/**
* Sample POJO rule with no annotations whatsoever.
*/
public class SampleRuleWithoutRuleAnnotation {
}
| apache-2.0 |
martin-neuhaeusser/benchexec | contrib/plots/generate-plots.sh | 1240 | #!/bin/sh
# Generate CSV for a scatter plot of CPU times.
table-generator --correct-only -f csv -x scatter.xml
# Generate CSV for a scatter plot where color indicates frequency of data points
# (not useful with the example data in this directory).
cut -f 3,7 < scatter.table.csv \
| sort -n \
| uniq -c \
> scatter.counted.csv
# Generate CSV for a quantile plot of CPU times.
for i in *.results.xml.bz2 ; do
./quantile-generator.py --correct-only $i > ${i%.results.xml.bz2}.quantile.csv
done
# Generate CSV for a score-based quantile plot of CPU times.
for i in *.results.xml.bz2 ; do
./quantile-generator.py --score-based $i > ${i%.results.xml.bz2}.quantile-score.csv
done
# Commands for generating plots with Gnuplot:
gnuplot scatter.gp
gnuplot scatter-counted.gp
gnuplot quantile.gp
gnuplot quantile-split.gp
gnuplot quantile-score.gp
# Commands for generating plots with LaTeX (not necessary if included in other LaTeX file):
pdflatex scatter.tex
pdflatex scatter-counted.tex
pdflatex quantile.tex
pdflatex quantile-score.tex
# Special command for generating plots as PNG files (just for recreating the demo files)
# for f in *.tex; do
# pdflatex -shell-escape "\PassOptionsToClass{convert}{standalone}\input{$f}"
# done
| apache-2.0 |
jbaiera/zookeeper-play | src/main/java/play/curator/lock/LockClient.java | 2027 | package play.curator.lock;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class LockClient {
public static final String NAMESPACE = "test/locks";
public static final String LOCK_NODE = "lockClient1";
/**
* Starts a process to test locking across Zookeeper using Curator
* @param args hostport waitTime processTime
* @throws Exception
*/
public static void main(String[] args)
throws Exception
{
new LockClient(args[0], Long.parseLong(args[1]), Long.parseLong(args[2])).run();
}
private String connectionString;
private long waitTime;
private long processTime;
public LockClient(String connectionString, long waitTime, long processTime) {
this.connectionString = connectionString;
this.waitTime = waitTime;
this.processTime = processTime;
}
public void run()
throws Exception
{
CuratorFramework framework = null;
try {
framework = CuratorFrameworkFactory.builder()
.connectString(connectionString)
.connectionTimeoutMs(3000)
.namespace(NAMESPACE)
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.build();
framework.start();
InterProcessLock lock = new InterProcessSemaphoreMutex(framework, LOCK_NODE);
System.out.println("Locking...");
if(lock.acquire(waitTime, TimeUnit.MILLISECONDS)) {
try {
System.out.println("Aquired Lock!");
System.out.println("Beginning 'Processing' ...");
Thread.sleep(processTime);
System.out.println("'Processing' finished...");
} finally {
lock.release();
System.out.println("Lock Released");
}
} else {
System.out.println("Could not aquire lock. Exiting...");
}
} finally {
if(framework != null) {
framework.close();
}
}
}
}
| apache-2.0 |
FDio/vpp | src/plugins/nat/nat44-ei/nat44_ei_in2out.c | 72987 | /*
* Copyright (c) 2016 Cisco 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.
*/
/**
* @file
* @brief NAT44 EI inside to outside network translation
*/
#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/ip/ip.h>
#include <vnet/ethernet/ethernet.h>
#include <vnet/udp/udp_local.h>
#include <vnet/fib/ip4_fib.h>
#include <vppinfra/hash.h>
#include <vppinfra/error.h>
#include <nat/lib/log.h>
#include <nat/lib/nat_syslog.h>
#include <nat/lib/ipfix_logging.h>
#include <nat/lib/nat_inlines.h>
#include <nat/nat44-ei/nat44_ei_inlines.h>
#include <nat/nat44-ei/nat44_ei.h>
extern vnet_feature_arc_registration_t vnet_feat_arc_ip4_local;
#define foreach_nat44_ei_in2out_error \
_ (UNSUPPORTED_PROTOCOL, "unsupported protocol") \
_ (OUT_OF_PORTS, "out of ports") \
_ (BAD_OUTSIDE_FIB, "outside VRF ID not found") \
_ (BAD_ICMP_TYPE, "unsupported ICMP type") \
_ (NO_TRANSLATION, "no translation") \
_ (MAX_SESSIONS_EXCEEDED, "maximum sessions exceeded") \
_ (CANNOT_CREATE_USER, "cannot create NAT user")
#define foreach_nat44_ei_hairpinning_handoff_error \
_ (CONGESTION_DROP, "congestion drop")
typedef enum
{
#define _(sym, str) NAT44_EI_IN2OUT_ERROR_##sym,
foreach_nat44_ei_in2out_error
#undef _
NAT44_EI_IN2OUT_N_ERROR,
} nat44_ei_in2out_error_t;
static char *nat44_ei_in2out_error_strings[] = {
#define _(sym,string) string,
foreach_nat44_ei_in2out_error
#undef _
};
typedef enum
{
#define _(sym, str) NAT44_EI_HAIRPINNING_HANDOFF_ERROR_##sym,
foreach_nat44_ei_hairpinning_handoff_error
#undef _
NAT44_EI_HAIRPINNING_HANDOFF_N_ERROR,
} nat44_ei_hairpinning_handoff_error_t;
static char *nat44_ei_hairpinning_handoff_error_strings[] = {
#define _(sym, string) string,
foreach_nat44_ei_hairpinning_handoff_error
#undef _
};
typedef enum
{
NAT44_EI_IN2OUT_NEXT_LOOKUP,
NAT44_EI_IN2OUT_NEXT_DROP,
NAT44_EI_IN2OUT_NEXT_ICMP_ERROR,
NAT44_EI_IN2OUT_NEXT_SLOW_PATH,
NAT44_EI_IN2OUT_NEXT_HAIRPINNING_HANDOFF,
NAT44_EI_IN2OUT_N_NEXT,
} nat44_ei_in2out_next_t;
typedef enum
{
NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_DROP,
NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_LOOKUP,
NAT44_EI_IN2OUT_HAIRPINNING_FINISH_N_NEXT,
} nat44_ei_in2out_hairpinnig_finish_next_t;
typedef enum
{
NAT44_EI_HAIRPIN_NEXT_LOOKUP,
NAT44_EI_HAIRPIN_NEXT_DROP,
NAT44_EI_HAIRPIN_NEXT_HANDOFF,
NAT44_EI_HAIRPIN_N_NEXT,
} nat44_ei_hairpin_next_t;
typedef struct
{
u32 sw_if_index;
u32 next_index;
u32 session_index;
u32 is_slow_path;
u32 is_hairpinning;
} nat44_ei_in2out_trace_t;
typedef struct
{
ip4_address_t addr;
u16 port;
u32 fib_index;
u32 session_index;
} nat44_ei_hairpin_trace_t;
typedef struct
{
u32 next_worker_index;
} nat44_ei_hairpinning_handoff_trace_t;
static u8 *
format_nat44_ei_in2out_trace (u8 *s, va_list *args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
nat44_ei_in2out_trace_t *t = va_arg (*args, nat44_ei_in2out_trace_t *);
char *tag;
tag = t->is_slow_path ? "NAT44_IN2OUT_SLOW_PATH" : "NAT44_IN2OUT_FAST_PATH";
s = format (s, "%s: sw_if_index %d, next index %d, session %d", tag,
t->sw_if_index, t->next_index, t->session_index);
if (t->is_hairpinning)
s = format (s, ", with-hairpinning");
return s;
}
static u8 *
format_nat44_ei_in2out_fast_trace (u8 *s, va_list *args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
nat44_ei_in2out_trace_t *t = va_arg (*args, nat44_ei_in2out_trace_t *);
s = format (s, "NAT44_IN2OUT_FAST: sw_if_index %d, next index %d",
t->sw_if_index, t->next_index);
return s;
}
static u8 *
format_nat44_ei_hairpin_trace (u8 *s, va_list *args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
nat44_ei_hairpin_trace_t *t = va_arg (*args, nat44_ei_hairpin_trace_t *);
s = format (s, "new dst addr %U port %u fib-index %u", format_ip4_address,
&t->addr, clib_net_to_host_u16 (t->port), t->fib_index);
if (~0 == t->session_index)
{
s = format (s, " is-static-mapping");
}
else
{
s = format (s, " session-index %u", t->session_index);
}
return s;
}
static u8 *
format_nat44_ei_hairpinning_handoff_trace (u8 *s, va_list *args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
nat44_ei_hairpinning_handoff_trace_t *t =
va_arg (*args, nat44_ei_hairpinning_handoff_trace_t *);
s = format (s, "nat44-ei-hairpinning-handoff: next-worker %d",
t->next_worker_index);
return s;
}
static_always_inline int
nat44_ei_not_translate_fast (vlib_node_runtime_t *node, u32 sw_if_index0,
ip4_header_t *ip0, u32 proto0, u32 rx_fib_index0)
{
nat44_ei_main_t *nm = &nat44_ei_main;
if (nm->out2in_dpo)
return 0;
fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
nat44_ei_outside_fib_t *outside_fib;
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_IP4,
.fp_len = 32,
.fp_addr = {
.ip4.as_u32 = ip0->dst_address.as_u32,
}
,
};
/* Don't NAT packet aimed at the intfc address */
if (PREDICT_FALSE (nat44_ei_is_interface_addr (
nm->ip4_main, node, sw_if_index0, ip0->dst_address.as_u32)))
return 1;
fei = fib_table_lookup (rx_fib_index0, &pfx);
if (FIB_NODE_INDEX_INVALID != fei)
{
u32 sw_if_index = fib_entry_get_resolving_interface (fei);
if (sw_if_index == ~0)
{
vec_foreach (outside_fib, nm->outside_fibs)
{
fei = fib_table_lookup (outside_fib->fib_index, &pfx);
if (FIB_NODE_INDEX_INVALID != fei)
{
sw_if_index = fib_entry_get_resolving_interface (fei);
if (sw_if_index != ~0)
break;
}
}
}
if (sw_if_index == ~0)
return 1;
nat44_ei_interface_t *i;
pool_foreach (i, nm->interfaces)
{
/* NAT packet aimed at outside interface */
if ((nat44_ei_interface_is_outside (i)) &&
(sw_if_index == i->sw_if_index))
return 0;
}
}
return 1;
}
static_always_inline int
nat44_ei_not_translate (nat44_ei_main_t *nm, vlib_node_runtime_t *node,
u32 sw_if_index0, ip4_header_t *ip0, u32 proto0,
u32 rx_fib_index0, u32 thread_index)
{
udp_header_t *udp0 = ip4_next_header (ip0);
clib_bihash_kv_8_8_t kv0, value0;
init_nat_k (&kv0, ip0->dst_address, udp0->dst_port, nm->outside_fib_index,
proto0);
/* NAT packet aimed at external address if */
/* has active sessions */
if (clib_bihash_search_8_8 (&nm->out2in, &kv0, &value0))
{
/* or is static mappings */
ip4_address_t placeholder_addr;
u16 placeholder_port;
u32 placeholder_fib_index;
if (!nat44_ei_static_mapping_match (ip0->dst_address, udp0->dst_port,
nm->outside_fib_index, proto0,
&placeholder_addr, &placeholder_port,
&placeholder_fib_index, 1, 0, 0))
return 0;
}
else
return 0;
if (nm->forwarding_enabled)
return 1;
return nat44_ei_not_translate_fast (node, sw_if_index0, ip0, proto0,
rx_fib_index0);
}
static_always_inline int
nat44_ei_not_translate_output_feature (nat44_ei_main_t *nm, ip4_header_t *ip0,
u32 proto0, u16 src_port, u16 dst_port,
u32 thread_index, u32 sw_if_index)
{
clib_bihash_kv_8_8_t kv0, value0;
nat44_ei_interface_t *i;
/* src NAT check */
init_nat_k (&kv0, ip0->src_address, src_port,
ip4_fib_table_get_index_for_sw_if_index (sw_if_index), proto0);
if (!clib_bihash_search_8_8 (&nm->out2in, &kv0, &value0))
return 1;
/* dst NAT check */
init_nat_k (&kv0, ip0->dst_address, dst_port,
ip4_fib_table_get_index_for_sw_if_index (sw_if_index), proto0);
if (!clib_bihash_search_8_8 (&nm->in2out, &kv0, &value0))
{
/* hairpinning */
pool_foreach (i, nm->output_feature_interfaces)
{
if ((nat44_ei_interface_is_inside (i)) &&
(sw_if_index == i->sw_if_index))
return 0;
}
return 1;
}
return 0;
}
#ifndef CLIB_MARCH_VARIANT
int
nat44_i2o_is_idle_session_cb (clib_bihash_kv_8_8_t * kv, void *arg)
{
nat44_ei_main_t *nm = &nat44_ei_main;
nat44_ei_is_idle_session_ctx_t *ctx = arg;
nat44_ei_session_t *s;
u64 sess_timeout_time;
nat44_ei_main_per_thread_data_t *tnm =
vec_elt_at_index (nm->per_thread_data, ctx->thread_index);
clib_bihash_kv_8_8_t s_kv;
if (ctx->thread_index != nat_value_get_thread_index (kv))
{
return 0;
}
s = pool_elt_at_index (tnm->sessions, nat_value_get_session_index (kv));
sess_timeout_time = s->last_heard + (f64) nat_session_get_timeout (
&nm->timeouts, s->nat_proto, s->state);
if (ctx->now >= sess_timeout_time)
{
init_nat_o2i_k (&s_kv, s);
if (clib_bihash_add_del_8_8 (&nm->out2in, &s_kv, 0))
nat_elog_warn (nm, "out2in key del failed");
nat_ipfix_logging_nat44_ses_delete (
ctx->thread_index, s->in2out.addr.as_u32, s->out2in.addr.as_u32,
nat_proto_to_ip_proto (s->nat_proto), s->in2out.port, s->out2in.port,
s->in2out.fib_index);
nat_syslog_nat44_apmdel (s->user_index, s->in2out.fib_index,
&s->in2out.addr, s->in2out.port,
&s->out2in.addr, s->out2in.port, s->nat_proto);
nat_ha_sdel (&s->out2in.addr, s->out2in.port, &s->ext_host_addr,
s->ext_host_port, s->nat_proto, s->out2in.fib_index,
ctx->thread_index);
if (!nat44_ei_is_session_static (s))
nat44_ei_free_outside_address_and_port (
nm->addresses, ctx->thread_index, &s->out2in.addr, s->out2in.port,
s->nat_proto);
nat44_ei_delete_session (nm, s, ctx->thread_index);
return 1;
}
return 0;
}
#endif
static u32
slow_path (nat44_ei_main_t *nm, vlib_buffer_t *b0, ip4_header_t *ip0,
ip4_address_t i2o_addr, u16 i2o_port, u32 rx_fib_index0,
nat_protocol_t nat_proto, nat44_ei_session_t **sessionp,
vlib_node_runtime_t *node, u32 next0, u32 thread_index, f64 now)
{
nat44_ei_user_t *u;
nat44_ei_session_t *s = 0;
clib_bihash_kv_8_8_t kv0;
u8 is_sm = 0;
nat44_ei_outside_fib_t *outside_fib;
fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
u8 identity_nat;
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_IP4,
.fp_len = 32,
.fp_addr = {
.ip4.as_u32 = ip0->dst_address.as_u32,
},
};
nat44_ei_is_idle_session_ctx_t ctx0;
ip4_address_t sm_addr;
u16 sm_port;
u32 sm_fib_index;
if (PREDICT_FALSE (nat44_ei_maximum_sessions_exceeded (nm, thread_index)))
{
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_MAX_SESSIONS_EXCEEDED];
nat_ipfix_logging_max_sessions (thread_index,
nm->max_translations_per_thread);
nat_elog_notice (nm, "maximum sessions exceeded");
return NAT44_EI_IN2OUT_NEXT_DROP;
}
/* First try to match static mapping by local address and port */
if (nat44_ei_static_mapping_match (i2o_addr, i2o_port, rx_fib_index0,
nat_proto, &sm_addr, &sm_port,
&sm_fib_index, 0, 0, &identity_nat))
{
/* Try to create dynamic translation */
if (nm->alloc_addr_and_port (
nm->addresses, rx_fib_index0, thread_index, nat_proto,
ip0->src_address, &sm_addr, &sm_port, nm->port_per_thread,
nm->per_thread_data[thread_index].snat_thread_index))
{
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_OUT_OF_PORTS];
return NAT44_EI_IN2OUT_NEXT_DROP;
}
}
else
{
if (PREDICT_FALSE (identity_nat))
{
*sessionp = s;
return next0;
}
is_sm = 1;
}
u = nat44_ei_user_get_or_create (nm, &ip0->src_address, rx_fib_index0,
thread_index);
if (!u)
{
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_CANNOT_CREATE_USER];
return NAT44_EI_IN2OUT_NEXT_DROP;
}
s = nat44_ei_session_alloc_or_recycle (nm, u, thread_index, now);
if (!s)
{
nat44_ei_delete_user_with_no_session (nm, u, thread_index);
nat_elog_warn (nm, "create NAT session failed");
return NAT44_EI_IN2OUT_NEXT_DROP;
}
if (is_sm)
s->flags |= NAT44_EI_SESSION_FLAG_STATIC_MAPPING;
nat44_ei_user_session_increment (nm, u, is_sm);
s->in2out.addr = i2o_addr;
s->in2out.port = i2o_port;
s->in2out.fib_index = rx_fib_index0;
s->nat_proto = nat_proto;
s->out2in.addr = sm_addr;
s->out2in.port = sm_port;
s->out2in.fib_index = nm->outside_fib_index;
switch (vec_len (nm->outside_fibs))
{
case 0:
s->out2in.fib_index = nm->outside_fib_index;
break;
case 1:
s->out2in.fib_index = nm->outside_fibs[0].fib_index;
break;
default:
vec_foreach (outside_fib, nm->outside_fibs)
{
fei = fib_table_lookup (outside_fib->fib_index, &pfx);
if (FIB_NODE_INDEX_INVALID != fei)
{
if (fib_entry_get_resolving_interface (fei) != ~0)
{
s->out2in.fib_index = outside_fib->fib_index;
break;
}
}
}
break;
}
s->ext_host_addr.as_u32 = ip0->dst_address.as_u32;
s->ext_host_port = vnet_buffer (b0)->ip.reass.l4_dst_port;
*sessionp = s;
/* Add to translation hashes */
ctx0.now = now;
ctx0.thread_index = thread_index;
init_nat_i2o_kv (&kv0, s, thread_index,
s - nm->per_thread_data[thread_index].sessions);
if (clib_bihash_add_or_overwrite_stale_8_8 (
&nm->in2out, &kv0, nat44_i2o_is_idle_session_cb, &ctx0))
nat_elog_notice (nm, "in2out key add failed");
init_nat_o2i_kv (&kv0, s, thread_index,
s - nm->per_thread_data[thread_index].sessions);
if (clib_bihash_add_or_overwrite_stale_8_8 (
&nm->out2in, &kv0, nat44_o2i_is_idle_session_cb, &ctx0))
nat_elog_notice (nm, "out2in key add failed");
/* log NAT event */
nat_ipfix_logging_nat44_ses_create (
thread_index, s->in2out.addr.as_u32, s->out2in.addr.as_u32,
nat_proto_to_ip_proto (s->nat_proto), s->in2out.port, s->out2in.port,
s->in2out.fib_index);
nat_syslog_nat44_apmadd (s->user_index, s->in2out.fib_index, &s->in2out.addr,
s->in2out.port, &s->out2in.addr, s->out2in.port,
s->nat_proto);
nat_ha_sadd (&s->in2out.addr, s->in2out.port, &s->out2in.addr,
s->out2in.port, &s->ext_host_addr, s->ext_host_port,
&s->ext_host_nat_addr, s->ext_host_nat_port, s->nat_proto,
s->in2out.fib_index, s->flags, thread_index, 0);
return next0;
}
static_always_inline nat44_ei_in2out_error_t
icmp_get_key (vlib_buffer_t *b, ip4_header_t *ip0, ip4_address_t *addr,
u16 *port, nat_protocol_t *nat_proto)
{
icmp46_header_t *icmp0;
icmp_echo_header_t *echo0, *inner_echo0 = 0;
ip4_header_t *inner_ip0 = 0;
void *l4_header = 0;
icmp46_header_t *inner_icmp0;
icmp0 = (icmp46_header_t *) ip4_next_header (ip0);
echo0 = (icmp_echo_header_t *) (icmp0 + 1);
if (!icmp_type_is_error_message
(vnet_buffer (b)->ip.reass.icmp_type_or_tcp_flags))
{
*nat_proto = NAT_PROTOCOL_ICMP;
*addr = ip0->src_address;
*port = vnet_buffer (b)->ip.reass.l4_src_port;
}
else
{
inner_ip0 = (ip4_header_t *) (echo0 + 1);
l4_header = ip4_next_header (inner_ip0);
*nat_proto = ip_proto_to_nat_proto (inner_ip0->protocol);
*addr = inner_ip0->dst_address;
switch (*nat_proto)
{
case NAT_PROTOCOL_ICMP:
inner_icmp0 = (icmp46_header_t *) l4_header;
inner_echo0 = (icmp_echo_header_t *) (inner_icmp0 + 1);
*port = inner_echo0->identifier;
break;
case NAT_PROTOCOL_UDP:
case NAT_PROTOCOL_TCP:
*port = ((tcp_udp_header_t *) l4_header)->dst_port;
break;
default:
return NAT44_EI_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL;
}
}
return -1; /* success */
}
static_always_inline u32
nat44_ei_icmp_match_in2out_slow (vlib_node_runtime_t *node, u32 thread_index,
vlib_buffer_t *b0, ip4_header_t *ip0,
ip4_address_t *addr, u16 *port,
u32 *fib_index, nat_protocol_t *proto,
nat44_ei_session_t **p_s0, u8 *dont_translate)
{
nat44_ei_main_t *nm = &nat44_ei_main;
nat44_ei_main_per_thread_data_t *tnm = &nm->per_thread_data[thread_index];
u32 sw_if_index0;
nat44_ei_session_t *s0 = 0;
clib_bihash_kv_8_8_t kv0, value0;
u32 next0 = ~0;
int err;
vlib_main_t *vm = vlib_get_main ();
*dont_translate = 0;
sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
*fib_index = ip4_fib_table_get_index_for_sw_if_index (sw_if_index0);
err = icmp_get_key (b0, ip0, addr, port, proto);
if (err != -1)
{
b0->error = node->errors[err];
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
init_nat_k (&kv0, *addr, *port, *fib_index, *proto);
if (clib_bihash_search_8_8 (&nm->in2out, &kv0, &value0))
{
if (vnet_buffer (b0)->sw_if_index[VLIB_TX] != ~0)
{
if (PREDICT_FALSE (nat44_ei_not_translate_output_feature (
nm, ip0, *proto, *port, *port, thread_index, sw_if_index0)))
{
*dont_translate = 1;
goto out;
}
}
else
{
if (PREDICT_FALSE (nat44_ei_not_translate (
nm, node, sw_if_index0, ip0, NAT_PROTOCOL_ICMP, *fib_index,
thread_index)))
{
*dont_translate = 1;
goto out;
}
}
if (PREDICT_FALSE
(icmp_type_is_error_message
(vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags)))
{
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_BAD_ICMP_TYPE];
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
next0 = slow_path (nm, b0, ip0, *addr, *port, *fib_index, *proto, &s0,
node, next0, thread_index, vlib_time_now (vm));
if (PREDICT_FALSE (next0 == NAT44_EI_IN2OUT_NEXT_DROP))
goto out;
if (!s0)
{
*dont_translate = 1;
goto out;
}
}
else
{
if (PREDICT_FALSE
(vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags !=
ICMP4_echo_request
&& vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags !=
ICMP4_echo_reply
&& !icmp_type_is_error_message (vnet_buffer (b0)->ip.
reass.icmp_type_or_tcp_flags)))
{
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_BAD_ICMP_TYPE];
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
s0 = pool_elt_at_index (tnm->sessions,
nat_value_get_session_index (&value0));
}
out:
if (s0)
{
*addr = s0->out2in.addr;
*port = s0->out2in.port;
*fib_index = s0->out2in.fib_index;
}
if (p_s0)
*p_s0 = s0;
return next0;
}
static_always_inline u32
nat44_ei_icmp_match_in2out_fast (vlib_node_runtime_t *node, u32 thread_index,
vlib_buffer_t *b0, ip4_header_t *ip0,
ip4_address_t *addr, u16 *port,
u32 *fib_index, nat_protocol_t *proto,
nat44_ei_session_t **s0, u8 *dont_translate)
{
u32 sw_if_index0;
u8 is_addr_only;
u32 next0 = ~0;
int err;
*dont_translate = 0;
sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
*fib_index = ip4_fib_table_get_index_for_sw_if_index (sw_if_index0);
err = icmp_get_key (b0, ip0, addr, port, proto);
if (err != -1)
{
b0->error = node->errors[err];
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
ip4_address_t sm_addr;
u16 sm_port;
u32 sm_fib_index;
if (nat44_ei_static_mapping_match (*addr, *port, *fib_index, *proto,
&sm_addr, &sm_port, &sm_fib_index, 0,
&is_addr_only, 0))
{
if (PREDICT_FALSE (nat44_ei_not_translate_fast (
node, sw_if_index0, ip0, IP_PROTOCOL_ICMP, *fib_index)))
{
*dont_translate = 1;
goto out;
}
if (icmp_type_is_error_message
(vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags))
{
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_NO_TRANSLATION];
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
if (PREDICT_FALSE
(vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags != ICMP4_echo_request
&& (vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags !=
ICMP4_echo_reply || !is_addr_only)
&& !icmp_type_is_error_message (vnet_buffer (b0)->ip.
reass.icmp_type_or_tcp_flags)))
{
b0->error = node->errors[NAT44_EI_IN2OUT_ERROR_BAD_ICMP_TYPE];
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
out:
return next0;
}
static_always_inline u32
nat44_ei_icmp_hairpinning (nat44_ei_main_t *nm, vlib_buffer_t *b0,
u32 thread_index, ip4_header_t *ip0,
icmp46_header_t *icmp0, u32 *required_thread_index)
{
clib_bihash_kv_8_8_t kv0, value0;
u32 old_dst_addr0, new_dst_addr0;
u32 old_addr0, new_addr0;
u16 old_port0, new_port0;
u16 old_checksum0, new_checksum0;
u32 si, ti = 0;
ip_csum_t sum0;
nat44_ei_session_t *s0;
nat44_ei_static_mapping_t *m0;
if (icmp_type_is_error_message (
vnet_buffer (b0)->ip.reass.icmp_type_or_tcp_flags))
{
ip4_header_t *inner_ip0 = 0;
tcp_udp_header_t *l4_header = 0;
inner_ip0 = (ip4_header_t *) ((icmp_echo_header_t *) (icmp0 + 1) + 1);
l4_header = ip4_next_header (inner_ip0);
u32 protocol = ip_proto_to_nat_proto (inner_ip0->protocol);
if (protocol != NAT_PROTOCOL_TCP && protocol != NAT_PROTOCOL_UDP)
return 1;
init_nat_k (&kv0, ip0->dst_address, l4_header->src_port,
nm->outside_fib_index, protocol);
if (clib_bihash_search_8_8 (&nm->out2in, &kv0, &value0))
return 1;
ti = nat_value_get_thread_index (&value0);
if (ti != thread_index)
{
*required_thread_index = ti;
return 1;
}
si = nat_value_get_session_index (&value0);
s0 = pool_elt_at_index (nm->per_thread_data[ti].sessions, si);
new_dst_addr0 = s0->in2out.addr.as_u32;
vnet_buffer (b0)->sw_if_index[VLIB_TX] = s0->in2out.fib_index;
/* update inner source IP address */
old_addr0 = inner_ip0->src_address.as_u32;
inner_ip0->src_address.as_u32 = new_dst_addr0;
new_addr0 = inner_ip0->src_address.as_u32;
sum0 = icmp0->checksum;
sum0 =
ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t, src_address);
icmp0->checksum = ip_csum_fold (sum0);
/* update inner IP header checksum */
old_checksum0 = inner_ip0->checksum;
sum0 = inner_ip0->checksum;
sum0 =
ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t, src_address);
inner_ip0->checksum = ip_csum_fold (sum0);
new_checksum0 = inner_ip0->checksum;
sum0 = icmp0->checksum;
sum0 = ip_csum_update (sum0, old_checksum0, new_checksum0, ip4_header_t,
checksum);
icmp0->checksum = ip_csum_fold (sum0);
/* update inner source port */
old_port0 = l4_header->src_port;
l4_header->src_port = s0->in2out.port;
new_port0 = l4_header->src_port;
sum0 = icmp0->checksum;
sum0 = ip_csum_update (sum0, old_port0, new_port0, tcp_udp_header_t,
src_port);
icmp0->checksum = ip_csum_fold (sum0);
}
else
{
init_nat_k (&kv0, ip0->dst_address, 0, nm->outside_fib_index, 0);
if (clib_bihash_search_8_8 (&nm->static_mapping_by_external, &kv0,
&value0))
{
icmp_echo_header_t *echo0 = (icmp_echo_header_t *) (icmp0 + 1);
u16 icmp_id0 = echo0->identifier;
init_nat_k (&kv0, ip0->dst_address, icmp_id0, nm->outside_fib_index,
NAT_PROTOCOL_ICMP);
int rv = clib_bihash_search_8_8 (&nm->out2in, &kv0, &value0);
if (!rv)
{
ti = nat_value_get_thread_index (&value0);
if (ti != thread_index)
{
*required_thread_index = ti;
return 1;
}
si = nat_value_get_session_index (&value0);
s0 = pool_elt_at_index (nm->per_thread_data[ti].sessions, si);
new_dst_addr0 = s0->in2out.addr.as_u32;
vnet_buffer (b0)->sw_if_index[VLIB_TX] = s0->in2out.fib_index;
echo0->identifier = s0->in2out.port;
sum0 = icmp0->checksum;
sum0 = ip_csum_update (sum0, icmp_id0, s0->in2out.port,
icmp_echo_header_t, identifier);
icmp0->checksum = ip_csum_fold (sum0);
goto change_addr;
}
return 1;
}
m0 = pool_elt_at_index (nm->static_mappings, value0.value);
new_dst_addr0 = m0->local_addr.as_u32;
if (vnet_buffer (b0)->sw_if_index[VLIB_TX] == ~0)
vnet_buffer (b0)->sw_if_index[VLIB_TX] = m0->fib_index;
}
change_addr:
/* Destination is behind the same NAT, use internal address and port */
if (new_dst_addr0)
{
old_dst_addr0 = ip0->dst_address.as_u32;
ip0->dst_address.as_u32 = new_dst_addr0;
sum0 = ip0->checksum;
sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0, ip4_header_t,
dst_address);
ip0->checksum = ip_csum_fold (sum0);
}
return 0;
}
static_always_inline u32
nat44_ei_icmp_in2out (vlib_buffer_t *b0, ip4_header_t *ip0,
icmp46_header_t *icmp0, u32 sw_if_index0,
u32 rx_fib_index0, vlib_node_runtime_t *node, u32 next0,
u32 thread_index, nat44_ei_session_t **p_s0)
{
nat44_ei_main_t *nm = &nat44_ei_main;
vlib_main_t *vm = vlib_get_main ();
ip4_address_t addr;
u16 port;
u32 fib_index;
nat_protocol_t proto;
icmp_echo_header_t *echo0, *inner_echo0 = 0;
ip4_header_t *inner_ip0;
void *l4_header = 0;
icmp46_header_t *inner_icmp0;
u8 dont_translate;
u32 new_addr0, old_addr0;
u16 old_id0, new_id0;
u16 old_checksum0, new_checksum0;
ip_csum_t sum0;
u16 checksum0;
u32 next0_tmp;
u32 required_thread_index = thread_index;
echo0 = (icmp_echo_header_t *) (icmp0 + 1);
if (PREDICT_TRUE (nm->pat))
{
next0_tmp = nat44_ei_icmp_match_in2out_slow (
node, thread_index, b0, ip0, &addr, &port, &fib_index, &proto, p_s0,
&dont_translate);
}
else
{
next0_tmp = nat44_ei_icmp_match_in2out_fast (
node, thread_index, b0, ip0, &addr, &port, &fib_index, &proto, p_s0,
&dont_translate);
}
if (next0_tmp != ~0)
next0 = next0_tmp;
if (next0 == NAT44_EI_IN2OUT_NEXT_DROP || dont_translate)
goto out;
if (PREDICT_TRUE (!ip4_is_fragment (ip0)))
{
sum0 =
ip_incremental_checksum_buffer (vm, b0,
(u8 *) icmp0 -
(u8 *) vlib_buffer_get_current (b0),
ntohs (ip0->length) -
ip4_header_bytes (ip0), 0);
checksum0 = ~ip_csum_fold (sum0);
if (PREDICT_FALSE (checksum0 != 0 && checksum0 != 0xffff))
{
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
}
old_addr0 = ip0->src_address.as_u32;
new_addr0 = ip0->src_address.as_u32 = addr.as_u32;
sum0 = ip0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
src_address /* changed member */ );
ip0->checksum = ip_csum_fold (sum0);
if (!vnet_buffer (b0)->ip.reass.is_non_first_fragment)
{
if (icmp0->checksum == 0)
icmp0->checksum = 0xffff;
if (!icmp_type_is_error_message (icmp0->type))
{
new_id0 = port;
if (PREDICT_FALSE (new_id0 != echo0->identifier))
{
old_id0 = echo0->identifier;
new_id0 = port;
echo0->identifier = new_id0;
sum0 = icmp0->checksum;
sum0 =
ip_csum_update (sum0, old_id0, new_id0, icmp_echo_header_t,
identifier);
icmp0->checksum = ip_csum_fold (sum0);
}
}
else
{
inner_ip0 = (ip4_header_t *) (echo0 + 1);
l4_header = ip4_next_header (inner_ip0);
if (!ip4_header_checksum_is_valid (inner_ip0))
{
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
goto out;
}
/* update inner destination IP address */
old_addr0 = inner_ip0->dst_address.as_u32;
inner_ip0->dst_address = addr;
new_addr0 = inner_ip0->dst_address.as_u32;
sum0 = icmp0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
dst_address /* changed member */ );
icmp0->checksum = ip_csum_fold (sum0);
/* update inner IP header checksum */
old_checksum0 = inner_ip0->checksum;
sum0 = inner_ip0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
dst_address /* changed member */ );
inner_ip0->checksum = ip_csum_fold (sum0);
new_checksum0 = inner_ip0->checksum;
sum0 = icmp0->checksum;
sum0 =
ip_csum_update (sum0, old_checksum0, new_checksum0, ip4_header_t,
checksum);
icmp0->checksum = ip_csum_fold (sum0);
switch (proto)
{
case NAT_PROTOCOL_ICMP:
inner_icmp0 = (icmp46_header_t *) l4_header;
inner_echo0 = (icmp_echo_header_t *) (inner_icmp0 + 1);
old_id0 = inner_echo0->identifier;
new_id0 = port;
inner_echo0->identifier = new_id0;
sum0 = icmp0->checksum;
sum0 =
ip_csum_update (sum0, old_id0, new_id0, icmp_echo_header_t,
identifier);
icmp0->checksum = ip_csum_fold (sum0);
break;
case NAT_PROTOCOL_UDP:
case NAT_PROTOCOL_TCP:
old_id0 = ((tcp_udp_header_t *) l4_header)->dst_port;
new_id0 = port;
((tcp_udp_header_t *) l4_header)->dst_port = new_id0;
sum0 = icmp0->checksum;
sum0 = ip_csum_update (sum0, old_id0, new_id0, tcp_udp_header_t,
dst_port);
icmp0->checksum = ip_csum_fold (sum0);
break;
default:
ASSERT (0);
}
}
}
if (vnet_buffer (b0)->sw_if_index[VLIB_TX] == ~0)
{
if (0 != nat44_ei_icmp_hairpinning (nm, b0, thread_index, ip0, icmp0,
&required_thread_index))
vnet_buffer (b0)->sw_if_index[VLIB_TX] = fib_index;
if (thread_index != required_thread_index)
{
vnet_buffer (b0)->snat.required_thread_index = required_thread_index;
next0 = NAT44_EI_IN2OUT_NEXT_HAIRPINNING_HANDOFF;
}
}
out:
return next0;
}
static_always_inline u32
nat44_ei_icmp_in2out_slow_path (nat44_ei_main_t *nm, vlib_buffer_t *b0,
ip4_header_t *ip0, icmp46_header_t *icmp0,
u32 sw_if_index0, u32 rx_fib_index0,
vlib_node_runtime_t *node, u32 next0, f64 now,
u32 thread_index, nat44_ei_session_t **p_s0)
{
vlib_main_t *vm = vlib_get_main ();
next0 = nat44_ei_icmp_in2out (b0, ip0, icmp0, sw_if_index0, rx_fib_index0,
node, next0, thread_index, p_s0);
nat44_ei_session_t *s0 = *p_s0;
if (PREDICT_TRUE (next0 != NAT44_EI_IN2OUT_NEXT_DROP && s0))
{
/* Accounting */
nat44_ei_session_update_counters (
s0, now, vlib_buffer_length_in_chain (vm, b0), thread_index);
/* Per-user LRU list maintenance */
nat44_ei_session_update_lru (nm, s0, thread_index);
}
return next0;
}
static_always_inline void
nat44_ei_hairpinning_sm_unknown_proto (nat44_ei_main_t *nm, vlib_buffer_t *b,
ip4_header_t *ip)
{
clib_bihash_kv_8_8_t kv, value;
nat44_ei_static_mapping_t *m;
u32 old_addr, new_addr;
ip_csum_t sum;
init_nat_k (&kv, ip->dst_address, 0, 0, 0);
if (clib_bihash_search_8_8 (&nm->static_mapping_by_external, &kv, &value))
return;
m = pool_elt_at_index (nm->static_mappings, value.value);
old_addr = ip->dst_address.as_u32;
new_addr = ip->dst_address.as_u32 = m->local_addr.as_u32;
sum = ip->checksum;
sum = ip_csum_update (sum, old_addr, new_addr, ip4_header_t, dst_address);
ip->checksum = ip_csum_fold (sum);
if (vnet_buffer (b)->sw_if_index[VLIB_TX] == ~0)
vnet_buffer (b)->sw_if_index[VLIB_TX] = m->fib_index;
}
static int
nat_in2out_sm_unknown_proto (nat44_ei_main_t *nm, vlib_buffer_t *b,
ip4_header_t *ip, u32 rx_fib_index)
{
clib_bihash_kv_8_8_t kv, value;
nat44_ei_static_mapping_t *m;
u32 old_addr, new_addr;
ip_csum_t sum;
init_nat_k (&kv, ip->src_address, 0, rx_fib_index, 0);
if (clib_bihash_search_8_8 (&nm->static_mapping_by_local, &kv, &value))
return 1;
m = pool_elt_at_index (nm->static_mappings, value.value);
old_addr = ip->src_address.as_u32;
new_addr = ip->src_address.as_u32 = m->external_addr.as_u32;
sum = ip->checksum;
sum = ip_csum_update (sum, old_addr, new_addr, ip4_header_t, src_address);
ip->checksum = ip_csum_fold (sum);
/* Hairpinning */
if (vnet_buffer (b)->sw_if_index[VLIB_TX] == ~0)
{
vnet_buffer (b)->sw_if_index[VLIB_TX] = m->fib_index;
nat44_ei_hairpinning_sm_unknown_proto (nm, b, ip);
}
return 0;
}
static_always_inline int
nat44_ei_hairpinning (vlib_main_t *vm, vlib_node_runtime_t *node,
nat44_ei_main_t *nm, u32 thread_index, vlib_buffer_t *b0,
ip4_header_t *ip0, udp_header_t *udp0,
tcp_header_t *tcp0, u32 proto0, int do_trace,
u32 *required_thread_index)
{
nat44_ei_session_t *s0 = NULL;
clib_bihash_kv_8_8_t kv0, value0;
ip_csum_t sum0;
u32 new_dst_addr0 = 0, old_dst_addr0, si = ~0;
u16 new_dst_port0 = ~0, old_dst_port0;
int rv;
ip4_address_t sm0_addr;
u16 sm0_port;
u32 sm0_fib_index;
u32 old_sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_TX];
/* Check if destination is static mappings */
if (!nat44_ei_static_mapping_match (
ip0->dst_address, udp0->dst_port, nm->outside_fib_index, proto0,
&sm0_addr, &sm0_port, &sm0_fib_index, 1 /* by external */, 0, 0))
{
new_dst_addr0 = sm0_addr.as_u32;
new_dst_port0 = sm0_port;
vnet_buffer (b0)->sw_if_index[VLIB_TX] = sm0_fib_index;
}
/* or active session */
else
{
init_nat_k (&kv0, ip0->dst_address, udp0->dst_port,
nm->outside_fib_index, proto0);
rv = clib_bihash_search_8_8 (&nm->out2in, &kv0, &value0);
if (rv)
{
rv = 0;
goto trace;
}
if (thread_index != nat_value_get_thread_index (&value0))
{
*required_thread_index = nat_value_get_thread_index (&value0);
return 0;
}
si = nat_value_get_session_index (&value0);
s0 = pool_elt_at_index (nm->per_thread_data[thread_index].sessions, si);
new_dst_addr0 = s0->in2out.addr.as_u32;
new_dst_port0 = s0->in2out.port;
vnet_buffer (b0)->sw_if_index[VLIB_TX] = s0->in2out.fib_index;
}
/* Check if anything has changed and if not, then return 0. This
helps avoid infinite loop, repeating the three nodes
nat44-hairpinning-->ip4-lookup-->ip4-local, in case nothing has
changed. */
old_dst_addr0 = ip0->dst_address.as_u32;
old_dst_port0 = tcp0->dst;
if (new_dst_addr0 == old_dst_addr0 && new_dst_port0 == old_dst_port0 &&
vnet_buffer (b0)->sw_if_index[VLIB_TX] == old_sw_if_index)
return 0;
/* Destination is behind the same NAT, use internal address and port */
if (new_dst_addr0)
{
old_dst_addr0 = ip0->dst_address.as_u32;
ip0->dst_address.as_u32 = new_dst_addr0;
sum0 = ip0->checksum;
sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0, ip4_header_t,
dst_address);
ip0->checksum = ip_csum_fold (sum0);
old_dst_port0 = tcp0->dst;
if (PREDICT_TRUE (new_dst_port0 != old_dst_port0))
{
if (PREDICT_TRUE (proto0 == NAT_PROTOCOL_TCP))
{
tcp0->dst = new_dst_port0;
sum0 = tcp0->checksum;
sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
ip4_header_t, dst_address);
sum0 = ip_csum_update (sum0, old_dst_port0, new_dst_port0,
ip4_header_t /* cheat */, length);
tcp0->checksum = ip_csum_fold (sum0);
}
else
{
udp0->dst_port = new_dst_port0;
udp0->checksum = 0;
}
}
else
{
if (PREDICT_TRUE (proto0 == NAT_PROTOCOL_TCP))
{
sum0 = tcp0->checksum;
sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
ip4_header_t, dst_address);
tcp0->checksum = ip_csum_fold (sum0);
}
}
rv = 1;
goto trace;
}
rv = 0;
trace:
if (do_trace && PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
(b0->flags & VLIB_BUFFER_IS_TRACED)))
{
nat44_ei_hairpin_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
t->addr.as_u32 = new_dst_addr0;
t->port = new_dst_port0;
t->fib_index = vnet_buffer (b0)->sw_if_index[VLIB_TX];
if (s0)
{
t->session_index = si;
}
else
{
t->session_index = ~0;
}
}
return rv;
}
static_always_inline uword
nat44_ei_hairpinning_handoff_fn_inline (vlib_main_t *vm,
vlib_node_runtime_t *node,
vlib_frame_t *frame, u32 fq_index)
{
vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b;
u32 n_enq, n_left_from, *from;
u16 thread_indices[VLIB_FRAME_SIZE], *ti;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
vlib_get_buffers (vm, from, bufs, n_left_from);
b = bufs;
ti = thread_indices;
while (n_left_from > 0)
{
ti[0] = vnet_buffer (b[0])->snat.required_thread_index;
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
(b[0]->flags & VLIB_BUFFER_IS_TRACED)))
{
nat44_ei_hairpinning_handoff_trace_t *t =
vlib_add_trace (vm, node, b[0], sizeof (*t));
t->next_worker_index = ti[0];
}
n_left_from -= 1;
ti += 1;
b += 1;
}
n_enq = vlib_buffer_enqueue_to_thread (vm, node, fq_index, from,
thread_indices, frame->n_vectors, 1);
if (n_enq < frame->n_vectors)
vlib_node_increment_counter (
vm, node->node_index, NAT44_EI_HAIRPINNING_HANDOFF_ERROR_CONGESTION_DROP,
frame->n_vectors - n_enq);
return frame->n_vectors;
}
static_always_inline uword
nat44_ei_in2out_node_fn_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_frame_t *frame, int is_slow_path,
int is_output_feature)
{
u32 n_left_from, *from;
nat44_ei_main_t *nm = &nat44_ei_main;
f64 now = vlib_time_now (vm);
u32 thread_index = vm->thread_index;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
vlib_get_buffers (vm, from, b, n_left_from);
while (n_left_from >= 2)
{
vlib_buffer_t *b0, *b1;
u32 next0, next1;
u32 rx_sw_if_index0, rx_sw_if_index1;
u32 tx_sw_if_index0, tx_sw_if_index1;
u32 cntr_sw_if_index0, cntr_sw_if_index1;
ip4_header_t *ip0, *ip1;
ip_csum_t sum0, sum1;
u32 new_addr0, old_addr0, new_addr1, old_addr1;
u16 old_port0, new_port0, old_port1, new_port1;
udp_header_t *udp0, *udp1;
tcp_header_t *tcp0, *tcp1;
icmp46_header_t *icmp0, *icmp1;
u32 rx_fib_index0, rx_fib_index1;
u32 proto0, proto1;
nat44_ei_session_t *s0 = 0, *s1 = 0;
clib_bihash_kv_8_8_t kv0, value0, kv1, value1;
u32 iph_offset0 = 0, iph_offset1 = 0;
b0 = *b;
b++;
b1 = *b;
b++;
/* Prefetch next iteration. */
if (PREDICT_TRUE (n_left_from >= 4))
{
vlib_buffer_t *p2, *p3;
p2 = *b;
p3 = *(b + 1);
vlib_prefetch_buffer_header (p2, LOAD);
vlib_prefetch_buffer_header (p3, LOAD);
clib_prefetch_load (p2->data);
clib_prefetch_load (p3->data);
}
if (is_output_feature)
iph_offset0 = vnet_buffer (b0)->ip.reass.save_rewrite_length;
ip0 = (ip4_header_t *) ((u8 *) vlib_buffer_get_current (b0) +
iph_offset0);
udp0 = ip4_next_header (ip0);
tcp0 = (tcp_header_t *) udp0;
icmp0 = (icmp46_header_t *) udp0;
rx_sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
tx_sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_TX];
cntr_sw_if_index0 =
is_output_feature ? tx_sw_if_index0 : rx_sw_if_index0;
rx_fib_index0 =
vec_elt (nm->ip4_main->fib_index_by_sw_if_index, rx_sw_if_index0);
next0 = next1 = NAT44_EI_IN2OUT_NEXT_LOOKUP;
if (PREDICT_FALSE (ip0->ttl == 1))
{
vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
ICMP4_time_exceeded_ttl_exceeded_in_transit,
0);
next0 = NAT44_EI_IN2OUT_NEXT_ICMP_ERROR;
goto trace00;
}
proto0 = ip_proto_to_nat_proto (ip0->protocol);
/* Next configured feature, probably ip4-lookup */
if (is_slow_path)
{
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_OTHER))
{
if (nat_in2out_sm_unknown_proto (nm, b0, ip0, rx_fib_index0))
{
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
b0->error =
node->errors[NAT44_EI_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL];
}
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.other :
&nm->counters.fastpath.in2out.other,
thread_index, cntr_sw_if_index0, 1);
goto trace00;
}
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_ICMP))
{
next0 = nat44_ei_icmp_in2out_slow_path (
nm, b0, ip0, icmp0, rx_sw_if_index0, rx_fib_index0, node,
next0, now, thread_index, &s0);
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.icmp :
&nm->counters.fastpath.in2out.icmp,
thread_index, cntr_sw_if_index0, 1);
goto trace00;
}
}
else
{
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_OTHER))
{
next0 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace00;
}
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_ICMP))
{
next0 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace00;
}
}
init_nat_k (&kv0, ip0->src_address,
vnet_buffer (b0)->ip.reass.l4_src_port, rx_fib_index0,
proto0);
if (PREDICT_FALSE (clib_bihash_search_8_8 (&nm->in2out, &kv0, &value0) !=
0))
{
if (is_slow_path)
{
if (is_output_feature)
{
if (PREDICT_FALSE (nat44_ei_not_translate_output_feature (
nm, ip0, proto0,
vnet_buffer (b0)->ip.reass.l4_src_port,
vnet_buffer (b0)->ip.reass.l4_dst_port, thread_index,
rx_sw_if_index0)))
goto trace00;
/*
* Send DHCP packets to the ipv4 stack, or we won't
* be able to use dhcp client on the outside interface
*/
if (PREDICT_FALSE
(proto0 == NAT_PROTOCOL_UDP
&& (vnet_buffer (b0)->ip.reass.l4_dst_port ==
clib_host_to_net_u16
(UDP_DST_PORT_dhcp_to_server))
&& ip0->dst_address.as_u32 == 0xffffffff))
goto trace00;
}
else
{
if (PREDICT_FALSE (nat44_ei_not_translate (
nm, node, rx_sw_if_index0, ip0, proto0, rx_fib_index0,
thread_index)))
goto trace00;
}
next0 = slow_path (nm, b0, ip0, ip0->src_address,
vnet_buffer (b0)->ip.reass.l4_src_port,
rx_fib_index0, proto0, &s0, node, next0,
thread_index, now);
if (PREDICT_FALSE (next0 == NAT44_EI_IN2OUT_NEXT_DROP))
goto trace00;
if (PREDICT_FALSE (!s0))
goto trace00;
}
else
{
next0 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace00;
}
}
else
s0 = pool_elt_at_index (nm->per_thread_data[thread_index].sessions,
nat_value_get_session_index (&value0));
b0->flags |= VNET_BUFFER_F_IS_NATED;
old_addr0 = ip0->src_address.as_u32;
ip0->src_address = s0->out2in.addr;
new_addr0 = ip0->src_address.as_u32;
if (!is_output_feature)
vnet_buffer (b0)->sw_if_index[VLIB_TX] = s0->out2in.fib_index;
sum0 = ip0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
ip4_header_t, src_address /* changed member */ );
ip0->checksum = ip_csum_fold (sum0);
if (PREDICT_TRUE (proto0 == NAT_PROTOCOL_TCP))
{
if (!vnet_buffer (b0)->ip.reass.is_non_first_fragment)
{
old_port0 = vnet_buffer (b0)->ip.reass.l4_src_port;
new_port0 = udp0->src_port = s0->out2in.port;
sum0 = tcp0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
ip4_header_t,
dst_address /* changed member */ );
sum0 = ip_csum_update (sum0, old_port0, new_port0,
ip4_header_t /* cheat */ ,
length /* changed member */ );
mss_clamping (nm->mss_clamping, tcp0, &sum0);
tcp0->checksum = ip_csum_fold (sum0);
}
vlib_increment_simple_counter (is_slow_path ?
&nm->counters.slowpath.in2out.tcp :
&nm->counters.fastpath.in2out.tcp,
thread_index, cntr_sw_if_index0, 1);
}
else
{
if (!vnet_buffer (b0)->ip.reass.is_non_first_fragment)
{
udp0->src_port = s0->out2in.port;
if (PREDICT_FALSE (udp0->checksum))
{
old_port0 = vnet_buffer (b0)->ip.reass.l4_src_port;
new_port0 = udp0->src_port;
sum0 = udp0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t, dst_address /* changed member */
);
sum0 =
ip_csum_update (sum0, old_port0, new_port0,
ip4_header_t /* cheat */ ,
length /* changed member */ );
udp0->checksum = ip_csum_fold (sum0);
}
}
vlib_increment_simple_counter (is_slow_path ?
&nm->counters.slowpath.in2out.udp :
&nm->counters.fastpath.in2out.udp,
thread_index, cntr_sw_if_index0, 1);
}
/* Accounting */
nat44_ei_session_update_counters (
s0, now, vlib_buffer_length_in_chain (vm, b0), thread_index);
/* Per-user LRU list maintenance */
nat44_ei_session_update_lru (nm, s0, thread_index);
trace00:
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
&& (b0->flags & VLIB_BUFFER_IS_TRACED)))
{
nat44_ei_in2out_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
t->is_slow_path = is_slow_path;
t->sw_if_index = rx_sw_if_index0;
t->next_index = next0;
t->session_index = ~0;
if (s0)
t->session_index = s0 - nm->per_thread_data[thread_index].sessions;
}
if (next0 == NAT44_EI_IN2OUT_NEXT_DROP)
{
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.drops :
&nm->counters.fastpath.in2out.drops,
thread_index, cntr_sw_if_index0, 1);
}
if (is_output_feature)
iph_offset1 = vnet_buffer (b1)->ip.reass.save_rewrite_length;
ip1 = (ip4_header_t *) ((u8 *) vlib_buffer_get_current (b1) +
iph_offset1);
udp1 = ip4_next_header (ip1);
tcp1 = (tcp_header_t *) udp1;
icmp1 = (icmp46_header_t *) udp1;
rx_sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
tx_sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_TX];
cntr_sw_if_index1 =
is_output_feature ? tx_sw_if_index1 : rx_sw_if_index1;
rx_fib_index1 =
vec_elt (nm->ip4_main->fib_index_by_sw_if_index, rx_sw_if_index1);
if (PREDICT_FALSE (ip1->ttl == 1))
{
vnet_buffer (b1)->sw_if_index[VLIB_TX] = (u32) ~ 0;
icmp4_error_set_vnet_buffer (b1, ICMP4_time_exceeded,
ICMP4_time_exceeded_ttl_exceeded_in_transit,
0);
next1 = NAT44_EI_IN2OUT_NEXT_ICMP_ERROR;
goto trace01;
}
proto1 = ip_proto_to_nat_proto (ip1->protocol);
/* Next configured feature, probably ip4-lookup */
if (is_slow_path)
{
if (PREDICT_FALSE (proto1 == NAT_PROTOCOL_OTHER))
{
if (nat_in2out_sm_unknown_proto (nm, b1, ip1, rx_fib_index1))
{
next1 = NAT44_EI_IN2OUT_NEXT_DROP;
b1->error =
node->errors[NAT44_EI_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL];
}
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.other :
&nm->counters.fastpath.in2out.other,
thread_index, cntr_sw_if_index1, 1);
goto trace01;
}
if (PREDICT_FALSE (proto1 == NAT_PROTOCOL_ICMP))
{
next1 = nat44_ei_icmp_in2out_slow_path (
nm, b1, ip1, icmp1, rx_sw_if_index1, rx_fib_index1, node,
next1, now, thread_index, &s1);
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.icmp :
&nm->counters.fastpath.in2out.icmp,
thread_index, cntr_sw_if_index1, 1);
goto trace01;
}
}
else
{
if (PREDICT_FALSE (proto1 == NAT_PROTOCOL_OTHER))
{
next1 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace01;
}
if (PREDICT_FALSE (proto1 == NAT_PROTOCOL_ICMP))
{
next1 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace01;
}
}
init_nat_k (&kv1, ip1->src_address,
vnet_buffer (b1)->ip.reass.l4_src_port, rx_fib_index1,
proto1);
if (PREDICT_FALSE (clib_bihash_search_8_8 (&nm->in2out, &kv1, &value1) !=
0))
{
if (is_slow_path)
{
if (is_output_feature)
{
if (PREDICT_FALSE (nat44_ei_not_translate_output_feature (
nm, ip1, proto1,
vnet_buffer (b1)->ip.reass.l4_src_port,
vnet_buffer (b1)->ip.reass.l4_dst_port, thread_index,
rx_sw_if_index1)))
goto trace01;
/*
* Send DHCP packets to the ipv4 stack, or we won't
* be able to use dhcp client on the outside interface
*/
if (PREDICT_FALSE
(proto1 == NAT_PROTOCOL_UDP
&& (vnet_buffer (b1)->ip.reass.l4_dst_port ==
clib_host_to_net_u16
(UDP_DST_PORT_dhcp_to_server))
&& ip1->dst_address.as_u32 == 0xffffffff))
goto trace01;
}
else
{
if (PREDICT_FALSE (nat44_ei_not_translate (
nm, node, rx_sw_if_index1, ip1, proto1, rx_fib_index1,
thread_index)))
goto trace01;
}
next1 = slow_path (nm, b1, ip1, ip1->src_address,
vnet_buffer (b1)->ip.reass.l4_src_port,
rx_fib_index1, proto1, &s1, node, next1,
thread_index, now);
if (PREDICT_FALSE (next1 == NAT44_EI_IN2OUT_NEXT_DROP))
goto trace01;
if (PREDICT_FALSE (!s1))
goto trace01;
}
else
{
next1 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace01;
}
}
else
s1 = pool_elt_at_index (nm->per_thread_data[thread_index].sessions,
nat_value_get_session_index (&value1));
b1->flags |= VNET_BUFFER_F_IS_NATED;
old_addr1 = ip1->src_address.as_u32;
ip1->src_address = s1->out2in.addr;
new_addr1 = ip1->src_address.as_u32;
if (!is_output_feature)
vnet_buffer (b1)->sw_if_index[VLIB_TX] = s1->out2in.fib_index;
sum1 = ip1->checksum;
sum1 = ip_csum_update (sum1, old_addr1, new_addr1,
ip4_header_t, src_address /* changed member */ );
ip1->checksum = ip_csum_fold (sum1);
if (PREDICT_TRUE (proto1 == NAT_PROTOCOL_TCP))
{
if (!vnet_buffer (b1)->ip.reass.is_non_first_fragment)
{
old_port1 = vnet_buffer (b1)->ip.reass.l4_src_port;
new_port1 = udp1->src_port = s1->out2in.port;
sum1 = tcp1->checksum;
sum1 = ip_csum_update (sum1, old_addr1, new_addr1,
ip4_header_t,
dst_address /* changed member */ );
sum1 = ip_csum_update (sum1, old_port1, new_port1,
ip4_header_t /* cheat */ ,
length /* changed member */ );
mss_clamping (nm->mss_clamping, tcp1, &sum1);
tcp1->checksum = ip_csum_fold (sum1);
}
vlib_increment_simple_counter (is_slow_path ?
&nm->counters.slowpath.in2out.tcp :
&nm->counters.fastpath.in2out.tcp,
thread_index, cntr_sw_if_index1, 1);
}
else
{
if (!vnet_buffer (b1)->ip.reass.is_non_first_fragment)
{
udp1->src_port = s1->out2in.port;
if (PREDICT_FALSE (udp1->checksum))
{
old_port1 = vnet_buffer (b1)->ip.reass.l4_src_port;
new_port1 = udp1->src_port;
sum1 = udp1->checksum;
sum1 = ip_csum_update (sum1, old_addr1, new_addr1, ip4_header_t, dst_address /* changed member */
);
sum1 =
ip_csum_update (sum1, old_port1, new_port1,
ip4_header_t /* cheat */ ,
length /* changed member */ );
udp1->checksum = ip_csum_fold (sum1);
}
}
vlib_increment_simple_counter (is_slow_path ?
&nm->counters.slowpath.in2out.udp :
&nm->counters.fastpath.in2out.udp,
thread_index, cntr_sw_if_index1, 1);
}
/* Accounting */
nat44_ei_session_update_counters (
s1, now, vlib_buffer_length_in_chain (vm, b1), thread_index);
/* Per-user LRU list maintenance */
nat44_ei_session_update_lru (nm, s1, thread_index);
trace01:
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
&& (b1->flags & VLIB_BUFFER_IS_TRACED)))
{
nat44_ei_in2out_trace_t *t =
vlib_add_trace (vm, node, b1, sizeof (*t));
t->sw_if_index = rx_sw_if_index1;
t->next_index = next1;
t->session_index = ~0;
if (s1)
t->session_index = s1 - nm->per_thread_data[thread_index].sessions;
}
if (next1 == NAT44_EI_IN2OUT_NEXT_DROP)
{
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.drops :
&nm->counters.fastpath.in2out.drops,
thread_index, cntr_sw_if_index1, 1);
}
n_left_from -= 2;
next[0] = next0;
next[1] = next1;
next += 2;
}
while (n_left_from > 0)
{
vlib_buffer_t *b0;
u32 next0;
u32 rx_sw_if_index0;
u32 tx_sw_if_index0;
u32 cntr_sw_if_index0;
ip4_header_t *ip0;
ip_csum_t sum0;
u32 new_addr0, old_addr0;
u16 old_port0, new_port0;
udp_header_t *udp0;
tcp_header_t *tcp0;
icmp46_header_t *icmp0;
u32 rx_fib_index0;
u32 proto0;
nat44_ei_session_t *s0 = 0;
clib_bihash_kv_8_8_t kv0, value0;
u32 iph_offset0 = 0;
b0 = *b;
b++;
next0 = NAT44_EI_IN2OUT_NEXT_LOOKUP;
if (is_output_feature)
iph_offset0 = vnet_buffer (b0)->ip.reass.save_rewrite_length;
ip0 = (ip4_header_t *) ((u8 *) vlib_buffer_get_current (b0) +
iph_offset0);
udp0 = ip4_next_header (ip0);
tcp0 = (tcp_header_t *) udp0;
icmp0 = (icmp46_header_t *) udp0;
rx_sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
tx_sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_TX];
cntr_sw_if_index0 =
is_output_feature ? tx_sw_if_index0 : rx_sw_if_index0;
rx_fib_index0 =
vec_elt (nm->ip4_main->fib_index_by_sw_if_index, rx_sw_if_index0);
if (PREDICT_FALSE (ip0->ttl == 1))
{
vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
ICMP4_time_exceeded_ttl_exceeded_in_transit,
0);
next0 = NAT44_EI_IN2OUT_NEXT_ICMP_ERROR;
goto trace0;
}
proto0 = ip_proto_to_nat_proto (ip0->protocol);
/* Next configured feature, probably ip4-lookup */
if (is_slow_path)
{
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_OTHER))
{
if (nat_in2out_sm_unknown_proto (nm, b0, ip0, rx_fib_index0))
{
next0 = NAT44_EI_IN2OUT_NEXT_DROP;
b0->error =
node->errors[NAT44_EI_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL];
}
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.other :
&nm->counters.fastpath.in2out.other,
thread_index, cntr_sw_if_index0, 1);
goto trace0;
}
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_ICMP))
{
next0 = nat44_ei_icmp_in2out_slow_path (
nm, b0, ip0, icmp0, rx_sw_if_index0, rx_fib_index0, node,
next0, now, thread_index, &s0);
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.icmp :
&nm->counters.fastpath.in2out.icmp,
thread_index, cntr_sw_if_index0, 1);
goto trace0;
}
}
else
{
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_OTHER))
{
next0 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace0;
}
if (PREDICT_FALSE (proto0 == NAT_PROTOCOL_ICMP))
{
next0 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace0;
}
}
init_nat_k (&kv0, ip0->src_address,
vnet_buffer (b0)->ip.reass.l4_src_port, rx_fib_index0,
proto0);
if (clib_bihash_search_8_8 (&nm->in2out, &kv0, &value0))
{
if (is_slow_path)
{
if (is_output_feature)
{
if (PREDICT_FALSE (nat44_ei_not_translate_output_feature (
nm, ip0, proto0,
vnet_buffer (b0)->ip.reass.l4_src_port,
vnet_buffer (b0)->ip.reass.l4_dst_port, thread_index,
rx_sw_if_index0)))
goto trace0;
/*
* Send DHCP packets to the ipv4 stack, or we won't
* be able to use dhcp client on the outside interface
*/
if (PREDICT_FALSE
(proto0 == NAT_PROTOCOL_UDP
&& (vnet_buffer (b0)->ip.reass.l4_dst_port ==
clib_host_to_net_u16
(UDP_DST_PORT_dhcp_to_server))
&& ip0->dst_address.as_u32 == 0xffffffff))
goto trace0;
}
else
{
if (PREDICT_FALSE (nat44_ei_not_translate (
nm, node, rx_sw_if_index0, ip0, proto0, rx_fib_index0,
thread_index)))
goto trace0;
}
next0 = slow_path (nm, b0, ip0, ip0->src_address,
vnet_buffer (b0)->ip.reass.l4_src_port,
rx_fib_index0, proto0, &s0, node, next0,
thread_index, now);
if (PREDICT_FALSE (next0 == NAT44_EI_IN2OUT_NEXT_DROP))
goto trace0;
if (PREDICT_FALSE (!s0))
goto trace0;
}
else
{
next0 = NAT44_EI_IN2OUT_NEXT_SLOW_PATH;
goto trace0;
}
}
else
s0 = pool_elt_at_index (nm->per_thread_data[thread_index].sessions,
nat_value_get_session_index (&value0));
b0->flags |= VNET_BUFFER_F_IS_NATED;
old_addr0 = ip0->src_address.as_u32;
ip0->src_address = s0->out2in.addr;
new_addr0 = ip0->src_address.as_u32;
if (!is_output_feature)
vnet_buffer (b0)->sw_if_index[VLIB_TX] = s0->out2in.fib_index;
sum0 = ip0->checksum;
sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
ip4_header_t, src_address /* changed member */ );
ip0->checksum = ip_csum_fold (sum0);
if (PREDICT_TRUE (proto0 == NAT_PROTOCOL_TCP))
{
if (!vnet_buffer (b0)->ip.reass.is_non_first_fragment)
{
old_port0 = vnet_buffer (b0)->ip.reass.l4_src_port;
new_port0 = udp0->src_port = s0->out2in.port;
sum0 = tcp0->checksum;
sum0 =
ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
dst_address /* changed member */ );
sum0 =
ip_csum_update (sum0, old_port0, new_port0,
ip4_header_t /* cheat */ ,
length /* changed member */ );
mss_clamping (nm->mss_clamping, tcp0, &sum0);
tcp0->checksum = ip_csum_fold (sum0);
}
vlib_increment_simple_counter (is_slow_path ?
&nm->counters.slowpath.in2out.tcp :
&nm->counters.fastpath.in2out.tcp,
thread_index, cntr_sw_if_index0, 1);
}
else
{
if (!vnet_buffer (b0)->ip.reass.is_non_first_fragment)
{
udp0->src_port = s0->out2in.port;
if (PREDICT_FALSE (udp0->checksum))
{
old_port0 = vnet_buffer (b0)->ip.reass.l4_src_port;
new_port0 = udp0->src_port;
sum0 = udp0->checksum;
sum0 =
ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
dst_address /* changed member */ );
sum0 =
ip_csum_update (sum0, old_port0, new_port0,
ip4_header_t /* cheat */ ,
length /* changed member */ );
udp0->checksum = ip_csum_fold (sum0);
}
}
vlib_increment_simple_counter (is_slow_path ?
&nm->counters.slowpath.in2out.udp :
&nm->counters.fastpath.in2out.udp,
thread_index, cntr_sw_if_index0, 1);
}
/* Accounting */
nat44_ei_session_update_counters (
s0, now, vlib_buffer_length_in_chain (vm, b0), thread_index);
/* Per-user LRU list maintenance */
nat44_ei_session_update_lru (nm, s0, thread_index);
trace0:
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
&& (b0->flags & VLIB_BUFFER_IS_TRACED)))
{
nat44_ei_in2out_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
t->is_slow_path = is_slow_path;
t->sw_if_index = rx_sw_if_index0;
t->next_index = next0;
t->session_index = ~0;
if (s0)
t->session_index = s0 - nm->per_thread_data[thread_index].sessions;
}
if (next0 == NAT44_EI_IN2OUT_NEXT_DROP)
{
vlib_increment_simple_counter (
is_slow_path ? &nm->counters.slowpath.in2out.drops :
&nm->counters.fastpath.in2out.drops,
thread_index, cntr_sw_if_index0, 1);
}
n_left_from--;
next[0] = next0;
next++;
}
vlib_buffer_enqueue_to_next (vm, node, from, (u16 *) nexts,
frame->n_vectors);
return frame->n_vectors;
}
static_always_inline uword
nat44_ei_in2out_hairpinning_finish_inline (vlib_main_t *vm,
vlib_node_runtime_t *node,
vlib_frame_t *frame)
{
u32 n_left_from, *from, *to_next;
u32 thread_index = vm->thread_index;
nat44_ei_in2out_next_t next_index;
nat44_ei_main_t *nm = &nat44_ei_main;
int is_hairpinning = 0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
u32 next0;
u32 sw_if_index0;
ip4_header_t *ip0;
udp_header_t *udp0;
tcp_header_t *tcp0;
icmp46_header_t *icmp0;
u32 proto0;
u32 required_thread_index = thread_index;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
next0 = NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_LOOKUP;
ip0 = vlib_buffer_get_current (b0);
udp0 = ip4_next_header (ip0);
tcp0 = (tcp_header_t *) udp0;
icmp0 = (icmp46_header_t *) udp0;
sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
proto0 = ip_proto_to_nat_proto (ip0->protocol);
switch (proto0)
{
case NAT_PROTOCOL_TCP:
// fallthrough
case NAT_PROTOCOL_UDP:
is_hairpinning = nat44_ei_hairpinning (
vm, node, nm, thread_index, b0, ip0, udp0, tcp0, proto0,
0 /* do_trace */, &required_thread_index);
break;
case NAT_PROTOCOL_ICMP:
is_hairpinning = (0 == nat44_ei_icmp_hairpinning (
nm, b0, thread_index, ip0, icmp0,
&required_thread_index));
break;
case NAT_PROTOCOL_OTHER:
// this should never happen
next0 = NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_DROP;
break;
}
if (thread_index != required_thread_index)
{
// but we already did a handoff ...
next0 = NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_DROP;
}
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
(b0->flags & VLIB_BUFFER_IS_TRACED)))
{
nat44_ei_in2out_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
t->sw_if_index = sw_if_index0;
t->next_index = next0;
t->is_hairpinning = is_hairpinning;
}
if (next0 != NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_DROP)
{
vlib_increment_simple_counter (
&nm->counters.fastpath.in2out.other, sw_if_index0,
vm->thread_index, 1);
}
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
return frame->n_vectors;
}
VLIB_NODE_FN (nat44_ei_hairpinning_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
u32 n_left_from, *from, *to_next;
u32 thread_index = vm->thread_index;
nat44_ei_hairpin_next_t next_index;
nat44_ei_main_t *nm = &nat44_ei_main;
vnet_feature_main_t *fm = &feature_main;
u8 arc_index = vnet_feat_arc_ip4_local.feature_arc_index;
vnet_feature_config_main_t *cm = &fm->feature_config_mains[arc_index];
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
u32 next0;
ip4_header_t *ip0;
u32 proto0;
udp_header_t *udp0;
tcp_header_t *tcp0;
u32 sw_if_index0;
u32 required_thread_index = thread_index;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
ip0 = vlib_buffer_get_current (b0);
udp0 = ip4_next_header (ip0);
tcp0 = (tcp_header_t *) udp0;
sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
proto0 = ip_proto_to_nat_proto (ip0->protocol);
int next0_resolved = 0;
if (nat44_ei_hairpinning (vm, node, nm, thread_index, b0, ip0, udp0,
tcp0, proto0, 1, &required_thread_index))
{
next0 = NAT44_EI_HAIRPIN_NEXT_LOOKUP;
next0_resolved = 1;
}
if (thread_index != required_thread_index)
{
vnet_buffer (b0)->snat.required_thread_index =
required_thread_index;
next0 = NAT44_EI_HAIRPIN_NEXT_HANDOFF;
next0_resolved = 1;
}
if (!next0_resolved)
vnet_get_config_data (&cm->config_main, &b0->current_config_index,
&next0, 0);
if (next0 != NAT44_EI_HAIRPIN_NEXT_DROP)
{
vlib_increment_simple_counter (
&nm->counters.hairpinning, vm->thread_index, sw_if_index0, 1);
}
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
return frame->n_vectors;
}
VLIB_NODE_FN (nat44_ei_in2out_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_in2out_node_fn_inline (vm, node, frame, 0, 0);
}
VLIB_NODE_FN (nat44_ei_in2out_output_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_in2out_node_fn_inline (vm, node, frame, 0, 1);
}
VLIB_NODE_FN (nat44_ei_in2out_slowpath_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_in2out_node_fn_inline (vm, node, frame, 1, 0);
}
VLIB_NODE_FN (nat44_ei_in2out_output_slowpath_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_in2out_node_fn_inline (vm, node, frame, 1, 1);
}
VLIB_NODE_FN (nat44_ei_in2out_hairpinning_handoff_ip4_lookup_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_hairpinning_handoff_fn_inline (
vm, node, frame,
nat44_ei_main.in2out_hairpinning_finish_ip4_lookup_node_fq_index);
}
VLIB_NODE_FN (nat44_ei_in2out_hairpinning_handoff_interface_output_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_hairpinning_handoff_fn_inline (
vm, node, frame,
nat44_ei_main.in2out_hairpinning_finish_interface_output_node_fq_index);
}
VLIB_NODE_FN (nat44_ei_in2out_hairpinning_finish_ip4_lookup_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_in2out_hairpinning_finish_inline (vm, node, frame);
}
VLIB_NODE_FN (nat44_ei_in2out_hairpinning_finish_interface_output_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_in2out_hairpinning_finish_inline (vm, node, frame);
}
VLIB_NODE_FN (nat44_ei_hairpinning_handoff_node)
(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
{
return nat44_ei_hairpinning_handoff_fn_inline (
vm, node, frame, nat44_ei_main.hairpinning_fq_index);
}
VLIB_REGISTER_NODE (nat44_ei_in2out_node) = {
.name = "nat44-ei-in2out",
.vector_size = sizeof (u32),
.format_trace = format_nat44_ei_in2out_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(nat44_ei_in2out_error_strings),
.error_strings = nat44_ei_in2out_error_strings,
.runtime_data_bytes = sizeof (nat44_ei_runtime_t),
.n_next_nodes = NAT44_EI_IN2OUT_N_NEXT,
.next_nodes = {
[NAT44_EI_IN2OUT_NEXT_DROP] = "error-drop",
[NAT44_EI_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
[NAT44_EI_IN2OUT_NEXT_SLOW_PATH] = "nat44-ei-in2out-slowpath",
[NAT44_EI_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
[NAT44_EI_IN2OUT_NEXT_HAIRPINNING_HANDOFF] = "nat44-ei-in2out-hairpinning-handoff-ip4-lookup",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_output_node) = {
.name = "nat44-ei-in2out-output",
.vector_size = sizeof (u32),
.format_trace = format_nat44_ei_in2out_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(nat44_ei_in2out_error_strings),
.error_strings = nat44_ei_in2out_error_strings,
.runtime_data_bytes = sizeof (nat44_ei_runtime_t),
.n_next_nodes = NAT44_EI_IN2OUT_N_NEXT,
.next_nodes = {
[NAT44_EI_IN2OUT_NEXT_DROP] = "error-drop",
[NAT44_EI_IN2OUT_NEXT_LOOKUP] = "interface-output",
[NAT44_EI_IN2OUT_NEXT_SLOW_PATH] = "nat44-ei-in2out-output-slowpath",
[NAT44_EI_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
[NAT44_EI_IN2OUT_NEXT_HAIRPINNING_HANDOFF] = "nat44-ei-in2out-hairpinning-handoff-interface-output",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_slowpath_node) = {
.name = "nat44-ei-in2out-slowpath",
.vector_size = sizeof (u32),
.format_trace = format_nat44_ei_in2out_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(nat44_ei_in2out_error_strings),
.error_strings = nat44_ei_in2out_error_strings,
.runtime_data_bytes = sizeof (nat44_ei_runtime_t),
.n_next_nodes = NAT44_EI_IN2OUT_N_NEXT,
.next_nodes = {
[NAT44_EI_IN2OUT_NEXT_DROP] = "error-drop",
[NAT44_EI_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
[NAT44_EI_IN2OUT_NEXT_SLOW_PATH] = "nat44-ei-in2out-slowpath",
[NAT44_EI_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
[NAT44_EI_IN2OUT_NEXT_HAIRPINNING_HANDOFF] = "nat44-ei-in2out-hairpinning-handoff-ip4-lookup",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_output_slowpath_node) = {
.name = "nat44-ei-in2out-output-slowpath",
.vector_size = sizeof (u32),
.format_trace = format_nat44_ei_in2out_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(nat44_ei_in2out_error_strings),
.error_strings = nat44_ei_in2out_error_strings,
.runtime_data_bytes = sizeof (nat44_ei_runtime_t),
.n_next_nodes = NAT44_EI_IN2OUT_N_NEXT,
.next_nodes = {
[NAT44_EI_IN2OUT_NEXT_DROP] = "error-drop",
[NAT44_EI_IN2OUT_NEXT_LOOKUP] = "interface-output",
[NAT44_EI_IN2OUT_NEXT_SLOW_PATH] = "nat44-ei-in2out-output-slowpath",
[NAT44_EI_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
[NAT44_EI_IN2OUT_NEXT_HAIRPINNING_HANDOFF] = "nat44-ei-in2out-hairpinning-handoff-interface-output",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_hairpinning_handoff_ip4_lookup_node) = {
.name = "nat44-ei-in2out-hairpinning-handoff-ip4-lookup",
.vector_size = sizeof (u32),
.n_errors = ARRAY_LEN(nat44_ei_hairpinning_handoff_error_strings),
.error_strings = nat44_ei_hairpinning_handoff_error_strings,
.format_trace = format_nat44_ei_hairpinning_handoff_trace,
.n_next_nodes = 1,
.next_nodes = {
[0] = "error-drop",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_hairpinning_handoff_interface_output_node) = {
.name = "nat44-ei-in2out-hairpinning-handoff-interface-output",
.vector_size = sizeof (u32),
.n_errors = ARRAY_LEN(nat44_ei_hairpinning_handoff_error_strings),
.error_strings = nat44_ei_hairpinning_handoff_error_strings,
.format_trace = format_nat44_ei_hairpinning_handoff_trace,
.n_next_nodes = 1,
.next_nodes = {
[0] = "error-drop",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_hairpinning_finish_ip4_lookup_node) = {
.name = "nat44-ei-in2out-hairpinning-finish-ip4-lookup",
.vector_size = sizeof (u32),
.format_trace = format_nat44_ei_in2out_fast_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(nat44_ei_in2out_error_strings),
.error_strings = nat44_ei_in2out_error_strings,
.runtime_data_bytes = sizeof (nat44_ei_runtime_t),
.n_next_nodes = NAT44_EI_IN2OUT_HAIRPINNING_FINISH_N_NEXT,
.next_nodes = {
[NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_DROP] = "error-drop",
[NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_LOOKUP] = "ip4-lookup",
},
};
VLIB_REGISTER_NODE (nat44_ei_in2out_hairpinning_finish_interface_output_node) = {
.name = "nat44-ei-in2out-hairpinning-finish-interface-output",
.vector_size = sizeof (u32),
.format_trace = format_nat44_ei_in2out_fast_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(nat44_ei_in2out_error_strings),
.error_strings = nat44_ei_in2out_error_strings,
.runtime_data_bytes = sizeof (nat44_ei_runtime_t),
.n_next_nodes = NAT44_EI_IN2OUT_HAIRPINNING_FINISH_N_NEXT,
.next_nodes = {
[NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_DROP] = "error-drop",
[NAT44_EI_IN2OUT_HAIRPINNING_FINISH_NEXT_LOOKUP] = "interface-output",
},
};
VLIB_REGISTER_NODE (nat44_ei_hairpinning_handoff_node) = {
.name = "nat44-ei-hairpinning-handoff",
.vector_size = sizeof (u32),
.n_errors = ARRAY_LEN(nat44_ei_hairpinning_handoff_error_strings),
.error_strings = nat44_ei_hairpinning_handoff_error_strings,
.format_trace = format_nat44_ei_hairpinning_handoff_trace,
.n_next_nodes = 1,
.next_nodes = {
[0] = "error-drop",
},
};
VLIB_REGISTER_NODE (nat44_ei_hairpinning_node) = {
.name = "nat44-ei-hairpinning",
.vector_size = sizeof (u32),
.type = VLIB_NODE_TYPE_INTERNAL,
.format_trace = format_nat44_ei_hairpin_trace,
.n_next_nodes = NAT44_EI_HAIRPIN_N_NEXT,
.next_nodes = {
[NAT44_EI_HAIRPIN_NEXT_DROP] = "error-drop",
[NAT44_EI_HAIRPIN_NEXT_LOOKUP] = "ip4-lookup",
[NAT44_EI_HAIRPIN_NEXT_HANDOFF] = "nat44-ei-hairpinning-handoff",
},
};
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
| apache-2.0 |
rogerthat-platform/rogerthat-backend | src/rogerthat/pages/legal/assets/nl/version_terms-and-conditions_20180524.html | 66556 | {% extends "version_base.html" %}
{% block content %}
<style type="text/css">
.lst-kix_qxs0kkqujc62-2>li:before {
content: "\0025a0 "
}
.lst-kix_qxs0kkqujc62-1>li:before {
content: "\0025cb "
}
.lst-kix_qxs0kkqujc62-3>li:before {
content: "\0025cf "
}
.lst-kix_qxs0kkqujc62-0>li:before {
content: "\0025cf "
}
ul.lst-kix_qxs0kkqujc62-0 {
list-style-type: none
}
.lst-kix_qxs0kkqujc62-4>li:before {
content: "\0025cb "
}
ul.lst-kix_qxs0kkqujc62-1 {
list-style-type: none
}
ul.lst-kix_qxs0kkqujc62-2 {
list-style-type: none
}
ul.lst-kix_qxs0kkqujc62-3 {
list-style-type: none
}
.lst-kix_qxs0kkqujc62-6>li:before {
content: "\0025cf "
}
.lst-kix_qxs0kkqujc62-5>li:before {
content: "\0025a0 "
}
.lst-kix_qxs0kkqujc62-7>li:before {
content: "\0025cb "
}
.lst-kix_qxs0kkqujc62-8>li:before {
content: "\0025a0 "
}
ul.lst-kix_qxs0kkqujc62-4 {
list-style-type: none
}
ul.lst-kix_qxs0kkqujc62-5 {
list-style-type: none
}
ul.lst-kix_qxs0kkqujc62-6 {
list-style-type: none
}
ul.lst-kix_qxs0kkqujc62-7 {
list-style-type: none
}
ul.lst-kix_qxs0kkqujc62-8 {
list-style-type: none
}
ol {
margin: 0;
padding: 0
}
table td, table th {
padding: 0
}
.c1 {
color: #000000;
font-weight: 400;
text-decoration: none;
vertical-align: baseline;
font-size: 11pt;
font-family: "Arial";
font-style: normal
}
.c4 {
color: #000000;
font-weight: 400;
text-decoration: none;
vertical-align: baseline;
font-size: 26pt;
font-family: "Arial";
font-style: normal
}
.c9 {
padding-top: 20pt;
padding-bottom: 6pt;
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
.c2 {
padding-top: 0pt;
padding-bottom: 0pt;
line-height: 1.15;
orphans: 2;
widows: 2;
text-align: left
}
.c5 {
color: #000000;
font-weight: 400;
text-decoration: none;
vertical-align: baseline;
font-family: "Arial";
font-style: normal
}
.c16 {
padding-top: 0pt;
padding-bottom: 10pt;
line-height: 1.15;
orphans: 2;
widows: 2;
text-align: left
}
.c0 {
padding-top: 10pt;
padding-bottom: 10pt;
line-height: 1.15;
orphans: 2;
widows: 2;
text-align: left
}
.c12 {
padding-top: 20pt;
padding-bottom: 6pt;
line-height: 1.15;
page-break-after: avoid;
text-align: left
}
.c15 {
padding-top: 0pt;
padding-bottom: 3pt;
line-height: 1.15;
page-break-after: avoid;
text-align: left
}
.c11 {
padding-top: 0pt;
padding-bottom: 0pt;
line-height: 1.0;
text-align: left
}
.c14 {
background-color: #ffffff;
max-width: 468pt;
padding: 72pt 72pt 72pt 72pt
}
.c10 {
margin-left: 36pt;
padding-left: 0pt
}
.c13 {
padding: 0;
margin: 0
}
.c7 {
border: 1px solid black;
margin: 5px
}
.c6 {
height: 11pt
}
.c3 {
font-size: 20pt
}
.c8 {
font-style: italic
}
.title {
padding-top: 0pt;
color: #000000;
font-size: 26pt;
padding-bottom: 3pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
.subtitle {
padding-top: 0pt;
color: #666666;
font-size: 15pt;
padding-bottom: 16pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
li {
color: #000000;
font-size: 11pt;
font-family: "Arial"
}
p {
margin: 0;
color: #000000;
font-size: 11pt;
font-family: "Arial"
}
h1 {
padding-top: 20pt;
color: #000000;
font-size: 20pt;
padding-bottom: 6pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
h2 {
padding-top: 18pt;
color: #000000;
font-size: 16pt;
padding-bottom: 6pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
h3 {
padding-top: 16pt;
color: #434343;
font-size: 14pt;
padding-bottom: 4pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
h4 {
padding-top: 14pt;
color: #666666;
font-size: 12pt;
padding-bottom: 4pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
h5 {
padding-top: 12pt;
color: #666666;
font-size: 11pt;
padding-bottom: 4pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
orphans: 2;
widows: 2;
text-align: left
}
h6 {
padding-top: 12pt;
color: #666666;
font-size: 11pt;
padding-bottom: 4pt;
font-family: "Arial";
line-height: 1.15;
page-break-after: avoid;
font-style: italic;
orphans: 2;
widows: 2;
text-align: left
}
</style>
<p class="c2">
<span>Welkom bij de Rogerthat-websites (inclusief
<a href="https://rogerth.at">https://rogerth.at</a> en <a href="http://www.rogerthat.net">http://www.rogerthat.net</a> en sites die verwijzen
naar een van voornoemde sites) (de "Website") of Rogerthat
mobiele applicatie (inclusief Onze Stad App en Rogerthat) (de
"App"). De Website en de App worden u ter beschikking
gesteld onder voorbehoud van uw onvoorwaardelijke acceptatie van alle
voorwaarden en bepalingen waarnaar verwezen wordt op de Website of
via de App, en van deze Algemene Voorwaarden (met inbegrip van (maar
niet beperkt tot) de </span><span><a href="/legal?doc=privacy-policy&l=NL">Privacyverklaring</a></span><span class="c1">), zoals
van tijd tot tijd kan worden gewijzigd of aangevuld zoals hierin
uiteengezet (gezamenlijk "de Overeenkomst"). Lees deze
Overeenkomst aandachtig door, aangezien deze de juridisch bindende
bepalingen en voorwaarden bevat voor uw gebruik van de Website, de
App en de diensten, inhoud, applicaties en widgets die beschikbaar
zijn op of via de Website of die anderszins worden aangeboden door
Mobicage NV, inclusief door middel van de App (gezamenlijk de
"Diensten"). Voor de toepassing van de Overeenkomst
bevatten verwijzingen naar de Website verwijzingen naar de App en
verwijzingen naar Diensten omvatten diensten die door Mobicage NV ter
beschikking worden gesteld, ongeacht of dit via de Website, de App of
anderszins gebeurt.</span>
</p>
<p class="c2">
<span class="c1">De termen "Mobicage",
"wij", "ons", "onze" verwijzen naar
Mobicage NV, een naamloze vennootschap opgericht naar Belgisch recht,
gevestigd aan de Antwerpse Steenweg 19, 9080 Lochristi, België,
BTW-BE-0835.560 0,572. De term "u" verwijst naar de
gebruiker die de Website bezoekt en / of zich registreert op de
Website en / of de Diensten bezoekt of gebruikt.</span>
</p>
<h1 class="c12" id="h.580z13catue">
<span class="c3 c5">1. Uw onvoorwaardelijke toestemming</span>
</h1>
<p class="c2">
<span class="c1">Door de Website of de Diensten te bezoeken, te
openen of te gebruiken, of door u te registreren op de Website, gaat
u er onvoorwaardelijk mee akkoord gebonden te zijn aan de
Overeenkomst.</span>
</p>
<p class="c2">
<span class="c1">Als u niet akkoord gaat met (een deel van) de
Overeenkomst, gelieve dan noch de Website noch de Diensten te
gebruiken.</span>
</p>
<p class="c2">
<span class="c1">Zorg ervoor dat u regelmatig naar deze pagina
terugkeert om de meest recente versie van de Overeenkomst te
bekijken. Wij behouden ons het recht voor om te allen tijde, naar
eigen goeddunken, de Overeenkomst te wijzigen of anderszins te
wijzigen, en uw verder gebruik van de Website en / of Diensten
betekent dat u akkoord gaat met de bijgewerkte of gewijzigde
Overeenkomst.</span>
</p>
<h1 class="c9" id="h.7bbn2kklco8v">
<span class="c5 c3">2. Uw lidmaatschap en registratie</span>
</h1>
<p class="c2">
<span class="c1">U mag op de Website surfen en de inhoud ervan
bekijken zonder u te registreren, maar als voorwaarde om bepaalde
aspecten van de Diensten te gebruiken, moet u zich bij Mobicage
registreren.</span>
</p>
<p class="c2">
<span class="c1">Door u te registreren op onze Website en als
voorwaarde om de Diensten te gebruiken, garandeert u dat (i) u
actuele, volledige, juiste en waarachtige informatie verstrekt, (ii)
als u een Website-account hebt, u uw accountgegevens zult beschermen
en zal toezicht houden op het gebruik van uw account door iemand
anders dan uzelf, en (iii) dat u wettelijk bevoegd bent om zich voor
een account te registreren en de Diensten te gebruiken. U stemt ermee
in om uw contactgegevens correct en actueel te houden.</span>
</p>
<p class="c2">
<span class="c1">U zal in geen geval:</span>
</p>
<ul class="c13 lst-kix_qxs0kkqujc62-0 start">
<li class="c2 c10"><span class="c1">valse persoonlijke
gegevens verstrekken, een account maken namens iemand anders dan
uzelf, of zich voordoen als een andere persoon bij het maken van een
account;</span></li>
<li class="c2 c10"><span class="c1">de persoonlijke
gegevens van een persoon (bijvoorbeeld naam, foto), ID of wachtwoord
gebruiken zonder toestemming van die persoon, of de Website of de
Diensten gebruiken terwijl u zich voordoet als een andere persoon;</span></li>
</ul>
<p class="c2">
<span class="c1">Onverminderd eventuele andere rechtsmiddelen
of sancties die ons ter beschikking staan, staat het Mobicage vrij om
uw account te allen tijde naar eigen goeddunken te annuleren of op te
schorten, zonder rechtvaardiging of voorafgaande waarschuwing en
zonder aansprakelijkheid van Mobicage.</span>
</p>
<h1 class="c9" id="h.gdh2btlszv2w">
<span class="c5 c3">3. Beveiliging van uw Account</span>
</h1>
<p class="c2">
<span class="c1">U bent zelf verantwoordelijk voor de gevolgen
van het gebruik van de Website en de Diensten.</span>
</p>
<p class="c2">
<span class="c1">U bent zelf verantwoordelijk voor het
beschermen van uw accountinformatie (inclusief eventuele wachtwoorden
of toegangscodes die u gebruikt voor toegang tot of gebruik van de
Diensten) en voor alle activiteiten of acties van iedereen die uw
account gebruikt. U deelt uw wachtwoorden of toegangscodes niet, laat
niemand anders zonder toezicht uw account openen of iets anders doen
dat de veiligheid van uw account in gevaar kan brengen.</span>
</p>
<p class="c16">
<span class="c1">U moet Mobicage onmiddellijk op de hoogte
stellen van een inbreuk op de beveiliging of ongeoorloofd gebruik van
uw account. Hoewel Mobicage niet aansprakelijk is voor de schade die
u of iemand anders veroorzaakt door ongeoorloofd gebruik van uw
account, bent u aansprakelijk voor alle schade en verliezen die
Mobicage of derden lijden als gevolg van dergelijk ongeoorloofd
gebruik en dient u Mobicage volledig te vrijwaren in dit verband.</span>
</p>
<p class="c0">
<span class="c3">4. Uw gebruik van de website en de diensten</span>
</p>
<p class="c2">
<span class="c1">Voor zover u deze Overeenkomst naleeft
verleent Mobicage u hierbij toestemming om de Website en de Diensten
te gebruiken, op voorwaarde dat:</span>
</p>
<p class="c2">
<span class="c1">- u de Website en de Diensten uitsluitend
gebruikt voor uw persoonlijk en niet-commercieel gebruik, behalve
zoals uitdrukkelijk anders toegestaan ​​door Mobicage;</span>
</p>
<p class="c2">
<span class="c1">- u de Website of de Diensten niet op een
onregelmatige manier gebruikt of voor onwettige doeleinden;</span>
</p>
<p class="c2">
<span class="c1">- u te allen tijde de Website en de Diensten
gebruikt in strikte overeenstemming met de Overeenkomst en de
toepasselijke wetgeving;</span>
</p>
<p class="c2">
<span class="c1">- u de Website en de Diensten gebruikt als een
normale, zorgvuldige en redelijke persoon;</span>
</p>
<p class="c2">
<span class="c1">- u geen toegang krijgt tot enige inhoud of
informatie van de Website, noch enige inhoud of informatie van de
Website kopieert, met behulp van een robot, spider, schraper of
andere geautomatiseerde middelen of een handmatig proces voor welk
doel dan ook zonder onze uitdrukkelijke schriftelijke toestemming;</span>
</p>
<p class="c2">
<span class="c1">- u geen actie onderneemt die een onredelijke
of onevenredig grote belasting van onze infrastructuur oplegt of kan
opleggen, en u geen activiteiten onderneemt die onze servers en
netwerken kunnen verstoren;</span>
</p>
<p class="c2">
<span class="c1">- u geen schadelijke inhoud publiceert of
linkt die bedoeld is om de browser of computer van een andere
gebruiker te beschadigen of te verstoren of om de privacy van een
gebruiker in gevaar te brengen;</span>
</p>
<p class="c2">
<span class="c1">- u geen seriële accounts aanmaakt voor
storende of beledigende doeleinden. Het aanmaken van massa-rekeningen
voor de hierboven genoemde doeleinden, of resulterend in de hierboven
genoemde doeleinden (of enige andere schending van de Overeenkomst)
kan leiden tot opschorting van alle gerelateerde accounts;</span>
</p>
<p class="c2">
<span class="c1">- u de Diensten niet gebruikt voor spamming
(dat wil zeggen het verzenden van ongevraagde bulkberichten). Wat
spamming inhoudt, wordt naar eigen goeddunken door Mobicage bepaald;</span>
</p>
<p class="c2">
<span class="c1">- u Mobicage of de account van andere
gebruikers niet hackt;</span>
</p>
<p class="c2">
<span>- u zich niet bezighoudt met het </span><span class="c8">squatten
</span><span class="c1">van gebruikersnamen (dwz de registratie ter
kwader trouw van een andere wettelijke naam dan die van u, of van een
naam die anders vaak wordt gebruikt om een ​​persoon
(bijv. bijnamen) te identificeren, anders dan uzelf, als
gebruikersnaam). Mobicage bepaalt naar eigen goeddunken welke acties
volgens haar het squatten van gebruikers uitmaakt;</span>
</p>
<p class="c2">
<span>- u niet </span><span class="c8">deep-linkt </span><span
class="c1">naar enig deel van de website voor welk doel dan
ook zonder onze uitdrukkelijke schriftelijke toestemming, noch op
enige wijze enig deel van de website opneemt in een andere website
zonder onze voorafgaande schriftelijke toestemming;</span>
</p>
<p class="c2">
<span class="c1">- u geen enkel deel van de Website of Diensten
in welk medium dan ook dupliceert, overdraagt, vrijgeeft, kopieert of
verspreidt, zonder voorafgaande schriftelijke toestemming van
Mobicage;</span>
</p>
<p class="c2">
<span class="c1">- voor zover dit verbod is toegestaan
​​volgens de toepasselijke wetgeving en tenzij
uitdrukkelijk anders is overeengekomen met Mobicage, zult u de
software of het communicatieprotocol dat ten grondslag ligt aan de
Website of Diensten niet ‘reverse engineeren’, noch
software schrijven die het communicatieprotocol of de interfaces met
de servers imiteert (of toestaat te imiteren), noch zult u afgeleide
werken van enig deel van de Website, de Diensten en / of de
onderliggende software of communicatieprotocol vertalen, wijzigen,
decompileren, disassembleren of anderszins creëren;</span>
</p>
<p class="c2">
<span class="c1">Accounts die betrokken zijn bij een van deze
acties (of enige andere schending van de Overeenkomst) kunnen worden
onderzocht op misbruik. Onverminderd eventuele andere rechtsmiddelen
of sancties die ons ter beschikking staan, staat het Mobicage vrij om
uw account te allen tijde naar eigen goeddunken te annuleren of op te
schorten, zonder rechtvaardiging of voorafgaande waarschuwing en
zonder aansprakelijkheid van Mobicage.</span>
</p>
<p class="c2">
<span class="c1">De Diensten die Mobicage aanbiedt, evolueren
voortdurend en de vorm en aard van de Diensten die Mobicage aanbiedt,
kan van tijd tot tijd zonder voorafgaande kennisgeving worden
gewijzigd. Bovendien kan Mobicage de Website beëindigen of
(permanent of tijdelijk) de Diensten of een functie binnen de
Diensten aan u of aan gebruikers over het algemeen zonder
voorafgaande kennisgeving, naar eigen goeddunken en zonder
aansprakelijkheid, beëindigen. Mobicage behoudt zich ook het
recht voor om op elk moment en zonder voorafgaande kennisgeving naar
eigen goeddunken gebruiks- en opslaglimieten op te leggen.</span>
</p>
<p class="c2">
<span class="c1">De Diensten van Mobicage zijn gratis voor
zover uitdrukkelijk aangegeven op de Website en onderworpen aan de
beperkingen die op de Website kunnen worden vermeld of anderszins
door Mobicage worden gemeld. Servicegebruikers zijn onderhevig aan de
"Voorwaarden voor servicegebruikers" die hieronder worden
vermeld, naast de andere bepalingen en voorwaarden van de
Overeenkomst.</span>
</p>
<p class="c0">
<span class="c5 c3">5. Uw Inhoud</span>
</p>
<p class="c2">
<span class="c1">Voor de doeleinden van de Overeenkomst
betekent "Inhoud" alle informatie, tekst, grafische
afbeeldingen, foto's of ander materiaal, inclusief eventuele
feedback, opmerkingen, suggesties of ideeën in dergelijk
materiaal, toegevoegd, gemaakt, geüpload, ingediend,
gedistribueerd, gepost of anders beschikbaar gesteld op de Website of
anderszins aan Mobicage, door gebruikers van de Website en de
Diensten, inclusief uzelf.</span>
</p>
<p class="c2">
<span class="c1">Mobicage neemt geen verantwoordelijkheid en
aanvaardt geen aansprakelijkheid met betrekking tot door u geleverde
Inhoud. Als u niet akkoord gaat met de gerelateerde bepalingen en
voorwaarden die in de Overeenkomst zijn uiteengezet, zal u ons geen
Inhoud verstrekken. U bent als enige verantwoordelijk voor de Inhoud
die u verstrekt en voor het verkrijgen van de nodige autorisaties om
de Inhoud beschikbaar te maken via de Website of anderszins aan
Mobicage en om dergelijke Inhoud te gebruiken door Mobicage zoals
hierin uiteengezet. U bent als enige verantwoordelijk voor de
gevolgen van het gebruik van uw inhoud door Mobicage, andere
gebruikers en onze externe partners. U dient ervoor te zorgen dat
alle Inhoud die u via de Diensten plaatst of verzendt of anderszins
beschikbaar maakt, strikt voldoet aan de voorwaarden van de
Overeenkomst. Geef alleen inhoud weer die u kunt delen met anderen,
want uw inhoud kan door anderen worden bekeken. U stemt ermee in om
inhoud die vertrouwelijk en / of eigendom is niet te delen zonder de
vereiste autorisaties te hebben verkregen en u erkent en gaat ermee
akkoord dat de door u verstrekte inhoud als niet-vertrouwelijk wordt
beschouwd.</span>
</p>
<p class="c2">
<span class="c1">U garandeert dat u de nodige autorisaties hebt
verkregen om enige Inhoud beschikbaar te maken en deze door ons te
laten gebruiken voor de doeleinden die hierin zijn uiteengezet. U
garandeert ook dat de Inhoud die u beschikbaar stelt, in
overeenstemming is met de vereisten uiteengezet in de Overeenkomst,
en u erkent en gaat ermee akkoord dat wij niet verplicht zijn om de
naleving van de Inhoud die u ter beschikking stelt te controleren.
Wij kunnen niet verantwoordelijk of aansprakelijk jegens u worden
gehouden, inclusief met betrekking tot aanspraken van derden tegen u,
op basis van door u ter beschikking gestelde Inhoud. U stemt ermee in
ons onmiddellijk op de hoogte te stellen (<a href="mailto:[email protected]">[email protected]</a>) nadat u
zich ervan bewust bent dat enige van de hierin vermelde garanties
niet of niet langer waar zijn.</span>
</p>
<p class="c2">
<span class="c1">Het is u in elk geval (zonder limitatief te
zijn) verboden om op de Website of op enige andere wijze via de
Diensten inhoud ter beschikking te stellen die (i) onwettig,
bedreigend, intimiderend, smadelijk, lasterlijk, lasterlijk,
beledigend, hatelijk, beledigend, obsceen of pornografisch materiaal
bevat of ander materiaal of inhoud die een persoon of entiteit in
verlegenheid kan brengen of die publiciteits- en / of privacyrechten
schendt of die anderszins toepasselijke wetgeving zou kunnen
schenden; (ii) inbreuk maakt op auteursrechten, databaserechten,
handelsmerken, octrooirechten of andere eigendomsrechten van derden;
we vragen dat u alsjeblieft naar bronnen verwijst of bronnen citeert
en zich onthoudt van plagiaat; (iii) die een instructie vormt,
aanmoedigt of verstrekt voor een strafbaar feit, de rechten van een
partij schendt of anderszins aansprakelijkheid zou creëren of
een lokale, nationale of internationale wet zou schenden; (iv)
privé-informatie van een derde partij, waaronder, maar niet
beperkt tot, achternaam, adressen, telefoonnummers, e-mailadressen,
sofinummers en creditcardnummers; bevat; of (v) virussen, beschadigde
gegevens of andere schadelijke, storende of destructieve bestanden
bevat, inclusief door het plaatsen van Inhoud die pop-ups veroorzaakt
of pogingen om software te installeren, of anderszins een impact
heeft op de Website, de Diensten en / of haar gebruikers met
kwaadaardige code.</span>
</p>
<p class="c2">
<span class="c1">Mobicage aanvaardt geen verantwoordelijkheid
en aanvaardt geen aansprakelijkheid voor enige Inhoud die door u of
een derde partij beschikbaar wordt gesteld of voor enig verlies of
beschadiging daarvan, noch aanvaardt Mobicage enige aansprakelijkheid
voor fouten, laster, laster, smaad, omissies, leugens, obsceniteit,
pornografie of godslastering die je in de Inhoud kunt tegenkomen.
Mobicage biedt geen garanties of verklaringen met betrekking tot de
geldigheid, volledigheid, waarachtigheid, nauwkeurigheid,
betrouwbaarheid of juridische status van enige Inhoud. Uw gebruik van
de Website en de Diensten is op eigen risico. Als aanbieder van
interactieve diensten fungeert Mobicage alleen als tussenpersoon, een
repository van de inhoud, en is niet aansprakelijk voor verklaringen,
afbeeldingen of inhoud die door gebruikers worden verstrekt op een
openbaar forum of ander interactief gebied. Hoewel Mobicage niet
verplicht is om de Inhoud die wordt gepost op of gedistribueerd via
een interactief gebied te screenen, te bewerken of te controleren,
behoudt Mobicage zich het recht voor en heeft het absolute discretie
om content zonder enige kennisgeving te verwijderen, te screenen of
te bewerken, geplaatst op de Website of op andere wijze via de
Diensten op elk moment en om welke reden dan ook, en u bent zelf
verantwoordelijk voor het maken van back-upkopieën van Inhoud
die u plaatst of opslaat op de Website of anders via de Diensten voor
uw eigen rekening en kosten.</span>
</p>
<p class="c2">
<span class="c1">Alle gebruikersadviezen die op de Website of
anderszins via de Diensten worden ingediend, vertegenwoordigen de
mening van de individuele gebruikers en vertegenwoordigen niet, noch
kunnen ze worden beschouwd als vertegenwoordiging van, Mobicage's
mening, aanbeveling of goedkeuring.</span>
</p>
<p class="c2">
<span class="c1">Hoewel we van u verwachten dat u voldoende
aandacht besteedt aan de privacy van anderen en aan onderwerpen die
als aanstootgevend of opruiend kunnen worden beschouwd (bijvoorbeeld
politiek, religie), zal Mobicage naar eigen goeddunken bepalen welke
Inhoud geschikt is met betrekking tot de Website en de Diensten.
Onverminderd eventuele andere rechtsmiddelen en sancties die ons ter
beschikking staan, behoudt Mobicage zich het recht voor om te allen
tijde, naar eigen goeddunken, zonder enige rechtvaardiging en zonder
aansprakelijkheid te geven, om:</span>
</p>
<p class="c2">
<span class="c1">(i) Inhoud te verwijderen, op te schorten, te
blokkeren, te bewerken of te wijzigen, zonder kennisgeving aan u;</span>
</p>
<p class="c2">
<span class="c1">(ii) zich toegang te verschaffen tot de
Inhoud, deze te lezen, te behouden, te kopiëren en openbaar te
maken zoals Mobicage nodig acht om (i) te voldoen aan toepasselijke
wetten, regelgeving, juridische procedures, overheidsverzoeken,
rechtbanken of rechtsorde, (ii) de Overeenkomst te handhaven,
inclusief onderzoek van mogelijke schendingen daarvan, (iii) het
detecteren, voorkomen of anderszins aanpakken van fraude, beveiliging
of technische problemen, (iv) reageren op verzoeken om
gebruikersondersteuning, of (v) de rechten en eigendommen van
Mobicage of een derde te beschermen en de beveiliging van de Website,
de Diensten en hun gebruikers te garanderen.</span>
</p>
<p class="c0">
<span class="c5 c3">6. Gebruik van Inhoud door Mobicage</span>
</p>
<p class="c2">
<span class="c1">Door Inhoud op de Website of via de Diensten
beschikbaar te stellen, verleent u Mobicage een wereldwijde,
niet-exclusieve, onherroepelijke, royaltyvrije, eeuwigdurende,
sublicentieerbare, overdraagbare en toewijsbare licentie om (i) de
Inhoud te verwerken, aan te passen, te verzenden, te distribueren,
(publiekelijk) weer te geven en uit te voeren via de Website
(inclusief zonder beperking voor het promoten en distribueren van
onze Diensten), en (ii) de naam te gebruiken die u in verband met
dergelijke Inhoud indient.</span>
</p>
<p class="c2">
<span class="c1">U erkent en gaat ermee akkoord dat Mobicage uw
Inhoud vrij mag aanpassen om deze via computernetwerken en in
verschillende media te verzenden, weer te geven of te verspreiden
en/of wijzigingen aan te brengen aan uw Inhoud die nodig zijn om die
Inhoud aan te passen aan eventuele vereisten en beperkingen van alle
netwerken, apparaten, diensten of media, of anderszins.</span>
</p>
<p class="c2">
<span>U erkent verder dat, wanneer u uw Inhoud verwijdert, deze
zal worden verwijderd van de Website en de Diensten, maar dat alle
verwijderde Inhoud kan blijven bestaan ​​in
reservekopieën op of onder de controle van Mobicage of met
gebruikers die eerder uw Inhoud hebben bezocht of gedownload .
Mobicage zal uw Inhoud echter alleen delen in overeenstemming met het
</span><span><a href="/legal?doc=privacy-policy&l=NL">Privacybeleid</a> </span><span
class="c1">van Mobicage dat van tijd tot tijd van kracht is.</span>
</p>
<p class="c0">
<span class="c3">7. Intellectuele eigendomsrechten</span>
</p>
<p class="c2">
<span class="c1">De Website, de Diensten en de informatie die
deze bevatten, worden kosteloos aan u verstrekt, uitsluitend voor uw
persoonlijk en niet-commercieel gebruik (behalve waar Mobicage
uitdrukkelijk anders toestaat). Alle informatie die door Mobicage op
de Website wordt aangeboden, wordt uitsluitend ter informatie
verstrekt.</span>
</p>
<p class="c2">
<span class="c1">Alle rechten, titels en belangen in de Website
en de Diensten, inclusief alle intellectuele en industriële
eigendomsrechten (bijvoorbeeld auteursrechten en databaserechten
(niet-limitatieve lijst)), zijn en blijven exclusief eigendom van
Mobicage.</span>
</p>
<p class="c2">
<span class="c1">Alle rechten, titels en belangen met
betrekking tot de inhoud van de Website en de Diensten (met
uitzondering van de Inhoud die valt onder Afdeling 6 (Gebruik van de
Inhoud van Mobicage)), inclusief intellectuele en industriële
eigendomsrechten, zijn en blijven de exclusieve eigendom van Mobicage
of haar licentiegevers (indien van toepassing).</span>
</p>
<p class="c2">
<span class="c1">Mobicage bezit alle rechten, aanspraken en
belangen, inclusief alle intellectuele en industriële
eigendomsrechten, in de handelsmerken, handelsnamen, bedrijfsnaam,
dienstmerken, logo's, en domeinnamen van Mobicage (en haar
producten en diensten).</span>
</p>
<p class="c2">
<span class="c1">Niets in de Overeenkomst mag worden
geïnterpreteerd als, noch zal uw gebruik van de Website of de
Diensten leiden tot, expliciet of impliciet, enige licentie of recht
op de Website, de Diensten of de inhoud ervan (anders dan de Inhoud
die wordt beheerd door Sectie 6 (gebruik van de Inhoud door
Mobicage), met uitzondering van de beperkte gebruikersrechten die
hierin worden uiteengezet. De Website, de Diensten en hun inhoud
mogen op geen enkele manier worden gereproduceerd of gedistribueerd,
geheel of gedeeltelijk, zonder de uitdrukkelijke voorafgaande
toestemming van Mobicage, behalve dat u dergelijk materiaal mag
reproduceren voor uw puur persoonlijk, niet-commercieel gebruik , op
voorwaarde dat u dergelijke materialen op geen enkele manier wijzigt,
dat u verwijst naar de Website als de bron van het materiaal en dat u
alle mededelingen op alle kopieën van het materiaal intact
houdt.</span>
</p>
<p class="c2">
<span class="c1">Alle software die beschikbaar wordt gemaakt om
te downloaden via de Website (de "Software") is het
auteursrechtelijk beschermde werk van Mobicage of haar
licentiegevers. Uw gebruik van dergelijke Software wordt beheerst
door de voorwaarden van de licentieovereenkomst voor eindgebruikers,
indien van toepassing, die wordt meegeleverd met of wordt meegeleverd
met de Software (de "Licentieovereenkomst"). U mag geen
Software installeren of gebruiken die een Licentieovereenkomst bevat,
tenzij u voor het eerst akkoord gaat met de voorwaarden van de
Licentieovereenkomst. Voor elke software die beschikbaar is voor
download op de website en die niet vergezeld gaat van een
licentieovereenkomst, verlenen wij u hierbij een beperkte,
persoonlijke, niet-exclusieve, niet-overdraagbare, niet-toewijsbare,
niet-sublicentieerbare, herroepbare licentie om deze software te
gebruiken voor zover noodzakelijk voor het bekijken en anderszins
gebruiken van de Website en de Diensten in overeenstemming met de
Overeenkomst. Met uitzondering van de beperkte gebruikersrechten die
hierin uitdrukkelijk worden vermeld, krijgt u geen rechten op de
Software. Houd er rekening mee dat alle software, inclusief maar niet
beperkt tot alle HTML-code en Active X-besturingselementen op de
Website, eigendom is van Mobicage of haar licentiegevers en mogelijk
wordt beschermd door intellectuele eigendomsrechten. Elke reproductie
of herdistributie van de Software is uitdrukkelijk verboden en kan
leiden tot ernstige civiele en strafrechtelijke sancties, inclusief
boetes. Zonder beperking van het voorgaande is het kopiëren of
reproduceren van de Software naar een andere server of locatie voor
verdere reproductie of herdistributie uitdrukkelijk verboden. Indien
al enige garantie omtrent de Software gegeven wordt, dan zal deze
beperkt blijven tot hetgeen in de Licentieovereenkomst is bepaald.</span>
</p>
<p class="c2">
<span class="c1">U stemt ermee in dat alle software of
materialen die door Mobicage hieronder beschikbaar worden gesteld en
die onderworpen zijn aan een open source licentie ("Open Source
Software"), onder de voorwaarden van de oorspronkelijke
aanbieders vallen en zullen blijven. Open Source-softwarelicenties
voor componenten van de Diensten die zijn uitgegeven onder een open
source-licentie vormen afzonderlijke schriftelijke overeenkomsten. In
de mate dat de Open Source Software-licenties in strijd zijn met de
voorwaarden van de Overeenkomst, zal de Open Source Software-licentie
uw overeenkomst met Mobicage hieronder regelen voor de specifieke
meegeleverde Open Source Software-componenten van de Diensten.</span>
</p>
<p class="c2">
<span class="c1">Mobicage behoudt zich alle rechten voor die
niet uitdrukkelijk zijn verleend op en voor de Website, de Diensten
en hun Inhoud.</span>
</p>
<p class="c2">
<span class="c1">Voor vragen of verzoeken met betrekking tot de
reproductie van een deel van de Website, de Diensten of hun Inhoud,
kunt u contact opnemen met <a href="mailto:[email protected]">[email protected]</a>. Als u op de hoogte bent
van schending van onze rechten op de Website of de Diensten of van
ons merk, laat het ons dan weten door ons een e-mail te sturen op het
bovenstaande e-mailadres. Als u te goeder trouw gelooft dat materiaal
dat door ons wordt gehost inbreuk maakt op uw (intellectuele of
industriële) eigendomsrechten, ga dan naar het beleid inzake
inbreuk op de intellectuele-eigendomsrechten (hieronder
gespecificeerd) en volg de instructies die daarin worden uiteengezet.</span>
</p>
<p class="c0">
<span class="c5 c3">8. IPR-beleid inzake inbreuk op klachten</span>
</p>
<p class="c2">
<span class="c1">Dit beleid inzake inbreuken op
intellectuele-eigendomsrechten (het 'IPR-beleid inzake inbreuk op
klachten') maakt integraal deel uit van de Overeenkomst.</span>
</p>
<p class="c2">
<span class="c1">(i) Melding van inbreuk</span>
</p>
<p class="c2">
<span class="c1">Als u te goeder trouw meent dat de Website, de
Diensten of Inhoud die door ons wordt gehost inbreuk maakt op uw
intellectuele eigendomsrechten ('IPR'), geef dan de hieronder
gevraagde schriftelijke informatie op. De hieronder beschreven
procedure dient uitsluitend te worden gebruikt om Mobicage ervan op
de hoogte te stellen dat uw IPR is geschonden.</span>
</p>
<p class="c2">
<span class="c1">Geef de volgende informatie op in de volgende
indeling:</span>
</p>
<p class="c2">
<span class="c1">1. Een duidelijke identificatie van het
auteursrechtelijk beschermde werk of ander intellectueel eigendom
waarvan u beweert dat het is geschonden.</span>
</p>
<p class="c2">
<span class="c1">2. Een duidelijke identificatie van het
materiaal waarvan u beweert dat het inbreuk maakt op het
auteursrechtelijk beschermde werk of ander intellectueel eigendom, en
informatie die ons in staat zal stellen dat materiaal op de Website,
de Diensten of de Inhoud te vinden, zoals een link naar het
inbreukmakende materiaal.</span>
</p>
<p class="c2">
<span class="c1">3. Uw contactgegevens zodat we uw klacht
kunnen beantwoorden, bij voorkeur inclusief een e-mailadres en
telefoonnummer.</span>
</p>
<p class="c2">
<span class="c1">4. Neem de volgende verklaring op: "Ik
ben oprecht van mening dat het materiaal dat als IPR-inbreuk wordt
geclaimd, niet is geautoriseerd door de eigenaar van de IPR, diens
vertegenwoordiger of de wet."</span>
</p>
<p class="c2">
<span class="c1">5. Neem de volgende verklaring op: "Ik
bevestig hierbij, te goeder trouw, dat de informatie in deze
kennisgeving juist is en dat ik de eigenaar van de
intellectuele-eigendomsrechten ben van of gemachtigd ben om op te
treden namens de eigenaar van de intellectuele-eigendomsrechten met
betrekking tot een exclusief recht dat naar verluidt is geschonden.
"</span>
</p>
<p class="c2">
<span class="c1">6. De kennisgeving moet worden ondertekend
door de persoon die gemachtigd is om op te treden namens de eigenaar
van een exclusief recht waarvan beweerd wordt dat deze is geschonden.</span>
</p>
<p class="c2">
<span class="c1">Kennisgevingen van claims van IER-inbreuken in
overeenstemming met dit IER-beleid inzake inbreuk op klachten dienen
te worden gemaild naar <a href="mailto:[email protected]">[email protected]</a>, met het bericht
"Inbreukmeldingen" in de kop van de e-mail.</span>
</p>
<p class="c2">
<span class="c1">We raden u aan eerst uw juridisch adviseur te
raadplegen voordat u een kennisgeving of tegenvordering indient. Houd
er ook rekening mee dat we u mogelijk aansprakelijk kunnen stellen
voor schade en kosten (inclusief juridische kosten en honoraria van
advocaten) die wij hebben geleden of opgelopen als gevolg van het
feit dat u een valse claim indient wegens inbreuk op
intellectuele-eigendomsrechten.</span>
</p>
<p class="c2">
<span class="c1">We zullen alle kennisgevingen die voldoen aan
de hierboven uiteengezette vereisten bekijken en behandelen.</span>
</p>
<p class="c2">
<span class="c1">(ii) Herhaaldelijke inbreuk beleid</span>
</p>
<p class="c2">
<span class="c1">Mobicage hanteert een beleid van
beëindiging, naar eigen goeddunken van Mobicage, van gebruikers
of accounteigenaars die worden beschouwd als herhaaldelijke
overtreders. Mobicage kan naar eigen goeddunken ook de toegang tot de
Website beperken en / of de accounts opschorten of beëindigen
van gebruikers die inbreuk maken op de intellectuele-eigendomsrechten
van een derde partij, ongeacht of er sprake is van herhaling.</span>
</p>
<p class="c0">
<span class="c5 c3">9. Privacyverklaring</span>
</p>
<p class="c2">
<span>Voor informatie over de behandeling van persoonlijke
gegevens door Mobicage, dient u de huidige Privacyverklaring van
Moibcage te lezen: </span><span><a href="/legal?doc=privacy-policy&l=NL">Privacyverklaring</a> van Mobicage</span><span class="c1">, dat
integraal deel uitmaakt van deze Overeenkomst; uw aanvaarding van
deze Overeenkomst vormt uw acceptatie en instemming om gebonden te
zijn aan de Privacyverklaring van Mobicage.</span>
</p>
<p class="c0">
<span class="c5 c3">10. Garantiebepaling</span>
</p>
<p class="c2">
<span class="c1">Behalve voor zover vereist onder de
toepasselijke wetgeving, accepteert Mobicage geen fiduciaire plichten
jegens u. U registratie op, en gebruik van de Website en de Diensten
zijn op uw eigen risico.</span>
</p>
<p class="c2">
<span class="c1">De Website en Diensten worden u ter
beschikking gesteld "in de staat waarin zij zich bevinden"
en "zoals beschikbaar", zonder enige vorm van garantie,
voor uw informatie en persoonlijk gebruik (behalve voor zover
anderszins uitdrukkelijk toegestaan ​​door Mobicage).
Voor zover toegestaan oner toepasselijke wetgeving, wijzen Mobicage,
haar functionarissen, directeurs, werknemers en agenten alle
garanties, expliciet of impliciet, af in verband met de Website, de
Diensten en hun Inhoud, en uw gebruik ervan. Mobicage biedt geen
garanties of verklaringen met betrekking tot de nauwkeurigheid,
actualiteit, beschikbaarheid, geschiktheid of volledigheid van de
inhoud die beschikbaar is op de Site en via de Diensten, en voor
zover maximaal toegestaan ​​onder de toepasselijke
wetgeving, wijst Mobicage alle garanties af dat de Website en
Diensten vrij zijn van virussen of andere schadelijke componenten, en
evenmin biedt Mobicage enige impliciete garantie van verkoopbaarheid,
geschiktheid voor een bepaald doel, titel en/of niet-inbreuk.
Mobicage biedt geen enkele garantie (i) dat de Website en Diensten
aan uw eisen of verwachtingen zullen voldoen, (ii) dat de Website en
Diensten beschikbaar zullen zijn op een ononderbroken, tijdige,
veilige of foutvrije basis, (iii) dat de resultaten die kunnen worden
verkregen uit het gebruik van de Website en Diensten accuraat en
betrouwbaar zijn, en (iv) met betrekking tot de kwaliteit van de
Website en de Diensten. In het bijzonder (zonder uitputtend te zijn)
aanvaardt Mobicage geen aansprakelijkheid of verantwoordelijkheid
voor enige:</span>
</p>
<p class="c2">
<span class="c1">- fouten, vergissingen of onnauwkeurigheden
van de inhoud (inclusief Inhoud),</span>
</p>
<p class="c2">
<span class="c1">- persoonlijk letsel of schade aan
eigendommen, van welke aard dan ook, die voortvloeit uit uw toegang
tot en gebruik van onze Website en Diensten,</span>
</p>
<p class="c2">
<span class="c1">- ongeautoriseerde toegang tot of gebruik van
onze servers en / of inhoud, inclusief Inhoud, persoonlijke
informatie en / of financiële informatie, die daarin is
opgeslagen;</span>
</p>
<p class="c2">
<span class="c1">- elke onderbreking of stopzetting van
verzending naar of van onze Website of Diensten,</span>
</p>
<p class="c2">
<span class="c1">- eventuele bugs, virussen, Trojaanse paarden
en dergelijke die kunnen worden overgedragen aan of via onze Website
of Diensten via acties van een derde partij, inclusief gebruikers, en
/ of</span>
</p>
<p class="c2">
<span class="c1">- eventuele fouten of weglatingen in enige
inhoud of voor verlies of schade van welke aard dan ook die is
opgelopen als gevolg van het gebruik van enige inhoud, inclusief
Inhoud.</span>
</p>
<p class="c2">
<span class="c1">Mobicage biedt geen garantie voor,
onderschrijft, adviseert, garandeert of neemt geen
verantwoordelijkheid op voor producten of diensten die door een derde
worden geadverteerd of aangeboden via de Website, de Diensten of een
hyperlinked website of die worden vermeld in een inzending van een
gebruiker of andere advertenties, en Mobicage zal geen partij zijn of
op enigerlei wijze verantwoordelijk zijn voor het bewaken van elke
transactie tussen u en derde leveranciers van producten of diensten.</span>
</p>
<p class="c2">
<span class="c1">De bovenstaande afwijzing van
aansprakelijkheid heeft geen invloed op wettelijke rechten die niet
kunnen worden uitgesloten volgens de toepasselijke wetgeving.</span>
</p>
<p class="c0">
<span class="c5 c3">11. Beperking van aansprakelijkheid</span>
</p>
<p class="c2">
<span class="c1">Voor zover maximaal toegestaan
​​onder het toepasselijk recht, sluit Mobicage hierbij
haar aansprakelijkheid en dat van haar verbonden ondernemingen,
bestuurders, werknemers en agenten jegens u en derden uit voor alle
directe, indirecte, incidentele, speciale, bestraffende, of
gevolgschade van welke aard dan ook die resulteert uit (uw toegang
tot en gebruik van) de Website, de Diensten en hun inhoud (inclusief
de Inhoud), inclusief (zonder limitatief te zijn) verlies van
gegevens, verlies van inkomsten of winst, verlies van verwachte
besparingen en/of reputatie schade.</span>
</p>
<p class="c2">
<span class="c1">Meer bepaald accepteert Mobicage geen enkele
aansprakelijkheid die voortvloeit uit (zonder limitatief te zijn):</span>
</p>
<p class="c2">
<span class="c1">- fouten, vergissingen of onnauwkeurigheden
van de inhoud (inclusief Inhoud),</span>
</p>
<p class="c2">
<span class="c1">- persoonlijk letsel of schade aan
eigendommen, van welke aard dan ook, die voortvloeit uit uw toegang
tot en gebruik van onze Website en / of Diensten,</span>
</p>
<p class="c2">
<span class="c1">- ongeautoriseerde toegang tot of gebruik van
onze beveiligde servers en / of enige inhoud (inclusief Inhoud),
persoonlijke informatie en / of financiële informatie die daarin
is opgeslagen;</span>
</p>
<p class="c2">
<span class="c1">- elke onderbreking of stopzetting van
verzending naar of van onze Website of Servers,</span>
</p>
<p class="c2">
<span class="c1">- eventuele bugs, virussen, Trojaanse paarden
en dergelijke, die kunnen worden overgedragen aan of via onze Website
en Diensten door een derde partij (inclusief gebruikers), en / of</span>
</p>
<p class="c2">
<span class="c1">- eventuele fouten of weglatingen in inhoud of
voor verlies of schade van welke aard dan ook die is opgelopen als
gevolg van uw gebruik van enige inhoud (inclusief inhoud).</span>
</p>
<p class="c2">
<span class="c1">- in het algemeen uw toegang tot, weergave en
indiening van Inhoud, uw vertrouwen op of gebruik van de Website of
de Diensten, of als gevolg van de vertraging of het niet kunnen
openen, weergeven of verzenden van Inhoud op of gebruik van de
Website of de Diensten.</span>
</p>
<p class="c0">
<span class="c5 c3">12. Vrijwaring</span>
</p>
<p class="c2">
<span class="c1">U stemt ermee in om Mobicage, haar verbonden
ondernemingen, functionarissen, bestuurders, werknemers en agenten,
op eerste verzoek van Mobicage, te verdedigen, schadeloos te stellen
en te behouden, van en tegen alle claims, schade, verplichtingen,
verliezen, aansprakelijkheden, kosten of schulden, boetes, boetes en
uitgaven (inclusief maar niet beperkt tot advocatenkosten) die
voortvloeien uit: (i) uw gebruik van en toegang tot de Website of
Diensten in strijd met de Overeenkomst; (ii) uw overtreding van
toepasselijke wetgeving of enige voorwaarde van de Overeenkomst;
(iii) uw schending van enig recht van derden, inclusief maar niet
beperkt tot het auteursrecht, eigendom of privacyrecht; of (iv) elke
claim dat de Inhoud die u hebt gepost, schade aan een derde heeft
veroorzaakt. Deze verplichting tot verdediging en vrijwaring zal de
Overeenkomst en uw gebruik van de Diensten overleven. Mobicage
behoudt zich het recht voor de exclusieve verdediging en controle te
aanvaarden van alle zaken waarvoor u hieronder bent vrijgesteld, in
welk geval u zult helpen en met Mobicage zult samenwerken bij het
verdedigen van alle beschikbare verdedigingen, op uw kosten.</span>
</p>
<p class="c2 c6">
<span class="c1"></span>
</p>
<p class="c0">
<span class="c5 c3">13. Algemene voorwaarden voor Professionele
Gebruikers</span>
</p>
<p class="c2">
<span class="c1">De huidige sectie bevat de specifieke
voorwaarden die van toepassing zijn op Professionele Gebruikers die
een integraal onderdeel zijn van de Overeenkomst als u een
Professionele Gebruiker bent (zoals hierin gedefinieerd).</span>
</p>
<p class="c2">
<span class="c1">"Professioneel Gebruik" betekent (en
“Professioneel Gebruiker” dient overeenkomstig te worden
uitgelegd) gebruik van de Diensten (met inbegrip van door Mobicage
zelf ontwikkelde tools en applicaties die mogelijk zijn gelicentieerd
aan de Professioneel Gebruiker) voor het communiceren met derden
anders dan voor persoonlijk gebruik, en / of het leveren van diensten
aan derden (ongeacht of dergelijke diensten worden aangerekend door
de Professioneel Gebruiker).</span>
</p>
<p class="c2">
<span class="c1">Deze Professioneel Gebruiker kan worden
onderworpen aan een afzonderlijke overeenkomst die wordt gesloten
tussen de Professioneel Gebruiker en Mobicage ("het
Contract"), online of anderszins, naar keuze van Mobicage. In
geval van tegenstrijdigheid tussen deze Algemene Voorwaarden en het
Contract, prevaleren de laatste.</span>
</p>
<p class="c2">
<span class="c1">U kunt Mobicage verzoeken om een
​​gratis proefversie te ontvangen met betrekking tot het
gebruik van de Diensten. Dergelijke gratis proefversies moeten online
worden aangevraagd, op de Website, via de daarvoor bestemde
formulieren. Indien verleend door Mobicage, zal een dergelijke gratis
proefversie per e-mail worden bevestigd en worden de details en
modaliteiten van de gratis proefversie uiteengezet (bijvoorbeeld de
duur van de gratis proefperiode, het aantal toegestane gebruikers).
Dergelijke gratis proefversies zijn onderworpen aan de volgende
aanvullende voorwaarden en bepalingen, die een integraal onderdeel
van de Overeenkomst vormen:</span>
</p>
<p class="c2">
<span class="c1">(i) Elke dergelijke gratis proefperiode die
door Mobicage wordt verleend, zal bestaan ​​uit een
beperkte, persoonlijke, niet-exclusieve, herroepbare,
niet-overdraagbare, niet-toewijsbare licentie, zonder het recht op
sublicentie, om de Diensten te gebruiken voor Professioneel Gebruik,
onderworpen aan de bepalingen en voorwaarden die zijn uiteengezet in
de Overeenkomst ("de Licentie"). De omvang van de licentie
wordt zo uitdrukkelijk verleend en er zijn geen impliciete licenties
of licenties verleend door afstand, estoppel of anderszins krachtens
de overeenkomst.</span>
</p>
<p class="c2">
<span class="c1">(ii) U mag de Licentie niet geheel of
gedeeltelijk overdragen, toewijzen of sublicentiëren zonder
uitdrukkelijke schriftelijke toestemming van Mobicage. Een dergelijke
overdracht, overdracht of sublicentie zonder de schriftelijke
toestemming van Mobicage is nietig en ongeldig.</span>
</p>
<p class="c2">
<span class="c1">(iii) U verbindt zich ertoe om een
​​accurate bedrijfsregistratie bij te houden van uw
Professioneel Gebruik van de Diensten voor zolang als u gerechtigd
bent om ze te gebruiken volgens de voorwaarden van de Overeenkomst. U
bewaart deze gegevens gedurende ten minste drie jaar na
beëindiging van uw recht om de Diensten te gebruiken (of een
langere periode die op grond van toepasselijk recht vereist is). U
zult Mobicage dergelijke informatie en documentatie over uw gebruik
van de Diensten verstrekken zoals redelijkerwijs door Mobicage wordt
gevraagd. U erkent en gaat ermee akkoord dat Mobicage uw gebruik van
de Diensten kan controleren. Mobicage en / of haar agenten kunnen uw
gebruik van de Diensten auditen (inclusief door het uitvoeren van
inspecties op de locatie) na een redelijke kennisgeving (behalve
wanneer een dergelijke kennisgeving het doel van de audit zou
verslaan), tijdens normale kantooruren. Als een dergelijke inspectie,
of een controle zoals hierboven beschreven, aantoont dat u in strijd
met de Overeenkomst handelde, dient u, onverminderd alle andere
rechten en rechtsmiddelen die beschikbaar zijn voor Mobicage,
onmiddellijk dergelijke acties te ondernemen als redelijkerwijs
gevraagd door Mobicage. De partijen dragen elk hun eigen kosten in
verband met dergelijke herzieningen en inspecties, op voorwaarde dat
in geval van een door u begane overtreding, zoals bepaald door een
dergelijke evaluatie of inspectie, alle kosten in verband met deze
controle en inspectie door u worden gedragen, onverminderd voor alle
andere rechten en rechtsmiddelen die beschikbaar zijn voor Mobicage
hieronder.</span>
</p>
<p class="c2">
<span class="c1">(iv) Naast de bepalingen van deze Algemene
Voorwaarden, gelden de volgende bepalingen:</span>
</p>
<p class="c2">
<span class="c1">· U bent volledig verantwoordelijk voor
uw activiteiten met betrekking tot de Diensten en voor het gebruik
door uw gebruikers van de Diensten die door en via u beschikbaar
worden gesteld.</span>
</p>
<p class="c2">
<span class="c1">· U zult de Overeenkomst volledig
naleven en u zult ervoor zorgen dat uw gebruikers de Overeenkomst
volledig naleven in de mate die op hen van toepassing is.</span>
</p>
<p class="c2">
<span class="c1">· U dient zich volledig te houden aan
alle van toepassing zijnde wet- en regelgeving en bent als enige
verantwoordelijk voor het verkrijgen van alle benodigde vergunningen
en autorisaties die vereist zijn voor het uitvoeren van uw zakelijke
activiteiten in overeenstemming met de Licentie.</span>
</p>
<p class="c2">
<span class="c1">· U staat uw gebruikers toe om
gemakkelijk de door u beschikbaar gestelde Diensten te verwijderen of
te verbreken door middel van de eigen applicatie van Mobicage en moet
alle vereiste toestemming van uw gebruikers verkrijgen, zoals vereist
door de toepasselijke wetgeving.</span>
</p>
<p class="c2">
<span class="c1">· We zullen u alle rechten verlenen die
noodzakelijk zijn om de Diensten te gebruiken, behalve voor zover
uitdrukkelijk anders is bepaald of medegedeeld. Alle rechten die door
Mobicage worden verleend, zijn beperkte, persoonlijke,
niet-exclusieve, herroepbare, niet-toewijsbare, niet-overdraagbare
gebruikersrechten, zonder het recht op sublicentie, en met
uitzondering van de beperkte gebruikersrechten die u krachtens de
Overeenkomst zijn verleend, behoudt Mobicage alle rechten, titels en
belangen in de Diensten en zijn eigen tools en applicaties.</span>
</p>
<p class="c2">
<span class="c1">· U mag onze code, API's of
hulpmiddelen niet verkopen, overdragen of in sublicentie geven aan
wie dan ook, noch een van de voorgaande bezwaren. U mag uw API- of
SIK-sleutel niet delen met een derde partij.</span>
</p>
<p class="c2">
<span class="c1">· We garanderen niet dat de Diensten
altijd beschikbaar of volledig functionerend zullen zijn.</span>
</p>
<p class="c2">
<span class="c1">· U mag uw naam en logo gebruiken en de
achtergrond van de Diensten aanpassen, met inachtneming van de
voorwaarden en beperkingen die zijn vastgelegd in deze Algemene
voorwaarden. U mag geen rechten van derden (bijvoorbeeld (zonder
exhaustieve) auteursrechten en databaserechten) schenden of
anderszins oneerlijke handelspraktijken of oneerlijke concurrentie
aangaan als gevolg van het aldus aanpassen van de Diensten, en u zult
Mobicage hierin vrijwaren en vrijwaren. respecteer volledige
schadevergoeding op eerste verzoek van Mobicage.</span>
</p>
<p class="c2">
<span class="c1">· U zult de Diensten spamvrij houden en
zult zelf geen spamming plegen. U zult Mobicage in dit verband
vrijwaren en vrijwaren op basis van volledige schadevergoeding op het
eerste verzoek van Mobicage.</span>
</p>
<p class="c2">
<span class="c1">· Mobicage (en zijn licentiegevers,
indien van toepassing) zijn eigenaar van alle rechten, eigendommen en
belangen, inclusief alle (aanvragen voor) intellectuele en
industriële eigendomsrechten en het recht om registratie van
dergelijke rechten aan te vragen, in eventuele wijzigingen,
toevoegingen of verbeteringen aan en in derivaten van de Diensten,
ongeacht of deze zijn ontwikkeld door of namens Mobicage of door u of
namens u.</span>
</p>
<p class="c2">
<span class="c1">· U zult alles in het werk stellen om
te zorgen voor bevredigende transacties met uw gebruikers en u zult
zich onthouden van handelingen of nalatigheden die een ongunstige
invloed zouden kunnen hebben op de Diensten, Mobicage en/of haar
reputatie.</span>
</p>
<p class="c2">
<span class="c1">· In het geval van een (vermoede)
inbreuk op enige van uw verplichtingen hieronder, heeft Mobicage,
onverminderd de andere rechten en rechtsmiddelen die beschikbaar zijn
voor Mobicage, het recht om, naar eigen goeddunken, de Licentie te
schorsen of te beëindigen zonder aansprakelijkheid van Mobicage.</span>
</p>
<p class="c2">
<span class="c1">· U zult Mobicage, op volledige
schadevergoeding en op eerste verzoek van Mobicage, vrijwaren tegen
alle schade, verliezen, kosten (inclusief juridische kosten en
honoraria van advocaten) en aansprakelijkheden die Mobicage lijdt en
oploopt, inclusief als gevolg van enige derde partij claim, die het
gevolg is van een schending door u of uw gebruikers van de
voorwaarden die zijn uiteengezet in de Overeenkomst. Deze
verplichting tot verweer en schadevergoeding blijft van kracht op de
Overeenkomst en uw gebruik van de Diensten hieronder. Mobicage
behoudt zich het recht voor om de exclusieve verdediging, controle en
afhandeling te aanvaarden van alle zaken waarvoor u hieronder bent
vrijgesteld, in welk geval u zult helpen en met Mobicage zult
samenwerken bij het verdedigen van alle beschikbare verdedigingen, op
uw kosten.</span>
</p>
<p class="c2">
<span class="c1">Voor de toepassing van artikel 28 van
Verordening (EU) 2016/679 (Algemene Verordening Gegevensbescherming)
vormen de voorwaarden van deze Overeenkomst het
gegevensverwerkingscontract tussen de Professionele Gebruiker als
‘verantwoordelijke voor de verwerking’ en Mobicage als de
‘verwerker’. De Professionele Gebruiker geeft Mobicage
hierbij de opdracht om de gegevens te verwerken zoals beschreven in
de voorwaarden van deze Overeenkomst.</span>
</p>
<p class="c2">
<span class="c1">Door akkoord te gaan met deze Overeenkomst
verleent u als Professionele Gebruiker Mobicage een algemene
machtiging in de zin van artikel 28, lid 2, van Verordening (EU)
2016/679 om subverwerkers aan te trekken voor het leveren van de
Diensten. Mobicage zal de Professionele Gebruiker informeren over
wijzigingen met betrekking tot dergelijke verwerkers in
overeenstemming met de procedure voor het wijzigen van deze
Overeenkomst zoals bepaald in artikel 20 van deze Overeenkomst.</span>
</p>
<p class="c2">
<span>Voor een lijst met verwerkers, verwijzen wij naar de </span><span><a href="/legal?doc=privacy-policy&l=NL">Privacyverklaring</a>
van Mobicage</span><span
class="c1">.</span>
</p>
<p class="c2">
<span class="c1">Mobicages biedt het platform waar de
Professionele Gebruiker, als verantwoordelijke voor de verwerking,
persoonlijke gegevens van betrokkenen (zoals bepaald door de
verantwoordelijke voor de verwerking) kan verzamelen, opslaan,
organiseren, overdragen en communiceren. De Website (inclusief de
App) is ontworpen om te werken als een mobiel communicatieplatform.
Voor zover niet geregeld door de voorwaarden van deze Overeenkomst,
bepalen de Professionele Gebruikers op welke wijze zij de Website
gebruiken.</span>
</p>
<p class="c2">
<span class="c1">Mobicage zal gegevens namens de Professionele
Gebruiker verwerken tot de beëindiging van de Diensten in
overeenstemming met de voorwaarden van deze Overeenkomst. Bij
beëindiging verwijdert Mobicage alle gegevens van de
Professionele Gebruiker, inclusief Persoonsgegevens en bestaande
kopieën, tenzij anders vereist onder de toepasselijke wetgeving.</span>
</p>
<p class="c2">
<span class="c1">Mobicage zorgt ervoor dat personen die bevoegd
zijn om de Persoonsgegevens te verwerken zich hebben verbonden tot
vertrouwelijkheid of een passende wettelijke verplichting tot
vertrouwelijkheid hebben. Mobicage neemt alle maatregelen die vereist
zijn op grond van artikel 32 van Verordening (EU) 2016/679. Mobicage
verbindt zich ertoe de verantwoordelijke voor de verwerking alle
informatie te verstrekken die nodig is om aan te tonen dat ze aan hun
verplichtingen voldoen en om audits toe te staan ​​en
daartoe bij te dragen, met inbegrip van inspecties die worden
uitgevoerd of verplicht gesteld door de Professionele Gebruiker als
verantwoordelijke voor de verwerking.</span>
</p>
<p class="c2">
<span class="c1">In het geval van (vermeende) schending van
enige van uw verplichtingen hieronder, heeft Mobicage, onverminderd
de andere rechten en rechtsmiddelen die beschikbaar zijn voor
Mobicage, het recht om, naar eigen goeddunken, uw Contract op te
schorten of te beëindigen, zonder aansprakelijkheid van
Mobicage. Bij beëindiging van het Contract moet u Mobicage
onmiddellijk en naar eigen keuze en op uw kosten alle materiaal
teruggeven of vernietigen dat door Mobicage ter beschikking is
gesteld met betrekking tot het Gebruik van de Service. U dient
Mobicage schadeloos te stellen, op volledige schadevergoeding en op
eerste verzoek van Mobicage, tegen alle schade, verliezen, kosten
(inclusief juridische kosten en honoraria van advocaten) en
aansprakelijkheden geleden en opgelopen door Mobicage, inclusief als
gevolg van een claim van een derde partij , als gevolg van een
schending door u of uw gebruikers van de voorwaarden die zijn
uiteengezet in de Overeenkomst. Deze verplichting tot verweer en
schadevergoeding blijft van kracht op de Overeenkomst en uw Service
Gebruik hieronder. Mobicage behoudt zich het recht voor om de
exclusieve verdediging en controle te aanvaarden van alle zaken
waarvoor u hieronder bent vrijgesteld. In dat geval zult u helpen en
samenwerken met Mobicage bij het verdedigen van alle beschikbare
verdedigingen, op uw kosten.</span>
</p>
<p class="c0">
<span class="c5 c3">14. Opdracht</span>
</p>
<p class="c2">
<span class="c1">De Overeenkomst en alle verplichtingen,
rechten en licenties die hieronder worden verleend, mogen niet door u
worden overgedragen, maar kunnen zonder beperking door Mobicage
worden overgedragen.</span>
</p>
<p class="c0">
<span class="c5 c3">15. Opschorting van Diensten</span>
</p>
<p class="c2">
<span class="c1">Onverminderd de andere rechten en
rechtsmiddelen die beschikbaar zijn voor Mobicage, heeft Mobicage het
recht om, in geval van schending van een of meer van uw
verplichtingen onder de Overeenkomst, de toegang tot uw account
tijdelijk of permanent en zonder enig recht te beperken of te
ontzeggen, zonder enig​​e schadevergoeding of enige
aansprakelijkheid in hoofde van Mobicage.</span>
</p>
<p class="c0">
<span class="c3">16. Beëindiging van de overeenkomst</span>
</p>
<p class="c2">
<span class="c1">Mobicage kan de Website of de Diensten geheel
of gedeeltelijk stopzetten of uw toegang tot de Website of de
Diensten op elk moment beëindigen, met of zonder reden, met of
zonder kennisgeving, met onmiddellijke ingang of anderszins, hetgeen
kan resulteren in de verbeurdverklaring en vernietiging van alle
informatie in verband met uw lidmaatschap. Als u uw account wilt
deactiveren / beëindigen, stuur dan een e-mail naar
<a href="mailto:[email protected]">[email protected]</a>, waarbij u expliciet vraagt ​​om uw
account te deactiveren. Dit verzoek moet vergezeld gaan van een
ondertekende kopie van een officieel identificatiemiddel (bijv.
identiteitskaart of paspoort). Alle bepalingen van de Overeenkomst
die expliciet of door hun aard bestemd zijn om na beëindiging te
overleven, blijven van kracht na beëindiging, inclusief, maar
niet beperkt tot, de bepalingen betreffende
intellectuele-eigendomsrechten, garantieaanspraken, vrijwaringen en
beperkingen van aansprakelijkheid.</span>
</p>
<p class="c0">
<span class="c5 c3">17. Toepasselijk recht en jurisdictie</span>
</p>
<p class="c2">
<span class="c1">De Overeenkomst wordt uitsluitend beheerst
door en geïnterpreteerd in overeenstemming met de Belgische
wetgeving, met uitsluiting van haar beginselen van Internationaal
Privaatrecht. Elk geschil in verband met of voortvloeiend uit de
Overeenkomst zal definitief worden beslecht door de bevoegde
rechtbanken van Gent, België.</span>
</p>
<p class="c2">
<span class="c1">U stemt ermee in om enige vordering die
voortkomt uit of verband houdt met de Website, de Diensten of deze
Overeenkomst, voor zover toegestaan ​​hieronder of onder
dwingend toepasselijk recht, binnen één (1) jaar na de
datum waarop de oorzaak van vordering is ontstaan, in te stellen, bij
gebreke waaraan een dergelijke vordering of een dergelijke reden tot
handelen definitief vervalt.</span>
</p>
<p class="c0">
<span class="c5 c3">18. Volledige overeenkomst en
scheidbaarheid</span>
</p>
<p class="c2">
<span class="c1">De Overeenkomst vormt de volledige
overeenkomst tussen u en Mobicage met betrekking tot de Website en de
Diensten. Indien enige bepaling van de Overeenkomst ongeldig wordt
verklaard door een bevoegde rechtbank, heeft de ongeldigheid van een
dergelijke bepaling geen invloed op de geldigheid van de overige
bepalingen van de Overeenkomst, die volledig van kracht blijven en de
ongeldige of niet-afdwingbare bepaling zal moet worden vervangen door
een geldige, afdwingbare bepaling die het meest overeenkomt met de
bedoeling van de oorspronkelijke bepaling. U erkent en gaat ermee
akkoord dat een gedrukt exemplaar van de Overeenkomst en elke
kennisgeving in elektronische of schriftelijke vorm in gerechtelijke
of administratieve procedures met betrekking tot de Overeenkomst in
dezelfde mate ontvankelijk is als andere bedrijfsdocumenten en
documenten die oorspronkelijk in gedrukte vorm werden gegenereerd en
bijgehouden .</span>
</p>
<p class="c0">
<span class="c5 c3">19. Ontheffing</span>
</p>
<p class="c2">
<span class="c1">Geen afstand door Mobicage van enige
voorwaarde van de Overeenkomst wordt beschouwd als een verdere of
voortdurende verklaring van afstand van een dergelijke voorwaarde of
een andere voorwaarde, en Mobicage's verzuim om enig recht of
bepaling onder deze Algemene voorwaarden te doen gelden vormt geen
verklaring van afstand van dat recht of deze bepaling.</span>
</p>
<p class="c0">
<span class="c5 c3">20. Wijzigingen</span>
</p>
<p class="c2">
<span class="c1">Mobicage behoudt zich het recht voor de
Overeenkomst te allen tijde te wijzigen. We moedigen u daarom aan om
regelmatig de Overeenkomst te controleren op eventuele wijzigingen.
Uw toegang tot de Website en / of gebruik van de Diensten na elke
wijziging van de Overeenkomst betekent dat u akkoord gaat met de
herziene voorwaarden.</span>
</p>
<p class="c0">
<span class="c5 c3">21. Diversen</span>
</p>
<p class="c2">
<span class="c1">Mobicage is niet aansprakelijk voor het niet
nakomen van zijn verplichtingen in het kader van deze Algemene
Voorwaarden, voor zover dergelijke tekortkoming het gevolg is van een
oorzaak die verder gaat dan de redelijke controle van Mobicage,
inclusief, maar niet beperkt tot, mechanische of elektronische
storingen of verslechtering van de communicatie (inclusief
"lijnruis" -interferentie). Er wordt geen agentschap,
partnerschap, joint venture of arbeidsrelatie gecreëerd als
gevolg van de Overeenkomst of uw bezoek van de Website en / of
gebruik van de Diensten.</span>
</p>
<p class="c0">
<span class="c5 c3">22. Taal</span>
</p>
<p class="c2">
<span class="c1">Wanneer Mobicage een vertaling van de Engelse
versie van de Overeenkomst ter beschikking stelt, stemt u ermee in
dat de vertaling uitsluitend ter informatie wordt verstrekt en dat de
Engelstalige versies van de Overeenkomst uw relatie met Mobicage
bepalen en dat, in geval van tegenstrijdigheid of discrepantie tussen
de Engelstalige versie van de Overeenkomst en een vertaling, de
Engelstalige versie voorrang heeft.</span>
</p>
<p class="c0">
<span class="c5 c3">23. Contact</span>
</p>
<p class="c2">
<span class="c1">U kunt contact opnemen met Mobicage via
<a href="mailto:[email protected]">[email protected]</a>, behalve wanneer specifieke contactgegevens zijn
verstrekt in de Overeenkomst met betrekking tot specifieke
aangelegenheden, in welk geval dergelijke contactgegevens moeten
worden gebruikt.</span>
</p>
{% endblock %} | apache-2.0 |
apache/incubator-shardingsphere | shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-mysql/src/main/java/org/apache/shardingsphere/sql/parser/mysql/parser/MySQLParserFacade.java | 1510 | /*
* 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.shardingsphere.sql.parser.mysql.parser;
import org.apache.shardingsphere.sql.parser.api.parser.SQLLexer;
import org.apache.shardingsphere.sql.parser.api.parser.SQLParser;
import org.apache.shardingsphere.sql.parser.spi.DatabaseTypedSQLParserFacade;
/**
* SQL parser facade for MySQL.
*/
public final class MySQLParserFacade implements DatabaseTypedSQLParserFacade {
@Override
public Class<? extends SQLLexer> getLexerClass() {
return MySQLLexer.class;
}
@Override
public Class<? extends SQLParser> getParserClass() {
return MySQLParser.class;
}
@Override
public String getDatabaseType() {
return "MySQL";
}
}
| apache-2.0 |
praveennet/azure-powershell | src/ServiceManagement/Compute/Commands.ServiceManagement/HostedServices/SetAzureDeployment.cs | 13839 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.
// ----------------------------------------------------------------------------------
using System;
using System.Management.Automation;
using System.Net;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Extensions;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Helpers;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.WindowsAzure.Management.Compute.Models;
using Microsoft.WindowsAzure.Management.Compute;
using Hyak.Common;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices
{
/// <summary>
/// Update deployment configuration, upgrade or status
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureDeployment"), OutputType(typeof(ManagementOperationContext))]
public class SetAzureDeploymentCommand : ServiceManagementBaseCmdlet
{
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "Upgrade", HelpMessage = "Upgrade Deployment")]
public SwitchParameter Upgrade
{
get;
set;
}
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "Config", HelpMessage = "Change Configuration of Deployment")]
public SwitchParameter Config
{
get;
set;
}
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "Status", HelpMessage = "Change Status of Deployment")]
public SwitchParameter Status
{
get;
set;
}
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "Upgrade", ValueFromPipelineByPropertyName = true, HelpMessage = "Service name")]
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "Config", ValueFromPipelineByPropertyName = true, HelpMessage = "Service name")]
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "Status", ValueFromPipelineByPropertyName = true, HelpMessage = "Service name")]
[ValidateNotNullOrEmpty]
public string ServiceName
{
get;
set;
}
[Parameter(Position = 2, Mandatory = true, ParameterSetName = "Upgrade", HelpMessage = "Package location. This parameter should have the local file path or URI to a .cspkg in blob storage whose storage account is part of the same subscription/project.")]
[ValidateNotNullOrEmpty]
public string Package
{
get;
set;
}
[Parameter(Position = 2, Mandatory = true, ParameterSetName = "Config", HelpMessage = "Configuration file path. This parameter should specifiy a .cscfg file on disk.")]
[Parameter(Position = 3, Mandatory = true, ParameterSetName = "Upgrade", HelpMessage = "Configuration file path. This parameter should specifiy a .cscfg file on disk.")]
[ValidateNotNullOrEmpty]
public string Configuration
{
get;
set;
}
[Parameter(Position = 4, Mandatory = true, ParameterSetName = "Upgrade", ValueFromPipelineByPropertyName = true, HelpMessage = "Deployment slot. Staging | Production")]
[Parameter(Position = 3, Mandatory = true, ParameterSetName = "Config", ValueFromPipelineByPropertyName = true, HelpMessage = "Deployment slot. Staging | Production")]
[Parameter(Position = 2, Mandatory = true, ParameterSetName = "Status", ValueFromPipelineByPropertyName = true, HelpMessage = "Deployment slot. Staging | Production")]
[ValidateSet(Model.DeploymentSlotType.Staging, Model.DeploymentSlotType.Production, IgnoreCase = true)]
public string Slot
{
get;
set;
}
[Parameter(Position = 5, ParameterSetName = "Upgrade", HelpMessage = "Upgrade mode. Auto | Manual | Simultaneous")]
[ValidateSet(Model.UpgradeType.Auto, Model.UpgradeType.Manual, Model.UpgradeType.Simultaneous, IgnoreCase = true)]
public string Mode
{
get;
set;
}
[Parameter(Position = 6, Mandatory = false, ParameterSetName = "Upgrade", HelpMessage = "Label name for the new deployment. Default: <Service Name> + <date time>")]
[ValidateNotNullOrEmpty]
public string Label
{
get;
set;
}
[Parameter(Position = 7, Mandatory = false, ParameterSetName = "Upgrade", HelpMessage = "Name of role to upgrade.")]
public string RoleName
{
get;
set;
}
[Parameter(Position = 8, Mandatory = false, ParameterSetName = "Upgrade", HelpMessage = "Force upgrade.")]
public SwitchParameter Force
{
get;
set;
}
[Parameter(Position = 3, Mandatory = true, ParameterSetName = "Status", HelpMessage = "New deployment status. Running | Suspended")]
[ValidateSet(Model.DeploymentStatus.Running, Model.DeploymentStatus.Suspended, IgnoreCase = true)]
public string NewStatus
{
get;
set;
}
[Parameter(Position = 9, ValueFromPipelineByPropertyName = true, Mandatory = false, ParameterSetName = "Upgrade", HelpMessage = "Extension configurations.")]
[Parameter(Position = 4, ValueFromPipelineByPropertyName = true, Mandatory = false, ParameterSetName = "Config", HelpMessage = "HelpMessage")]
public ExtensionConfigurationInput[] ExtensionConfiguration
{
get;
set;
}
public void ExecuteCommand()
{
string configString = string.Empty;
if (!string.IsNullOrEmpty(Configuration))
{
configString = GeneralUtilities.GetConfiguration(Configuration);
}
ExtensionConfiguration extConfig = null;
if (ExtensionConfiguration != null)
{
string errorConfigInput = null;
if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput))
{
throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput));
}
foreach (ExtensionConfigurationInput context in ExtensionConfiguration)
{
if (context != null && context.X509Certificate != null)
{
ExecuteClientActionNewSM(
null,
string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint),
() => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate)));
}
}
Func<DeploymentSlot, DeploymentGetResponse> func = t =>
{
DeploymentGetResponse d = null;
try
{
d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, t);
}
catch (CloudException ex)
{
if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false)
{
this.WriteExceptionDetails(ex);
}
}
return d;
};
var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true);
DeploymentGetResponse currentDeployment = null;
InvokeInOperationContext(() => currentDeployment = func(slotType));
var peerSlottype = slotType == DeploymentSlot.Production ? DeploymentSlot.Staging : DeploymentSlot.Production;
DeploymentGetResponse peerDeployment = null;
InvokeInOperationContext(() => peerDeployment = func(peerSlottype));
ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName);
extConfig = extensionMgr.Add(currentDeployment, peerDeployment, ExtensionConfiguration, this.Slot);
}
// Upgrade Parameter Set
if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0)
{
bool removePackage = false;
var storageName = Profile.Context.Subscription.GetProperty(AzureSubscription.Property.StorageAccount);
Uri packageUrl = null;
if (Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
{
packageUrl = new Uri(Package);
}
else
{
if (string.IsNullOrEmpty(storageName))
{
throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
}
var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage);
WriteProgress(progress);
removePackage = true;
InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.StorageClient, storageName, Package, null)));
}
DeploymentUpgradeMode upgradeMode;
if (!Enum.TryParse<DeploymentUpgradeMode>(Mode, out upgradeMode))
{
upgradeMode = DeploymentUpgradeMode.Auto;
}
var upgradeDeploymentInput = new DeploymentUpgradeParameters
{
Mode = upgradeMode,
Configuration = configString,
ExtensionConfiguration = extConfig,
PackageUri = packageUrl,
Label = Label ?? ServiceName,
Force = Force.IsPresent
};
if (!string.IsNullOrEmpty(RoleName))
{
upgradeDeploymentInput.RoleToUpgrade = RoleName;
}
InvokeInOperationContext(() =>
{
try
{
ExecuteClientActionNewSM(
upgradeDeploymentInput,
CommandRuntime.ToString(),
() => this.ComputeClient.Deployments.UpgradeBySlot(
this.ServiceName,
(DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
upgradeDeploymentInput));
if (removePackage == true)
{
this.RetryCall(s =>
AzureBlob.DeletePackageFromBlob(
this.StorageClient,
storageName,
packageUrl));
}
}
catch (CloudException ex)
{
this.WriteExceptionDetails(ex);
}
});
}
else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0)
{
// Config parameter set
var changeDeploymentStatusParams = new DeploymentChangeConfigurationParameters
{
Configuration = configString,
ExtensionConfiguration = extConfig
};
ExecuteClientActionNewSM(
changeDeploymentStatusParams,
CommandRuntime.ToString(),
() => this.ComputeClient.Deployments.ChangeConfigurationBySlot(
this.ServiceName,
(DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
changeDeploymentStatusParams));
}
else
{
// Status parameter set
var updateDeploymentStatusParams = new DeploymentUpdateStatusParameters
{
Status = (UpdatedDeploymentStatus)Enum.Parse(typeof(UpdatedDeploymentStatus), this.NewStatus, true)
};
ExecuteClientActionNewSM(
null,
CommandRuntime.ToString(),
() => this.ComputeClient.Deployments.UpdateStatusByDeploymentSlot(
this.ServiceName,
(DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
updateDeploymentStatusParams));
}
}
protected override void OnProcessRecord()
{
ServiceManagementProfile.Initialize();
this.ExecuteCommand();
}
}
}
| apache-2.0 |
telefonicaid/fiware-cosmos-ambari | ambari-agent/src/main/puppet/modules/hdp/lib/puppet/parser/functions/hdp_host.rb | 1024 | #
#
# 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.
#
#
module Puppet::Parser::Functions
newfunction(:hdp_host, :type => :rvalue) do |args|
args = function_hdp_args_as_array(args)
var = args[0]
val = lookupvar("::"+var)
function_hdp_is_empty(val) ? "" : val
end
end
| apache-2.0 |
fengyouchao/fucksocks | src/main/java/sockslib/common/Credentials.java | 1041 | /*
* Copyright 2015-2025 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 sockslib.common;
import java.security.Principal;
/**
* The class <code>Credentials</code> represents a credentials.
*
* @author Youchao Feng
* @version 1.0
* @date May 14, 2015 2:35:26 PM
*/
public interface Credentials {
/**
* Returns principal.
*
* @return principal.
*/
Principal getUserPrincipal();
/**
* Returns password.
*
* @return password.
*/
String getPassword();
}
| apache-2.0 |
apereo/dotnet-cas-client | DotNetCasClient/CasAuthentication.cs | 71180 | /*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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.
*/
using System;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Xml;
using DotNetCasClient.Configuration;
using DotNetCasClient.Logging;
using DotNetCasClient.Security;
using DotNetCasClient.State;
using DotNetCasClient.Utils;
using DotNetCasClient.Validation;
using DotNetCasClient.Validation.Schema.Cas20;
using DotNetCasClient.Validation.TicketValidator;
using System.Collections.Generic;
namespace DotNetCasClient
{
/// <summary>
/// CasAuthentication exposes a public API for use in working with CAS Authentication
/// in the .NET framework. It also exposes all configured CAS client configuration
/// parameters as public static properties.
/// </summary>
/// <author>Marvin S. Addison</author>
/// <author>Scott Holodak</author>
/// <author>William G. Thompson, Jr.</author>
/// <author>Catherine D. Winfrey</author>
public sealed class CasAuthentication
{
#region Constants
private const string XML_SESSION_INDEX_ELEMENT_NAME = "samlp:SessionIndex";
private const string PARAM_PROXY_GRANTING_TICKET_IOU = "pgtIou";
private const string PARAM_PROXY_GRANTING_TICKET = "pgtId";
#endregion
#region Fields
// Loggers
private static readonly Logger configLogger = new Logger(Category.Config);
private static readonly Logger protoLogger = new Logger(Category.Protocol);
private static readonly Logger securityLogger = new Logger(Category.Security);
// Thread-safe initialization
private static readonly object LockObject;
private static bool initialized;
// System.Web/Authentication and System.Web/Authentication/Forms static classes
internal static AuthenticationSection AuthenticationConfig;
internal static CasClientConfiguration CasClientConfig;
// Ticket validator fields
private static string ticketValidatorName;
private static ITicketValidator ticketValidator;
// Ticket manager fields
private static string serviceTicketManagerProvider;
private static IServiceTicketManager serviceTicketManager;
// Proxy ticket fields
private static string proxyTicketManagerProvider;
private static IProxyTicketManager proxyTicketManager;
// Gateway fields
private static bool gateway;
private static string gatewayStatusCookieName;
// Configuration fields
private static string formsLoginUrl;
private static TimeSpan formsTimeout;
private static string casServerLoginUrl;
private static string casServerUrlPrefix;
private static long ticketTimeTolerance;
private static string serverName;
private static bool renew;
private static bool redirectAfterValidation;
private static bool singleSignOut;
private static string notAuthorizedUrl;
private static string cookiesRequiredUrl;
private static string gatewayParameterName;
private static string proxyCallbackParameterName;
private static string casProxyCallbackUrl;
private static bool requireCasForMissingContentTypes;
private static string[] requireCasForContentTypes;
private static string[] bypassCasForHandlers;
// Provide reliable way for arbitrary components in forms
// authentication pipeline to access CAS principal
[ThreadStatic]
private static ICasPrincipal currentPrincipal;
// XML Reader Settings for SAML parsing.
private static XmlReaderSettings xmlReaderSettings;
// XML Name Table for namespace resolution in SSO SAML Parsing routine
private static NameTable xmlNameTable;
/// XML Namespace Manager for namespace resolution in SSO SAML Parsing routine
private static XmlNamespaceManager xmlNamespaceManager;
#endregion
#region Methods
/// <summary>
/// Static constructor
/// </summary>
static CasAuthentication()
{
LockObject = new object();
}
/// <summary>
/// Current authenticated principal or null if current user is unauthenticated.
/// </summary>
public static ICasPrincipal CurrentPrincipal
{
get { return currentPrincipal; }
}
/// <summary>
/// Initializes configuration-related properties and validates configuration.
/// </summary>
public static void Initialize()
{
if (!initialized)
{
lock (LockObject)
{
if (!initialized)
{
FormsAuthentication.Initialize();
AuthenticationConfig = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");
CasClientConfig = CasClientConfiguration.Config;
if (AuthenticationConfig == null)
{
LogAndThrowConfigurationException(
"The CAS authentication provider requires Forms authentication to be enabled in web.config.");
}
if (AuthenticationConfig.Mode != AuthenticationMode.Forms)
{
LogAndThrowConfigurationException(
"The CAS authentication provider requires Forms authentication to be enabled in web.config.");
}
if (FormsAuthentication.CookieMode != HttpCookieMode.UseCookies)
{
LogAndThrowConfigurationException(
"CAS requires Forms Authentication to use cookies (cookieless='UseCookies').");
}
xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ConformanceLevel = ConformanceLevel.Auto;
xmlReaderSettings.IgnoreWhitespace = true;
xmlNameTable = new NameTable();
xmlNamespaceManager = new XmlNamespaceManager(xmlNameTable);
xmlNamespaceManager.AddNamespace("cas", "http://www.yale.edu/tp/cas");
xmlNamespaceManager.AddNamespace("saml", "urn: oasis:names:tc:SAML:1.0:assertion");
xmlNamespaceManager.AddNamespace("saml2", "urn: oasis:names:tc:SAML:1.0:assertion");
xmlNamespaceManager.AddNamespace("samlp", "urn: oasis:names:tc:SAML:1.0:protocol");
formsLoginUrl = AuthenticationConfig.Forms.LoginUrl;
formsTimeout = AuthenticationConfig.Forms.Timeout;
if (string.IsNullOrEmpty(CasClientConfig.CasServerUrlPrefix))
{
LogAndThrowConfigurationException("The CasServerUrlPrefix is required");
}
casServerUrlPrefix = CasClientConfig.CasServerUrlPrefix;
configLogger.Info("casServerUrlPrefix = " + casServerUrlPrefix);
casServerLoginUrl = CasClientConfig.CasServerLoginUrl;
configLogger.Info("casServerLoginUrl = " + casServerLoginUrl);
ticketValidatorName = CasClientConfig.TicketValidatorName;
configLogger.Info("ticketValidatorName = " + ticketValidatorName);
ticketTimeTolerance = CasClientConfig.TicketTimeTolerance;
configLogger.Info("ticketTimeTolerance = " + ticketTimeTolerance);
serverName = CasClientConfig.ServerName;
configLogger.Info("serverName = " + serverName);
renew = CasClientConfig.Renew;
configLogger.Info("renew = " + renew);
gateway = CasClientConfig.Gateway;
configLogger.Info("gateway = " + gateway);
gatewayStatusCookieName = CasClientConfig.GatewayStatusCookieName;
configLogger.Info("gatewayStatusCookieName = " + gatewayStatusCookieName);
redirectAfterValidation = CasClientConfig.RedirectAfterValidation;
configLogger.Info("redirectAfterValidation = " + redirectAfterValidation);
singleSignOut = CasClientConfig.SingleSignOut;
configLogger.Info("singleSignOut = " + singleSignOut);
serviceTicketManagerProvider = CasClientConfig.ServiceTicketManager;
configLogger.Info("serviceTicketManagerProvider = " + serviceTicketManagerProvider);
proxyTicketManagerProvider = CasClientConfig.ProxyTicketManager;
configLogger.Info("proxyTicketManagerProvider = " + proxyTicketManagerProvider);
notAuthorizedUrl = CasClientConfig.NotAuthorizedUrl;
configLogger.Info("notAuthorizedUrl = " + notAuthorizedUrl);
cookiesRequiredUrl = CasClientConfig.CookiesRequiredUrl;
configLogger.Info("cookiesRequiredUrl = " + cookiesRequiredUrl);
gatewayParameterName = CasClientConfig.GatewayParameterName;
configLogger.Info("gatewayParameterName = " + gatewayParameterName);
proxyCallbackParameterName = CasClientConfig.ProxyCallbackParameterName;
configLogger.Info("proxyCallbackParameterName = " + proxyCallbackParameterName);
casProxyCallbackUrl = CasClientConfig.ProxyCallbackUrl;
configLogger.Info("proxyCallbackUrl = " + casProxyCallbackUrl);
requireCasForMissingContentTypes = CasClientConfig.RequireCasForMissingContentTypes;
configLogger.Info("requireCasForMissingContentTypes = " + requireCasForMissingContentTypes);
requireCasForContentTypes = CasClientConfig.RequireCasForContentTypes;
configLogger.Info("requireCasForContentTypes = " + requireCasForContentTypes);
bypassCasForHandlers = CasClientConfig.BypassCasForHandlers;
configLogger.Info("bypassCasForHandlers = " + bypassCasForHandlers);
if (!String.IsNullOrEmpty(ticketValidatorName))
{
if (String.Compare(CasClientConfiguration.CAS10_TICKET_VALIDATOR_NAME,ticketValidatorName) == 0)
ticketValidator = new Cas10TicketValidator();
else if (String.Compare(CasClientConfiguration.CAS20_TICKET_VALIDATOR_NAME, ticketValidatorName) == 0)
ticketValidator = new Cas20ServiceTicketValidator();
else if (String.Compare(CasClientConfiguration.SAML11_TICKET_VALIDATOR_NAME, ticketValidatorName) == 0)
ticketValidator = new Saml11TicketValidator();
else
{
// the ticket validator name is not recognized, let's try to get it using Reflection then
Type ticketValidatorType = Type.GetType(ticketValidatorName, false, true);
if (ticketValidatorType != null)
{
if (typeof(ITicketValidator).IsAssignableFrom(ticketValidatorType))
ticketValidator = (ITicketValidator)Activator.CreateInstance(ticketValidatorType);
else
LogAndThrowConfigurationException("Ticket validator type is not correct " + ticketValidatorName);
}
else
LogAndThrowConfigurationException("Could not find ticket validatory type " + ticketValidatorName);
}
configLogger.Info("TicketValidator type = " + ticketValidator.GetType().ToString());
}
else
LogAndThrowConfigurationException("Ticket validator name missing");
if (String.IsNullOrEmpty(serviceTicketManagerProvider))
{
// Web server cannot maintain ticket state, verify tickets, perform SSO, etc.
}
else
{
if (String.Compare(CasClientConfiguration.CACHE_SERVICE_TICKET_MANAGER, serviceTicketManagerProvider) == 0)
{
#if NET20 || NET35
// Use the service ticket manager that implements an in-memory cache supported by .NET 2.0/3.5.
serviceTicketManager = new CacheServiceTicketManager();
#endif
#if NET40 || NET45
// Use the service ticket manager that implements an in-memory cache supported by .NET 4.x.
serviceTicketManager = new MemoryCacheServiceTicketManager();
#endif
}
else
{
// the service ticket manager is not recognized, let's try to get it using Reflection then
Type serviceTicketManagerType = Type.GetType(serviceTicketManagerProvider, false, true);
if (serviceTicketManagerType != null)
{
if (typeof(IServiceTicketManager).IsAssignableFrom(serviceTicketManagerType))
serviceTicketManager = (IServiceTicketManager)Activator.CreateInstance(serviceTicketManagerType);
else
LogAndThrowConfigurationException("Service Ticket Manager type is not correct " + serviceTicketManagerProvider);
}
else
LogAndThrowConfigurationException("Could not find Service Ticket Manager type " + serviceTicketManagerProvider);
}
configLogger.Info("ServiceTicketManager type = " + serviceTicketManager.GetType().ToString());
}
if (String.IsNullOrEmpty(proxyTicketManagerProvider))
{
// Web server cannot generate proxy tickets
}
else
{
if (String.Compare(CasClientConfiguration.CACHE_PROXY_TICKET_MANAGER, proxyTicketManagerProvider) == 0)
{
#if NET20 || NET35
// Use the proxy ticket manager that implements an in-memory cache supported by .NET 2.0/3.5.
proxyTicketManager = new CacheProxyTicketManager();
#endif
#if NET40 || NET45
// Use the proxy ticket manager that implements an in-memory cache supported by .NET 4.x.
proxyTicketManager = new MemoryCacheProxyTicketManager();
#endif
}
else
{
// the proxy ticket manager is not recognized, let's try to get it using Reflection then
Type proxyTicketManagerType = Type.GetType(proxyTicketManagerProvider, false, true);
if (proxyTicketManagerType != null)
{
if (typeof(IProxyTicketManager).IsAssignableFrom(proxyTicketManagerType))
proxyTicketManager = (IProxyTicketManager)Activator.CreateInstance(proxyTicketManagerType);
else
LogAndThrowConfigurationException("Proxy Ticket Manager type is not correct " + proxyTicketManagerProvider);
}
else
LogAndThrowConfigurationException("Could not find Proxy Ticket Manager type " + proxyTicketManagerProvider);
}
configLogger.Info("ProxyTicketManager type = " + proxyTicketManager.GetType().ToString());
}
// Validate configuration
bool haveServerName = !String.IsNullOrEmpty(serverName);
if (!haveServerName)
{
LogAndThrowConfigurationException(CasClientConfiguration.SERVER_NAME + " cannot be null or empty.");
}
if (String.IsNullOrEmpty(casServerLoginUrl))
{
LogAndThrowConfigurationException(CasClientConfiguration.CAS_SERVER_LOGIN_URL + " cannot be null or empty.");
}
if (serviceTicketManager == null && singleSignOut)
{
LogAndThrowConfigurationException("Single Sign Out support requires a ServiceTicketManager.");
}
if (gateway && renew)
{
LogAndThrowConfigurationException("Gateway and Renew functionalities are mutually exclusive");
}
if (!redirectAfterValidation)
{
LogAndThrowConfigurationException(
"Forms Authentication based modules require RedirectAfterValidation to be set to true.");
}
initialized = true;
}
}
if (ServiceTicketManager != null) ServiceTicketManager.Initialize();
if (ProxyTicketManager != null) ProxyTicketManager.Initialize();
if (TicketValidator != null) TicketValidator.Initialize();
}
}
/// <summary>
/// Obtain a Proxy ticket and redirect to the foreign service url with
/// that ticket included in the url. The foreign service must be configured
/// to accept the ticket.
/// </summary>
/// <param name="url">The foreign service to redirect to</param>
/// <exception cref="ArgumentNullException">The url supplied is null</exception>
/// <exception cref="ArgumentException">The url supplied is empty</exception>
public static void ProxyRedirect(string url)
{
ProxyRedirect(url, "ticket", false);
}
/// <summary>
/// Obtain a Proxy ticket and redirect to the foreign service url with
/// that ticket included in the url. The foreign service must be configured
/// to accept the ticket.
/// </summary>
/// <param name="url">The foreign service to redirect to</param>
/// <param name="endResponse">
/// Boolean indicating whether or not to short circuit the remaining request
/// pipeline events
/// </param>
/// <exception cref="ArgumentNullException">The url supplied is null</exception>
/// <exception cref="ArgumentException">The url supplied is empty</exception>
public static void ProxyRedirect(string url, bool endResponse)
{
ProxyRedirect(url, "ticket", endResponse);
}
/// <summary>
/// Obtain a Proxy ticket and redirect to the foreign service url with
/// that ticket included in the url. The foreign service must be configured
/// to accept the ticket.
/// </summary>
/// <param name="url">The foreign service to redirect to</param>
/// <param name="proxyTicketUrlParameter">
/// The ticket parameter to include in the remote service Url.
/// </param>
/// <exception cref="ArgumentNullException">
/// The url or proxyTicketUrlParameter supplied is null
/// </exception>
/// <exception cref="ArgumentException">
/// The url or proxyTicketUrlParametersupplied is empty
/// </exception>
public static void ProxyRedirect(string url, string proxyTicketUrlParameter)
{
ProxyRedirect(url, proxyTicketUrlParameter, false);
}
/// <summary>
/// </summary>
/// <param name="url">The foreign service to redirect to</param>
/// <param name="proxyTicketUrlParameter">
/// The ticket parameter to include in the remote service Url.
/// </param>
/// <param name="endResponse">
/// Boolean indicating whether or not to short circuit the remaining request
/// pipeline events
/// </param>
/// <exception cref="ArgumentNullException">
/// The url or proxyTicketUrlParameter supplied is null
/// </exception>
/// <exception cref="ArgumentException">
/// The url or proxyTicketUrlParametersupplied is empty
/// </exception>
public static void ProxyRedirect(string url, string proxyTicketUrlParameter, bool endResponse)
{
CommonUtils.AssertNotNullOrEmpty(url, "url parameter cannot be null or empty.");
CommonUtils.AssertNotNull(proxyTicketUrlParameter, "proxyTicketUrlParameter parameter cannot be null or empty.");
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
string proxyRedirectUrl = UrlUtil.GetProxyRedirectUrl(url, proxyTicketUrlParameter);
response.Redirect(proxyRedirectUrl, endResponse);
}
/// <summary>
/// Attempts to connect to the CAS server to retrieve a proxy ticket
/// for the target URL specified.
/// </summary>
/// <remarks>
/// Problems retrieving proxy tickets are generally caused by SSL misconfiguration.
/// The CAS server must be configured to trust the SSL certificate on the web application's
/// server. The CAS server will attempt to establish an SSL connection to this web
/// application server to confirm that the proxy ticket request is legitimate. If the
/// server does not trust the SSL certificate or the certificate authority/chain of the SSL
/// certificate, the request will fail.
/// </remarks>
/// <param name="targetServiceUrl">The target Url to obtain a proxy ticket for</param>
/// <returns>
/// A proxy ticket for the target Url or an empty string if the request failed.
/// </returns>
public static string GetProxyTicketIdFor(string targetServiceUrl)
{
CommonUtils.AssertNotNullOrEmpty(targetServiceUrl, "targetServiceUrl parameter cannot be null or empty.");
if (ServiceTicketManager == null)
{
LogAndThrowConfigurationException("Proxy authentication requires a ServiceTicketManager");
}
FormsAuthenticationTicket formsAuthTicket = GetFormsAuthenticationTicket();
if (formsAuthTicket == null)
{
LogAndThrowOperationException("The request is not authenticated (does not have a CAS Service or Proxy ticket).");
}
if (string.IsNullOrEmpty(formsAuthTicket.UserData))
{
LogAndThrowOperationException("The request does not have a CAS Service Ticket.");
}
CasAuthenticationTicket casTicket = ServiceTicketManager.GetTicket(formsAuthTicket.UserData);
if (casTicket == null)
{
LogAndThrowOperationException("The request does not have a valid CAS Service Ticket.");
}
string proxyTicketResponse = null;
try
{
string proxyUrl = UrlUtil.ConstructProxyTicketRequestUrl(casTicket.ProxyGrantingTicket, targetServiceUrl);
proxyTicketResponse = HttpUtil.PerformHttpGet(proxyUrl, true);
}
catch
{
LogAndThrowOperationException("Unable to obtain CAS Proxy Ticket.");
}
if (String.IsNullOrEmpty(proxyTicketResponse))
{
LogAndThrowOperationException("Unable to obtain CAS Proxy Ticket (response was empty)");
}
string proxyTicket = null;
try
{
ServiceResponse serviceResponse = ServiceResponse.ParseResponse(proxyTicketResponse);
if (serviceResponse.IsProxySuccess)
{
ProxySuccess success = (ProxySuccess)serviceResponse.Item;
if (!String.IsNullOrEmpty(success.ProxyTicket))
{
protoLogger.Info(String.Format("Proxy success: {0}", success.ProxyTicket));
}
proxyTicket = success.ProxyTicket;
}
else
{
ProxyFailure failure = (ProxyFailure)serviceResponse.Item;
if (!String.IsNullOrEmpty(failure.Message) && !String.IsNullOrEmpty(failure.Code))
{
protoLogger.Info(String.Format("Proxy failure: {0} ({1})", failure.Message, failure.Code));
}
else if (!String.IsNullOrEmpty(failure.Message))
{
protoLogger.Info(String.Format("Proxy failure: {0}", failure.Message));
}
else if (!String.IsNullOrEmpty(failure.Code))
{
protoLogger.Info(String.Format("Proxy failure: Code {0}", failure.Code));
}
}
}
catch (InvalidOperationException)
{
LogAndThrowOperationException("CAS Server response does not conform to CAS 2.0 schema");
}
return proxyTicket;
}
/// <summary>
/// Redirects the current request to the CAS Login page
/// </summary>
public static void RedirectToLoginPage()
{
RedirectToLoginPage(Renew);
}
/// <summary>
/// Redirects the current request to the Login page and requires renewed
/// CAS credentials
/// </summary>
public static void RedirectToLoginPage(bool forceRenew)
{
Initialize();
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
string redirectUrl = UrlUtil.ConstructLoginRedirectUrl(false, forceRenew);
protoLogger.Info("Redirecting to " + redirectUrl);
response.Redirect(redirectUrl, false);
}
/// <summary>
/// Redirects the current request to the Cookies Required page
/// </summary>
public static void RedirectToCookiesRequiredPage()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
response.Redirect(UrlUtil.ResolveUrl(CookiesRequiredUrl), false);
}
/// <summary>
/// Redirects the current request to the Not Authorized page
/// </summary>
public static void RedirectToNotAuthorizedPage()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
response.Redirect(UrlUtil.ResolveUrl(NotAuthorizedUrl), false);
}
/// <summary>
/// Redirects the current request back to the requested page without
/// the CAS ticket artifact in the URL.
/// </summary>
internal static void RedirectFromLoginCallback()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (RequestEvaluator.GetRequestHasGatewayParameter())
{
// TODO: Only set Success if request is authenticated? Otherwise Failure.
// Doesn't make a difference from a security perspective, but may be clearer for users
SetGatewayStatusCookie(GatewayStatus.Success);
}
response.Redirect(UrlUtil.RemoveCasArtifactsFromUrl(request.Url.AbsoluteUri), false);
}
/// <summary>
/// Redirects the current request back to the requested page without
/// the gateway callback artifact in the URL.
/// </summary>
internal static void RedirectFromFailedGatewayCallback()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
SetGatewayStatusCookie(GatewayStatus.Failed);
string urlWithoutCasArtifact = UrlUtil.RemoveCasArtifactsFromUrl(request.Url.AbsoluteUri);
response.Redirect(urlWithoutCasArtifact, false);
}
/// <summary>
/// Attempt to perform a CAS gateway authentication. This causes a transparent
/// redirection out to the CAS server and back to the requesting page with or
/// without a CAS service ticket. If the user has already authenticated for
/// another service against the CAS server and the CAS server supports Single
/// Sign On, this will result in the user being automatically authenticated.
/// Otherwise, the user will remain anonymous.
/// </summary>
/// <param name="ignoreGatewayStatusCookie">
/// The Gateway Status Cookie reflects whether a gateway authentication has
/// already been attempted, in which case the redirection is generally
/// unnecessary. This property allows you to override the behavior and
/// perform a redirection regardless of whether it has already been attempted.
/// </param>
public static void GatewayAuthenticate(bool ignoreGatewayStatusCookie)
{
Initialize();
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
HttpApplication application = context.ApplicationInstance;
if (!ignoreGatewayStatusCookie)
{
if (GetGatewayStatus() != GatewayStatus.NotAttempted)
{
return;
}
}
SetGatewayStatusCookie(GatewayStatus.Attempting);
string redirectUrl = UrlUtil.ConstructLoginRedirectUrl(true, false);
protoLogger.Info("Performing gateway redirect to " + redirectUrl);
response.Redirect(redirectUrl, false);
application.CompleteRequest();
}
/// <summary>
/// Logs the user out of the application and attempts to perform a Single Sign
/// Out against the CAS server. If the CAS server is configured to support
/// Single Sign Out, this will prevent users from gateway authenticating
/// to other services. The CAS server will attempt to notify any other
/// applications to revoke the session. Each of the applications must be
/// configured to maintain session state on the server. In the case of
/// ASP.NET web applications using DotNetCasClient, this requires defining a
/// serviceTicketManager. The configuration for other client types (Java,
/// PHP) varies based on the client implementation. Consult the Apereo wiki
/// for more details.
/// </summary>
public static void SingleSignOut()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
// Necessary for ASP.NET MVC Support.
if (context.User.Identity.IsAuthenticated)
{
ClearAuthCookie();
string singleSignOutRedirectUrl = UrlUtil.ConstructSingleSignOutRedirectUrl();
// Leave endResponse as true. This will throw a handled ThreadAbortException
// but it is necessary to support SingleSignOut in ASP.NET MVC applications.
response.Redirect(singleSignOutRedirectUrl, true);
}
}
/// <summary>
/// Process SingleSignOut requests originating from another web application by removing the ticket
/// from the ServiceTicketManager (assuming one is configured). Without a ServiceTicketManager
/// configured, this method will not execute and this web application cannot respect external
/// SingleSignOut requests.
/// </summary>
/// <returns>
/// Boolean indicating whether the request was a SingleSignOut request, regardless of
/// whether or not the request actually required processing (non-existent/already expired).
/// </returns>
internal static void ProcessSingleSignOutRequest()
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
protoLogger.Debug("Examining request for single sign-out signature");
if (request.HttpMethod == "POST" && request.Form["logoutRequest"] != null)
{
protoLogger.Debug("Attempting to get CAS service ticket from request");
// TODO: Should we be checking to make sure that this special POST is coming from a trusted source?
// It would be tricky to do this by IP address because there might be a white list or something.
string casTicket = ExtractSingleSignOutTicketFromSamlResponse(request.Params["logoutRequest"]);
if (!String.IsNullOrEmpty(casTicket))
{
protoLogger.Info("Processing single sign-out request for " + casTicket);
ServiceTicketManager.RevokeTicket(casTicket);
protoLogger.Debug("Successfully removed " + casTicket);
response.StatusCode = 200;
response.ContentType = "text/plain";
response.Clear();
response.Write("OK");
context.ApplicationInstance.CompleteRequest();
}
}
}
/// <summary>
/// Process a Proxy Callback request from the CAS server. Proxy Callback requests occur as a part
/// of a proxy ticket request. When the web application requests a proxy ticket for a third party
/// service from the CAS server, the CAS server attempts to connect back to the web application
/// over an HTTPS connection. The success of this callback is essential for the proxy ticket
/// request to succeed. Failures are generally caused by SSL configuration errors. See the
/// description of the SingleSignOut method for more details. Assuming the SSL configuration is
/// correct, this method is responsible for handling the callback from the CAS server. For
/// more details, see the CAS protocol specification.
/// </summary>
/// <returns>
/// A Boolean indicating whether or not the proxy callback request is valid and mapped to a valid,
/// outstanding Proxy Granting Ticket IOU.
/// </returns>
internal static bool ProcessProxyCallbackRequest()
{
HttpContext context = HttpContext.Current;
HttpApplication application = context.ApplicationInstance;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string proxyGrantingTicketIou = request.Params[PARAM_PROXY_GRANTING_TICKET_IOU];
string proxyGrantingTicket = request.Params[PARAM_PROXY_GRANTING_TICKET];
if (String.IsNullOrEmpty(proxyGrantingTicket))
{
protoLogger.Info("Invalid request - {0} parameter not found", PARAM_PROXY_GRANTING_TICKET);
return false;
}
else if (String.IsNullOrEmpty(proxyGrantingTicketIou))
{
protoLogger.Info("Invalid request - {0} parameter not found", PARAM_PROXY_GRANTING_TICKET_IOU);
return false;
}
protoLogger.Info("Recieved proxyGrantingTicketId [{0}] for proxyGrantingTicketIou [{1}]", proxyGrantingTicket, proxyGrantingTicketIou);
ProxyTicketManager.InsertProxyGrantingTicketMapping(proxyGrantingTicketIou, proxyGrantingTicket);
// TODO: Consider creating a DotNetCasClient.Validation.Schema.Cas20.ProxySuccess object and serializing it.
response.Write("<?xml version=\"1.0\"?>");
response.Write("<casClient:proxySuccess xmlns:casClient=\"http://www.yale.edu/tp/casClient\" />");
application.CompleteRequest();
return true;
}
/// <summary>
/// Validates a ticket contained in the URL, presumably generated by
/// the CAS server after a successful authentication. The actual ticket
/// validation is performed by the configured TicketValidator
/// (i.e., CAS 1.0, CAS 2.0, SAML 1.0). If the validation succeeds, the
/// request is authenticated and a FormsAuthenticationCookie and
/// corresponding CasAuthenticationTicket are created for the purpose of
/// authenticating subsequent requests (see ProcessTicketValidation
/// method). If the validation fails, the authentication status remains
/// unchanged (generally the user is and remains anonymous).
/// </summary>
internal static void ProcessTicketValidation()
{
HttpContext context = HttpContext.Current;
HttpApplication app = context.ApplicationInstance;
HttpRequest request = context.Request;
CasAuthenticationTicket casTicket;
ICasPrincipal principal;
string ticket = request[TicketValidator.ArtifactParameterName];
try
{
// Attempt to authenticate the ticket and resolve to an ICasPrincipal
principal = TicketValidator.Validate(ticket);
// Save the ticket in the FormsAuthTicket. Encrypt the ticket and send it as a cookie.
casTicket = new CasAuthenticationTicket(
ticket,
UrlUtil.RemoveCasArtifactsFromUrl(request.Url.AbsoluteUri),
request.UserHostAddress,
principal.Assertion
);
if (ProxyTicketManager != null && !string.IsNullOrEmpty(principal.ProxyGrantingTicket))
{
casTicket.ProxyGrantingTicketIou = principal.ProxyGrantingTicket;
casTicket.Proxies.AddRange(principal.Proxies);
string proxyGrantingTicket = ProxyTicketManager.GetProxyGrantingTicket(casTicket.ProxyGrantingTicketIou);
if (!string.IsNullOrEmpty(proxyGrantingTicket))
{
casTicket.ProxyGrantingTicket = proxyGrantingTicket;
}
}
// TODO: Check the last 2 parameters. We want to take the from/to dates from the FormsAuthenticationTicket. However, we may need to do some clock drift correction.
FormsAuthenticationTicket formsAuthTicket = CreateFormsAuthenticationTicket(principal.Identity.Name, FormsAuthentication.FormsCookiePath, ticket, null, null);
SetAuthCookie(formsAuthTicket);
// Also save the ticket in the server store (if configured)
if (ServiceTicketManager != null)
{
ServiceTicketManager.UpdateTicketExpiration(casTicket, formsAuthTicket.Expiration);
}
// Jump directly to EndRequest. Don't allow the Page and/or Handler to execute.
// EndRequest will redirect back without the ticket in the URL
app.CompleteRequest();
return;
}
catch (TicketValidationException e)
{
// Leave principal null. This might not have been a CAS service ticket.
protoLogger.Error("Ticket validation error: " + e);
}
}
/// <summary>
/// Attempts to authenticate requests subsequent to the initial authentication
/// request (handled by ProcessTicketValidation). This method looks for a
/// FormsAuthenticationCookie containing a FormsAuthenticationTicket and attempts
/// to confirms its validitiy. It either contains the CAS service ticket or a
/// reference to a CasAuthenticationTicket stored in the ServiceTicketManager
/// (if configured). If it succeeds, the context.User and Thread.CurrentPrincipal
/// are set with a ICasPrincipal and the current request is considered
/// authenticated. Otherwise, the current request is effectively anonymous.
/// </summary>
internal static void ProcessRequestAuthentication()
{
HttpContext context = HttpContext.Current;
// Look for a valid FormsAuthenticationTicket encrypted in a cookie.
CasAuthenticationTicket casTicket = null;
FormsAuthenticationTicket formsAuthenticationTicket = GetFormsAuthenticationTicket();
if (formsAuthenticationTicket != null)
{
ICasPrincipal principal;
if (ServiceTicketManager != null)
{
string serviceTicket = formsAuthenticationTicket.UserData;
casTicket = ServiceTicketManager.GetTicket(serviceTicket);
if (casTicket != null)
{
IAssertion assertion = casTicket.Assertion;
if (!ServiceTicketManager.VerifyClientTicket(casTicket))
{
securityLogger.Warn("CasAuthenticationTicket failed verification: " + casTicket);
// Deletes the invalid FormsAuthentication cookie from the client.
ClearAuthCookie();
ServiceTicketManager.RevokeTicket(serviceTicket);
// Don't give this request a User/Principal. Remove it if it was created
// by the underlying FormsAuthenticationModule or another module.
principal = null;
}
else
{
if (ProxyTicketManager != null && !string.IsNullOrEmpty(casTicket.ProxyGrantingTicketIou) && string.IsNullOrEmpty(casTicket.ProxyGrantingTicket))
{
string proxyGrantingTicket = ProxyTicketManager.GetProxyGrantingTicket(casTicket.ProxyGrantingTicketIou);
if (!string.IsNullOrEmpty(proxyGrantingTicket))
{
casTicket.ProxyGrantingTicket = proxyGrantingTicket;
}
}
principal = new CasPrincipal(assertion);
}
}
else
{
// This didn't resolve to a ticket in the TicketStore. Revoke it.
ClearAuthCookie();
securityLogger.Debug("Revoking ticket " + serviceTicket);
ServiceTicketManager.RevokeTicket(serviceTicket);
// Don't give this request a User/Principal. Remove it if it was created
// by the underlying FormsAuthenticationModule or another module.
principal = null;
}
}
else
{
principal = new CasPrincipal(new Assertion(formsAuthenticationTicket.Name));
}
context.User = principal;
Thread.CurrentPrincipal = principal;
currentPrincipal = principal;
if (principal == null)
{
// Remove the cookie from the client
ClearAuthCookie();
}
else
{
// Extend the expiration of the cookie if FormsAuthentication is configured to do so.
if (FormsAuthentication.SlidingExpiration)
{
FormsAuthenticationTicket newTicket = FormsAuthentication.RenewTicketIfOld(formsAuthenticationTicket);
if (newTicket != null && newTicket != formsAuthenticationTicket)
{
SetAuthCookie(newTicket);
if (ServiceTicketManager != null)
{
ServiceTicketManager.UpdateTicketExpiration(casTicket, newTicket.Expiration);
}
}
}
}
}
}
/// <summary>
/// Attempts to set the GatewayStatus client cookie. If the cookie is not
/// present and equal to GatewayStatus.Attempting when a CAS Gateway request
/// comes in (indicated by the presence of the 'gatewayParameterName'
/// defined in web.config appearing in the URL), the server knows that the
/// client is not accepting session cookies and will optionally redirect
/// the user to the 'cookiesRequiredUrl' (also defined in web.config). If
/// 'cookiesRequiredUrl' is not defined but 'gateway' is, every page request
/// will result in a round-trip to the CAS server.
/// </summary>
/// <param name="gatewayStatus">The GatewayStatus to attempt to store</param>
internal static void SetGatewayStatusCookie(GatewayStatus gatewayStatus)
{
Initialize();
HttpContext current = HttpContext.Current;
HttpCookie cookie = new HttpCookie(GatewayStatusCookieName, gatewayStatus.ToString());
cookie.HttpOnly = false;
cookie.Path = FormsAuthentication.FormsCookiePath;
cookie.Secure = false;
if (FormsAuthentication.CookieDomain != null)
{
cookie.Domain = FormsAuthentication.CookieDomain;
}
// Add it to the request collection for later processing during this request
current.Request.Cookies.Remove(GatewayStatusCookieName);
current.Request.Cookies.Add(cookie);
// Add it to the response collection for delivery to client
current.Response.Cookies.Add(cookie);
}
/// <summary>
/// Retrieves the GatewayStatus from the client cookie.
/// </summary>
/// <returns>
/// The GatewayStatus stored in the cookie if present, otherwise
/// GatewayStatus.NotAttempted.
/// </returns>
public static GatewayStatus GetGatewayStatus()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpCookie cookie = context.Request.Cookies[GatewayStatusCookieName];
GatewayStatus status;
if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
{
try
{
// Parse the value out of the cookie
status = (GatewayStatus) Enum.Parse(typeof (GatewayStatus), cookie.Value);
}
catch (ArgumentException)
{
// If the cookie contains an invalid value, clear the cookie
// and return GatewayStatus.NotAttempted
SetGatewayStatusCookie(GatewayStatus.NotAttempted);
status = GatewayStatus.NotAttempted;
}
}
else
{
// Use the default value GatewayStatus.NotAttempted
status = GatewayStatus.NotAttempted;
}
return status;
}
/// <summary>
/// Sends a blank and expired FormsAuthentication cookie to the
/// client response. This effectively removes the FormsAuthentication
/// cookie and revokes the FormsAuthenticationTicket. It also removes
/// the cookie from the current Request object, preventing subsequent
/// code from being able to access it during the execution of the
/// current request.
/// </summary>
public static void ClearAuthCookie()
{
Initialize();
HttpContext current = HttpContext.Current;
// Don't let anything see the incoming cookie
current.Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
// Remove the cookie from the response collection (by adding an expired/empty version).
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
cookie.Expires = DateTime.Now.AddMonths(-1);
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.FormsCookiePath;
current.Response.Cookies.Add(cookie);
}
/// <summary>
/// Encrypts a FormsAuthenticationTicket in an HttpCookie (using
/// GetAuthCookie) and includes it in both the request and the response.
/// </summary>
/// <param name="clientTicket">The FormsAuthenticationTicket to encode</param>
public static void SetAuthCookie(FormsAuthenticationTicket clientTicket)
{
Initialize();
HttpContext current = HttpContext.Current;
if (!current.Request.IsSecureConnection && FormsAuthentication.RequireSSL)
{
throw new HttpException("Connection not secure while creating secure cookie");
}
// Obtain the forms authentication cookie from the ticket
HttpCookie authCookie = GetAuthCookie(clientTicket);
// Clear the previous cookie from the current HTTP request
current.Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
// Store the new cookie in both the request and response objects
current.Request.Cookies.Add(authCookie);
current.Response.Cookies.Add(authCookie);
}
/// <summary>
/// Creates an HttpCookie containing an encrypted FormsAuthenticationTicket,
/// which in turn contains a CAS service ticket.
/// </summary>
/// <param name="ticket">The FormsAuthenticationTicket to encode</param>
/// <returns>An HttpCookie containing the encrypted FormsAuthenticationTicket</returns>
public static HttpCookie GetAuthCookie(FormsAuthenticationTicket ticket)
{
Initialize();
string str = FormsAuthentication.Encrypt(ticket);
if (String.IsNullOrEmpty(str))
{
throw new HttpException("Unable to encrypt cookie ticket");
}
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, str);
// Per http://support.microsoft.com/kb/900111 :
// In ASP.NET 2.0, forms authentication cookies are HttpOnly cookies.
// HttpOnly cookies cannot be accessed through client script. This
// functionality helps reduce the chances of replay attacks.
cookie.HttpOnly = true;
cookie.Path = FormsAuthentication.FormsCookiePath;
cookie.Secure = FormsAuthentication.RequireSSL;
if (FormsAuthentication.CookieDomain != null)
{
cookie.Domain = FormsAuthentication.CookieDomain;
}
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
return cookie;
}
/// <summary>
/// Creates a FormsAuthenticationTicket for storage on the client.
/// The UserData field contains the CAS Service Ticket which can be
/// used by the server-side ServiceTicketManager to retrieve additional
/// details about the ticket (e.g. assertions)
/// </summary>
/// <param name="netId">User associated with the ticket</param>
/// <param name="cookiePath">Relative path on server in which cookie is valid</param>
/// <param name="serviceTicket">CAS service ticket</param>
/// <param name="validFromDate">Ticket valid from date</param>
/// <param name="validUntilDate">Ticket valid too date</param>
/// <returns>Instance of a FormsAuthenticationTicket</returns>
public static FormsAuthenticationTicket CreateFormsAuthenticationTicket(string netId, string cookiePath, string serviceTicket, DateTime? validFromDate, DateTime? validUntilDate)
{
Initialize();
protoLogger.Debug("Creating FormsAuthenticationTicket for " + serviceTicket);
DateTime fromDate = validFromDate.HasValue ? validFromDate.Value : DateTime.Now;
DateTime toDate = validUntilDate.HasValue ? validUntilDate.Value : fromDate.Add(FormsTimeout);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2,
netId,
fromDate,
toDate,
false,
serviceTicket,
cookiePath ?? FormsAuthentication.FormsCookiePath
);
return ticket;
}
/// <summary>
/// Looks for a FormsAuthentication cookie and attempts to
/// parse a valid, non-expired FormsAuthenticationTicket.
/// It ensures that the UserData field has a value (presumed
/// to be a CAS Service Ticket).
/// </summary>
/// <returns>
/// Returns the FormsAuthenticationTicket contained in the
/// cookie or null if any issues are encountered.
/// </returns>
public static FormsAuthenticationTicket GetFormsAuthenticationTicket()
{
Initialize();
HttpContext context = HttpContext.Current;
HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null)
{
return null;
}
if (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now)
{
ClearAuthCookie();
return null;
}
if (String.IsNullOrEmpty(cookie.Value))
{
ClearAuthCookie();
return null;
}
FormsAuthenticationTicket formsAuthTicket;
try
{
formsAuthTicket = FormsAuthentication.Decrypt(cookie.Value);
}
catch
{
ClearAuthCookie();
return null;
}
if (formsAuthTicket == null)
{
ClearAuthCookie();
return null;
}
if (formsAuthTicket.Expired)
{
ClearAuthCookie();
return null;
}
if (String.IsNullOrEmpty(formsAuthTicket.UserData))
{
ClearAuthCookie();
return null;
}
return formsAuthTicket;
}
/// <summary>
/// Extracts the CAS ticket from the SAML message supplied.
/// </summary>
/// <param name="xmlAsString">SAML message from CAS server</param>
/// <returns>The CAS ticket contained in SAML message</returns>
private static string ExtractSingleSignOutTicketFromSamlResponse(string xmlAsString)
{
XmlParserContext xmlParserContext = new XmlParserContext(null, xmlNamespaceManager, null, XmlSpace.None);
string elementText = null;
if (!String.IsNullOrEmpty(xmlAsString) && !String.IsNullOrEmpty(XML_SESSION_INDEX_ELEMENT_NAME))
{
using (TextReader textReader = new StringReader(xmlAsString))
{
XmlReader reader = XmlReader.Create(textReader, xmlReaderSettings, xmlParserContext);
bool foundElement = reader.ReadToFollowing(XML_SESSION_INDEX_ELEMENT_NAME);
if (foundElement)
{
elementText = reader.ReadElementString();
}
reader.Close();
}
}
return elementText;
}
private static void LogAndThrowConfigurationException(string message)
{
configLogger.Error(message);
throw new CasConfigurationException(message);
}
private static void LogAndThrowOperationException(string message)
{
protoLogger.Error(message);
throw new InvalidOperationException(message);
}
#endregion
#region Properties
/// <summary>
/// Name of ticket validator that validates CAS tickets using a
/// particular protocol. Valid values are Cas10, Cas20, and Saml11.
/// </summary>
public static string TicketValidatorName
{
get
{
Initialize();
return ticketValidatorName;
}
}
/// <summary>
/// An instance of the TicketValidator specified in the
/// TicketValidatorName property. This will either be an instance of
/// a Cas10TicketValidator, Cas20TicketValidator, or
/// Saml11TicketValidator.
/// </summary>
internal static ITicketValidator TicketValidator
{
get
{
Initialize();
return ticketValidator;
}
}
/// <summary>
/// The ticket manager to use to store tickets returned by the CAS server
/// for validation, revocation, and single sign out support.
/// <remarks>
/// Currently supported values: CacheServiceTicketManager
/// </remarks>
/// </summary>
public static string ServiceTicketManagerProvider
{
get
{
Initialize();
return serviceTicketManagerProvider;
}
}
/// <summary>
/// An instance of the provider specified in the ServiceTicketManagerProvider property.
/// ServiceTicketManager will be null if no serviceTicketManager is
/// defined in web.config. If a ServiceTicketManager is defined, this will allow
/// access to and revocation of outstanding CAS service tickets along with
/// additional information about the service tickets (i.e., IP address,
/// assertions, etc.).
/// </summary>
public static IServiceTicketManager ServiceTicketManager
{
get
{
Initialize();
return serviceTicketManager;
}
}
/// <summary>
/// The ticket manager to use to store and resolve ProxyGrantingTicket IOUs to
/// ProxyGrantingTickets
/// <remarks>
/// Currently supported values: CacheProxyTicketManager
/// </remarks>
/// </summary>
public static string ProxyTicketManagerProvider
{
get
{
Initialize();
return proxyTicketManagerProvider;
}
}
/// <summary>
/// An instance of the provider specified in the ProxyTicketManagerProvider property.
/// ProxyTicketManager will be null if no proxyTicketManager is
/// defined in web.config. If a ProxyTicketManager is defined, this will allow
/// generation of proxy tickets for external sites and services.
/// </summary>
public static IProxyTicketManager ProxyTicketManager
{
get
{
Initialize();
return proxyTicketManager;
}
}
/// <summary>
/// Enable CAS gateway feature, see https://apereo.github.io/cas/5.1.x/protocol/CAS-Protocol-Specification.html section 2.1.1.
/// Default is false.
/// </summary>
public static bool Gateway
{
get
{
Initialize();
return gateway;
}
}
/// <summary>
/// The name of the cookie used to store the Gateway status (NotAttempted,
/// Success, Failed). This cookie is used to prevent the client from
/// attempting to gateway authenticate every request.
/// </summary>
public static string GatewayStatusCookieName
{
get
{
Initialize();
return gatewayStatusCookieName;
}
}
/// <summary>
/// The Forms LoginUrl property set in system.web/authentication/forms
/// </summary>
public static string FormsLoginUrl
{
get
{
Initialize();
return formsLoginUrl;
}
}
/// <summary>
/// The Forms Timeout property set in system.web/authentication/forms
/// </summary>
public static TimeSpan FormsTimeout
{
get
{
Initialize();
return formsTimeout;
}
}
/// <summary>
/// URL of CAS login form.
/// </summary>
public static string CasServerLoginUrl
{
get
{
Initialize();
return casServerLoginUrl;
}
}
/// <summary>
/// URL to root of CAS server application. For example, if your
/// CasServerLoginUrl is https://fed.example.com/cas/login
/// then your CasServerUrlPrefix would be https://fed.example.com/cas/
/// </summary>
public static string CasServerUrlPrefix
{
get
{
Initialize();
return casServerUrlPrefix;
}
}
/// <summary>
/// SAML ticket validator property to allow at most the given time
/// difference in ms between artifact (ticket) timestamp and CAS server
/// system time. Increasing this may have negative security consequences;
/// we recommend fixing sources of clock drift rather than increasing
/// this value.
/// </summary>
public static long TicketTimeTolerance
{
get
{
Initialize();
return ticketTimeTolerance;
}
}
/// <summary>
/// The server name of the server hosting the client application. Service URL
/// will be dynamically constructed using this value if Service is not specified.
/// e.g. https://app.princeton.edu/
/// </summary>
public static string ServerName
{
get
{
Initialize();
return serverName;
}
}
/// <summary>
/// Force user to reauthenticate to CAS before accessing this application.
/// This provides additional security at the cost of usability since it effectively
/// disables SSO for this application.
/// </summary>
public static bool Renew
{
get
{
Initialize();
return renew;
}
}
/// <summary>
/// Whether to redirect to the same URL after ticket validation, but without the ticket
/// in the parameter.
/// </summary>
public static bool RedirectAfterValidation
{
get
{
Initialize();
return redirectAfterValidation;
}
}
/// <summary>
/// Specifies whether external single sign out requests should be processed.
/// </summary>
public static bool ProcessIncomingSingleSignOutRequests
{
get
{
Initialize();
return singleSignOut;
}
}
/// <summary>
/// The URL to redirect to when the request has a valid CAS ticket but the user is
/// not authorized to access the URL or resource. If this option is set, users will
/// be redirected to this URL. If it is not set, the user will be redirected to the
/// CAS login screen with a Renew option in the URL (to force for alternate credential
/// collection).
/// </summary>
public static string NotAuthorizedUrl
{
get
{
Initialize();
return notAuthorizedUrl;
}
}
/// <summary>
/// The URL to redirect to when the client is not accepting session
/// cookies. This condition is detected only when gateway is enabled.
/// This will lock the users onto a specific page. Otherwise, every
/// request will cause a silent round-trip to the CAS server, adding
/// a parameter to the URL.
/// </summary>
public static string CookiesRequiredUrl
{
get
{
Initialize();
return cookiesRequiredUrl;
}
}
/// <summary>
/// The URL parameter to append to outbound CAS request's ServiceName
/// when initiating an automatic CAS Gateway request. This parameter
/// plays a role in detecting whether or not the client has cookies
/// enabled. The default value is 'gatewayResponse' and only needs to
/// be explicitly defined if that URL parameter has a meaning elsewhere
/// in your application.
/// </summary>
public static string GatewayParameterName
{
get
{
Initialize();
return gatewayParameterName;
}
}
/// <summary>
/// The URL parameter to append to outbound CAS proxy request's pgtUrl
/// when initiating an proxy ticket service validation. This is used
/// to determine whether the request is originating from the CAS server
/// and contains a pgtIou.
/// </summary>
public static string ProxyCallbackParameterName
{
get
{
Initialize();
return proxyCallbackParameterName;
}
}
/// <summary>
/// URL for CAS Proxy callback
/// </summary>
public static String CasProxyCallbackUrl
{
get
{
Initialize();
return casProxyCallbackUrl;
}
}
/// <summary>
/// Specifies whether to require CAS for requests that have null/empty content-types
/// </summary>
public static bool RequireCasForMissingContentTypes
{
get
{
Initialize();
return requireCasForMissingContentTypes;
}
}
/// <summary>
/// Content-types for which CAS authentication will be required
/// </summary>
public static string[] RequireCasForContentTypes
{
get
{
Initialize();
return requireCasForContentTypes;
}
}
/// <summary>
/// Handlers for which CAS authentication will be bypassed.
/// </summary>
public static string[] BypassCasForHandlers
{
get
{
Initialize();
return bypassCasForHandlers;
}
}
#endregion
}
} | apache-2.0 |
Ramzi-Alqrainy/SELK | solr-4.10.0/docs/solr-dataimporthandler/org/apache/solr/handler/dataimport/class-use/RegexTransformer.html | 4956 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Tue Aug 26 20:50:25 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.handler.dataimport.RegexTransformer (Solr 4.10.0 API)</title>
<meta name="date" content="2014-08-26">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.handler.dataimport.RegexTransformer (Solr 4.10.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/handler/dataimport/RegexTransformer.html" title="class in org.apache.solr.handler.dataimport">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/dataimport/class-use/RegexTransformer.html" target="_top">Frames</a></li>
<li><a href="RegexTransformer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.handler.dataimport.RegexTransformer" class="title">Uses of Class<br>org.apache.solr.handler.dataimport.RegexTransformer</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.handler.dataimport.RegexTransformer</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/handler/dataimport/RegexTransformer.html" title="class in org.apache.solr.handler.dataimport">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/dataimport/class-use/RegexTransformer.html" target="_top">Frames</a></li>
<li><a href="RegexTransformer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| apache-2.0 |
izenecloud/izenelib | source/3rdparty/yaml-cpp/node.cpp | 272 | #include <3rdparty/yaml-cpp/node/node.h>
#include "nodebuilder.h"
#include "nodeevents.h"
namespace YAML
{
Node Clone(const Node& node)
{
NodeEvents events(node);
NodeBuilder builder;
events.Emit(builder);
return builder.Root();
}
}
| apache-2.0 |
miaotu3/Mitotu | MiaoTu/src/main/java/com/miaotu/adapter/GroupUserAdapter.java | 2624 | package com.miaotu.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import com.miaotu.R;
import com.miaotu.activity.PersonCenterActivity;
import com.miaotu.model.GroupUserInfo;
import com.miaotu.util.Util;
import com.miaotu.view.CircleImageView;
import java.util.List;
/**
* Created by Jayden on 2015/5/29.
*/
public class GroupUserAdapter extends BaseAdapter{
private List<GroupUserInfo> groupInfos;
private LayoutInflater mLayoutInflater = null;
private Context mContext;
public GroupUserAdapter(Context context, List<GroupUserInfo> groupInfos){
this.groupInfos = groupInfos;
mLayoutInflater = LayoutInflater.from(context);
this.mContext = context;
}
@Override
public int getCount() {
return groupInfos == null?0:groupInfos.size();
}
@Override
public Object getItem(int i) {
return groupInfos.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder holder = null;
if(view == null){
view = mLayoutInflater.inflate(R.layout.item_group_user, null);
holder = new ViewHolder();
holder.ivPhoto = (CircleImageView) view.findViewById(R.id.iv_head_photo);
holder.tvName = (TextView) view.findViewById(R.id.tv_name);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
UrlImageViewHelper.setUrlDrawable(holder.ivPhoto, groupInfos.get(i).getHeadurl(),
R.drawable.icon_default_head_photo);
holder.tvName.setText(groupInfos.get(i).getNickname());
holder.ivPhoto.setTag(i);
holder.ivPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!Util.isNetworkConnected(mContext)) {
return;
}
int pos = (int) view.getTag();
Intent intent = new Intent(mContext, PersonCenterActivity.class);
intent.putExtra("uid", groupInfos.get(pos).getUid());
mContext.startActivity(intent);
}
});
return view;
}
public class ViewHolder{
CircleImageView ivPhoto;
TextView tvName;
}
}
| apache-2.0 |
shlyren/ONE-OC | ONE/Classes/Music-音乐/View/ONECommentCell.h | 624 | //
// ONECommentCell.h
// ONE
//
// Created by 任玉祥 on 16/4/2.
// Copyright © 2016年 任玉祥. All rights reserved.
//
#import <UIKit/UIKit.h>
@class ONEMusicCommentItem;
@interface ONECommentCell : UITableViewCell
/** 评论模型 */
@property (nonatomic, strong) ONEMusicCommentItem *commentItem;
/** 详情id */
@property (nonatomic, strong) NSString *detail_id;
/** 是属于哪一种评论的点赞参数 比如 阅读,还是音乐 */
@property (nonatomic, strong) NSString *commentType;
/** 行高 */
@property (nonatomic, assign) CGFloat rowHeight;
@end
| apache-2.0 |
nguerrera/roslyn | src/Workspaces/Core/Portable/Shared/Extensions/IAssemblySymbolExtensions.cs | 2282 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class IAssemblySymbolExtensions
{
private const string AttributeSuffix = "Attribute";
public static bool ContainsNamespaceName(
this List<IAssemblySymbol> assemblies,
string namespaceName)
{
// PERF: Expansion of "assemblies.Any(a => a.NamespaceNames.Contains(namespaceName))"
// to avoid allocating a lambda.
foreach (var a in assemblies)
{
if (a.NamespaceNames.Contains(namespaceName))
{
return true;
}
}
return false;
}
public static bool ContainsTypeName(this List<IAssemblySymbol> assemblies, string typeName, bool tryWithAttributeSuffix = false)
{
if (!tryWithAttributeSuffix)
{
// PERF: Expansion of "assemblies.Any(a => a.TypeNames.Contains(typeName))"
// to avoid allocating a lambda.
foreach (var a in assemblies)
{
if (a.TypeNames.Contains(typeName))
{
return true;
}
}
}
else
{
var attributeName = typeName + AttributeSuffix;
foreach (var a in assemblies)
{
var typeNames = a.TypeNames;
if (typeNames.Contains(typeName) || typeNames.Contains(attributeName))
{
return true;
}
}
}
return false;
}
public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly)
{
return
Equals(assembly, toAssembly) ||
(assembly.IsInteractive && toAssembly.IsInteractive) ||
toAssembly.GivesAccessTo(assembly);
}
}
}
| apache-2.0 |
akshayahn/parfait | parfait-spring/src/test/java/com/custardsource/parfait/spring/DelayingBean.java | 355 | package com.custardsource.parfait.spring;
import java.util.Random;
@Profiled
public class DelayingBean {
private final int delay;
public DelayingBean() {
this.delay = new Random().nextInt(100);
}
@Profiled
public void doThing() {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
qubs/data-centre | climate_data/migrations/0014_auto_20160906_0135.py | 506 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-06 01:35
from __future__ import unicode_literals
from django.db import migrations, models
def load_settings(apps, schema_editor):
Setting = apps.get_model("climate_data", "Setting")
Setting(
name="receiving_data",
value="0"
).save()
class Migration(migrations.Migration):
dependencies = [
('climate_data', '0013_setting'),
]
operations = [
migrations.RunPython(load_settings)
]
| apache-2.0 |
kushalagrawal/RestExpress | src/java/com/strategicgains/restexpress/response/ResponseProcessorResolver.java | 2010 | /*
Copyright 2012, Strategic Gains, 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.strategicgains.restexpress.response;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author toddf
* @since May 14, 2012
*/
public class ResponseProcessorResolver
{
private Map<String, ResponseProcessor> processors = new HashMap<String, ResponseProcessor>();
private String defaultFormat;
public ResponseProcessorResolver()
{
super();
}
public ResponseProcessorResolver(Map<String, ResponseProcessor> processors, String defaultFormat)
{
super();
this.processors.putAll(processors);
this.defaultFormat = defaultFormat;
}
public ResponseProcessor put(String format, ResponseProcessor processor)
{
return processors.put(format, processor);
}
public void setDefaultFormat(String format)
{
this.defaultFormat = format;
}
public ResponseProcessor resolve(String requestFormat)
{
if (requestFormat == null || requestFormat.trim().isEmpty())
{
return getDefault();
}
return resolveViaSpecifiedFormat(requestFormat);
}
public ResponseProcessor getDefault()
{
return resolveViaSpecifiedFormat(defaultFormat);
}
private ResponseProcessor resolveViaSpecifiedFormat(String format)
{
if (format == null || format.trim().isEmpty())
{
return null;
}
return processors.get(format);
}
/**
* @return
*/
public Collection<String> getSupportedFormats()
{
return processors.keySet();
}
}
| apache-2.0 |
kevinearls/camel | examples/camel-example-fhir-osgi/src/test/java/org/apache/camel/example/fhir/osgi/FhirOsgiIT.java | 3055 | /**
* 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.example.fhir.osgi;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.inject.Inject;
import org.apache.camel.CamelContext;
import org.apache.camel.ServiceStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import static org.ops4j.pax.exam.CoreOptions.when;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.debugConfiguration;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class FhirOsgiIT {
@Inject
private CamelContext context;
@Configuration
public Option[] config() throws IOException {
return options(
PaxExamOptions.KARAF.option(),
PaxExamOptions.CAMEL_FHIR.option(),
streamBundle(
TinyBundles.bundle()
.read(
Files.newInputStream(
Paths.get("target")
.resolve("camel-example-fhir-osgi.jar")))
.build()),
when(false)
.useOptions(
debugConfiguration("5005", true)),
CoreOptions.composite(editConfigurationFilePut(
"etc/org.apache.camel.example.fhir.osgi.configuration.cfg",
new File("org.apache.camel.example.fhir.osgi.configuration.cfg")))
);
}
@Test
public void testRouteStatus() {
assertNotNull(context);
assertEquals("Route status is incorrect!", ServiceStatus.Started, context.getRouteController().getRouteStatus("fhir-example-osgi"));
}
}
| apache-2.0 |
apache/olingo-odata4 | samples/tutorials/p11_batch/src/main/java/myservice/mynamespace/web/DemoServlet.java | 3114 | /*
* 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 myservice.mynamespace.web;
import java.io.IOException;
import java.lang.Override;import java.lang.RuntimeException;import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import myservice.mynamespace.data.Storage;
import myservice.mynamespace.service.DemoBatchProcessor;
import myservice.mynamespace.service.DemoEdmProvider;
import myservice.mynamespace.service.DemoEntityCollectionProcessor;
import myservice.mynamespace.service.DemoEntityProcessor;
import myservice.mynamespace.service.DemoPrimitiveProcessor;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHttpHandler;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(DemoServlet.class);
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
HttpSession session = req.getSession(true);
Storage storage = (Storage) session.getAttribute(Storage.class.getName());
if (storage == null) {
storage = new Storage();
session.setAttribute(Storage.class.getName(), storage);
}
// create odata handler and configure it with EdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList<EdmxReference>());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new DemoEntityCollectionProcessor(storage));
handler.register(new DemoEntityProcessor(storage));
handler.register(new DemoPrimitiveProcessor(storage));
handler.register(new DemoBatchProcessor(storage));
// let the handler do the work
handler.process(req, resp);
} catch (RuntimeException e) {
LOG.error("Server Error occurred in ExampleServlet", e);
throw new ServletException(e);
}
}
}
| apache-2.0 |
googleapis/google-cloud-ruby | google-cloud-resource_settings-v1/proto_docs/README.md | 189 | # Resource Settings V1 Protocol Buffer Documentation
These files are for the YARD documentation of the generated protobuf files.
They are not intended to be required or loaded at runtime.
| apache-2.0 |
orwir/processor | core/src/main/java/ingvar/android/processor/service/Processor.java | 8123 | package ingvar.android.processor.service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import ingvar.android.processor.exception.ProcessorException;
import ingvar.android.processor.observation.IObserver;
import ingvar.android.processor.observation.ScheduledObserver;
import ingvar.android.processor.persistence.Time;
import ingvar.android.processor.task.AbstractTask;
import ingvar.android.processor.task.Execution;
import ingvar.android.processor.task.ITask;
import ingvar.android.processor.task.ScheduledExecution;
import ingvar.android.processor.util.LW;
/**
* Wrapper for processing service.
* Just provide helper methods.
* Logged under DEBUG level.
*
* <br/><br/>Created by Igor Zubenko on 2015.03.19.
*/
public class Processor<S extends ProcessorService> {
public static final String TAG = Processor.class.getSimpleName();
private Class<? extends ProcessorService> serviceClass;
private Map<AbstractTask, IObserver[]> plannedTasks;
private ServiceConnection connection;
private S service;
public Processor(Class<? extends ProcessorService> serviceClass) {
this.serviceClass = serviceClass;
this.service = null;
this.connection = new Connection();
this.plannedTasks = new ConcurrentHashMap<>();
}
/**
* Send task for execution.
*
* @param task task
* @param observers task observers
* @return {@link Future} of task execution
*/
public Execution execute(AbstractTask task, IObserver... observers) {
if(service == null) {
throw new ProcessorException("Service is not bound yet!");
}
return service.execute(task, observers);
}
/**
* If service is bound execute task, otherwise add to queue.
*
* @param task task
* @param observers task observers
*/
public void planExecute(AbstractTask task, IObserver... observers) {
if(isBound()) {
execute(task, observers);
} else {
plannedTasks.put(task, observers);
LW.d(TAG, "Queued task %s", task);
}
}
/**
* Schedule task for single execution.
* If task with same key & cache class already exists it will be cancelled and their observers will be removed.
*
* @param task task
* @param delay the time from now to delay execution (millis)
* @param observers task observers
* @return {@link ScheduledFuture} of task execution
*/
public ScheduledExecution schedule(AbstractTask task, long delay, ScheduledObserver... observers) {
if(!isBound()) {
throw new ProcessorException("Service is not bound yet!");
}
return service.schedule(task, delay, observers);
}
/**
* Schedule task for multiple executions.
* If task with same key & cache class already exists it will be cancelled and their observers will be removed.
*
* @param task task
* @param initialDelay the time to delay first execution
* @param delay the delay between the termination of one execution and the commencement of the next.
* @param observers task observers
* @return {@link ScheduledFuture} of task execution
*/
public ScheduledExecution schedule(AbstractTask task, long initialDelay, long delay, ScheduledObserver... observers) {
if(!isBound()) {
throw new ProcessorException("Service is not bound yet!");
}
return service.schedule(task, initialDelay, delay, observers);
}
public void cancel(AbstractTask task) {
if(!isBound()) {
throw new ProcessorException("Service is not bound yet!");
}
service.cancel(task);
}
public ScheduledExecution getScheduled(AbstractTask task) {
if(!isBound()) {
throw new ProcessorException("Service is not bound yet!");
}
return service.getScheduled(task);
}
/**
* Remove registered observers from task.
*
* @param task task
*/
public void removeObservers(ITask task) {
service.getObserverManager().remove(task);
}
/**
* Obtain task result from cache.
*
* @param key result identifier
* @param dataClass single result item class
* @param expiryTime how much time data consider valid in the repository
* @param <R> returned result class
* @return cached result if exists and did not expired, null otherwise
*/
public <R> R obtainFromCache(Object key, Class dataClass, long expiryTime) {
return service.getCacheManager().obtain(key, dataClass, expiryTime);
}
/**
* Obtain task result from cache if exists.
*
* @param key result identifier
* @param dataClass single result item class
* @param <R> returned result class
* @return cached result if exists, null otherwise
*/
public <R> R obtainFromCache(Object key, Class dataClass) {
return obtainFromCache(key, dataClass, Time.ALWAYS_RETURNED);
}
public void removeFromCache(Object key, Class dataClass) {
service.getCacheManager().remove(key, dataClass);
}
/**
* Remove all data by class.
*
* @param dataClass data class
*/
public void clearCache(Class dataClass) {
service.getCacheManager().remove(dataClass);
}
/**
* Remove all data from cache.
*/
public void clearCache() {
service.clearCache();
}
/**
* Bind service to context.
*
* @param context context
*/
public void bind(Context context) {
LW.d(TAG, "Bind service '%s' to context '%s'", serviceClass.getSimpleName(), context.getClass().getSimpleName());
Intent intent = new Intent(context, serviceClass);
context.startService(intent); //keep service alive after context unbound.
if(!context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
throw new ProcessorException("Connection is not made. Maybe you forgot add your service to AndroidManifest.xml?");
}
}
/**
* Unbind service from context.
* Remove all planned tasks if exist.
*
* @param context
*/
public void unbind(Context context) {
LW.d(TAG, "Unbind service '%s' from context '%s'", serviceClass.getSimpleName(), context.getClass().getSimpleName());
if(service != null) {
service.removeObservers(context);
}
context.unbindService(connection);
plannedTasks.clear();
service = null;
}
/**
* Check bound service or not.
*
* @return true if bound, false otherwise
*/
public boolean isBound() {
return service != null;
}
/**
* Get service.
*
* @return service or null if not bound
*/
public S getService() {
return service;
}
private class Connection implements ServiceConnection {
@Override
@SuppressWarnings("unchecked")
public void onServiceConnected(ComponentName name, IBinder service) {
LW.d(TAG, "Service '%s' connected.", name);
Processor.this.service = (S) ((ProcessorService.ProcessorBinder) service).getService();
if(plannedTasks.size() > 0) {
LW.d(TAG, "Execute planned %d tasks.", plannedTasks.size());
for (Map.Entry<AbstractTask, IObserver[]> entry : plannedTasks.entrySet()) {
Processor.this.service.execute(entry.getKey(), entry.getValue());
}
plannedTasks.clear();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
LW.d(TAG, "Service '%s' disconnected.", name);
plannedTasks.clear();
Processor.this.service = null;
}
}
}
| apache-2.0 |
Forexware/quickfixj | src/main/java/quickfix/field/OfferSwapPoints.java | 1279 | /*******************************************************************************
* 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.DecimalField;
public class OfferSwapPoints extends DecimalField
{
static final long serialVersionUID = 20050617;
public static final int FIELD = 1066;
public OfferSwapPoints()
{
super(1066);
}
public OfferSwapPoints(java.math.BigDecimal data)
{
super(1066, data);
}
public OfferSwapPoints(double data)
{
super(1066, new java.math.BigDecimal(data));
}
}
| apache-2.0 |
GoogleCloudPlatform/prometheus-engine | vendor/github.com/prometheus/prometheus/tsdb/index/postings.go | 16432 | // Copyright 2017 The Prometheus 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 index
import (
"container/heap"
"encoding/binary"
"runtime"
"sort"
"strings"
"sync"
"github.com/prometheus/prometheus/pkg/labels"
)
var allPostingsKey = labels.Label{}
// AllPostingsKey returns the label key that is used to store the postings list of all existing IDs.
func AllPostingsKey() (name, value string) {
return allPostingsKey.Name, allPostingsKey.Value
}
// MemPostings holds postings list for series ID per label pair. They may be written
// to out of order.
// ensureOrder() must be called once before any reads are done. This allows for quick
// unordered batch fills on startup.
type MemPostings struct {
mtx sync.RWMutex
m map[string]map[string][]uint64
ordered bool
}
// NewMemPostings returns a memPostings that's ready for reads and writes.
func NewMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: true,
}
}
// NewUnorderedMemPostings returns a memPostings that is not safe to be read from
// until ensureOrder was called once.
func NewUnorderedMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: false,
}
}
// SortedKeys returns a list of sorted label keys of the postings.
func (p *MemPostings) SortedKeys() []labels.Label {
p.mtx.RLock()
keys := make([]labels.Label, 0, len(p.m))
for n, e := range p.m {
for v := range e {
keys = append(keys, labels.Label{Name: n, Value: v})
}
}
p.mtx.RUnlock()
sort.Slice(keys, func(i, j int) bool {
if d := strings.Compare(keys[i].Name, keys[j].Name); d != 0 {
return d < 0
}
return keys[i].Value < keys[j].Value
})
return keys
}
// LabelNames returns all the unique label names.
func (p *MemPostings) LabelNames() []string {
p.mtx.RLock()
defer p.mtx.RUnlock()
n := len(p.m)
if n == 0 {
return nil
}
names := make([]string, 0, n-1)
for name := range p.m {
if name != allPostingsKey.Name {
names = append(names, name)
}
}
return names
}
// LabelValues returns label values for the given name.
func (p *MemPostings) LabelValues(name string) []string {
p.mtx.RLock()
defer p.mtx.RUnlock()
values := make([]string, 0, len(p.m[name]))
for v := range p.m[name] {
values = append(values, v)
}
return values
}
// PostingsStats contains cardinality based statistics for postings.
type PostingsStats struct {
CardinalityMetricsStats []Stat
CardinalityLabelStats []Stat
LabelValueStats []Stat
LabelValuePairsStats []Stat
NumLabelPairs int
}
// Stats calculates the cardinality statistics from postings.
func (p *MemPostings) Stats(label string) *PostingsStats {
const maxNumOfRecords = 10
var size uint64
p.mtx.RLock()
metrics := &maxHeap{}
labels := &maxHeap{}
labelValueLength := &maxHeap{}
labelValuePairs := &maxHeap{}
numLabelPairs := 0
metrics.init(maxNumOfRecords)
labels.init(maxNumOfRecords)
labelValueLength.init(maxNumOfRecords)
labelValuePairs.init(maxNumOfRecords)
for n, e := range p.m {
if n == "" {
continue
}
labels.push(Stat{Name: n, Count: uint64(len(e))})
numLabelPairs += len(e)
size = 0
for name, values := range e {
if n == label {
metrics.push(Stat{Name: name, Count: uint64(len(values))})
}
labelValuePairs.push(Stat{Name: n + "=" + name, Count: uint64(len(values))})
size += uint64(len(name))
}
labelValueLength.push(Stat{Name: n, Count: size})
}
p.mtx.RUnlock()
return &PostingsStats{
CardinalityMetricsStats: metrics.get(),
CardinalityLabelStats: labels.get(),
LabelValueStats: labelValueLength.get(),
LabelValuePairsStats: labelValuePairs.get(),
NumLabelPairs: numLabelPairs,
}
}
// Get returns a postings list for the given label pair.
func (p *MemPostings) Get(name, value string) Postings {
var lp []uint64
p.mtx.RLock()
l := p.m[name]
if l != nil {
lp = l[value]
}
p.mtx.RUnlock()
if lp == nil {
return EmptyPostings()
}
return newListPostings(lp...)
}
// All returns a postings list over all documents ever added.
func (p *MemPostings) All() Postings {
return p.Get(AllPostingsKey())
}
// EnsureOrder ensures that all postings lists are sorted. After it returns all further
// calls to add and addFor will insert new IDs in a sorted manner.
func (p *MemPostings) EnsureOrder() {
p.mtx.Lock()
defer p.mtx.Unlock()
if p.ordered {
return
}
n := runtime.GOMAXPROCS(0)
workc := make(chan []uint64)
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
for l := range workc {
sort.Slice(l, func(a, b int) bool { return l[a] < l[b] })
}
wg.Done()
}()
}
for _, e := range p.m {
for _, l := range e {
workc <- l
}
}
close(workc)
wg.Wait()
p.ordered = true
}
// Delete removes all ids in the given map from the postings lists.
func (p *MemPostings) Delete(deleted map[uint64]struct{}) {
var keys, vals []string
// Collect all keys relevant for deletion once. New keys added afterwards
// can by definition not be affected by any of the given deletes.
p.mtx.RLock()
for n := range p.m {
keys = append(keys, n)
}
p.mtx.RUnlock()
for _, n := range keys {
p.mtx.RLock()
vals = vals[:0]
for v := range p.m[n] {
vals = append(vals, v)
}
p.mtx.RUnlock()
// For each posting we first analyse whether the postings list is affected by the deletes.
// If yes, we actually reallocate a new postings list.
for _, l := range vals {
// Only lock for processing one postings list so we don't block reads for too long.
p.mtx.Lock()
found := false
for _, id := range p.m[n][l] {
if _, ok := deleted[id]; ok {
found = true
break
}
}
if !found {
p.mtx.Unlock()
continue
}
repl := make([]uint64, 0, len(p.m[n][l]))
for _, id := range p.m[n][l] {
if _, ok := deleted[id]; !ok {
repl = append(repl, id)
}
}
if len(repl) > 0 {
p.m[n][l] = repl
} else {
delete(p.m[n], l)
}
p.mtx.Unlock()
}
p.mtx.Lock()
if len(p.m[n]) == 0 {
delete(p.m, n)
}
p.mtx.Unlock()
}
}
// Iter calls f for each postings list. It aborts if f returns an error and returns it.
func (p *MemPostings) Iter(f func(labels.Label, Postings) error) error {
p.mtx.RLock()
defer p.mtx.RUnlock()
for n, e := range p.m {
for v, p := range e {
if err := f(labels.Label{Name: n, Value: v}, newListPostings(p...)); err != nil {
return err
}
}
}
return nil
}
// Add a label set to the postings index.
func (p *MemPostings) Add(id uint64, lset labels.Labels) {
p.mtx.Lock()
for _, l := range lset {
p.addFor(id, l)
}
p.addFor(id, allPostingsKey)
p.mtx.Unlock()
}
func (p *MemPostings) addFor(id uint64, l labels.Label) {
nm, ok := p.m[l.Name]
if !ok {
nm = map[string][]uint64{}
p.m[l.Name] = nm
}
list := append(nm[l.Value], id)
nm[l.Value] = list
if !p.ordered {
return
}
// There is no guarantee that no higher ID was inserted before as they may
// be generated independently before adding them to postings.
// We repair order violations on insert. The invariant is that the first n-1
// items in the list are already sorted.
for i := len(list) - 1; i >= 1; i-- {
if list[i] >= list[i-1] {
break
}
list[i], list[i-1] = list[i-1], list[i]
}
}
// ExpandPostings returns the postings expanded as a slice.
func ExpandPostings(p Postings) (res []uint64, err error) {
for p.Next() {
res = append(res, p.At())
}
return res, p.Err()
}
// Postings provides iterative access over a postings list.
type Postings interface {
// Next advances the iterator and returns true if another value was found.
Next() bool
// Seek advances the iterator to value v or greater and returns
// true if a value was found.
Seek(v uint64) bool
// At returns the value at the current iterator position.
At() uint64
// Err returns the last error of the iterator.
Err() error
}
// errPostings is an empty iterator that always errors.
type errPostings struct {
err error
}
func (e errPostings) Next() bool { return false }
func (e errPostings) Seek(uint64) bool { return false }
func (e errPostings) At() uint64 { return 0 }
func (e errPostings) Err() error { return e.err }
var emptyPostings = errPostings{}
// EmptyPostings returns a postings list that's always empty.
// NOTE: Returning EmptyPostings sentinel when index.Postings struct has no postings is recommended.
// It triggers optimized flow in other functions like Intersect, Without etc.
func EmptyPostings() Postings {
return emptyPostings
}
// ErrPostings returns new postings that immediately error.
func ErrPostings(err error) Postings {
return errPostings{err}
}
// Intersect returns a new postings list over the intersection of the
// input postings.
func Intersect(its ...Postings) Postings {
if len(its) == 0 {
return EmptyPostings()
}
if len(its) == 1 {
return its[0]
}
for _, p := range its {
if p == EmptyPostings() {
return EmptyPostings()
}
}
return newIntersectPostings(its...)
}
type intersectPostings struct {
arr []Postings
cur uint64
}
func newIntersectPostings(its ...Postings) *intersectPostings {
return &intersectPostings{arr: its}
}
func (it *intersectPostings) At() uint64 {
return it.cur
}
func (it *intersectPostings) doNext() bool {
Loop:
for {
for _, p := range it.arr {
if !p.Seek(it.cur) {
return false
}
if p.At() > it.cur {
it.cur = p.At()
continue Loop
}
}
return true
}
}
func (it *intersectPostings) Next() bool {
for _, p := range it.arr {
if !p.Next() {
return false
}
if p.At() > it.cur {
it.cur = p.At()
}
}
return it.doNext()
}
func (it *intersectPostings) Seek(id uint64) bool {
it.cur = id
return it.doNext()
}
func (it *intersectPostings) Err() error {
for _, p := range it.arr {
if p.Err() != nil {
return p.Err()
}
}
return nil
}
// Merge returns a new iterator over the union of the input iterators.
func Merge(its ...Postings) Postings {
if len(its) == 0 {
return EmptyPostings()
}
if len(its) == 1 {
return its[0]
}
p, ok := newMergedPostings(its)
if !ok {
return EmptyPostings()
}
return p
}
type postingsHeap []Postings
func (h postingsHeap) Len() int { return len(h) }
func (h postingsHeap) Less(i, j int) bool { return h[i].At() < h[j].At() }
func (h *postingsHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] }
func (h *postingsHeap) Push(x interface{}) {
*h = append(*h, x.(Postings))
}
func (h *postingsHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
type mergedPostings struct {
h postingsHeap
initialized bool
cur uint64
err error
}
func newMergedPostings(p []Postings) (m *mergedPostings, nonEmpty bool) {
ph := make(postingsHeap, 0, len(p))
for _, it := range p {
// NOTE: mergedPostings struct requires the user to issue an initial Next.
if it.Next() {
ph = append(ph, it)
} else {
if it.Err() != nil {
return &mergedPostings{err: it.Err()}, true
}
}
}
if len(ph) == 0 {
return nil, false
}
return &mergedPostings{h: ph}, true
}
func (it *mergedPostings) Next() bool {
if it.h.Len() == 0 || it.err != nil {
return false
}
// The user must issue an initial Next.
if !it.initialized {
heap.Init(&it.h)
it.cur = it.h[0].At()
it.initialized = true
return true
}
for {
cur := it.h[0]
if !cur.Next() {
heap.Pop(&it.h)
if cur.Err() != nil {
it.err = cur.Err()
return false
}
if it.h.Len() == 0 {
return false
}
} else {
// Value of top of heap has changed, re-heapify.
heap.Fix(&it.h, 0)
}
if it.h[0].At() != it.cur {
it.cur = it.h[0].At()
return true
}
}
}
func (it *mergedPostings) Seek(id uint64) bool {
if it.h.Len() == 0 || it.err != nil {
return false
}
if !it.initialized {
if !it.Next() {
return false
}
}
for it.cur < id {
cur := it.h[0]
if !cur.Seek(id) {
heap.Pop(&it.h)
if cur.Err() != nil {
it.err = cur.Err()
return false
}
if it.h.Len() == 0 {
return false
}
} else {
// Value of top of heap has changed, re-heapify.
heap.Fix(&it.h, 0)
}
it.cur = it.h[0].At()
}
return true
}
func (it mergedPostings) At() uint64 {
return it.cur
}
func (it mergedPostings) Err() error {
return it.err
}
// Without returns a new postings list that contains all elements from the full list that
// are not in the drop list.
func Without(full, drop Postings) Postings {
if full == EmptyPostings() {
return EmptyPostings()
}
if drop == EmptyPostings() {
return full
}
return newRemovedPostings(full, drop)
}
type removedPostings struct {
full, remove Postings
cur uint64
initialized bool
fok, rok bool
}
func newRemovedPostings(full, remove Postings) *removedPostings {
return &removedPostings{
full: full,
remove: remove,
}
}
func (rp *removedPostings) At() uint64 {
return rp.cur
}
func (rp *removedPostings) Next() bool {
if !rp.initialized {
rp.fok = rp.full.Next()
rp.rok = rp.remove.Next()
rp.initialized = true
}
for {
if !rp.fok {
return false
}
if !rp.rok {
rp.cur = rp.full.At()
rp.fok = rp.full.Next()
return true
}
fcur, rcur := rp.full.At(), rp.remove.At()
if fcur < rcur {
rp.cur = fcur
rp.fok = rp.full.Next()
return true
} else if rcur < fcur {
// Forward the remove postings to the right position.
rp.rok = rp.remove.Seek(fcur)
} else {
// Skip the current posting.
rp.fok = rp.full.Next()
}
}
}
func (rp *removedPostings) Seek(id uint64) bool {
if rp.cur >= id {
return true
}
rp.fok = rp.full.Seek(id)
rp.rok = rp.remove.Seek(id)
rp.initialized = true
return rp.Next()
}
func (rp *removedPostings) Err() error {
if rp.full.Err() != nil {
return rp.full.Err()
}
return rp.remove.Err()
}
// ListPostings implements the Postings interface over a plain list.
type ListPostings struct {
list []uint64
cur uint64
}
func NewListPostings(list []uint64) Postings {
return newListPostings(list...)
}
func newListPostings(list ...uint64) *ListPostings {
return &ListPostings{list: list}
}
func (it *ListPostings) At() uint64 {
return it.cur
}
func (it *ListPostings) Next() bool {
if len(it.list) > 0 {
it.cur = it.list[0]
it.list = it.list[1:]
return true
}
it.cur = 0
return false
}
func (it *ListPostings) Seek(x uint64) bool {
// If the current value satisfies, then return.
if it.cur >= x {
return true
}
if len(it.list) == 0 {
return false
}
// Do binary search between current position and end.
i := sort.Search(len(it.list), func(i int) bool {
return it.list[i] >= x
})
if i < len(it.list) {
it.cur = it.list[i]
it.list = it.list[i+1:]
return true
}
it.list = nil
return false
}
func (it *ListPostings) Err() error {
return nil
}
// bigEndianPostings implements the Postings interface over a byte stream of
// big endian numbers.
type bigEndianPostings struct {
list []byte
cur uint32
}
func newBigEndianPostings(list []byte) *bigEndianPostings {
return &bigEndianPostings{list: list}
}
func (it *bigEndianPostings) At() uint64 {
return uint64(it.cur)
}
func (it *bigEndianPostings) Next() bool {
if len(it.list) >= 4 {
it.cur = binary.BigEndian.Uint32(it.list)
it.list = it.list[4:]
return true
}
return false
}
func (it *bigEndianPostings) Seek(x uint64) bool {
if uint64(it.cur) >= x {
return true
}
num := len(it.list) / 4
// Do binary search between current position and end.
i := sort.Search(num, func(i int) bool {
return binary.BigEndian.Uint32(it.list[i*4:]) >= uint32(x)
})
if i < num {
j := i * 4
it.cur = binary.BigEndian.Uint32(it.list[j:])
it.list = it.list[j+4:]
return true
}
it.list = nil
return false
}
func (it *bigEndianPostings) Err() error {
return nil
}
| apache-2.0 |
OSEHRA-Sandbox/MOCHA | etc/database/dropFdbDifTables.sql | 9360 | drop table FDB_AGID_AXSID cascade;
drop table FDB_AHFSCLASS_DRUGCONCEPT cascade;
drop table FDB_AHFSCLASSIFICATION_DRUGS cascade;
drop table FDB_AHFSCLASSIFICATION_LINK cascade;
drop table FDB_ALLERGEN_HICSEQNO cascade;
drop table FDB_ALLERGENGROUP cascade;
drop table FDB_ALLERGENGROUP_II cascade;
drop table FDB_ALLERGENGROUPSEARCH cascade;
drop table FDB_ALLERGENGROUPSEARCH_II cascade;
drop table FDB_ALLERGENPICKLIST cascade;
drop table FDB_ALLERGENPICKLISTSEARCH cascade;
drop table FDB_ALLERGENS cascade;
drop table FDB_ALLERGENS_II cascade;
drop table FDB_ALLERGYCROSSSENSITIVITY cascade;
drop table FDB_CLASS_AHFS cascade;
drop table FDB_CLASS_AHFSSEARCH cascade;
drop table FDB_CLASS_FDB cascade;
drop table FDB_CLASS_FDBSEARCH cascade;
drop table FDB_CLASSIFICATION_AHFS cascade;
drop table FDB_CLASSIFICATION_AHFSSEARCH cascade;
drop table FDB_CLASSIFICATION_ETC cascade;
drop table FDB_CLASSIFICATION_ETCSEARCH cascade;
drop table FDB_CLASSIFICATION_EXT cascade;
drop table FDB_CLASSIFICATION_EXTSEARCH cascade;
drop table FDB_CLASSIFICATION_FDB cascade;
drop table FDB_CLASSIFICATION_FDBSEARCH cascade;
drop table FDB_CODEDEFINITION cascade;
drop table FDB_COMPOUND cascade;
drop table FDB_COMPOUND_RTGEN cascade;
drop table FDB_COMPOUNDSEARCH cascade;
drop table FDB_CONCEPT_IISURVEY cascade;
drop table FDB_CONCEPT_PEMDRUGLINK cascade;
drop table FDB_CONCEPT_WITHINACTIVES cascade;
drop table FDB_CUSTOM_ALLERGENPICKLIST cascade;
drop table FDB_CUSTOM_ALLERGENPICKLSTSRCH cascade;
drop table FDB_CUSTOM_ATTRIBUTENAMES cascade;
drop table FDB_CUSTOM_ATTRIBUTEVALUES cascade;
drop table FDB_CUSTOM_CLASS cascade;
drop table FDB_CUSTOM_CLASS_DRUGCONCEPT cascade;
drop table FDB_CUSTOM_CLASS_SEARCH cascade;
drop table FDB_CUSTOM_DDIM cascade;
drop table FDB_CUSTOM_DDIMDRUGLINKCAT cascade;
drop table FDB_CUSTOM_DDIMINTERACTION cascade;
drop table FDB_CUSTOM_DDIMSTRINGS cascade;
drop table FDB_CUSTOM_DOSERANGECHECK cascade;
drop table FDB_CUSTOM_DOSING cascade;
drop table FDB_CUSTOM_DOSINGNEO cascade;
drop table FDB_CUSTOM_DRUGMAPPING cascade;
drop table FDB_CUSTOM_DTCAT cascade;
drop table FDB_CUSTOM_INDICATION cascade;
drop table FDB_CUSTOM_INTERACTCATEGORY cascade;
drop table FDB_CUSTOM_MONOGRAPH cascade;
drop table FDB_CUSTOM_MSG_CATDEF cascade;
drop table FDB_CUSTOM_MSG_DEF cascade;
drop table FDB_CUSTOM_MSG_LINK cascade;
drop table FDB_CUSTOM_MSG_TEXT cascade;
drop table FDB_CUSTOM_PACKAGEDDRUGPRICING cascade;
drop table FDB_DAMSCREEN cascade;
drop table FDB_DAMSCREEN_II cascade;
drop table FDB_DAMSCREENINFO cascade;
drop table FDB_DAMSCREENINFO_II cascade;
drop table FDB_DDCM cascade;
drop table FDB_DDCMDRUGLINK cascade;
drop table FDB_DDIM_CATSEVERITIES cascade;
drop table FDB_DDIMDRUGLINK cascade;
drop table FDB_DDIMINACTIVEDRUGLINK cascade;
drop table FDB_DDIMINTERACTION cascade;
drop table FDB_DFIMDRUGLINK cascade;
drop table FDB_DFIMINTERACTION cascade;
drop table FDB_DISCLAIMER cascade;
drop table FDB_DISCREEN cascade;
drop table FDB_DISPENSABLE cascade;
drop table FDB_DISPENSABLE_IMAGE cascade;
drop table FDB_DISPENSABLE_LABELER cascade;
drop table FDB_DOSEFORM cascade;
drop table FDB_DOSERANGECHECK cascade;
drop table FDB_DOSEROUTE cascade;
drop table FDB_DOSETYPE cascade;
drop table FDB_DOSEUNITSCONVERSION cascade;
drop table FDB_DOSEUNITSTYPE cascade;
drop table FDB_DOSING cascade;
drop table FDB_DOSINGNEO cascade;
drop table FDB_DRCNEO cascade;
drop table FDB_DRUG_MONOGRAPH_EXT cascade;
drop table FDB_DRUG_PCM cascade;
drop table FDB_DRUG_PLBLW cascade;
drop table FDB_DRUG_RTGENID cascade;
drop table FDB_DRUGNAME cascade;
drop table FDB_DRUGVALIDATION cascade;
drop table FDB_DTDRUGLINK cascade;
drop table FDB_DUPLICATETHERAPY cascade;
drop table FDB_DXID_RELATEDDXID cascade;
drop table FDB_ETCLASSIFICATION_DRUGS cascade;
drop table FDB_ETCLASSIFICATION_LINK cascade;
drop table FDB_EXTCLASSIFICATION_DRUGS cascade;
drop table FDB_EXTCLASSIFICATION_IDRUGS cascade;
drop table FDB_EXTCLASSIFICATION_LINK cascade;
drop table FDB_EXTVOCAB_RELATEDDXID cascade;
drop table FDB_FDBCLASS_DRUGCONCEPT cascade;
drop table FDB_FDBCLASSIFICATION_DRUGS cascade;
drop table FDB_FDBCLASSIFICATION_LINK cascade;
drop table FDB_GCNSEQNO_PCM cascade;
drop table FDB_GCNSEQNO_PEM cascade;
drop table FDB_GCNSEQNO_PLBLW cascade;
drop table FDB_GENERIC_DISPENSABLE cascade;
drop table FDB_GENERIC_DISPENSABLE_TEMP cascade;
drop table FDB_GENERIC_DISPSEARCH cascade;
drop table FDB_GENERIC_DRUGNAME cascade;
drop table FDB_GENERIC_DRUGNAMESEARCH cascade;
drop table FDB_GENERIC_ROUTEDDFDRUG cascade;
drop table FDB_GENERIC_ROUTEDDFDRUGSEARCH cascade;
drop table FDB_GENERIC_ROUTEDDRUG cascade;
drop table FDB_GENERIC_ROUTEDDRUG_TEMP cascade;
drop table FDB_GENERIC_ROUTEDDRUGSEARCH cascade;
drop table FDB_GENERICDOSEFORM cascade;
drop table FDB_HICL_HICSEQNO cascade;
drop table FDB_HICSEQNO_AGID cascade;
drop table FDB_HICSEQNO_AXSID cascade;
drop table FDB_HICSEQNO_BASEINGREDIENT cascade;
drop table FDB_IMAGE cascade;
drop table FDB_IMPCOLORPALETTE cascade;
drop table FDB_IMPDESCCOLORS cascade;
drop table FDB_IMPRINT cascade;
drop table FDB_IMPRINTCOLORS cascade;
drop table FDB_IMPRINTDESCRIPTION cascade;
drop table FDB_IMPRINTDESCTEXT cascade;
drop table FDB_IMPRINTSHAPE cascade;
drop table FDB_IMPSHAPEPALETTE cascade;
drop table FDB_IND cascade;
drop table FDB_INDDRUGLINK cascade;
drop table FDB_INGREDIENT cascade;
drop table FDB_INGREDIENTSEARCH cascade;
drop table FDB_IVM cascade;
drop table FDB_IVM_COMPDESC cascade;
drop table FDB_IVM_MFGDESC cascade;
drop table FDB_IVM_REMARKLINK cascade;
drop table FDB_IVM_REMARKS cascade;
drop table FDB_IVM_TESTCOMPCOUNT cascade;
drop table FDB_IVM_TPN_INGRED cascade;
drop table FDB_LABELER cascade;
drop table FDB_LANGUAGE cascade;
drop table FDB_MANUFDRUG cascade;
drop table FDB_MANUFDRUGEXTID cascade;
drop table FDB_MANUFDRUGPROPNAME cascade;
drop table FDB_MANUFDRUGPROPVALUE cascade;
drop table FDB_MANUFDRUGSEARCH cascade;
drop table FDB_MEDCOND cascade;
drop table FDB_MEDCOND_HIERARCHY cascade;
drop table FDB_MEDCONDEXT_HIERARCHY cascade;
drop table FDB_MEDCONDEXTVOCAB cascade;
drop table FDB_MEDCONDEXTVOCABLINK cascade;
drop table FDB_MEDCONDEXTVOCABSEARCH cascade;
drop table FDB_MEDCONDSEARCH cascade;
drop table FDB_MEDCONDSEARCHFML cascade;
drop table FDB_MEDCONDXREF cascade;
drop table FDB_MINMAXDOSING cascade;
drop table FDB_MINMAXWARNINGS cascade;
drop table FDB_MNID_HICL cascade;
drop table FDB_MONOGRAPH_DDIM cascade;
drop table FDB_MONOGRAPH_DFIM cascade;
drop table FDB_MONOGRAPH_EXT cascade;
drop table FDB_MONOGRAPH_PEM cascade;
drop table FDB_PACKAGEDDRUG cascade;
drop table FDB_PACKAGEDDRUGCURRENTPRICING cascade;
drop table FDB_PACKAGEDDRUGPRICINGHISTORY cascade;
drop table FDB_PATIENTCOUNSELING cascade;
drop table FDB_PEDIATRICWEIGHT cascade;
drop table FDB_PLBLWARN_VENDCODE cascade;
drop table FDB_PLBLWARNINGS cascade;
drop table FDB_POEM cascade;
drop table FDB_POEM_ADMINRATES cascade;
drop table FDB_POEM_DEFAULT cascade;
drop table FDB_POEM_DOSEFORMUNITS cascade;
drop table FDB_POEM_ORDERSTRING cascade;
drop table FDB_POEM_ORDERSTRING_ADDLTEXT cascade;
drop table FDB_POEM_UNITS cascade;
drop table FDB_POEMTEXT cascade;
drop table FDB_PRECGERI cascade;
drop table FDB_PRECGERI_DRUGLINK cascade;
drop table FDB_PRECGERI_GCNSEQNO cascade;
drop table FDB_PRECGERI_RTDFGEN cascade;
drop table FDB_PRECGERI_RTGEN cascade;
drop table FDB_PRECLACT cascade;
drop table FDB_PRECLACT_DRUGLINK cascade;
drop table FDB_PRECLACT_GCNSEQNO cascade;
drop table FDB_PRECLACT_RTDFGEN cascade;
drop table FDB_PRECLACT_RTGEN cascade;
drop table FDB_PRECPEDI cascade;
drop table FDB_PRECPEDI_DRUGLINK cascade;
drop table FDB_PRECPEDI_GCNSEQNO cascade;
drop table FDB_PRECPEDI_RTDFGEN cascade;
drop table FDB_PRECPEDI_RTGEN cascade;
drop table FDB_PRECPREG cascade;
drop table FDB_PRECPREG_DRUGLINK cascade;
drop table FDB_PRECPREG_GCNSEQNO cascade;
drop table FDB_PRECPREG_RTDFGEN cascade;
drop table FDB_PRECPREG_RTGEN cascade;
drop table FDB_RDFMID_RTDFGENID cascade;
drop table FDB_REFITEM cascade;
drop table FDB_REFITEM_ATTRIBUTENAMES cascade;
drop table FDB_REFITEM_ATTRIBUTEVALUES cascade;
drop table FDB_REFITEM_MSG_CATDEF cascade;
drop table FDB_REFITEM_MSG_DEF cascade;
drop table FDB_REFITEM_MSG_LINK cascade;
drop table FDB_REFITEM_MSG_TEXT cascade;
drop table FDB_REFITEM_SEARCH cascade;
drop table FDB_REGPACKAGED cascade;
drop table FDB_REGPACKAGEDEXTID cascade;
drop table FDB_REGPACKAGEDPROPNAME cascade;
drop table FDB_REGPACKAGEDPROPVALUE cascade;
drop table FDB_REGPACKAGEDSEARCH cascade;
drop table FDB_REPLACEMENTALLERGENGROUPS cascade;
drop table FDB_REPLACEMENTDRUGS cascade;
drop table FDB_REPLACEMENTDXIDS cascade;
drop table FDB_REPLACEMENTINGREDIENTS cascade;
drop table FDB_RMID_RTGENID cascade;
drop table FDB_ROUTE cascade;
drop table FDB_ROUTEDDFDRUG cascade;
drop table FDB_ROUTEDDRUG cascade;
drop table FDB_RTGENID_GENERICRMID cascade;
drop table FDB_SETTINGS cascade;
drop table FDB_SIDE cascade;
drop table FDB_SIDEDRUGLINK cascade;
drop table FDB_SUBSET_DRUGVALUES cascade;
drop table FDB_SUBSET_SET cascade;
drop table FDB_SUBSET_SITE cascade;
drop table FDB_USER_DDIM cascade;
drop table FDB_USER_DDIMDRUGLINK_CATEGORY cascade;
drop table FDB_USER_DDIMINTERACTION cascade;
drop table FDB_USER_INTERACTION_CATEGORY cascade;
drop table FDB_VERSION cascade;
drop table CT_VERSION cascade;
| apache-2.0 |
chinadev/Restful | src/Restful/Restful/Collections/Generic/ThreadSafeDictionary.cs | 4347 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace Restful.Collections.Generic
{
/// <summary>
/// 表示键值对的线程安全泛型集合
/// </summary>
/// <typeparam name="TKey">键类型</typeparam>
/// <typeparam name="TValue">值类型</typeparam>
[Serializable]
public class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private object syncRoot;
private readonly IDictionary<TKey, TValue> dictionary;
public ThreadSafeDictionary()
{
this.dictionary = new Dictionary<TKey, TValue>();
}
public ThreadSafeDictionary( IDictionary<TKey, TValue> dictionary )
{
this.dictionary = dictionary;
}
public object SyncRoot
{
get
{
if( syncRoot == null )
{
Interlocked.CompareExchange( ref syncRoot, new object(), null );
}
return syncRoot;
}
}
#region IDictionary<TKey,TValue> Members
public bool ContainsKey( TKey key )
{
return dictionary.ContainsKey( key );
}
public void Add( TKey key, TValue value )
{
lock( SyncRoot )
{
dictionary.Add( key, value );
}
}
public bool Remove( TKey key )
{
lock( SyncRoot )
{
return dictionary.Remove( key );
}
}
public bool TryGetValue( TKey key, out TValue value )
{
return dictionary.TryGetValue( key, out value );
}
public TValue this[TKey key]
{
get
{
return dictionary[key];
}
set
{
lock( SyncRoot )
{
dictionary[key] = value;
}
}
}
public ICollection<TKey> Keys
{
get
{
lock( SyncRoot )
{
return dictionary.Keys;
}
}
}
public ICollection<TValue> Values
{
get
{
lock( SyncRoot )
{
return dictionary.Values;
}
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add( KeyValuePair<TKey, TValue> item )
{
lock( SyncRoot )
{
dictionary.Add( item );
}
}
public void Clear()
{
lock( SyncRoot )
{
dictionary.Clear();
}
}
public bool Contains( KeyValuePair<TKey, TValue> item )
{
return dictionary.Contains( item );
}
public void CopyTo( KeyValuePair<TKey, TValue>[] array, int arrayIndex )
{
lock( SyncRoot )
{
dictionary.CopyTo( array, arrayIndex );
}
}
public bool Remove( KeyValuePair<TKey, TValue> item )
{
lock( SyncRoot )
{
return dictionary.Remove( item );
}
}
public int Count
{
get { return dictionary.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
lock( SyncRoot )
{
KeyValuePair<TKey, TValue>[] pairArray = new KeyValuePair<TKey, TValue>[dictionary.Count];
this.dictionary.CopyTo( pairArray, 0 );
return Array.AsReadOnly( pairArray ).GetEnumerator();
}
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return ( (IEnumerable<KeyValuePair<TKey, TValue>>)this ).GetEnumerator();
}
#endregion
}
}
| apache-2.0 |
manolovn/Renderers | sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/LiveVideoRenderer.java | 2132 | /*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* 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.pedrogomez.renderers.sample.ui.renderers;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.pedrogomez.renderers.sample.R;
import com.pedrogomez.renderers.sample.model.Video;
import java.util.Date;
/**
* VideoRenderer created to contains the live video presentation logic. This VideoRenderer subtype
* change the inflated layout and override the renderer algorithm to add a new phase to render the
* date.
*
* @author Pedro Vicente Gómez Sánchez.
*/
public class LiveVideoRenderer extends VideoRenderer {
@Bind(R.id.date) TextView date;
@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) {
View inflatedView = inflater.inflate(R.layout.live_video_renderer, parent, false);
ButterKnife.bind(this, inflatedView);
return inflatedView;
}
@Override protected void setUpView(View rootView) {
/*
* Empty implementation substituted with the usage of ButterKnife library by Jake Wharton.
*/
}
@Override protected void renderLabel() {
getLabel().setText(getContext().getString(R.string.live_label));
}
@Override protected void renderMarker(Video video) {
getMarker().setVisibility(View.GONE);
}
@Override public void render() {
super.render();
renderDate();
}
private void renderDate() {
String now = new Date().toLocaleString();
date.setText(now);
}
}
| apache-2.0 |
pivotal-amurmann/geode | geode-core/src/main/java/org/apache/geode/internal/cache/execute/AbstractExecution.java | 17394 | /*
* 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.execute;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.logging.log4j.Logger;
import org.apache.geode.InternalGemFireException;
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.LowMemoryException;
import org.apache.geode.cache.TransactionException;
import org.apache.geode.cache.client.internal.ProxyCache;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.FunctionException;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.cache.execute.ResultSender;
import org.apache.geode.cache.query.QueryInvalidException;
import org.apache.geode.distributed.internal.DM;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LocalizedMessage;
/**
* Abstract implementation of InternalExecution interface.
*
* @since GemFire 5.8LA
*
*/
public abstract class AbstractExecution implements InternalExecution {
private static final Logger logger = LogService.getLogger();
protected boolean isMemberMappedArgument;
protected MemberMappedArgument memberMappedArg;
protected Object args;
protected ResultCollector rc;
protected Set filter = new HashSet();
protected boolean hasRoutingObjects;
protected volatile boolean isReExecute = false;
protected volatile boolean isClientServerMode = false;
protected Set<String> failedNodes = new HashSet<String>();
protected boolean isFnSerializationReqd;
/***
* yjing The following code is added to get a set of function executing nodes by the data aware
* procedure
*/
protected Collection<InternalDistributedMember> executionNodes = null;
public static interface ExecutionNodesListener {
public void afterExecutionNodesSet(AbstractExecution execution);
public void reset();
}
protected ExecutionNodesListener executionNodesListener = null;
protected boolean waitOnException = false;
protected boolean forwardExceptions = false;
protected boolean ignoreDepartedMembers = false;
protected ProxyCache proxyCache;
private final static ConcurrentHashMap<String, byte[]> idToFunctionAttributes =
new ConcurrentHashMap<String, byte[]>();
public static final byte NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE = 0;
public static final byte NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE = 2;
public static final byte HA_HASRESULT_NO_OPTIMIZEFORWRITE = 3;
public static final byte NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE = 4;
public static final byte NO_HA_HASRESULT_OPTIMIZEFORWRITE = 6;
public static final byte HA_HASRESULT_OPTIMIZEFORWRITE = 7;
public static final byte HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE = 11;
public static final byte HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE = 15;
public static byte getFunctionState(boolean isHA, boolean hasResult, boolean optimizeForWrite) {
if (isHA) {
if (hasResult) {
if (optimizeForWrite) {
return HA_HASRESULT_OPTIMIZEFORWRITE;
} else {
return HA_HASRESULT_NO_OPTIMIZEFORWRITE;
}
}
return (byte) 1; // ERROR scenario
} else {
if (hasResult) {
if (optimizeForWrite) {
return NO_HA_HASRESULT_OPTIMIZEFORWRITE;
} else {
return NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE;
}
} else {
if (optimizeForWrite) {
return NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE;
} else {
return NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE;
}
}
}
}
public static byte getReexecuteFunctionState(byte fnState) {
if (fnState == HA_HASRESULT_NO_OPTIMIZEFORWRITE) {
return HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE;
} else if (fnState == HA_HASRESULT_OPTIMIZEFORWRITE) {
return HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE;
}
throw new InternalGemFireException("Wrong fnState provided.");
}
protected AbstractExecution() {}
protected AbstractExecution(AbstractExecution ae) {
if (ae.args != null) {
this.args = ae.args;
}
if (ae.rc != null) {
this.rc = ae.rc;
}
if (ae.memberMappedArg != null) {
this.memberMappedArg = ae.memberMappedArg;
}
this.isMemberMappedArgument = ae.isMemberMappedArgument;
this.isClientServerMode = ae.isClientServerMode;
if (ae.proxyCache != null) {
this.proxyCache = ae.proxyCache;
}
this.isFnSerializationReqd = ae.isFnSerializationReqd;
}
protected AbstractExecution(AbstractExecution ae, boolean isReExecute) {
this(ae);
this.isReExecute = isReExecute;
}
public boolean isMemberMappedArgument() {
return this.isMemberMappedArgument;
}
public Object getArgumentsForMember(String memberId) {
if (!isMemberMappedArgument) {
return this.args;
} else {
return this.memberMappedArg.getArgumentsForMember(memberId);
}
}
public MemberMappedArgument getMemberMappedArgument() {
return this.memberMappedArg;
}
public Object getArguments() {
return this.args;
}
public ResultCollector getResultCollector() {
return this.rc;
}
public Set getFilter() {
return this.filter;
}
public AbstractExecution setIsReExecute() {
this.isReExecute = true;
if (this.executionNodesListener != null) {
this.executionNodesListener.reset();
}
return this;
}
public boolean isReExecute() {
return isReExecute;
}
public Set<String> getFailedNodes() {
return this.failedNodes;
}
public void addFailedNode(String failedNode) {
this.failedNodes.add(failedNode);
}
public void clearFailedNodes() {
this.failedNodes.clear();
}
public boolean isClientServerMode() {
return isClientServerMode;
}
public boolean isFnSerializationReqd() {
return isFnSerializationReqd;
}
public Collection<InternalDistributedMember> getExecutionNodes() {
return this.executionNodes;
}
public void setRequireExecutionNodes(ExecutionNodesListener listener) {
this.executionNodes = Collections.emptySet();
this.executionNodesListener = listener;
}
public void setExecutionNodes(Set<InternalDistributedMember> nodes) {
if (this.executionNodes != null) {
this.executionNodes = nodes;
if (this.executionNodesListener != null) {
this.executionNodesListener.afterExecutionNodesSet(this);
}
}
}
public void executeFunctionOnLocalPRNode(final Function fn, final FunctionContext cx,
final PartitionedRegionFunctionResultSender sender, DM dm, boolean isTx) {
if (dm instanceof DistributionManager && !isTx) {
if (ServerConnection.isExecuteFunctionOnLocalNodeOnly().byteValue() == 1) {
ServerConnection.executeFunctionOnLocalNodeOnly((byte) 3);// executed locally
executeFunctionLocally(fn, cx, sender, dm);
if (!sender.isLastResultReceived() && fn.hasResult()) {
((InternalResultSender) sender).setException(new FunctionException(
LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT
.toString(fn.getId())));
}
} else {
final DistributionManager newDM = (DistributionManager) dm;
newDM.getFunctionExcecutor().execute(new Runnable() {
public void run() {
executeFunctionLocally(fn, cx, sender, newDM);
if (!sender.isLastResultReceived() && fn.hasResult()) {
((InternalResultSender) sender).setException(new FunctionException(
LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT
.toString(fn.getId())));
}
}
});
}
} else {
executeFunctionLocally(fn, cx, sender, dm);
if (!sender.isLastResultReceived() && fn.hasResult()) {
((InternalResultSender) sender).setException(new FunctionException(
LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT
.toString(fn.getId())));
}
}
}
// Bug41118 : in case of lonerDistribuedSystem do local execution through
// main thread otherwise give execution to FunctionExecutor from
// DistributionManager
public void executeFunctionOnLocalNode(final Function<?> fn, final FunctionContext cx,
final ResultSender sender, DM dm, final boolean isTx) {
if (dm instanceof DistributionManager && !isTx) {
final DistributionManager newDM = (DistributionManager) dm;
newDM.getFunctionExcecutor().execute(new Runnable() {
public void run() {
executeFunctionLocally(fn, cx, sender, newDM);
if (!((InternalResultSender) sender).isLastResultReceived() && fn.hasResult()) {
((InternalResultSender) sender).setException(new FunctionException(
LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT
.toString(fn.getId())));
}
}
});
} else {
executeFunctionLocally(fn, cx, sender, dm);
if (!((InternalResultSender) sender).isLastResultReceived() && fn.hasResult()) {
((InternalResultSender) sender).setException(new FunctionException(
LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT
.toString(fn.getId())));
}
}
}
public void executeFunctionLocally(final Function<?> fn, final FunctionContext cx,
final ResultSender sender, DM dm) {
FunctionStats stats = FunctionStats.getFunctionStats(fn.getId(), dm.getSystem());
try {
long start = stats.startTime();
stats.startFunctionExecution(fn.hasResult());
if (logger.isDebugEnabled()) {
logger.debug("Executing Function: {} on local node with context: {}", fn.getId(),
cx.toString());
}
fn.execute(cx);
stats.endFunctionExecution(start, fn.hasResult());
} catch (FunctionInvocationTargetException fite) {
FunctionException functionException = null;
if (fn.isHA()) {
functionException =
new FunctionException(new InternalFunctionInvocationTargetException(fite.getMessage()));
} else {
functionException = new FunctionException(fite);
}
handleException(functionException, fn, cx, sender, dm);
} catch (BucketMovedException bme) {
FunctionException functionException = null;
if (fn.isHA()) {
functionException =
new FunctionException(new InternalFunctionInvocationTargetException(bme));
} else {
functionException = new FunctionException(bme);
}
handleException(functionException, fn, cx, sender, dm);
} catch (VirtualMachineError e) {
SystemFailure.initiateFailure(e);
throw e;
} catch (Throwable t) {
SystemFailure.checkFailure();
handleException(t, fn, cx, sender, dm);
}
}
public ResultCollector execute(final String functionName) {
if (functionName == null) {
throw new FunctionException(
LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL
.toLocalizedString());
}
this.isFnSerializationReqd = false;
Function functionObject = FunctionService.getFunction(functionName);
if (functionObject == null) {
throw new FunctionException(
LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED
.toLocalizedString(functionName));
}
return executeFunction(functionObject);
}
public ResultCollector execute(Function function) throws FunctionException {
if (function == null) {
throw new FunctionException(
LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL
.toLocalizedString());
}
if (function.isHA() && !function.hasResult()) {
throw new FunctionException(
LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH.toLocalizedString());
}
String id = function.getId();
if (id == null) {
throw new IllegalArgumentException(
LocalizedStrings.ExecuteFunction_THE_FUNCTION_GET_ID_RETURNED_NULL.toLocalizedString());
}
this.isFnSerializationReqd = true;
return executeFunction(function);
}
public void setWaitOnExceptionFlag(boolean waitOnException) {
this.setForwardExceptions(waitOnException);
this.waitOnException = waitOnException;
}
public boolean getWaitOnExceptionFlag() {
return this.waitOnException;
}
public void setForwardExceptions(boolean forward) {
this.forwardExceptions = forward;
}
public boolean isForwardExceptions() {
return forwardExceptions;
}
@Override
public void setIgnoreDepartedMembers(boolean ignore) {
this.ignoreDepartedMembers = ignore;
if (ignore) {
setWaitOnExceptionFlag(true);
}
}
public boolean isIgnoreDepartedMembers() {
return this.ignoreDepartedMembers;
}
protected abstract ResultCollector executeFunction(Function fn);
/**
* validates whether a function should execute in presence of transaction and HeapCritical
* members. If the function is the first operation in a transaction, bootstraps the function.
*
* @param function the function
* @param targetMembers the set of members the function will be executed on
* @throws TransactionException if more than one nodes are targeted within a transaction
* @throws LowMemoryException if the set contains a heap critical member
*/
public abstract void validateExecution(Function function, Set targetMembers);
public LocalResultCollector<?, ?> getLocalResultCollector(Function function,
final ResultCollector<?, ?> rc) {
if (rc instanceof LocalResultCollector) {
return (LocalResultCollector) rc;
} else {
return new LocalResultCollectorImpl(function, rc, this);
}
}
/**
* Returns the function attributes defined by the functionId, returns null if no function is found
* for the specified functionId
*
* @param functionId
* @return byte[]
* @throws FunctionException if functionID passed is null
* @since GemFire 6.6
*/
public byte[] getFunctionAttributes(String functionId) {
if (functionId == null) {
throw new FunctionException(LocalizedStrings.FunctionService_0_PASSED_IS_NULL
.toLocalizedString("functionId instance "));
}
return idToFunctionAttributes.get(functionId);
}
public void removeFunctionAttributes(String functionId) {
idToFunctionAttributes.remove(functionId);
}
public void addFunctionAttributes(String functionId, byte[] functionAttributes) {
idToFunctionAttributes.put(functionId, functionAttributes);
}
private void handleException(Throwable functionException, final Function fn,
final FunctionContext cx, final ResultSender sender, DM dm) {
FunctionStats stats = FunctionStats.getFunctionStats(fn.getId(), dm.getSystem());
if (logger.isDebugEnabled()) {
logger.debug("Exception occurred on local node while executing Function: {}", fn.getId(),
functionException);
}
stats.endFunctionExecutionWithException(fn.hasResult());
if (fn.hasResult()) {
if (waitOnException || forwardExceptions) {
if (functionException instanceof FunctionException
&& functionException.getCause() instanceof QueryInvalidException) {
// Handle this exception differently since it can contain
// non-serializable objects.
// java.io.NotSerializableException: antlr.CommonToken
// create a new FunctionException on the original one's message (not cause).
functionException = new FunctionException(functionException.getLocalizedMessage());
}
sender.lastResult(functionException);
} else {
((InternalResultSender) sender).setException(functionException);
}
} else {
logger.warn(LocalizedMessage.create(LocalizedStrings.FunctionService_EXCEPTION_ON_LOCAL_NODE),
functionException);
}
}
}
| apache-2.0 |
eayunstack/oslo.messaging | oslo/messaging/notify/notifier.py | 11163 |
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
# Copyright 2013 Red Hat, 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.
import abc
import logging
import uuid
import six
from stevedore import named
from oslo.config import cfg
from oslo.messaging import serializer as msg_serializer
from oslo.utils import timeutils
_notifier_opts = [
cfg.MultiStrOpt('notification_driver',
default=[],
help='Driver or drivers to handle sending notifications.'),
cfg.ListOpt('notification_topics',
default=['notifications', ],
deprecated_name='topics',
deprecated_group='rpc_notifier2',
help='AMQP topic used for OpenStack notifications.'),
]
_LOG = logging.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class _Driver(object):
def __init__(self, conf, topics, transport):
self.conf = conf
self.topics = topics
self.transport = transport
@abc.abstractmethod
def notify(self, ctxt, msg, priority, retry):
pass
class Notifier(object):
"""Send notification messages.
The Notifier class is used for sending notification messages over a
messaging transport or other means.
Notification messages follow the following format::
{'message_id': six.text_type(uuid.uuid4()),
'publisher_id': 'compute.host1',
'timestamp': timeutils.utcnow(),
'priority': 'WARN',
'event_type': 'compute.create_instance',
'payload': {'instance_id': 12, ... }}
A Notifier object can be instantiated with a transport object and a
publisher ID:
notifier = messaging.Notifier(get_transport(CONF), 'compute')
and notifications are sent via drivers chosen with the notification_driver
config option and on the topics chosen with the notification_topics config
option.
Alternatively, a Notifier object can be instantiated with a specific
driver or topic::
notifier = notifier.Notifier(RPC_TRANSPORT,
'compute.host',
driver='messaging',
topic='notifications')
Notifier objects are relatively expensive to instantiate (mostly the cost
of loading notification drivers), so it is possible to specialize a given
Notifier object with a different publisher id using the prepare() method::
notifier = notifier.prepare(publisher_id='compute')
notifier.info(ctxt, event_type, payload)
"""
def __init__(self, transport, publisher_id=None,
driver=None, topic=None,
serializer=None, retry=None):
"""Construct a Notifier object.
:param transport: the transport to use for sending messages
:type transport: oslo.messaging.Transport
:param publisher_id: field in notifications sent, for example
'compute.host1'
:type publisher_id: str
:param driver: a driver to lookup from oslo.messaging.notify.drivers
:type driver: str
:param topic: the topic which to send messages on
:type topic: str
:param serializer: an optional entity serializer
:type serializer: Serializer
:param retry: an connection retries configuration
None or -1 means to retry forever
0 means no retry
N means N retries
:type retry: int
"""
transport.conf.register_opts(_notifier_opts)
self.transport = transport
self.publisher_id = publisher_id
self.retry = retry
self._driver_names = ([driver] if driver is not None
else transport.conf.notification_driver)
self._topics = ([topic] if topic is not None
else transport.conf.notification_topics)
self._serializer = serializer or msg_serializer.NoOpSerializer()
self._driver_mgr = named.NamedExtensionManager(
'oslo.messaging.notify.drivers',
names=self._driver_names,
invoke_on_load=True,
invoke_args=[transport.conf],
invoke_kwds={
'topics': self._topics,
'transport': self.transport,
}
)
_marker = object()
def prepare(self, publisher_id=_marker, retry=_marker):
"""Return a specialized Notifier instance.
Returns a new Notifier instance with the supplied publisher_id. Allows
sending notifications from multiple publisher_ids without the overhead
of notification driver loading.
:param publisher_id: field in notifications sent, for example
'compute.host1'
:type publisher_id: str
:param retry: an connection retries configuration
None or -1 means to retry forever
0 means no retry
N means N retries
:type retry: int
"""
return _SubNotifier._prepare(self, publisher_id, retry=retry)
def _notify(self, ctxt, event_type, payload, priority, publisher_id=None,
retry=None):
payload = self._serializer.serialize_entity(ctxt, payload)
ctxt = self._serializer.serialize_context(ctxt)
msg = dict(message_id=six.text_type(uuid.uuid4()),
publisher_id=publisher_id or self.publisher_id,
event_type=event_type,
priority=priority,
payload=payload,
timestamp=six.text_type(timeutils.utcnow()))
def do_notify(ext):
try:
ext.obj.notify(ctxt, msg, priority, retry or self.retry)
except Exception as e:
_LOG.exception("Problem '%(e)s' attempting to send to "
"notification system. Payload=%(payload)s",
dict(e=e, payload=payload))
if self._driver_mgr.extensions:
self._driver_mgr.map(do_notify)
def audit(self, ctxt, event_type, payload):
"""Send a notification at audit level.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'AUDIT')
def debug(self, ctxt, event_type, payload):
"""Send a notification at debug level.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'DEBUG')
def info(self, ctxt, event_type, payload):
"""Send a notification at info level.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'INFO')
def warn(self, ctxt, event_type, payload):
"""Send a notification at warning level.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'WARN')
warning = warn
def error(self, ctxt, event_type, payload):
"""Send a notification at error level.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'ERROR')
def critical(self, ctxt, event_type, payload):
"""Send a notification at critical level.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'CRITICAL')
def sample(self, ctxt, event_type, payload):
"""Send a notification at sample level.
Sample notifications are for high-frequency events
that typically contain small payloads. eg: "CPU = 70%"
Not all drivers support the sample level
(log, for example) so these could be dropped.
:param ctxt: a request context dict
:type ctxt: dict
:param event_type: describes the event, for example
'compute.create_instance'
:type event_type: str
:param payload: the notification payload
:type payload: dict
:raises: MessageDeliveryFailure
"""
self._notify(ctxt, event_type, payload, 'SAMPLE')
class _SubNotifier(Notifier):
_marker = Notifier._marker
def __init__(self, base, publisher_id, retry):
self._base = base
self.transport = base.transport
self.publisher_id = publisher_id
self.retry = retry
self._serializer = self._base._serializer
self._driver_mgr = self._base._driver_mgr
def _notify(self, ctxt, event_type, payload, priority):
super(_SubNotifier, self)._notify(ctxt, event_type, payload, priority)
@classmethod
def _prepare(cls, base, publisher_id=_marker, retry=_marker):
if publisher_id is cls._marker:
publisher_id = base.publisher_id
if retry is cls._marker:
retry = base.retry
return cls(base, publisher_id, retry=retry)
| apache-2.0 |
Yinux/TranslateProject | published/20220227 12 Simple Tools to Protect Your Privacy.md | 11192 | [#]: subject: "12 Simple Tools to Protect Your Privacy"
[#]: via: "https://itsfoss.com/privacy-tools/"
[#]: author: "Ankush Das https://itsfoss.com/author/ankush/"
[#]: collector: "lujun9972"
[#]: translator: "aREversez"
[#]: reviewer: "wxy"
[#]: publisher: "wxy"
[#]: url: "https://linux.cn/article-14337-1.html"
12 款简单好用的保护隐私的软件
======

数据是最宝贵的一项资产。
无论影响好坏,数据收集技术都会一直存在。现实生活中,人们进行分析、研究以及学习,都需要各种各样的数据。
当然,数据收集也会带来风险,比如不法机构会收集用户的浏览数据(或网络活动)。
匿名数据收集等技术虽然在不断发展,但在隐私保护这方面可能做的并不是十分完善。
不过先别担心,保护好自己的隐私并不是件难事。
一些简单好用的软件可以在不影响用户体验的前提下,增强用户的隐私保护。更重要的是,搞明白这些软件,你根本不需要着急花大把的时间。
本文将会推荐一些简单的软件,可以轻松保护你的网络隐私。
### 一些增强隐私保护的基本工具
保护数据安全最有效的办法就是,关注你使用频率最高的产品。
担心数据安全是必要的,但不能顾此失彼,忘记产品最基本的用途。
比如,你使用一款去中心化的社交软件,但是你的亲朋好友都不去用它,他们大多时候还是使用 WhatsApp。那么,你的这种做法就没有任何意义。
因此,我们在这里列出了一些不用付出特别的努力就能轻松试用的软件,并将它们归为以下几类:
* 网页浏览器
* 虚拟专用网络
* 搜索引擎
* 社交软件
* 操作系统
* 密码管理
### 关注隐私保护的开源网页浏览器
从办理银行业务到访问社交媒体,网页浏览器能帮你做各种事情。
如果你选择了一款提供优质安全服务以及强大隐私保护功能的网页浏览器,你几乎就可以高枕无忧了。
在我们推荐的 [最好的网页浏览器][7] 之中,(重点关注隐私的)包括:
#### 1、Tor 浏览器
![][8]
[Tor 浏览器][10] 是一款自由开源的网页浏览器,提供了强大的隐私保护功能。它是火狐浏览器的定制版本。
Tor 浏览器借助 [Tor 网络][9] 连接,通过多个节点来传递你的网络请求,以隐藏 IP 地址和位置信息。
在 Tor 浏览器上浏览网页,几乎没有人可以追踪到你。
然而,Tor 浏览器的浏览体验可能稍差一些,它的响应速度极慢。所以,如果你不介意这一点,Tor 浏览器绝对是你的不二之选。
#### 2、Firefox
![][11]
可以说,[Firefox][15] 是最优秀的 [开源浏览器][12]。也难怪 [我会一次又一次地回归 Firefox][13]。
Firefox 浏览器不仅内置最强大的隐私保护功能,而且还经常引入新的行业标准,以确保用户安全地浏览网页。
你可以在 Firefox 上安装一些 [最好的开源插件][14],然后自行配置,更好地保护自己的隐私。
#### 3、Brave
![][16]
[Brave][18] 是 Linux 系统上最好的浏览器之一,用户体验清新简洁,外观与 Chrome 有些相似。
Brave 凭借其强大的跟踪保护功能,以及开箱即用的自动运行的跟踪拦截器,一直以来都是 Linux 用户的最佳选择。
请阅读我们的文章:《[Brave vs. Firefox:你的私人网络体验的终极浏览器选择][17]》,进一步了解 Brave 的优点与缺陷。
### 保护隐私的虚拟专用网络
无论你使用的是电脑还是手机,虚拟专用网络都可以全程保护你的网络连接。
它还可以隐藏你真实的 IP 地址与位置,让你轻松浏览受限制的内容。
[专注隐私保护的虚拟专用网络服务][19] 有很多,这里我们推荐以下几款:
#### 1、ProtonVPN
![][20]
[ProtonVPN][21] 是一款强大的隐私保护服务,提供桌面版和移动版的开源客户端。
你可以免费使用这款软件;也可以选择付费,享受恶意软件拦截以及跟踪保护等功能。ProtonVPN 还可以与 ProtonMail 一起付费订阅。
#### 2、Mullvad
![][22]
[Mullvad][23] 也提供了开源的客户端。有趣的是,它不需要你使用邮箱注册。
你只需生成一个用户 ID,然后就可以使用加密货币或信用卡购买服务。
### 使用保护隐私的搜索引擎,确保网络活动的安全
网上浏览信息会透露你的身份和工作。
不法组织可能会利用你的搜索内容,对你实施欺诈。
所以,能够保护隐私的搜索引擎就显得十分重要了。我推荐以下两款:
#### 1、DuckDuckGo
![][24]
[DuckDuckGo][26] 是最流行的 [保护隐私的搜索引擎][25]之一,它声明不会记录用户的任何浏览数据。
一直以来,DuckDuckGo 也在不断提升自身的搜索结果质量,所以一般情况下你都可以搜索到想要的内容。
#### 2、Startpage
![][27]
[Startpage][28] 是一款很有趣的搜索引擎,外观和谷歌搜索相似,搜索结果也与谷歌搜索同步。不过,它不会收集你的信息。
如果你想要获取和谷歌搜索最相似的搜索结果,并且还希望可以使用隐私保护功能,那么你可以试试 Startpage。
### 使用安全的社交软件,保护聊天隐私
无论是政府还是软件本身,如果你不想别人在未经同意下获取你的聊天记录,你需要使用具有隐私保护功能的社交软件。
尽管大多数用户选择信赖 WhatsApp,但是它并不是最有效的隐私保护解决方案。当然,Facebook Messenger就更不用考虑了。
这里我推荐一些 [能够代替 WhatsApp 的社交软件][29]:
#### 1、Signal
![][30]
[Signal][32] 是一款开源的社交软件,支持端对端加密,[可安装在 Linux 桌面上][31]。
它也有一些隐私保护功能,可以保证聊天对话的安全。
#### 2、Threema
![][33]
[Threema][34] 是一款付费软件,内置 Signal 的全部核心功能,无需手机号码即可登录使用。
这款软件也提供了办公版本。如果你的亲朋好友愿意一次性花费 3 美元购买一款软件,那么Threema 是一个不错的选择。
### 选用安全的操作系统,为隐私保护打好基础
可以理解,为了满足个人需求,你 [选择了 Windows,而没有选择 Linux][35]。
但是,如果你为了保护隐私,想换个系统,可以考虑下面这些 [安全的 Linux 发行版][36]。
#### 1、Linux Mint
![][37]
[Linux Mint][39] 可以满足日常所需,是一款非常出色的 Linux 发行版。它基于 Ubuntu,追求青出于蓝胜于蓝,[希望在一些方面做得更好][38]
Linux Mint 通过关注用户的选择以及常规的安全升级,确保操作系统的安全。
#### 2、Qubes OS
![][40]
[Qubes OS][41] 专注安全和隐私问题。对新手来说,使用起来可能比较困难。
不过,如果你想尝试体验一下最安全、最强大的隐私保护操作系统,那你一定要试试 Qubes OS。
### 选择可靠的密码管理器,保护账号安全
如果不法分子可以轻易获取你的账户信息,那么就算你准备再多的隐私措施,也无济于事。
因此,你必须设置更强大、更复杂的密码。此外,要想做到这些,必须先有密码管理器。
在 [Linux 上最好的密码管理器][42] 之中,我建议使用下面这个:
#### 1、Bitwarden
![][43]
[Bitwarden][44] 是一款开源的密码管理器,全部的主要功能均可免费使用。
解锁这款软件的高级功能,每年只需花费 10 美元。
### 总结
专注隐私保护的软件有很多,数不胜数。
但是,很多都只是打着“隐私保护”的幌子,实际上不过是营销噱头;还有一些则根本无法使用。
所以,坚持使用那些自己用过的、适合自己的软件,才是比较好的选择。
以上软件你喜欢哪些?最喜欢的又是哪一款呢?请在下方评论留言。
--------------------------------------------------------------------------------
via: https://itsfoss.com/privacy-tools/
作者:[Ankush Das][a]
选题:[lujun9972][b]
译者:[aREversez](https://github.com/aREversez)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://itsfoss.com/author/ankush/
[b]: https://github.com/lujun9972
[1]: tmp.ETCQ3mkg7S#web
[2]: tmp.ETCQ3mkg7S#vpn
[3]: tmp.ETCQ3mkg7S#search
[4]: tmp.ETCQ3mkg7S#message
[5]: tmp.ETCQ3mkg7S#os
[6]: tmp.ETCQ3mkg7S#pwm
[7]: https://itsfoss.com/best-browsers-ubuntu-linux/
[8]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2022/02/tor-browser.png?resize=800%2C514&ssl=1
[9]: https://itsfoss.com/tor-guide/
[10]: https://www.torproject.org/download/
[11]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2021/08/firefox-proton.png?resize=800%2C450&ssl=1
[12]: https://itsfoss.com/open-source-browsers-linux/
[13]: https://news.itsfoss.com/why-mozilla-firefox/
[14]: https://itsfoss.com/best-firefox-add-ons/
[15]: https://www.mozilla.org/en-US/firefox/new/
[16]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2022/01/brave-tab-management.png?resize=800%2C523&ssl=1
[17]: https://linux.cn/article-13736-1.html
[18]: https://brave.com/
[19]: https://itsfoss.com/best-vpn-linux/
[20]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2021/07/protonvpn-ui.png?resize=789%2C800&ssl=1
[21]: https://itsfoss.com/recommends/protonvpn/
[22]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2022/02/mullvad-vpn.png?resize=800%2C460&ssl=1
[23]: https://mullvad.net/en/
[24]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2022/02/duckduckgo-light-v.png?resize=800%2C418&ssl=1
[25]: https://itsfoss.com/privacy-search-engines/
[26]: https://duckduckgo.com/
[27]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2020/02/startpage-screenshot.jpg?resize=800%2C395&ssl=1
[28]: https://startpage.com/
[29]: https://itsfoss.com/private-whatsapp-alternatives/
[30]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2021/01/signal-messenger-new.jpg?resize=800%2C450&ssl=1
[31]: https://itsfoss.com/install-signal-ubuntu/
[32]: https://signal.org/en/
[33]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2021/01/threema.jpg?resize=800%2C450&ssl=1
[34]: https://threema.ch/en
[35]: https://itsfoss.com/linux-better-than-windows/
[36]: https://itsfoss.com/privacy-focused-linux-distributions/
[37]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2022/02/linux-mint-20-3-screenshot.png?resize=800%2C449&ssl=1
[38]: https://itsfoss.com/linux-mint-vs-ubuntu/
[39]: https://linuxmint.com/
[40]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2020/03/qubes-os.jpg?resize=800%2C450&ssl=1
[41]: https://www.qubes-os.org/
[42]: https://itsfoss.com/password-managers-linux/
[43]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2022/01/bitwarden-firefox-extension.png?resize=800%2C500&ssl=1
[44]: https://bitwarden.com/
| apache-2.0 |
luci/luci-go | server/auth/authdb/validation.go | 4474 | // Copyright 2015 The LUCI 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 authdb
import (
"fmt"
"net"
"go.chromium.org/luci/auth/identity"
"go.chromium.org/luci/server/auth/service/protocol"
)
// validateAuthDB returns nil if AuthDB looks correct.
func validateAuthDB(db *protocol.AuthDB) error {
groups := make(map[string]*protocol.AuthGroup, len(db.Groups))
for _, g := range db.Groups {
groups[g.Name] = g
}
for name := range groups {
if err := validateAuthGroup(name, groups); err != nil {
return err
}
}
for _, wl := range db.IpWhitelists {
if err := validateIPWhitelist(wl); err != nil {
return fmt.Errorf("auth: bad IP whitlist %q - %s", wl.Name, err)
}
}
if db.Realms != nil {
perms := uint32(len(db.Realms.Permissions))
conds := uint32(len(db.Realms.Conditions))
for _, realm := range db.Realms.Realms {
if err := validateRealm(realm, perms, conds); err != nil {
return fmt.Errorf("auth: bad realm %q - %s", realm.Name, err)
}
}
}
return nil
}
// validateAuthGroup returns nil if AuthGroup looks correct.
func validateAuthGroup(name string, groups map[string]*protocol.AuthGroup) error {
g := groups[name]
for _, ident := range g.Members {
if _, err := identity.MakeIdentity(ident); err != nil {
return fmt.Errorf("auth: invalid identity %q in group %q - %s", ident, name, err)
}
}
for _, glob := range g.Globs {
if _, err := identity.MakeGlob(glob); err != nil {
return fmt.Errorf("auth: invalid glob %q in group %q - %s", glob, name, err)
}
}
for _, nested := range g.Nested {
if groups[nested] == nil {
return fmt.Errorf("auth: unknown nested group %q in group %q", nested, name)
}
}
if cycle := findGroupCycle(name, groups); len(cycle) != 0 {
return fmt.Errorf("auth: dependency cycle found - %v", cycle)
}
return nil
}
// findGroupCycle searches for a group dependency cycle that contains group
// `name`. Returns list of groups that form the cycle if found, empty list
// if no cycles. Unknown groups are considered empty.
func findGroupCycle(name string, groups map[string]*protocol.AuthGroup) []string {
// Set of groups that are completely explored (all subtree is traversed).
visited := map[string]bool{}
// Stack of groups that are being explored now. In case a cycle is detected
// it would contain that cycle.
var visiting []string
// Recursively explores `group` subtree, returns true if finds a cycle.
var visit func(string) bool
visit = func(group string) bool {
g := groups[group]
if g == nil {
visited[group] = true
return false
}
visiting = append(visiting, group)
for _, nested := range g.GetNested() {
// Cross edge. Can happen in diamond-like graph, not a cycle.
if visited[nested] {
continue
}
// Is `group` references its own ancestor -> cycle is detected.
for _, v := range visiting {
if v == nested {
return true
}
}
// Explore subtree.
if visit(nested) {
return true
}
}
visiting = visiting[:len(visiting)-1]
visited[group] = true
return false
}
visit(name)
return visiting // will contain a cycle, if any
}
// validateIPWhitelist checks IPs in the whitelist are parsable.
func validateIPWhitelist(wl *protocol.AuthIPWhitelist) error {
for _, subnet := range wl.Subnets {
if _, _, err := net.ParseCIDR(subnet); err != nil {
return fmt.Errorf("bad subnet %q - %s", subnet, err)
}
}
return nil
}
// validateRealm checks indexes of permissions and conditions in bindings.
func validateRealm(r *protocol.Realm, permsCount, condsCount uint32) error {
for _, b := range r.Bindings {
for _, perm := range b.Permissions {
if perm >= permsCount {
return fmt.Errorf("referencing out-of-bounds permission: %d>=%d", perm, permsCount)
}
}
for _, cond := range b.Conditions {
if cond >= condsCount {
return fmt.Errorf("referencing out-of-bounds condition: %d>=%d", cond, condsCount)
}
}
}
return nil
}
| apache-2.0 |
gavincook/IntelliJ-Platform-SDK-DevGuide | reference_guide/messaging_infrastructure.md | 8689 | ---
title: Messaging infrastructure
---
# Purpose
The purpose of this document is to introduce the messaging infrastructure available in the IntelliJ Platform to developers and plugin writers. It is intended to answer why, when and how to use it.
# Rationale
So, what is messaging in the IntelliJ Platform and why do we need it? Basically, its implementation of
[Observer pattern](https://en.wikipedia.org/wiki/Observer_pattern)
that provides additional features like _broadcasting on hierarchy_ and special _nested events_ processing (_nested event_ here is a situation when new event is fired (directly or indirectly) from the callback of another event).
# Design
Here are the main components of the messaging API.
## Topic
This class serves as an endpoint at the messaging infrastructure. I.e. clients are allowed to subscribe to the topic within particular bus and to send messages to particular topic within particular bus.

* *display name* just a human-readable name used for logging/monitoring purposes;
* *broadcast direction* will be explained in details at Broadcasting. Default value is *TO\_CHILDREN*;
* *listener class* that is a business interface for particular topic.
Subscribers register implementation of this interface at the messaging infrastructure and publishers may later retrieve object that conforms (IS-A) to it and call any method defined there. Messaging infrastructure takes care on dispatching that to all subscribers of the topic, i.e. the same method with the same arguments will be called on the registered callbacks;
## Message bus
Is the core of the messaging system. Is used at the following scenarios:

## Connection
Manages all subscriptions for particular client within particular bus.

* keeps number of *topic handler* mappings (callbacks to invoke when message for the target topic is received)
*Note*: not more than one handler per-topic within the same connection is allowed;
* it's possible to specify *default handler* and subscribe to the target topic without explicitly provided callback.
Connection will use that *default handler* when storing *(topic-handler)* mapping;
* it's possible to explicitly release acquired resources (*disconnect()* method).
Also it can be plugged to standard semi-automatic disposing
(
[Disposable](upsource:///platform/util/src/com/intellij/openapi/Disposable.java)
);
## Putting altogether
*Defining business interface and topic*
```java
public interface ChangeActionNotifier {
Topic<ChangeActionNotifier> CHANGE_ACTION_TOPIC = Topic.create("custom name", ChangeActionNotifier.class)
void beforeAction(Context context);
void afterAction(Context context);
}
```
*Subscribing*

```java
public void init(MessageBus bus) {
bus.connect().subscribe(ActionTopics.CHANGE_ACTION_TOPIC, new ChangeActionNotifier() {
@Override
public void beforeAction(Context context) {
// Process 'before action' event.
}
@Override
public void afterAction(Context context) {
// Process 'after action' event.
}
});
}
```
*Publishing*

```java
public void doChange(Context context) {
ChangeActionNotifier publisher = myBus.syncPublisher(ActionTopics.CHANGE_ACTION_TOPIC);
publisher.beforeAction(context);
try {
// Do action
// ...
} finally {
publisher.afterAction(context)
}
}
```
*Existing resources*
* *MessageBus* instances are available via
[ComponentManager.getMessageBus()](upsource:///platform/core-api/src/com/intellij/openapi/components/ComponentManager.java)<!--#L85-->
(many standard interfaces implement it, e.g.
[Application](upsource:///platform/core-api/src/com/intellij/openapi/application/Application.java),
[Project](upsource:///platform/core-api/src/com/intellij/openapi/project/Project.java);
* number of public topics are used by the *IntelliJ Platform*, e.g.
[AppTopics](upsource:///platform/platform-api/src/com/intellij/AppTopics.java),
[ProjectTopics](upsource:///platform/projectModel-api/src/com/intellij/ProjectTopics.java)
etc.
So, it's possible to subscribe to them in order to receive information about the processing;
# Broadcasting
Message buses can be organised into hierarchies. Moreover, the *IntelliJ Platform* has them already:

That allows to notify subscribers registered in one message bus on messages sent to another message bus.
*Example:*

Here we have a simple hierarchy (*application bus* is a parent of *project bus*) with three subscribers for the same topic.
We get the following if *topic1* defines broadcast direction as *TO\_CHILDREN*:
1. A message is sent to *topic1* via *application bus*;
2. *handler1* is notified about the message;
3. The message is delivered to the subscribers of the same topic within *project bus* (*handler2* and *handler3*);
*Benefits*
We don't need to bother with memory management of subscribers that are bound to child buses but interested in parent bus-level events.
Consider the example above we may want to have project-specific functionality that reacts to the application-level events.
All we need to do is to subscribe to the target topic within the *project bus*.
No hard reference to the project-level subscriber will be stored at application-level then,
i.e. we just avoided memory leak on project re-opening.
*Options*
Broadcast configuration is defined per-topic. Following options are available:
* _TO\_CHILDREN_ (default);
* _NONE_;
* _TO\_PARENT_;
# Nested messages
_Nested message_ is a message sent (directly or indirectly) during another message processing.
The IntelliJ Platform's Messaging infrastructure guarantees that all messages sent to particular topic will be delivered at the sending order.
*Example:*
Suppose we have the following configuration:

Let's see what happens if someone sends a message to the target topic:
* _message1_ is sent;
* _handler1_ receives _message1_ and sends _message2_ to the same topic;
* _handler2_ receives _message1_;
* _handler2_ receives _message2_;
* _handler1_ receives _message2_;
# Tips'n'tricks
## Relief listeners management
Messaging infrastructure is very light-weight, so, it's possible to reuse it at local sub-systems in order to relief
[Observers](https://en.wikipedia.org/wiki/Observer_pattern) construction. Let's see what is necessary to do then:
1. Define business interface to work with;
2. Create shared message bus and topic that uses the interface above (_shared_ here means that either _subject_ or _observers_ know about them);
Let's compare that with a manual implementation:
1. Define listener interface (business interface);
2. Provide reference to the _subject_ to all interested listeners;
3. Add listeners storage and listeners management methods (add/remove) to the _subject_;
4. Manually iterate all listeners and call target callback in all places where new event is fired;
## Avoid shared data modification from subscribers
We had a problem in a situation when two subscribers tried to modify the same document
([IDEA-71701](http://youtrack.jetbrains.net/issue/IDEA-71701)).
The thing is that every document change is performed by the following scenario:
1. _before change_ event is sent to all document listeners and some of them publish new messages during that;
2. actual change is performed;
3. _after change_ event is sent to all document listeners;
We had the following then:
1. _message1_ is sent to the topic with two subscribers;
2. _message1_ is queued for both subscribers;
3. _message1_ delivery starts;
4. _subscriber1_ receives _message1_;
5. _subscriber1_ issues document modification request at particular range (e.g. _document.delete(startOffset, endOffset)_);
6. _before change_ notification is sent to the document listeners;
7. _message2_ is sent by one of the standard document listeners to another topic within the same message bus during _before change_ processing;
8. the bus tries to deliver all pending messages before queuing _message2_;
9. _subscriber2_ receives _message1_ and also modifies a document;
10. the call stack is unwinded and _actual change_ phase of document modification operation requested by _subscriber1_ begins;
**The problem** is that document range used by _subscriber1_ for initial modification request is invalid if _subscriber2_ has changed document's range before it.
| apache-2.0 |
ccccjason/android | wearables/ui/confirm.md | 4419 | # 顯示確認界面
> 編寫: [roya](https://github.com/RoyaAoki) 原文:<https://developer.android.com/training/wearables/ui/confirm.html>
Android Wear應用中的[確認界面(Confirmations)](https://developer.android.com/design/wear/patterns.html#Countdown)通常是全屏或者相比於手持應用佔更大的部分。這樣確保用戶可以一眼看到確認界面(confirmations)且有一個足夠大的觸摸區域用於取消一個操作。
Wearable UI庫幫助我們在Android Wear應用中顯示確認動畫和定時器:
*確認定時器*
* 自動確認定時器為用戶顯示一個定時器動畫,讓用戶可以取消他們最近的操作。
*確認界面動畫*
* 確認界面動畫給用戶在完成一個操作時的視覺反饋。
下面的章節將演示瞭如何實現這些模式。
## 使用自動確認定時器
自動確認定時器讓用戶取消剛做的操作。當用戶做一個操作,我們的應用會顯示一個帶有定時動畫的取消按鈕,並且啟動該定時器。用戶可以在定時結束前選擇取消操作。如果用戶選擇取消操作或定時結束,我們的應用會得到一個通知。

**Figure 1:** 一個確認定時器.
為了在用戶完成操作時顯示一個確認定時器:
1. 添加`DelayedConfirmationView`元素到layout中。
2. 在activity中實現`DelayedConfirmationListener`接口。
3. 當用戶完成一個操作時,設置定時器的定時時間然後啟動它。
像下面這樣添加`DelayedConfirmationView`元素到layout中:
```xml
<android.support.wearable.view.DelayedConfirmationView
android:id="@+id/delayed_confirm"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/cancel_circle"
app:circle_border_color="@color/lightblue"
app:circle_border_width="4dp"
app:circle_radius="16dp">
</android.support.wearable.view.DelayedConfirmationView>
```
在layout定義中,我們可以用`android:src`制定一個drawable資源,用於顯示在圓形裡。然後直接設置圓的參數。
為了獲得定時結束或用戶點擊按鈕時的通知,需要在activity中實現相應的listener方法:
```java
public class WearActivity extends Activity implements
DelayedConfirmationView.DelayedConfirmationListener {
private DelayedConfirmationView mDelayedView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear_activity);
mDelayedView =
(DelayedConfirmationView) findViewById(R.id.delayed_confirm);
mDelayedView.setListener(this);
}
@Override
public void onTimerFinished(View view) {
// User didn't cancel, perform the action
}
@Override
public void onTimerSelected(View view) {
// User canceled, abort the action
}
}
```
為了啟動定時器,添加下面的代碼到activity處理用戶選擇某個操作的位置中:
```java
// Two seconds to cancel the action
mDelayedView.setTotalTimeMs(2000);
// Start the timer
mDelayedView.start();
```
## 顯示確認動畫
為了當用戶在我們的應用中完成一個操作時顯示確認動畫,我們需要創建一個從應用中的某個activity啟動`ConfirmationActivity`的intent。我們可以用`EXTRA_ANIMATION_TYPE` intent extra來指定下面其中一種動畫:
* `SUCCESS_ANIMATION`
* `FAILURE_ANIMATION`
* `OPEN_ON_PHONE_ANIMATION`
我們還可以在確認圖標下面添加一條消息。

**Figure 2:** 一個確認動畫
要在應用中使用`ConfirmationActivity`,首先在manifest文件聲明這個activity:
```xml
<manifest>
<application>
...
<activity
android:name="android.support.wearable.activity.ConfirmationActivity">
</activity>
</application>
</manifest>
```
然後確定用戶操作的結果,並使用intent啟動activity:
```java
Intent intent = new Intent(this, ConfirmationActivity.class);
intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE,
ConfirmationActivity.SUCCESS_ANIMATION);
intent.putExtra(ConfirmationActivity.EXTRA_MESSAGE,
getString(R.string.msg_sent));
startActivity(intent);
```
當確認動畫顯示結束後,`ConfirmationActivity`會銷燬(Finish),我們的的activity會恢復(Resume)。 | apache-2.0 |
flandr/minio | doc.go | 701 | /*
* Minimalist Object Storage, (C) 2014 Minio, 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.
*/
// Minio - Object storage inspired by Amazon S3 and Facebook Haystack.
package main
| apache-2.0 |
chenyujie/hybrid-murano | tools/lintstack.py | 6700 | #!/usr/bin/env python
# Copyright (c) 2015 OpenStack Foundation.
# 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.
"""pylint error checking."""
from __future__ import print_function
import json
import os
import re
import sys
from pylint import lint
from pylint.reporters import text
from six.moves import cStringIO as StringIO
# enabled checks
# http://pylint-messages.wikidot.com/all-codes
ENABLED_CODES=(
# refactor category
"R0801", "R0911", "R0912", "R0913", "R0914", "R0915",
# warning category
"W0612", "W0613", "W0703",
# convention category
"C1001")
KNOWN_PYLINT_EXCEPTIONS_FILE = "tools/pylint_exceptions"
class LintOutput(object):
_cached_filename = None
_cached_content = None
def __init__(self, filename, lineno, line_content, code, message,
lintoutput):
self.filename = filename
self.lineno = lineno
self.line_content = line_content
self.code = code
self.message = message
self.lintoutput = lintoutput
@classmethod
def get_duplicate_code_location(cls, remaining_lines):
module, lineno = remaining_lines.pop(0)[2:].split(":")
filename = module.replace(".", os.sep) + ".py"
return filename, int(lineno)
@classmethod
def get_line_content(cls, filename, lineno):
if cls._cached_filename != filename:
with open(filename) as f:
cls._cached_content = list(f.readlines())
cls._cached_filename = filename
# find first non-empty line
lineno -= 1
while True:
line_content = cls._cached_content[lineno].rstrip()
lineno +=1
if line_content:
return line_content
@classmethod
def from_line(cls, line, remaining_lines):
m = re.search(r"(\S+):(\d+): \[(\S+)(, \S*)?] (.*)", line)
if not m:
return None
matched = m.groups()
filename, lineno, code, message = (matched[0], int(matched[1]),
matched[2], matched[-1])
# duplicate code output needs special handling
if "duplicate-code" in code:
filename, lineno = cls.get_duplicate_code_location(remaining_lines)
# fixes incorrectly reported file path
line = line.replace(matched[0], filename)
line_content = cls.get_line_content(filename, lineno)
return cls(filename, lineno, line_content, code, message,
line.rstrip())
@classmethod
def from_msg_to_dict(cls, msg):
"""From the output of pylint msg, to a dict, where each key
is a unique error identifier, value is a list of LintOutput
"""
result = {}
lines = msg.splitlines()
while lines:
line = lines.pop(0)
obj = cls.from_line(line, lines)
if not obj:
continue
key = obj.key()
if key not in result:
result[key] = []
result[key].append(obj)
return result
def key(self):
return self.message, self.line_content.strip()
def json(self):
return json.dumps(self.__dict__)
def review_str(self):
return ("File %(filename)s\nLine %(lineno)d:%(line_content)s\n"
"%(code)s: %(message)s" % self.__dict__)
class ErrorKeys(object):
@classmethod
def print_json(cls, errors, output=sys.stdout):
print("# automatically generated by tools/lintstack.py", file=output)
for i in sorted(errors.keys()):
print(json.dumps(i), file=output)
@classmethod
def from_file(cls, filename):
keys = set()
for line in open(filename):
if line and line[0] != "#":
d = json.loads(line)
keys.add(tuple(d))
return keys
def run_pylint():
buff = StringIO()
reporter = text.ParseableTextReporter(output=buff)
args = ["-rn", "--disable=all", "--enable=" + ",".join(ENABLED_CODES),"murano"]
lint.Run(args, reporter=reporter, exit=False)
val = buff.getvalue()
buff.close()
return val
def generate_error_keys(msg=None):
print("Generating", KNOWN_PYLINT_EXCEPTIONS_FILE)
if msg is None:
msg = run_pylint()
errors = LintOutput.from_msg_to_dict(msg)
with open(KNOWN_PYLINT_EXCEPTIONS_FILE, "w") as f:
ErrorKeys.print_json(errors, output=f)
def validate(newmsg=None):
print("Loading", KNOWN_PYLINT_EXCEPTIONS_FILE)
known = ErrorKeys.from_file(KNOWN_PYLINT_EXCEPTIONS_FILE)
if newmsg is None:
print("Running pylint. Be patient...")
newmsg = run_pylint()
errors = LintOutput.from_msg_to_dict(newmsg)
print()
print("Unique errors reported by pylint: was %d, now %d."
% (len(known), len(errors)))
passed = True
for err_key, err_list in errors.items():
for err in err_list:
if err_key not in known:
print()
print(err.lintoutput)
print(err.review_str())
passed = False
if passed:
print("Congrats! pylint check passed.")
redundant = known - set(errors.keys())
if redundant:
print("Extra credit: some known pylint exceptions disappeared.")
for i in sorted(redundant):
print(json.dumps(i))
print("Consider regenerating the exception file if you will.")
else:
print()
print("Please fix the errors above. If you believe they are false "
"positives, run 'tools/lintstack.py generate' to overwrite.")
sys.exit(1)
def usage():
print("""Usage: tools/lintstack.py [generate|validate]
To generate pylint_exceptions file: tools/lintstack.py generate
To validate the current commit: tools/lintstack.py
""")
def main():
option = "validate"
if len(sys.argv) > 1:
option = sys.argv[1]
if option == "generate":
generate_error_keys()
elif option == "validate":
validate()
else:
usage()
if __name__ == "__main__":
main()
| apache-2.0 |
tomasdubec/openstack-cinder | cinder/tests/api/v1/test_volumes.py | 33659 | # Copyright 2013 Josh Durgin
# 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.
import datetime
from lxml import etree
import webob
from cinder.api import extensions
from cinder.api.v1 import volumes
from cinder import context
from cinder import db
from cinder import exception
from cinder import flags
from cinder import test
from cinder.tests.api import fakes
from cinder.tests.api.v2 import stubs
from cinder.tests.image import fake as fake_image
from cinder.volume import api as volume_api
FLAGS = flags.FLAGS
NS = '{http://docs.openstack.org/volume/api/v1}'
TEST_SNAPSHOT_UUID = '00000000-0000-0000-0000-000000000001'
def stub_snapshot_get(self, context, snapshot_id):
if snapshot_id != TEST_SNAPSHOT_UUID:
raise exception.NotFound
return {'id': snapshot_id,
'volume_id': 12,
'status': 'available',
'volume_size': 100,
'created_at': None,
'display_name': 'Default name',
'display_description': 'Default description', }
class VolumeApiTest(test.TestCase):
def setUp(self):
super(VolumeApiTest, self).setUp()
self.ext_mgr = extensions.ExtensionManager()
self.ext_mgr.extensions = {}
fake_image.stub_out_image_service(self.stubs)
self.controller = volumes.VolumeController(self.ext_mgr)
self.stubs.Set(db, 'volume_get_all', stubs.stub_volume_get_all)
self.stubs.Set(db, 'volume_get_all_by_project',
stubs.stub_volume_get_all_by_project)
self.stubs.Set(volume_api.API, 'get', stubs.stub_volume_get)
self.stubs.Set(volume_api.API, 'delete', stubs.stub_volume_delete)
def test_volume_create(self):
self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)
vol = {"size": 100,
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "zone1:host1"}
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
res_dict = self.controller.create(req, body)
expected = {'volume': {'status': 'fakestatus',
'display_description': 'Volume Test Desc',
'availability_zone': 'zone1:host1',
'display_name': 'Volume Test Name',
'attachments': [{'device': '/',
'server_id': 'fakeuuid',
'id': '1',
'volume_id': '1'}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': 100}}
self.assertEqual(res_dict, expected)
def test_volume_create_with_type(self):
vol_type = FLAGS.default_volume_type
db.volume_type_create(context.get_admin_context(),
dict(name=vol_type, extra_specs={}))
db_vol_type = db.volume_type_get_by_name(context.get_admin_context(),
vol_type)
vol = {"size": 100,
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "zone1:host1",
"volume_type": db_vol_type['name'], }
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
res_dict = self.controller.create(req, body)
self.assertEquals(res_dict['volume']['volume_type'],
db_vol_type['name'])
def test_volume_creation_fails_with_bad_size(self):
vol = {"size": '',
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "zone1:host1"}
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
self.assertRaises(exception.InvalidInput,
self.controller.create,
req,
body)
def test_volume_create_with_image_id(self):
self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)
self.ext_mgr.extensions = {'os-image-create': 'fake'}
test_id = "c905cedb-7281-47e4-8a62-f26bc5fc4c77"
vol = {"size": '1',
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "nova",
"imageRef": test_id}
expected = {'volume': {'status': 'fakestatus',
'display_description': 'Volume Test Desc',
'availability_zone': 'nova',
'display_name': 'Volume Test Name',
'attachments': [{'device': '/',
'server_id': 'fakeuuid',
'id': '1',
'volume_id': '1'}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'image_id': test_id,
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': '1'}}
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
res_dict = self.controller.create(req, body)
self.assertEqual(res_dict, expected)
def test_volume_create_with_image_id_and_snapshot_id(self):
self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)
self.stubs.Set(volume_api.API, "get_snapshot", stub_snapshot_get)
self.ext_mgr.extensions = {'os-image-create': 'fake'}
vol = {"size": '1',
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "cinder",
"imageRef": 'c905cedb-7281-47e4-8a62-f26bc5fc4c77',
"source_volid": None,
"snapshot_id": TEST_SNAPSHOT_UUID}
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller.create,
req,
body)
def test_volume_create_with_image_id_is_integer(self):
self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)
self.ext_mgr.extensions = {'os-image-create': 'fake'}
vol = {"size": '1',
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "cinder",
"imageRef": 1234}
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller.create,
req,
body)
def test_volume_create_with_image_id_not_uuid_format(self):
self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)
self.ext_mgr.extensions = {'os-image-create': 'fake'}
vol = {"size": '1',
"display_name": "Volume Test Name",
"display_description": "Volume Test Desc",
"availability_zone": "cinder",
"imageRef": '12345'}
body = {"volume": vol}
req = fakes.HTTPRequest.blank('/v1/volumes')
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller.create,
req,
body)
def test_volume_update(self):
self.stubs.Set(volume_api.API, "update", stubs.stub_volume_update)
updates = {
"display_name": "Updated Test Name",
}
body = {"volume": updates}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.update(req, '1', body)
expected = {'volume': {
'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'Updated Test Name',
'attachments': [{
'id': '1',
'volume_id': '1',
'server_id': 'fakeuuid',
'device': '/',
}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1, 1, 1, 1),
'size': 1,
}}
self.assertEquals(res_dict, expected)
def test_volume_update_metadata(self):
self.stubs.Set(volume_api.API, "update", stubs.stub_volume_update)
updates = {
"metadata": {"qos_max_iops": 2000}
}
body = {"volume": updates}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.update(req, '1', body)
expected = {'volume': {
'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'displayname',
'attachments': [{
'id': '1',
'volume_id': '1',
'server_id': 'fakeuuid',
'device': '/',
}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {"qos_max_iops": 2000},
'id': '1',
'created_at': datetime.datetime(1, 1, 1, 1, 1, 1),
'size': 1,
}}
self.assertEquals(res_dict, expected)
def test_update_empty_body(self):
body = {}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
self.assertRaises(webob.exc.HTTPUnprocessableEntity,
self.controller.update,
req, '1', body)
def test_update_invalid_body(self):
body = {'display_name': 'missing top level volume key'}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
self.assertRaises(webob.exc.HTTPUnprocessableEntity,
self.controller.update,
req, '1', body)
def test_update_not_found(self):
self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound)
updates = {
"display_name": "Updated Test Name",
}
body = {"volume": updates}
req = fakes.HTTPRequest.blank('/v1/volumes/1')
self.assertRaises(webob.exc.HTTPNotFound,
self.controller.update,
req, '1', body)
def test_volume_list(self):
self.stubs.Set(volume_api.API, 'get_all',
stubs.stub_volume_get_all_by_project)
req = fakes.HTTPRequest.blank('/v1/volumes')
res_dict = self.controller.index(req)
expected = {'volumes': [{'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'displayname',
'attachments': [{'device': '/',
'server_id': 'fakeuuid',
'id': '1',
'volume_id': '1'}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': 1}]}
self.assertEqual(res_dict, expected)
def test_volume_list_detail(self):
self.stubs.Set(volume_api.API, 'get_all',
stubs.stub_volume_get_all_by_project)
req = fakes.HTTPRequest.blank('/v1/volumes/detail')
res_dict = self.controller.index(req)
expected = {'volumes': [{'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'displayname',
'attachments': [{'device': '/',
'server_id': 'fakeuuid',
'id': '1',
'volume_id': '1'}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': 1}]}
self.assertEqual(res_dict, expected)
def test_volume_list_by_name(self):
def stub_volume_get_all_by_project(context, project_id, marker, limit,
sort_key, sort_dir):
return [
stubs.stub_volume(1, display_name='vol1'),
stubs.stub_volume(2, display_name='vol2'),
stubs.stub_volume(3, display_name='vol3'),
]
self.stubs.Set(db, 'volume_get_all_by_project',
stub_volume_get_all_by_project)
# no display_name filter
req = fakes.HTTPRequest.blank('/v1/volumes')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 3)
# filter on display_name
req = fakes.HTTPRequest.blank('/v1/volumes?display_name=vol2')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 1)
self.assertEqual(resp['volumes'][0]['display_name'], 'vol2')
# filter no match
req = fakes.HTTPRequest.blank('/v1/volumes?display_name=vol4')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 0)
def test_volume_list_by_status(self):
def stub_volume_get_all_by_project(context, project_id, marker, limit,
sort_key, sort_dir):
return [
stubs.stub_volume(1, display_name='vol1', status='available'),
stubs.stub_volume(2, display_name='vol2', status='available'),
stubs.stub_volume(3, display_name='vol3', status='in-use'),
]
self.stubs.Set(db, 'volume_get_all_by_project',
stub_volume_get_all_by_project)
# no status filter
req = fakes.HTTPRequest.blank('/v1/volumes')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 3)
# single match
req = fakes.HTTPRequest.blank('/v1/volumes?status=in-use')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 1)
self.assertEqual(resp['volumes'][0]['status'], 'in-use')
# multiple match
req = fakes.HTTPRequest.blank('/v1/volumes?status=available')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 2)
for volume in resp['volumes']:
self.assertEqual(volume['status'], 'available')
# multiple filters
req = fakes.HTTPRequest.blank('/v1/volumes?status=available&'
'display_name=vol1')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 1)
self.assertEqual(resp['volumes'][0]['display_name'], 'vol1')
self.assertEqual(resp['volumes'][0]['status'], 'available')
# no match
req = fakes.HTTPRequest.blank('/v1/volumes?status=in-use&'
'display_name=vol1')
resp = self.controller.index(req)
self.assertEqual(len(resp['volumes']), 0)
def test_volume_show(self):
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.show(req, '1')
expected = {'volume': {'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'displayname',
'attachments': [{'device': '/',
'server_id': 'fakeuuid',
'id': '1',
'volume_id': '1'}],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': 1}}
self.assertEqual(res_dict, expected)
def test_volume_show_no_attachments(self):
def stub_volume_get(self, context, volume_id):
return stubs.stub_volume(volume_id, attach_status='detached')
self.stubs.Set(volume_api.API, 'get', stub_volume_get)
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.show(req, '1')
expected = {'volume': {'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'displayname',
'attachments': [],
'bootable': 'false',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': 1}}
self.assertEqual(res_dict, expected)
def test_volume_show_bootable(self):
def stub_volume_get(self, context, volume_id):
return (stubs.stub_volume(volume_id,
volume_glance_metadata=dict(foo='bar')))
self.stubs.Set(volume_api.API, 'get', stub_volume_get)
req = fakes.HTTPRequest.blank('/v1/volumes/1')
res_dict = self.controller.show(req, '1')
expected = {'volume': {'status': 'fakestatus',
'display_description': 'displaydesc',
'availability_zone': 'fakeaz',
'display_name': 'displayname',
'attachments': [{'device': '/',
'server_id': 'fakeuuid',
'id': '1',
'volume_id': '1'}],
'bootable': 'true',
'volume_type': 'vol_type_name',
'snapshot_id': None,
'source_volid': None,
'metadata': {},
'id': '1',
'created_at': datetime.datetime(1, 1, 1,
1, 1, 1),
'size': 1}}
self.assertEqual(res_dict, expected)
def test_volume_show_no_volume(self):
self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound)
req = fakes.HTTPRequest.blank('/v1/volumes/1')
self.assertRaises(webob.exc.HTTPNotFound,
self.controller.show,
req,
1)
def test_volume_delete(self):
req = fakes.HTTPRequest.blank('/v1/volumes/1')
resp = self.controller.delete(req, 1)
self.assertEqual(resp.status_int, 202)
def test_volume_delete_no_volume(self):
self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound)
req = fakes.HTTPRequest.blank('/v1/volumes/1')
self.assertRaises(webob.exc.HTTPNotFound,
self.controller.delete,
req,
1)
def test_admin_list_volumes_limited_to_project(self):
req = fakes.HTTPRequest.blank('/v1/fake/volumes',
use_admin_context=True)
res = self.controller.index(req)
self.assertTrue('volumes' in res)
self.assertEqual(1, len(res['volumes']))
def test_admin_list_volumes_all_tenants(self):
req = fakes.HTTPRequest.blank('/v1/fake/volumes?all_tenants=1',
use_admin_context=True)
res = self.controller.index(req)
self.assertTrue('volumes' in res)
self.assertEqual(3, len(res['volumes']))
def test_all_tenants_non_admin_gets_all_tenants(self):
req = fakes.HTTPRequest.blank('/v1/fake/volumes?all_tenants=1')
res = self.controller.index(req)
self.assertTrue('volumes' in res)
self.assertEqual(1, len(res['volumes']))
def test_non_admin_get_by_project(self):
req = fakes.HTTPRequest.blank('/v1/fake/volumes')
res = self.controller.index(req)
self.assertTrue('volumes' in res)
self.assertEqual(1, len(res['volumes']))
class VolumeSerializerTest(test.TestCase):
def _verify_volume_attachment(self, attach, tree):
for attr in ('id', 'volume_id', 'server_id', 'device'):
self.assertEqual(str(attach[attr]), tree.get(attr))
def _verify_volume(self, vol, tree):
self.assertEqual(tree.tag, NS + 'volume')
for attr in ('id', 'status', 'size', 'availability_zone', 'created_at',
'display_name', 'display_description', 'volume_type',
'snapshot_id'):
self.assertEqual(str(vol[attr]), tree.get(attr))
for child in tree:
print child.tag
self.assertTrue(child.tag in (NS + 'attachments', NS + 'metadata'))
if child.tag == 'attachments':
self.assertEqual(1, len(child))
self.assertEqual('attachment', child[0].tag)
self._verify_volume_attachment(vol['attachments'][0], child[0])
elif child.tag == 'metadata':
not_seen = set(vol['metadata'].keys())
for gr_child in child:
self.assertTrue(gr_child.get("key") in not_seen)
self.assertEqual(str(vol['metadata'][gr_child.get("key")]),
gr_child.text)
not_seen.remove(gr_child.get('key'))
self.assertEqual(0, len(not_seen))
def test_volume_show_create_serializer(self):
serializer = volumes.VolumeTemplate()
raw_volume = dict(
id='vol_id',
status='vol_status',
size=1024,
availability_zone='vol_availability',
created_at=datetime.datetime.now(),
attachments=[dict(id='vol_id',
volume_id='vol_id',
server_id='instance_uuid',
device='/foo')],
display_name='vol_name',
display_description='vol_desc',
volume_type='vol_type',
snapshot_id='snap_id',
source_volid='source_volid',
metadata=dict(foo='bar',
baz='quux', ), )
text = serializer.serialize(dict(volume=raw_volume))
print text
tree = etree.fromstring(text)
self._verify_volume(raw_volume, tree)
def test_volume_index_detail_serializer(self):
serializer = volumes.VolumesTemplate()
raw_volumes = [dict(id='vol1_id',
status='vol1_status',
size=1024,
availability_zone='vol1_availability',
created_at=datetime.datetime.now(),
attachments=[dict(id='vol1_id',
volume_id='vol1_id',
server_id='instance_uuid',
device='/foo1')],
display_name='vol1_name',
display_description='vol1_desc',
volume_type='vol1_type',
snapshot_id='snap1_id',
source_volid=None,
metadata=dict(foo='vol1_foo',
bar='vol1_bar', ), ),
dict(id='vol2_id',
status='vol2_status',
size=1024,
availability_zone='vol2_availability',
created_at=datetime.datetime.now(),
attachments=[dict(id='vol2_id',
volume_id='vol2_id',
server_id='instance_uuid',
device='/foo2')],
display_name='vol2_name',
display_description='vol2_desc',
volume_type='vol2_type',
snapshot_id='snap2_id',
source_volid=None,
metadata=dict(foo='vol2_foo',
bar='vol2_bar', ), )]
text = serializer.serialize(dict(volumes=raw_volumes))
print text
tree = etree.fromstring(text)
self.assertEqual(NS + 'volumes', tree.tag)
self.assertEqual(len(raw_volumes), len(tree))
for idx, child in enumerate(tree):
self._verify_volume(raw_volumes[idx], child)
class TestVolumeCreateRequestXMLDeserializer(test.TestCase):
def setUp(self):
super(TestVolumeCreateRequestXMLDeserializer, self).setUp()
self.deserializer = volumes.CreateDeserializer()
def test_minimal_volume(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
size="1"></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {"volume": {"size": "1", }, }
self.assertEquals(request['body'], expected)
def test_display_name(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
size="1"
display_name="Volume-xml"></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {
"volume": {
"size": "1",
"display_name": "Volume-xml",
},
}
self.assertEquals(request['body'], expected)
def test_display_description(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
size="1"
display_name="Volume-xml"
display_description="description"></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {
"volume": {
"size": "1",
"display_name": "Volume-xml",
"display_description": "description",
},
}
self.assertEquals(request['body'], expected)
def test_volume_type(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
size="1"
display_name="Volume-xml"
display_description="description"
volume_type="289da7f8-6440-407c-9fb4-7db01ec49164"></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {
"volume": {
"display_name": "Volume-xml",
"size": "1",
"display_name": "Volume-xml",
"display_description": "description",
"volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164",
},
}
self.assertEquals(request['body'], expected)
def test_availability_zone(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
size="1"
display_name="Volume-xml"
display_description="description"
volume_type="289da7f8-6440-407c-9fb4-7db01ec49164"
availability_zone="us-east1"></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {
"volume": {
"size": "1",
"display_name": "Volume-xml",
"display_description": "description",
"volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164",
"availability_zone": "us-east1",
},
}
self.assertEquals(request['body'], expected)
def test_metadata(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
display_name="Volume-xml"
size="1">
<metadata><meta key="Type">work</meta></metadata></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {
"volume": {
"display_name": "Volume-xml",
"size": "1",
"metadata": {
"Type": "work",
},
},
}
self.assertEquals(request['body'], expected)
def test_full_volume(self):
self_request = """
<volume xmlns="http://docs.openstack.org/compute/api/v1.1"
size="1"
display_name="Volume-xml"
display_description="description"
volume_type="289da7f8-6440-407c-9fb4-7db01ec49164"
availability_zone="us-east1">
<metadata><meta key="Type">work</meta></metadata></volume>"""
request = self.deserializer.deserialize(self_request)
expected = {
"volume": {
"size": "1",
"display_name": "Volume-xml",
"display_description": "description",
"volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164",
"availability_zone": "us-east1",
"metadata": {
"Type": "work",
},
},
}
self.assertEquals(request['body'], expected)
class VolumesUnprocessableEntityTestCase(test.TestCase):
"""
Tests of places we throw 422 Unprocessable Entity from
"""
def setUp(self):
super(VolumesUnprocessableEntityTestCase, self).setUp()
self.ext_mgr = extensions.ExtensionManager()
self.ext_mgr.extensions = {}
self.controller = volumes.VolumeController(self.ext_mgr)
def _unprocessable_volume_create(self, body):
req = fakes.HTTPRequest.blank('/v2/fake/volumes')
req.method = 'POST'
self.assertRaises(webob.exc.HTTPUnprocessableEntity,
self.controller.create, req, body)
def test_create_no_body(self):
self._unprocessable_volume_create(body=None)
def test_create_missing_volume(self):
body = {'foo': {'a': 'b'}}
self._unprocessable_volume_create(body=body)
def test_create_malformed_entity(self):
body = {'volume': 'string'}
self._unprocessable_volume_create(body=body)
| apache-2.0 |
dropbox/bazel | src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/SkylarkOSApi.java | 1570 | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skylarkbuildapi.repository;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;
/** A Skylark structure to deliver information about the system we are running on. */
@SkylarkModule(
name = "repository_os",
category = SkylarkModuleCategory.NONE,
doc = "Various data about the current platform Bazel is running on."
)
public interface SkylarkOSApi {
@SkylarkCallable(name = "environ", structField = true, doc = "The list of environment variables.")
public ImmutableMap<String, String> getEnvironmentVariables();
@SkylarkCallable(
name = "name",
structField = true,
doc = "A string identifying the current system Bazel is running on."
)
public String getName();
}
| apache-2.0 |
Gaduo/hapi-fhir | hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Resource.java | 17114 | package org.hl7.fhir.dstu3.model;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0
import java.util.*;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.dstu3.model.Enumerations.*;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.ChildOrder;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Block;
import org.hl7.fhir.instance.model.api.*;
import org.hl7.fhir.exceptions.FHIRException;
/**
* This is the base resource type for everything.
*/
public abstract class Resource extends BaseResource implements IAnyResource {
/**
* The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.
*/
@Child(name = "id", type = {IdType.class}, order=0, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Logical id of this artifact", formalDefinition="The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes." )
protected IdType id;
/**
* The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.
*/
@Child(name = "meta", type = {Meta.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Metadata about the resource", formalDefinition="The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource." )
protected Meta meta;
/**
* A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.
*/
@Child(name = "implicitRules", type = {UriType.class}, order=2, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="A set of rules under which this content was created", formalDefinition="A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content." )
protected UriType implicitRules;
/**
* The base language in which the resource is written.
*/
@Child(name = "language", type = {CodeType.class}, order=3, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Language of the resource content", formalDefinition="The base language in which the resource is written." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/languages")
protected CodeType language;
private static final long serialVersionUID = -559462759L;
/**
* Constructor
*/
public Resource() {
super();
}
/**
* @return {@link #id} (The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.). This is the underlying object with id, value and extensions. The accessor "getId" gives direct access to the value
*/
public IdType getIdElement() {
if (this.id == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Resource.id");
else if (Configuration.doAutoCreate())
this.id = new IdType(); // bb
return this.id;
}
public boolean hasIdElement() {
return this.id != null && !this.id.isEmpty();
}
public boolean hasId() {
return this.id != null && !this.id.isEmpty();
}
/**
* @param value {@link #id} (The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.). This is the underlying object with id, value and extensions. The accessor "getId" gives direct access to the value
*/
public Resource setIdElement(IdType value) {
this.id = value;
return this;
}
/**
* @return The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.
*/
public String getId() {
return this.id == null ? null : this.id.getValue();
}
/**
* @param value The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.
*/
public Resource setId(String value) {
if (Utilities.noString(value))
this.id = null;
else {
if (this.id == null)
this.id = new IdType();
this.id.setValue(value);
}
return this;
}
/**
* @return {@link #meta} (The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.)
*/
public Meta getMeta() {
if (this.meta == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Resource.meta");
else if (Configuration.doAutoCreate())
this.meta = new Meta(); // cc
return this.meta;
}
public boolean hasMeta() {
return this.meta != null && !this.meta.isEmpty();
}
/**
* @param value {@link #meta} (The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.)
*/
public Resource setMeta(Meta value) {
this.meta = value;
return this;
}
/**
* @return {@link #implicitRules} (A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.). This is the underlying object with id, value and extensions. The accessor "getImplicitRules" gives direct access to the value
*/
public UriType getImplicitRulesElement() {
if (this.implicitRules == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Resource.implicitRules");
else if (Configuration.doAutoCreate())
this.implicitRules = new UriType(); // bb
return this.implicitRules;
}
public boolean hasImplicitRulesElement() {
return this.implicitRules != null && !this.implicitRules.isEmpty();
}
public boolean hasImplicitRules() {
return this.implicitRules != null && !this.implicitRules.isEmpty();
}
/**
* @param value {@link #implicitRules} (A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.). This is the underlying object with id, value and extensions. The accessor "getImplicitRules" gives direct access to the value
*/
public Resource setImplicitRulesElement(UriType value) {
this.implicitRules = value;
return this;
}
/**
* @return A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.
*/
public String getImplicitRules() {
return this.implicitRules == null ? null : this.implicitRules.getValue();
}
/**
* @param value A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.
*/
public Resource setImplicitRules(String value) {
if (Utilities.noString(value))
this.implicitRules = null;
else {
if (this.implicitRules == null)
this.implicitRules = new UriType();
this.implicitRules.setValue(value);
}
return this;
}
/**
* @return {@link #language} (The base language in which the resource is written.). This is the underlying object with id, value and extensions. The accessor "getLanguage" gives direct access to the value
*/
public CodeType getLanguageElement() {
if (this.language == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Resource.language");
else if (Configuration.doAutoCreate())
this.language = new CodeType(); // bb
return this.language;
}
public boolean hasLanguageElement() {
return this.language != null && !this.language.isEmpty();
}
public boolean hasLanguage() {
return this.language != null && !this.language.isEmpty();
}
/**
* @param value {@link #language} (The base language in which the resource is written.). This is the underlying object with id, value and extensions. The accessor "getLanguage" gives direct access to the value
*/
public Resource setLanguageElement(CodeType value) {
this.language = value;
return this;
}
/**
* @return The base language in which the resource is written.
*/
public String getLanguage() {
return this.language == null ? null : this.language.getValue();
}
/**
* @param value The base language in which the resource is written.
*/
public Resource setLanguage(String value) {
if (Utilities.noString(value))
this.language = null;
else {
if (this.language == null)
this.language = new CodeType();
this.language.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
childrenList.add(new Property("id", "id", "The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.", 0, java.lang.Integer.MAX_VALUE, id));
childrenList.add(new Property("meta", "Meta", "The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource.", 0, java.lang.Integer.MAX_VALUE, meta));
childrenList.add(new Property("implicitRules", "uri", "A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content.", 0, java.lang.Integer.MAX_VALUE, implicitRules));
childrenList.add(new Property("language", "code", "The base language in which the resource is written.", 0, java.lang.Integer.MAX_VALUE, language));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case 3355: /*id*/ return this.id == null ? new Base[0] : new Base[] {this.id}; // IdType
case 3347973: /*meta*/ return this.meta == null ? new Base[0] : new Base[] {this.meta}; // Meta
case -961826286: /*implicitRules*/ return this.implicitRules == null ? new Base[0] : new Base[] {this.implicitRules}; // UriType
case -1613589672: /*language*/ return this.language == null ? new Base[0] : new Base[] {this.language}; // CodeType
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case 3355: // id
this.id = castToId(value); // IdType
break;
case 3347973: // meta
this.meta = castToMeta(value); // Meta
break;
case -961826286: // implicitRules
this.implicitRules = castToUri(value); // UriType
break;
case -1613589672: // language
this.language = castToCode(value); // CodeType
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("id"))
this.id = castToId(value); // IdType
else if (name.equals("meta"))
this.meta = castToMeta(value); // Meta
else if (name.equals("implicitRules"))
this.implicitRules = castToUri(value); // UriType
else if (name.equals("language"))
this.language = castToCode(value); // CodeType
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 3355: throw new FHIRException("Cannot make property id as it is not a complex type"); // IdType
case 3347973: return getMeta(); // Meta
case -961826286: throw new FHIRException("Cannot make property implicitRules as it is not a complex type"); // UriType
case -1613589672: throw new FHIRException("Cannot make property language as it is not a complex type"); // CodeType
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("id")) {
throw new FHIRException("Cannot call addChild on a primitive type Resource.id");
}
else if (name.equals("meta")) {
this.meta = new Meta();
return this.meta;
}
else if (name.equals("implicitRules")) {
throw new FHIRException("Cannot call addChild on a primitive type Resource.implicitRules");
}
else if (name.equals("language")) {
throw new FHIRException("Cannot call addChild on a primitive type Resource.language");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Resource";
}
public abstract Resource copy();
public void copyValues(Resource dst) {
dst.id = id == null ? null : id.copy();
dst.meta = meta == null ? null : meta.copy();
dst.implicitRules = implicitRules == null ? null : implicitRules.copy();
dst.language = language == null ? null : language.copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Resource))
return false;
Resource o = (Resource) other;
return compareDeep(id, o.id, true) && compareDeep(meta, o.meta, true) && compareDeep(implicitRules, o.implicitRules, true)
&& compareDeep(language, o.language, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Resource))
return false;
Resource o = (Resource) other;
return compareValues(id, o.id, true) && compareValues(implicitRules, o.implicitRules, true) && compareValues(language, o.language, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(id, meta, implicitRules
, language);
}
@Override
public String getIdBase() {
return getId();
}
@Override
public void setIdBase(String value) {
setId(value);
}
public abstract ResourceType getResourceType();
}
| apache-2.0 |
minermoder27/equivalent_exchange | equivalent_exchange/alchemical_chest.lua | 2005 | local modname = "equivalent_exchange:"
-- chest = {
-- talisman_check = function(pos)
-- local meta = minetest.get_meta(pos)
-- local inventory = meta:get_inventory()
-- local size = inventory:get_size("container")
-- for i = 1, size do
-- local stack = inventory:get_stack("from", i)
-- end
-- }
-- Registering Nodes --
minetest.register_node(modname.."alchemical_chest", {
description = "Alchemical Chest",
tiles = {
"ee_alchemical_chest_top.png",
"ee_alchemical_chest_bottom.png",
"ee_alchemical_chest_side.png",
"ee_alchemical_chest_side.png",
"ee_alchemical_chest_side.png",
"ee_alchemical_chest_front.png",
},
paramtype2 = "facedir",
groups = {cracky = 2},
is_ground_content = false,
sounds = default.node_sound_stone_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec",
"size[13,13]"..
"label[0,0;Alchemical Chest]"..
"list[current_name;container;0,0.5;13,8;]"..
"list[current_player;main;2.5,9;8,4;]")
meta:set_string("infotext", "Alchemical Chest")
local inv = meta:get_inventory()
inv:set_size("container", 13*8)
end,
can_dig = function(pos,player)
local meta = minetest.env:get_meta(pos);
local inv = meta:get_inventory()
return inv:is_empty("main")
end,
-- on_metadata_inventory_put = function(pos, listname, index, stack, player)
-- chest.talisman_check(pos)
-- end,
-- on_metadata_inventory_take = function(pos, listname, index, stack, player)
-- chest.talisman_check(pos)
-- end,
-- on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
-- chest.talisman_check(pos)
-- end,
emc = 8987
})
-- Registering Crafts --
minetest.register_craft({
output = modname.."alchemical_chest",
recipe = {
{modname.."low_covalence", modname.."medium_covalence", modname.."high_covalence"},
{"default:stone", "default:diamond", "default:stone"},
{"default:steel_ingot", "default:chest", "default:steel_ingot"}
}
}) | apache-2.0 |
HebaKhaled/bposs | src/com.mentor.nucleus.bp.als.oal.test/src/com/mentor/nucleus/bp/als/oal/test/SingleDimensionFixedArrayAssigmentTest_1_Generics.java | 183440 | //=====================================================================
//
//File: $RCSfile: SingleDimensionFixedArrayAssigmentTest_1_Generics.java,v $
//Version: $Revision: 1.5 $
//Modified: $Date: 2013/05/10 04:52:46 $
//
// Generated by: UnitTestGenerator.pl
// Version: 1.9
// Matrix: SingleDimensionFixedArrayAssigmentMatrix.txt
//
//(c) Copyright 2007-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================
package com.mentor.nucleus.bp.als.oal.test;
import org.eclipse.ui.IEditorPart;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.mentor.nucleus.bp.core.*;
import com.mentor.nucleus.bp.core.common.NonRootModelElement;
import com.mentor.nucleus.bp.test.common.*;
import com.mentor.nucleus.bp.ui.canvas.*;
import com.mentor.nucleus.bp.ui.canvas.test.*;
import com.mentor.nucleus.bp.ui.graphics.editor.GraphicalEditor;
import antlr.RecognitionException;
import antlr.TokenStreamException;
public class SingleDimensionFixedArrayAssigmentTest_1_Generics extends ArrayBaseTest {
private static boolean configured = false;
protected String getResultName() {
return super.getResultName();
}
public SingleDimensionFixedArrayAssigmentTest_1_Generics(String arg0) {
super("APVT", arg0);
}
protected void setUp() throws Exception {
if (!configured) {
super.setUp();
configured = true;
}
}
protected void tearDown() throws Exception {
try {
super.tearDown();
OalParserTest_Generics.tearDownActionData();
} catch (RecognitionException re) {
// do nothing
} catch (TokenStreamException te) {
// do nothing
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV1D8).
*
*/
public void testT1RV1D3_T1LV1D8() {
test_id = getTestId("T1RV1D3", "T1LV1D8", "1");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV1D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV1D9).
*
*/
public void testT1RV1D3_T1LV1D9() {
test_id = getTestId("T1RV1D3", "T1LV1D9", "2");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV1D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D1).
// *
// */
// public void testT1RV1D3_T1LV2D1() {
// test_id = getTestId("T1RV1D3", "T1LV2D1", "3");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV2D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure4, checkResult_Failure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D2).
// *
// */
// public void testT1RV1D3_T1LV2D2() {
// test_id = getTestId("T1RV1D3", "T1LV2D2", "4");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV2D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure4, checkResult_Failure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D3).
*
*/
public void testT1RV1D3_T1LV2D3() {
test_id = getTestId("T1RV1D3", "T1LV2D3", "5");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D4).
*
*/
public void testT1RV1D3_T1LV2D4() {
test_id = getTestId("T1RV1D3", "T1LV2D4", "6");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D5).
*
*/
public void testT1RV1D3_T1LV2D5() {
test_id = getTestId("T1RV1D3", "T1LV2D5", "7");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D5");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D6).
*
*/
public void testT1RV1D3_T1LV2D6() {
test_id = getTestId("T1RV1D3", "T1LV2D6", "8");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D7).
*
*/
public void testT1RV1D3_T1LV2D7() {
test_id = getTestId("T1RV1D3", "T1LV2D7", "9");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D8).
*
*/
public void testT1RV1D3_T1LV2D8() {
test_id = getTestId("T1RV1D3", "T1LV2D8", "10");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV2D9).
*
*/
public void testT1RV1D3_T1LV2D9() {
test_id = getTestId("T1RV1D3", "T1LV2D9", "11");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV2D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D1).
// *
// */
// public void testT1RV1D3_T1LV3D1() {
// test_id = getTestId("T1RV1D3", "T1LV3D1", "12");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV3D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D2).
// *
// */
// public void testT1RV1D3_T1LV3D2() {
// test_id = getTestId("T1RV1D3", "T1LV3D2", "13");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV3D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D3).
*
*/
public void testT1RV1D3_T1LV3D3() {
test_id = getTestId("T1RV1D3", "T1LV3D3", "14");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D4).
*
*/
public void testT1RV1D3_T1LV3D4() {
test_id = getTestId("T1RV1D3", "T1LV3D4", "15");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D5).
*
*/
public void testT1RV1D3_T1LV3D5() {
test_id = getTestId("T1RV1D3", "T1LV3D5", "16");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D5");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D6).
*
*/
public void testT1RV1D3_T1LV3D6() {
test_id = getTestId("T1RV1D3", "T1LV3D6", "17");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D7).
*
*/
public void testT1RV1D3_T1LV3D7() {
test_id = getTestId("T1RV1D3", "T1LV3D7", "18");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D8).
*
*/
public void testT1RV1D3_T1LV3D8() {
test_id = getTestId("T1RV1D3", "T1LV3D8", "19");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV3D9).
*
*/
public void testT1RV1D3_T1LV3D9() {
test_id = getTestId("T1RV1D3", "T1LV3D9", "20");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV3D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D1).
// *
// */
// public void testT1RV1D3_T1LV4D1() {
// test_id = getTestId("T1RV1D3", "T1LV4D1", "21");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV4D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D2).
// *
// */
// public void testT1RV1D3_T1LV4D2() {
// test_id = getTestId("T1RV1D3", "T1LV4D2", "22");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV4D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D3).
*
*/
public void testT1RV1D3_T1LV4D3() {
test_id = getTestId("T1RV1D3", "T1LV4D3", "23");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D4).
*
*/
public void testT1RV1D3_T1LV4D4() {
test_id = getTestId("T1RV1D3", "T1LV4D4", "24");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D5).
*
*/
public void testT1RV1D3_T1LV4D5() {
test_id = getTestId("T1RV1D3", "T1LV4D5", "25");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D5");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D6).
*
*/
public void testT1RV1D3_T1LV4D6() {
test_id = getTestId("T1RV1D3", "T1LV4D6", "26");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D7).
*
*/
public void testT1RV1D3_T1LV4D7() {
test_id = getTestId("T1RV1D3", "T1LV4D7", "27");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D8).
*
*/
public void testT1RV1D3_T1LV4D8() {
test_id = getTestId("T1RV1D3", "T1LV4D8", "28");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV4D9).
*
*/
public void testT1RV1D3_T1LV4D9() {
test_id = getTestId("T1RV1D3", "T1LV4D9", "29");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV4D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D1).
// *
// */
// public void testT1RV1D3_T1LV5D1() {
// test_id = getTestId("T1RV1D3", "T1LV5D1", "30");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV5D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D2).
// *
// */
// public void testT1RV1D3_T1LV5D2() {
// test_id = getTestId("T1RV1D3", "T1LV5D2", "31");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV5D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D3).
*
*/
public void testT1RV1D3_T1LV5D3() {
test_id = getTestId("T1RV1D3", "T1LV5D3", "32");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D4).
*
*/
public void testT1RV1D3_T1LV5D4() {
test_id = getTestId("T1RV1D3", "T1LV5D4", "33");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D5).
*
*/
public void testT1RV1D3_T1LV5D5() {
test_id = getTestId("T1RV1D3", "T1LV5D5", "34");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D5");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D6).
*
*/
public void testT1RV1D3_T1LV5D6() {
test_id = getTestId("T1RV1D3", "T1LV5D6", "35");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D7).
*
*/
public void testT1RV1D3_T1LV5D7() {
test_id = getTestId("T1RV1D3", "T1LV5D7", "36");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D8).
*
*/
public void testT1RV1D3_T1LV5D8() {
test_id = getTestId("T1RV1D3", "T1LV5D8", "37");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV5D9).
*
*/
public void testT1RV1D3_T1LV5D9() {
test_id = getTestId("T1RV1D3", "T1LV5D9", "38");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV5D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D1).
// *
// */
// public void testT1RV1D3_T1LV6D1() {
// test_id = getTestId("T1RV1D3", "T1LV6D1", "39");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV6D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100659374 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D2).
// *
// */
// public void testT1RV1D3_T1LV6D2() {
// test_id = getTestId("T1RV1D3", "T1LV6D2", "40");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV6D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D3).
*
*/
public void testT1RV1D3_T1LV6D3() {
test_id = getTestId("T1RV1D3", "T1LV6D3", "41");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D4).
*
*/
public void testT1RV1D3_T1LV6D4() {
test_id = getTestId("T1RV1D3", "T1LV6D4", "42");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D5).
*
*/
public void testT1RV1D3_T1LV6D5() {
test_id = getTestId("T1RV1D3", "T1LV6D5", "43");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D5");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D6).
*
*/
public void testT1RV1D3_T1LV6D6() {
test_id = getTestId("T1RV1D3", "T1LV6D6", "44");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D7).
*
*/
public void testT1RV1D3_T1LV6D7() {
test_id = getTestId("T1RV1D3", "T1LV6D7", "45");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D8).
*
*/
public void testT1RV1D3_T1LV6D8() {
test_id = getTestId("T1RV1D3", "T1LV6D8", "46");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV6D9).
*
*/
public void testT1RV1D3_T1LV6D9() {
test_id = getTestId("T1RV1D3", "T1LV6D9", "47");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV6D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV7D1).
// *
// */
// public void testT1RV1D3_T1LV7D1() {
// test_id = getTestId("T1RV1D3", "T1LV7D1", "48");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV7D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row (T1LV7D2).
// *
// */
// public void testT1RV1D3_T1LV7D2() {
// test_id = getTestId("T1RV1D3", "T1LV7D2", "49");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV7D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV7D3).
*
*/
public void testT1RV1D3_T1LV7D3() {
test_id = getTestId("T1RV1D3", "T1LV7D3", "50");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV7D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV8D1).
*
*/
public void testT1RV1D3_T1LV8D1() {
test_id = getTestId("T1RV1D3", "T1LV8D1", "51");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV8D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV8D2).
*
*/
public void testT1RV1D3_T1LV8D2() {
test_id = getTestId("T1RV1D3", "T1LV8D2", "52");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV8D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV8D3).
*
*/
public void testT1RV1D3_T1LV8D3() {
test_id = getTestId("T1RV1D3", "T1LV8D3", "53");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV8D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV9D1).
*
*/
public void testT1RV1D3_T1LV9D1() {
test_id = getTestId("T1RV1D3", "T1LV9D1", "54");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV9D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV9D2).
*
*/
public void testT1RV1D3_T1LV9D2() {
test_id = getTestId("T1RV1D3", "T1LV9D2", "55");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV9D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row (T1LV9D3).
*
*/
public void testT1RV1D3_T1LV9D3() {
test_id = getTestId("T1RV1D3", "T1LV9D3", "56");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV9D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV10D1).
*
*/
public void testT1RV1D3_T1LV10D1() {
test_id = getTestId("T1RV1D3", "T1LV10D1", "57");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV10D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV10D2).
*
*/
public void testT1RV1D3_T1LV10D2() {
test_id = getTestId("T1RV1D3", "T1LV10D2", "58");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV10D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV10D3).
*
*/
public void testT1RV1D3_T1LV10D3() {
test_id = getTestId("T1RV1D3", "T1LV10D3", "59");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV10D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV11D1).
*
*/
public void testT1RV1D3_T1LV11D1() {
test_id = getTestId("T1RV1D3", "T1LV11D1", "60");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV11D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV11D2).
*
*/
public void testT1RV1D3_T1LV11D2() {
test_id = getTestId("T1RV1D3", "T1LV11D2", "61");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV11D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure4,
checkResult_ReturnFailure4(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV11D3).
*
*/
public void testT1RV1D3_T1LV11D3() {
test_id = getTestId("T1RV1D3", "T1LV11D3", "62");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV11D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV12D1).
// *
// */
// public void testT1RV1D3_T1LV12D1() {
// test_id = getTestId("T1RV1D3", "T1LV12D1", "63");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV12D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV12D2).
// *
// */
// public void testT1RV1D3_T1LV12D2() {
// test_id = getTestId("T1RV1D3", "T1LV12D2", "64");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV12D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV12D3).
*
*/
public void testT1RV1D3_T1LV12D3() {
test_id = getTestId("T1RV1D3", "T1LV12D3", "65");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV12D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV13D1).
// *
// */
// public void testT1RV1D3_T1LV13D1() {
// test_id = getTestId("T1RV1D3", "T1LV13D1", "66");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV13D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV13D2).
// *
// */
// public void testT1RV1D3_T1LV13D2() {
// test_id = getTestId("T1RV1D3", "T1LV13D2", "67");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV13D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV13D3).
*
*/
public void testT1RV1D3_T1LV13D3() {
test_id = getTestId("T1RV1D3", "T1LV13D3", "68");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV13D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV14D1).
// *
// */
// public void testT1RV1D3_T1LV14D1() {
// test_id = getTestId("T1RV1D3", "T1LV14D1", "69");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV14D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV14D2).
// *
// */
// public void testT1RV1D3_T1LV14D2() {
// test_id = getTestId("T1RV1D3", "T1LV14D2", "70");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV14D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV14D3).
*
*/
public void testT1RV1D3_T1LV14D3() {
test_id = getTestId("T1RV1D3", "T1LV14D3", "71");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV14D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV15D1).
// *
// */
// public void testT1RV1D3_T1LV15D1() {
// test_id = getTestId("T1RV1D3", "T1LV15D1", "72");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV15D1");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100650072 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D3) and row
// * (T1LV15D2).
// *
// */
// public void testT1RV1D3_T1LV15D2() {
// test_id = getTestId("T1RV1D3", "T1LV15D2", "73");
//
// String src = selectTRVD("T1RV1D3");
//
// String dest = selectTLVD("T1LV15D2");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(ParamFailure4, checkResult_ParamFailure4(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D3) and row
* (T1LV15D3).
*
*/
public void testT1RV1D3_T1LV15D3() {
test_id = getTestId("T1RV1D3", "T1LV15D3", "74");
String src = selectTRVD("T1RV1D3");
String dest = selectTLVD("T1LV15D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D1).
*
*/
public void testT1RV1D4_T1LV1D1() {
test_id = getTestId("T1RV1D4", "T1LV1D1", "75");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D2).
*
*/
public void testT1RV1D4_T1LV1D2() {
test_id = getTestId("T1RV1D4", "T1LV1D2", "76");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D3).
*
*/
public void testT1RV1D4_T1LV1D3() {
test_id = getTestId("T1RV1D4", "T1LV1D3", "77");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D4).
*
*/
public void testT1RV1D4_T1LV1D4() {
test_id = getTestId("T1RV1D4", "T1LV1D4", "78");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D5).
// *
// */
// public void testT1RV1D4_T1LV1D5() {
// test_id = getTestId("T1RV1D4", "T1LV1D5", "79");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV1D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D6).
*
*/
public void testT1RV1D4_T1LV1D6() {
test_id = getTestId("T1RV1D4", "T1LV1D6", "80");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure6, checkResult_Failure6(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D7).
*
*/
public void testT1RV1D4_T1LV1D7() {
test_id = getTestId("T1RV1D4", "T1LV1D7", "81");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D8).
*
*/
public void testT1RV1D4_T1LV1D8() {
test_id = getTestId("T1RV1D4", "T1LV1D8", "82");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure6, checkResult_Failure6(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV1D9).
*
*/
public void testT1RV1D4_T1LV1D9() {
test_id = getTestId("T1RV1D4", "T1LV1D9", "83");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV1D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D1).
*
*/
public void testT1RV1D4_T1LV2D1() {
test_id = getTestId("T1RV1D4", "T1LV2D1", "84");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D2).
*
*/
public void testT1RV1D4_T1LV2D2() {
test_id = getTestId("T1RV1D4", "T1LV2D2", "85");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D3).
*
*/
public void testT1RV1D4_T1LV2D3() {
test_id = getTestId("T1RV1D4", "T1LV2D3", "86");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D4).
*
*/
public void testT1RV1D4_T1LV2D4() {
test_id = getTestId("T1RV1D4", "T1LV2D4", "87");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D5).
// *
// */
// public void testT1RV1D4_T1LV2D5() {
// test_id = getTestId("T1RV1D4", "T1LV2D5", "88");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV2D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D6).
*
*/
public void testT1RV1D4_T1LV2D6() {
test_id = getTestId("T1RV1D4", "T1LV2D6", "89");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure6, checkResult_Failure6(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D7).
*
*/
public void testT1RV1D4_T1LV2D7() {
test_id = getTestId("T1RV1D4", "T1LV2D7", "90");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D8).
*
*/
public void testT1RV1D4_T1LV2D8() {
test_id = getTestId("T1RV1D4", "T1LV2D8", "91");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure6, checkResult_Failure6(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV2D9).
*
*/
public void testT1RV1D4_T1LV2D9() {
test_id = getTestId("T1RV1D4", "T1LV2D9", "92");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV2D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D1).
*
*/
public void testT1RV1D4_T1LV3D1() {
test_id = getTestId("T1RV1D4", "T1LV3D1", "93");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV3D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D2).
*
*/
public void testT1RV1D4_T1LV3D2() {
test_id = getTestId("T1RV1D4", "T1LV3D2", "94");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV3D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D3).
*
*/
public void testT1RV1D4_T1LV3D3() {
test_id = getTestId("T1RV1D4", "T1LV3D3", "95");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV3D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D4).
*
*/
public void testT1RV1D4_T1LV3D4() {
test_id = getTestId("T1RV1D4", "T1LV3D4", "96");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV3D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D5).
// *
// */
// public void testT1RV1D4_T1LV3D5() {
// test_id = getTestId("T1RV1D4", "T1LV3D5", "97");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV3D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D6).
// *
// */
// public void testT1RV1D4_T1LV3D6() {
// test_id = getTestId("T1RV1D4", "T1LV3D6", "98");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV3D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D7).
*
*/
public void testT1RV1D4_T1LV3D7() {
test_id = getTestId("T1RV1D4", "T1LV3D7", "99");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV3D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D8).
// *
// */
// public void testT1RV1D4_T1LV3D8() {
// test_id = getTestId("T1RV1D4", "T1LV3D8", "100");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV3D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV3D9).
*
*/
public void testT1RV1D4_T1LV3D9() {
test_id = getTestId("T1RV1D4", "T1LV3D9", "101");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV3D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D1).
*
*/
public void testT1RV1D4_T1LV4D1() {
test_id = getTestId("T1RV1D4", "T1LV4D1", "102");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV4D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D2).
*
*/
public void testT1RV1D4_T1LV4D2() {
test_id = getTestId("T1RV1D4", "T1LV4D2", "103");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV4D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D3).
*
*/
public void testT1RV1D4_T1LV4D3() {
test_id = getTestId("T1RV1D4", "T1LV4D3", "104");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV4D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D4).
*
*/
public void testT1RV1D4_T1LV4D4() {
test_id = getTestId("T1RV1D4", "T1LV4D4", "105");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV4D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D5).
// *
// */
// public void testT1RV1D4_T1LV4D5() {
// test_id = getTestId("T1RV1D4", "T1LV4D5", "106");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV4D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D6).
// *
// */
// public void testT1RV1D4_T1LV4D6() {
// test_id = getTestId("T1RV1D4", "T1LV4D6", "107");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV4D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D7).
*
*/
public void testT1RV1D4_T1LV4D7() {
test_id = getTestId("T1RV1D4", "T1LV4D7", "108");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV4D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D8).
// *
// */
// public void testT1RV1D4_T1LV4D8() {
// test_id = getTestId("T1RV1D4", "T1LV4D8", "109");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV4D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV4D9).
*
*/
public void testT1RV1D4_T1LV4D9() {
test_id = getTestId("T1RV1D4", "T1LV4D9", "110");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV4D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D1).
*
*/
public void testT1RV1D4_T1LV5D1() {
test_id = getTestId("T1RV1D4", "T1LV5D1", "111");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV5D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D2).
*
*/
public void testT1RV1D4_T1LV5D2() {
test_id = getTestId("T1RV1D4", "T1LV5D2", "112");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV5D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D3).
*
*/
public void testT1RV1D4_T1LV5D3() {
test_id = getTestId("T1RV1D4", "T1LV5D3", "113");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV5D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D4).
*
*/
public void testT1RV1D4_T1LV5D4() {
test_id = getTestId("T1RV1D4", "T1LV5D4", "114");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV5D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D5).
// *
// */
// public void testT1RV1D4_T1LV5D5() {
// test_id = getTestId("T1RV1D4", "T1LV5D5", "115");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV5D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D6).
// *
// */
// public void testT1RV1D4_T1LV5D6() {
// test_id = getTestId("T1RV1D4", "T1LV5D6", "116");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV5D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D7).
*
*/
public void testT1RV1D4_T1LV5D7() {
test_id = getTestId("T1RV1D4", "T1LV5D7", "117");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV5D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D8).
// *
// */
// public void testT1RV1D4_T1LV5D8() {
// test_id = getTestId("T1RV1D4", "T1LV5D8", "118");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV5D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV5D9).
*
*/
public void testT1RV1D4_T1LV5D9() {
test_id = getTestId("T1RV1D4", "T1LV5D9", "119");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV5D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D1).
*
*/
public void testT1RV1D4_T1LV6D1() {
test_id = getTestId("T1RV1D4", "T1LV6D1", "120");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV6D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D2).
*
*/
public void testT1RV1D4_T1LV6D2() {
test_id = getTestId("T1RV1D4", "T1LV6D2", "121");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV6D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D3).
*
*/
public void testT1RV1D4_T1LV6D3() {
test_id = getTestId("T1RV1D4", "T1LV6D3", "122");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV6D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D4).
*
*/
public void testT1RV1D4_T1LV6D4() {
test_id = getTestId("T1RV1D4", "T1LV6D4", "123");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV6D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D5).
// *
// */
// public void testT1RV1D4_T1LV6D5() {
// test_id = getTestId("T1RV1D4", "T1LV6D5", "124");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV6D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D6).
// *
// */
// public void testT1RV1D4_T1LV6D6() {
// test_id = getTestId("T1RV1D4", "T1LV6D6", "125");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV6D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D7).
*
*/
public void testT1RV1D4_T1LV6D7() {
test_id = getTestId("T1RV1D4", "T1LV6D7", "126");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV6D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100676237 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D8).
// *
// */
// public void testT1RV1D4_T1LV6D8() {
// test_id = getTestId("T1RV1D4", "T1LV6D8", "127");
//
// String src = selectTRVD("T1RV1D4");
//
// String dest = selectTLVD("T1LV6D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure6, checkResult_Failure6(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV6D9).
*
*/
public void testT1RV1D4_T1LV6D9() {
test_id = getTestId("T1RV1D4", "T1LV6D9", "128");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV6D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV7D1).
*
*/
public void testT1RV1D4_T1LV7D1() {
test_id = getTestId("T1RV1D4", "T1LV7D1", "129");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV7D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV7D2).
*
*/
public void testT1RV1D4_T1LV7D2() {
test_id = getTestId("T1RV1D4", "T1LV7D2", "130");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV7D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV7D3).
*
*/
public void testT1RV1D4_T1LV7D3() {
test_id = getTestId("T1RV1D4", "T1LV7D3", "131");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV7D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV8D1).
*
*/
public void testT1RV1D4_T1LV8D1() {
test_id = getTestId("T1RV1D4", "T1LV8D1", "132");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV8D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV8D2).
*
*/
public void testT1RV1D4_T1LV8D2() {
test_id = getTestId("T1RV1D4", "T1LV8D2", "133");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV8D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV8D3).
*
*/
public void testT1RV1D4_T1LV8D3() {
test_id = getTestId("T1RV1D4", "T1LV8D3", "134");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV8D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV9D1).
*
*/
public void testT1RV1D4_T1LV9D1() {
test_id = getTestId("T1RV1D4", "T1LV9D1", "135");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV9D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV9D2).
*
*/
public void testT1RV1D4_T1LV9D2() {
test_id = getTestId("T1RV1D4", "T1LV9D2", "136");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV9D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row (T1LV9D3).
*
*/
public void testT1RV1D4_T1LV9D3() {
test_id = getTestId("T1RV1D4", "T1LV9D3", "137");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV9D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV10D1).
*
*/
public void testT1RV1D4_T1LV10D1() {
test_id = getTestId("T1RV1D4", "T1LV10D1", "138");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV10D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV10D2).
*
*/
public void testT1RV1D4_T1LV10D2() {
test_id = getTestId("T1RV1D4", "T1LV10D2", "139");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV10D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV10D3).
*
*/
public void testT1RV1D4_T1LV10D3() {
test_id = getTestId("T1RV1D4", "T1LV10D3", "140");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV10D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV11D1).
*
*/
public void testT1RV1D4_T1LV11D1() {
test_id = getTestId("T1RV1D4", "T1LV11D1", "141");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV11D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV11D2).
*
*/
public void testT1RV1D4_T1LV11D2() {
test_id = getTestId("T1RV1D4", "T1LV11D2", "142");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV11D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV11D3).
*
*/
public void testT1RV1D4_T1LV11D3() {
test_id = getTestId("T1RV1D4", "T1LV11D3", "143");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV11D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV12D1).
*
*/
public void testT1RV1D4_T1LV12D1() {
test_id = getTestId("T1RV1D4", "T1LV12D1", "144");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV12D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV12D2).
*
*/
public void testT1RV1D4_T1LV12D2() {
test_id = getTestId("T1RV1D4", "T1LV12D2", "145");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV12D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV12D3).
*
*/
public void testT1RV1D4_T1LV12D3() {
test_id = getTestId("T1RV1D4", "T1LV12D3", "146");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV12D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV13D1).
*
*/
public void testT1RV1D4_T1LV13D1() {
test_id = getTestId("T1RV1D4", "T1LV13D1", "147");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV13D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV13D2).
*
*/
public void testT1RV1D4_T1LV13D2() {
test_id = getTestId("T1RV1D4", "T1LV13D2", "148");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV13D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV13D3).
*
*/
public void testT1RV1D4_T1LV13D3() {
test_id = getTestId("T1RV1D4", "T1LV13D3", "149");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV13D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV14D1).
*
*/
public void testT1RV1D4_T1LV14D1() {
test_id = getTestId("T1RV1D4", "T1LV14D1", "150");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV14D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV14D2).
*
*/
public void testT1RV1D4_T1LV14D2() {
test_id = getTestId("T1RV1D4", "T1LV14D2", "151");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV14D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV14D3).
*
*/
public void testT1RV1D4_T1LV14D3() {
test_id = getTestId("T1RV1D4", "T1LV14D3", "152");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV14D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV15D1).
*
*/
public void testT1RV1D4_T1LV15D1() {
test_id = getTestId("T1RV1D4", "T1LV15D1", "153");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV15D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV15D2).
*
*/
public void testT1RV1D4_T1LV15D2() {
test_id = getTestId("T1RV1D4", "T1LV15D2", "154");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV15D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D4) and row
* (T1LV15D3).
*
*/
public void testT1RV1D4_T1LV15D3() {
test_id = getTestId("T1RV1D4", "T1LV15D3", "155");
String src = selectTRVD("T1RV1D4");
String dest = selectTLVD("T1LV15D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D1).
*
*/
public void testT1RV1D5_T1LV1D1() {
test_id = getTestId("T1RV1D5", "T1LV1D1", "156");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV1D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D2).
*
*/
public void testT1RV1D5_T1LV1D2() {
test_id = getTestId("T1RV1D5", "T1LV1D2", "157");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV1D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D3).
*
*/
public void testT1RV1D5_T1LV1D3() {
test_id = getTestId("T1RV1D5", "T1LV1D3", "158");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV1D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D4).
*
*/
public void testT1RV1D5_T1LV1D4() {
test_id = getTestId("T1RV1D5", "T1LV1D4", "159");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV1D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D5).
// *
// */
// public void testT1RV1D5_T1LV1D5() {
// test_id = getTestId("T1RV1D5", "T1LV1D5", "160");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV1D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D6).
// *
// */
// public void testT1RV1D5_T1LV1D6() {
// test_id = getTestId("T1RV1D5", "T1LV1D6", "161");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV1D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D7).
*
*/
public void testT1RV1D5_T1LV1D7() {
test_id = getTestId("T1RV1D5", "T1LV1D7", "162");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV1D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D8).
// *
// */
// public void testT1RV1D5_T1LV1D8() {
// test_id = getTestId("T1RV1D5", "T1LV1D8", "163");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV1D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV1D9).
*
*/
public void testT1RV1D5_T1LV1D9() {
test_id = getTestId("T1RV1D5", "T1LV1D9", "164");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV1D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D1).
*
*/
public void testT1RV1D5_T1LV2D1() {
test_id = getTestId("T1RV1D5", "T1LV2D1", "165");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV2D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D2).
*
*/
public void testT1RV1D5_T1LV2D2() {
test_id = getTestId("T1RV1D5", "T1LV2D2", "166");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV2D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D3).
*
*/
public void testT1RV1D5_T1LV2D3() {
test_id = getTestId("T1RV1D5", "T1LV2D3", "167");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV2D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D4).
*
*/
public void testT1RV1D5_T1LV2D4() {
test_id = getTestId("T1RV1D5", "T1LV2D4", "168");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV2D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D5).
// *
// */
// public void testT1RV1D5_T1LV2D5() {
// test_id = getTestId("T1RV1D5", "T1LV2D5", "169");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV2D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D6).
// *
// */
// public void testT1RV1D5_T1LV2D6() {
// test_id = getTestId("T1RV1D5", "T1LV2D6", "170");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV2D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D7).
*
*/
public void testT1RV1D5_T1LV2D7() {
test_id = getTestId("T1RV1D5", "T1LV2D7", "171");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV2D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D8).
// *
// */
// public void testT1RV1D5_T1LV2D8() {
// test_id = getTestId("T1RV1D5", "T1LV2D8", "172");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV2D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV2D9).
*
*/
public void testT1RV1D5_T1LV2D9() {
test_id = getTestId("T1RV1D5", "T1LV2D9", "173");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV2D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D1).
*
*/
public void testT1RV1D5_T1LV3D1() {
test_id = getTestId("T1RV1D5", "T1LV3D1", "174");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV3D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D2).
*
*/
public void testT1RV1D5_T1LV3D2() {
test_id = getTestId("T1RV1D5", "T1LV3D2", "175");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV3D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D3).
*
*/
public void testT1RV1D5_T1LV3D3() {
test_id = getTestId("T1RV1D5", "T1LV3D3", "176");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV3D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D4).
*
*/
public void testT1RV1D5_T1LV3D4() {
test_id = getTestId("T1RV1D5", "T1LV3D4", "177");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV3D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D5).
// *
// */
// public void testT1RV1D5_T1LV3D5() {
// test_id = getTestId("T1RV1D5", "T1LV3D5", "178");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV3D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D6).
// *
// */
// public void testT1RV1D5_T1LV3D6() {
// test_id = getTestId("T1RV1D5", "T1LV3D6", "179");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV3D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D7).
*
*/
public void testT1RV1D5_T1LV3D7() {
test_id = getTestId("T1RV1D5", "T1LV3D7", "180");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV3D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D8).
// *
// */
// public void testT1RV1D5_T1LV3D8() {
// test_id = getTestId("T1RV1D5", "T1LV3D8", "181");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV3D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV3D9).
*
*/
public void testT1RV1D5_T1LV3D9() {
test_id = getTestId("T1RV1D5", "T1LV3D9", "182");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV3D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D1).
*
*/
public void testT1RV1D5_T1LV4D1() {
test_id = getTestId("T1RV1D5", "T1LV4D1", "183");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV4D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D2).
*
*/
public void testT1RV1D5_T1LV4D2() {
test_id = getTestId("T1RV1D5", "T1LV4D2", "184");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV4D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D3).
*
*/
public void testT1RV1D5_T1LV4D3() {
test_id = getTestId("T1RV1D5", "T1LV4D3", "185");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV4D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D4).
*
*/
public void testT1RV1D5_T1LV4D4() {
test_id = getTestId("T1RV1D5", "T1LV4D4", "186");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV4D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D5).
// *
// */
// public void testT1RV1D5_T1LV4D5() {
// test_id = getTestId("T1RV1D5", "T1LV4D5", "187");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV4D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D6).
// *
// */
// public void testT1RV1D5_T1LV4D6() {
// test_id = getTestId("T1RV1D5", "T1LV4D6", "188");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV4D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D7).
*
*/
public void testT1RV1D5_T1LV4D7() {
test_id = getTestId("T1RV1D5", "T1LV4D7", "189");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV4D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D8).
// *
// */
// public void testT1RV1D5_T1LV4D8() {
// test_id = getTestId("T1RV1D5", "T1LV4D8", "190");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV4D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV4D9).
*
*/
public void testT1RV1D5_T1LV4D9() {
test_id = getTestId("T1RV1D5", "T1LV4D9", "191");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV4D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D1).
*
*/
public void testT1RV1D5_T1LV5D1() {
test_id = getTestId("T1RV1D5", "T1LV5D1", "192");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV5D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D2).
*
*/
public void testT1RV1D5_T1LV5D2() {
test_id = getTestId("T1RV1D5", "T1LV5D2", "193");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV5D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D3).
*
*/
public void testT1RV1D5_T1LV5D3() {
test_id = getTestId("T1RV1D5", "T1LV5D3", "194");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV5D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D4).
*
*/
public void testT1RV1D5_T1LV5D4() {
test_id = getTestId("T1RV1D5", "T1LV5D4", "195");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV5D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D5).
// *
// */
// public void testT1RV1D5_T1LV5D5() {
// test_id = getTestId("T1RV1D5", "T1LV5D5", "196");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV5D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D6).
// *
// */
// public void testT1RV1D5_T1LV5D6() {
// test_id = getTestId("T1RV1D5", "T1LV5D6", "197");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV5D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D7).
*
*/
public void testT1RV1D5_T1LV5D7() {
test_id = getTestId("T1RV1D5", "T1LV5D7", "198");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV5D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D8).
// *
// */
// public void testT1RV1D5_T1LV5D8() {
// test_id = getTestId("T1RV1D5", "T1LV5D8", "199");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV5D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV5D9).
*
*/
public void testT1RV1D5_T1LV5D9() {
test_id = getTestId("T1RV1D5", "T1LV5D9", "200");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV5D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D1).
*
*/
public void testT1RV1D5_T1LV6D1() {
test_id = getTestId("T1RV1D5", "T1LV6D1", "201");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV6D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D2).
*
*/
public void testT1RV1D5_T1LV6D2() {
test_id = getTestId("T1RV1D5", "T1LV6D2", "202");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV6D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D3).
*
*/
public void testT1RV1D5_T1LV6D3() {
test_id = getTestId("T1RV1D5", "T1LV6D3", "203");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV6D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D4).
*
*/
public void testT1RV1D5_T1LV6D4() {
test_id = getTestId("T1RV1D5", "T1LV6D4", "204");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV6D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D5).
// *
// */
// public void testT1RV1D5_T1LV6D5() {
// test_id = getTestId("T1RV1D5", "T1LV6D5", "205");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV6D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D6).
// *
// */
// public void testT1RV1D5_T1LV6D6() {
// test_id = getTestId("T1RV1D5", "T1LV6D6", "206");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV6D6");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D7).
*
*/
public void testT1RV1D5_T1LV6D7() {
test_id = getTestId("T1RV1D5", "T1LV6D7", "207");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV6D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure3, checkResult_ParamFailure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D8).
// *
// */
// public void testT1RV1D5_T1LV6D8() {
// test_id = getTestId("T1RV1D5", "T1LV6D8", "208");
//
// String src = selectTRVD("T1RV1D5");
//
// String dest = selectTLVD("T1LV6D8");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV6D9).
*
*/
public void testT1RV1D5_T1LV6D9() {
test_id = getTestId("T1RV1D5", "T1LV6D9", "209");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV6D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV7D1).
*
*/
public void testT1RV1D5_T1LV7D1() {
test_id = getTestId("T1RV1D5", "T1LV7D1", "210");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV7D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV7D2).
*
*/
public void testT1RV1D5_T1LV7D2() {
test_id = getTestId("T1RV1D5", "T1LV7D2", "211");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV7D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV7D3).
*
*/
public void testT1RV1D5_T1LV7D3() {
test_id = getTestId("T1RV1D5", "T1LV7D3", "212");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV7D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV8D1).
*
*/
public void testT1RV1D5_T1LV8D1() {
test_id = getTestId("T1RV1D5", "T1LV8D1", "213");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV8D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV8D2).
*
*/
public void testT1RV1D5_T1LV8D2() {
test_id = getTestId("T1RV1D5", "T1LV8D2", "214");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV8D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV8D3).
*
*/
public void testT1RV1D5_T1LV8D3() {
test_id = getTestId("T1RV1D5", "T1LV8D3", "215");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV8D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV9D1).
*
*/
public void testT1RV1D5_T1LV9D1() {
test_id = getTestId("T1RV1D5", "T1LV9D1", "216");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV9D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV9D2).
*
*/
public void testT1RV1D5_T1LV9D2() {
test_id = getTestId("T1RV1D5", "T1LV9D2", "217");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV9D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row (T1LV9D3).
*
*/
public void testT1RV1D5_T1LV9D3() {
test_id = getTestId("T1RV1D5", "T1LV9D3", "218");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV9D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV10D1).
*
*/
public void testT1RV1D5_T1LV10D1() {
test_id = getTestId("T1RV1D5", "T1LV10D1", "219");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV10D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV10D2).
*
*/
public void testT1RV1D5_T1LV10D2() {
test_id = getTestId("T1RV1D5", "T1LV10D2", "220");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV10D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV10D3).
*
*/
public void testT1RV1D5_T1LV10D3() {
test_id = getTestId("T1RV1D5", "T1LV10D3", "221");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV10D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV11D1).
*
*/
public void testT1RV1D5_T1LV11D1() {
test_id = getTestId("T1RV1D5", "T1LV11D1", "222");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV11D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV11D2).
*
*/
public void testT1RV1D5_T1LV11D2() {
test_id = getTestId("T1RV1D5", "T1LV11D2", "223");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV11D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV11D3).
*
*/
public void testT1RV1D5_T1LV11D3() {
test_id = getTestId("T1RV1D5", "T1LV11D3", "224");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV11D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ReturnFailure2,
checkResult_ReturnFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV12D1).
*
*/
public void testT1RV1D5_T1LV12D1() {
test_id = getTestId("T1RV1D5", "T1LV12D1", "225");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV12D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV12D2).
*
*/
public void testT1RV1D5_T1LV12D2() {
test_id = getTestId("T1RV1D5", "T1LV12D2", "226");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV12D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV12D3).
*
*/
public void testT1RV1D5_T1LV12D3() {
test_id = getTestId("T1RV1D5", "T1LV12D3", "227");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV12D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV13D1).
*
*/
public void testT1RV1D5_T1LV13D1() {
test_id = getTestId("T1RV1D5", "T1LV13D1", "228");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV13D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV13D2).
*
*/
public void testT1RV1D5_T1LV13D2() {
test_id = getTestId("T1RV1D5", "T1LV13D2", "229");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV13D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV13D3).
*
*/
public void testT1RV1D5_T1LV13D3() {
test_id = getTestId("T1RV1D5", "T1LV13D3", "230");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV13D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV14D1).
*
*/
public void testT1RV1D5_T1LV14D1() {
test_id = getTestId("T1RV1D5", "T1LV14D1", "231");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV14D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV14D2).
*
*/
public void testT1RV1D5_T1LV14D2() {
test_id = getTestId("T1RV1D5", "T1LV14D2", "232");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV14D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV14D3).
*
*/
public void testT1RV1D5_T1LV14D3() {
test_id = getTestId("T1RV1D5", "T1LV14D3", "233");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV14D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV15D1).
*
*/
public void testT1RV1D5_T1LV15D1() {
test_id = getTestId("T1RV1D5", "T1LV15D1", "234");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV15D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV15D2).
*
*/
public void testT1RV1D5_T1LV15D2() {
test_id = getTestId("T1RV1D5", "T1LV15D2", "235");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV15D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D5) and row
* (T1LV15D3).
*
*/
public void testT1RV1D5_T1LV15D3() {
test_id = getTestId("T1RV1D5", "T1LV15D3", "236");
String src = selectTRVD("T1RV1D5");
String dest = selectTLVD("T1LV15D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(ParamFailure2, checkResult_ParamFailure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D1).
*
*/
public void testT1RV1D6_T1LV1D1() {
test_id = getTestId("T1RV1D6", "T1LV1D1", "237");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D2).
*
*/
public void testT1RV1D6_T1LV1D2() {
test_id = getTestId("T1RV1D6", "T1LV1D2", "238");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D3).
*
*/
public void testT1RV1D6_T1LV1D3() {
test_id = getTestId("T1RV1D6", "T1LV1D3", "239");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D4).
*
*/
public void testT1RV1D6_T1LV1D4() {
test_id = getTestId("T1RV1D6", "T1LV1D4", "240");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D5).
// *
// */
// public void testT1RV1D6_T1LV1D5() {
// test_id = getTestId("T1RV1D6", "T1LV1D5", "241");
//
// String src = selectTRVD("T1RV1D6");
//
// String dest = selectTLVD("T1LV1D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D6).
*
*/
public void testT1RV1D6_T1LV1D6() {
test_id = getTestId("T1RV1D6", "T1LV1D6", "242");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D6");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D7).
*
*/
public void testT1RV1D6_T1LV1D7() {
test_id = getTestId("T1RV1D6", "T1LV1D7", "243");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D7");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D8).
*
*/
public void testT1RV1D6_T1LV1D8() {
test_id = getTestId("T1RV1D6", "T1LV1D8", "244");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D8");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Success, checkResult_Success(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV1D9).
*
*/
public void testT1RV1D6_T1LV1D9() {
test_id = getTestId("T1RV1D6", "T1LV1D9", "245");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV1D9");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV2D1).
*
*/
public void testT1RV1D6_T1LV2D1() {
test_id = getTestId("T1RV1D6", "T1LV2D1", "246");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV2D1");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV2D2).
*
*/
public void testT1RV1D6_T1LV2D2() {
test_id = getTestId("T1RV1D6", "T1LV2D2", "247");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV2D2");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV2D3).
*
*/
public void testT1RV1D6_T1LV2D3() {
test_id = getTestId("T1RV1D6", "T1LV2D3", "248");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV2D3");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure2, checkResult_Failure2(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
/**
* Perform the test for the given matrix column (T1RV1D6) and row (T1LV2D4).
*
*/
public void testT1RV1D6_T1LV2D4() {
test_id = getTestId("T1RV1D6", "T1LV2D4", "249");
String src = selectTRVD("T1RV1D6");
String dest = selectTLVD("T1LV2D4");
String result = ".";
try {
result = TRVD_TLVD_Action(src, dest);
} catch (RecognitionException e) {
e.printStackTrace();
} catch (TokenStreamException e) {
e.printStackTrace();
}
assertTrue(Failure3, checkResult_Failure3(src, dest, result));
GraphicalEditor editor = getActiveEditor();
if (editor != null) {
validateOrGenerateResults(editor, generateResults);
}
}
// TODO FIXME: This test must pass when CQ issue
// dts0100668874 is resolved.
// /**
// * Perform the test for the given matrix column (T1RV1D6) and row (T1LV2D5).
// *
// */
// public void testT1RV1D6_T1LV2D5() {
// test_id = getTestId("T1RV1D6", "T1LV2D5", "250");
//
// String src = selectTRVD("T1RV1D6");
//
// String dest = selectTLVD("T1LV2D5");
//
// String result = ".";
// try {
// result = TRVD_TLVD_Action(src, dest);
// } catch (RecognitionException e) {
// e.printStackTrace();
// } catch (TokenStreamException e) {
// e.printStackTrace();
// }
// assertTrue(Failure5, checkResult_Failure5(src, dest, result));
//
// GraphicalEditor editor = getActiveEditor();
// if (editor != null) {
// validateOrGenerateResults(editor, generateResults);
// }
// }
}
| apache-2.0 |
52North/OpenSensorSearch | sor-common/src/main/java/org/n52/sor/client/GetMatchingDefinitionsBean.java | 3262 | /**
* Copyright 2013 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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.n52.sor.client;
import org.n52.sor.ISorRequest.SorMatchingType;
import org.n52.sor.OwsExceptionReport;
import org.n52.sor.PropertiesManager;
import org.n52.sor.util.XmlTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.x52North.sor.x031.GetMatchingDefinitionsRequestDocument;
import org.x52North.sor.x031.GetMatchingDefinitionsRequestDocument.GetMatchingDefinitionsRequest;
/**
* @author Jan Schulte, Daniel Nüst
*
*/
public class GetMatchingDefinitionsBean extends AbstractBean {
private static Logger log = LoggerFactory.getLogger(GetMatchingDefinitionsBean.class);
private String inputURI = "";
private String matchingTypeString;
private int searchDepth;
@Override
public void buildRequest() {
GetMatchingDefinitionsRequestDocument requestDoc = GetMatchingDefinitionsRequestDocument.Factory.newInstance();
GetMatchingDefinitionsRequest request = requestDoc.addNewGetMatchingDefinitionsRequest();
request.setService(PropertiesManager.getInstance().getService());
request.setVersion(PropertiesManager.getInstance().getServiceVersion());
// inputURI
if ( !this.inputURI.isEmpty()) {
request.setInputURI(this.inputURI);
}
else {
this.requestString = "Please choose an input URI!";
return;
}
// matchingType
try {
request.setMatchingType(SorMatchingType.getSorMatchingType(this.matchingTypeString).getSchemaMatchingType());
}
catch (OwsExceptionReport e) {
log.warn("Matching type NOT supported!");
this.requestString = "The matching type is not supported!\n\n" + e.getDocument();
}
// searchDepth
request.setSearchDepth(this.searchDepth);
if ( !requestDoc.validate()) {
log.warn("Request is NOT valid, service may return error!\n"
+ XmlTools.validateAndIterateErrors(requestDoc));
}
this.requestString = requestDoc.toString();
}
public String getInputURI() {
return this.inputURI;
}
public String getMatchingTypeString() {
return this.matchingTypeString;
}
public int getSearchDepth() {
return this.searchDepth;
}
public void setInputURI(String inputURI) {
this.inputURI = inputURI;
}
public void setMatchingTypeString(String matchingTypeString) {
this.matchingTypeString = matchingTypeString;
}
public void setSearchDepth(int searchDepth) {
this.searchDepth = searchDepth;
}
} | apache-2.0 |
e-ucm/a2 | routes/applications.js | 25370 | /*
* Copyright 2016 e-UCM (http://www.e-ucm.es/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* This project has received funding from the European Union’s Horizon
* 2020 research and innovation programme under grant agreement No 644187.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 (link is external)
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var express = require('express'),
authentication = require('../util/authentication'),
router = express.Router(),
async = require('async'),
applicationIdRoute = '/:applicationId',
unselectedFields = '-__v',
removeFields = ['__v'];
var Validator = require('jsonschema').Validator,
v = new Validator();
var appSchema = {
id: '/AppSchema',
type: 'object',
properties: {
_id: {type: 'string'},
name: { type: 'string'},
prefix: { type: 'string'},
host: { type: 'string'},
owner: { type: 'string'},
roles: {
type: 'array',
items: {
type: 'object',
properties: {
roles: {
anyOf: [{
type: 'array',
items: {type: 'string'}
},{
type: 'string'
}]
},
allows: {
type: 'array',
items: {$ref: '/AllowsSchema'}
}
}
}
},
autoroles: {
type: 'array',
items: {type: 'string'}
},
routes: {
type: 'array',
items: {type: 'string'}
},
anonymous: {
anyOf: [{
type: 'array',
items: {type: 'string'}
}, {
type: 'string'
}]
},
look: {
type: 'array',
items: {$ref: '/LookSchema'}
}
},
additionalProperties: false
};
var allowsSchema = {
id: '/AllowsSchema',
type: 'object',
properties: {
resources: {
type: 'array',
items: {type: 'string'}
},
permissions: {
type: 'array',
items: {type: 'string'}
}
}
};
var lookSchema = {
id: '/LookSchema',
type: 'object',
properties: {
url: { type: 'string'},
key: { type: 'string'},
methods: {
type: 'array',
items: {type: 'string'}
},
permissions: {type: 'object'}
},
additionalProperties: false
};
var putLookSchema = {
id: '/PutLookSchema',
type: 'object',
properties: {
key: {type: 'string'},
users: {
type: 'array',
items: {type: 'string'}
},
resources: {
type: 'array',
items: {type: 'string'}
},
methods: {
type: 'array',
items: {type: 'string'}
},
url: {type: 'string'}
},
additionalProperties: false
};
v.addSchema(allowsSchema, '/AllowsSchema');
v.addSchema(lookSchema, '/LookSchema');
v.addSchema(appSchema, '/AppSchema');
v.addSchema(putLookSchema, '/PutLookSchema');
/**
* @api {get} /applications Returns all the registered applications.
* @apiName GetApplications
* @apiGroup Applications
*
* @apiParam {String} [fields] The fields to be populated in the resulting objects.
* An empty string will return the complete document.
* @apiParam {String} [sort=_id] Place - before the field for a descending sort.
* @apiParam {Number} [limit=20]
* @apiParam {Number} [page=1]
*
* @apiPermission admin
*
* @apiParamExample {json} Request-Example:
* {
* "fields": "_id name prefix host anonymous timeCreated",
* "sort": "-name",
* "limit": 20,
* "page": 1
* }
*
* @apiParamExample {json} Request-Example:
* {
* "fields": "",
* "sort": "name",
* "limit": 20,
* "page": 1
* }
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": [
* {
* "_id": "559a447831b7acec185bf513",
* "name": "Gleaner App.",
* "prefix": "gleaner",
* "host": "localhost:3300",
* "owner": "root",
* "autoroles": [
* "student",
* "teacher,
* "developer"
* ],
* "timeCreated": "2015-07-06T09:03:52.636Z",
* "routes": [
* "gleaner/games",
* "gleaner/activities",
* "gleaner/classes"
* ],
* "anonymous": [
* "/collector",
* "/env"
* ],
* "look":[
* {
* "url": "route/get",
* "permissions: {
* "user1: [
* "dashboard1",
* "dashboard2"
* ],
* "user2: [
* "dashboard1",
* "dashboard3"
* ]
* }
* }
* ]
* }],
* "pages": {
* "current": 1,
* "prev": 0,
* "hasPrev": false,
* "next": 2,
* "hasNext": false,
* "total": 1
* },
* "items": {
* "limit": 20,
* "begin": 1,
* "end": 1,
* "total": 1
* }
* }
*
*/
router.get('/', authentication.authorized, function (req, res, next) {
var query = {};
var fields = req.body.fields || '';
var sort = req.body.sort || '_id';
var limit = req.body.limit || 20;
var page = req.body.page || 1;
req.app.db.model('application').pagedFind(query, fields, removeFields, sort, limit, page, function (err, results) {
if (err) {
return next(err);
}
res.json(results);
});
});
/**
* @api {post} /applications Register a new application, if an application with the same prefix already exists it will be overridden with the new values.
* @apiName PostApplications
* @apiGroup Applications
*
* @apiParam {String} prefix Application prefix.
* @apiParam {String} host Application host.
* @apiParam {String[]} [anonymous Express-like] routes for whom unidentified (anonymous) requests will be forwarded anyway.
* @apiParam {String[]} [autoroles] Roles that the application use.
* @apiParam {Object[]} [look] Allow access to routes for specific users. Key field identify specific field that the algorithm need look to
* allow the access. In the next example, the user1 can use the route POST "rout/get" to see results if the req.body
* contains the value "dashboard1" in "docs._id" field.
* "look":[{"url": "route/get",
* "permissions: { "user1: ["dashboard1"] },
* "key": "docs._id",
* "_id": "59ce615e3ef2df4d94f734fc",
* "methods": ["post"]}]
* @apiParam {String[]} [routes] All the applications routes that are not anonymous
* @apiParam {String} [owner] The (user) owner of the application
*
* @apiPermission admin
*
* @apiParamExample {json} Request-Example:
* {
* "name": "Gleaner",
* "prefix" : "gleaner",
* "host" : "localhost:3300",
* "autoroles": [
* "student",
* "teacher,
* "developer"
* ],
* "look":[
* {
* "url": "route/get",
* "permissions: {
* "user1: [
* "dashboard1",
* "dashboard2"
* ],
* "user2: [
* "dashboard1",
* "dashboard3"
* ]
* },
* "key": "docs._id",
* "_id": "59ce615e3ef2df4d94f734fc",
* "methods": [
* "post",
* "put"
* ]
* }
* ]
* "anonymous": [
* "/collector",
* "/env"
* ],
* "routes": [
* "gleaner/games",
* "gleaner/activities",
* "gleaner/classes"
* ],
* "owner": "root"
* }
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "_id": "559a447831b7acec185bf513",
* "prefix": "gleaner",
* "host": "localhost:3300",
* "anonymous": [
* "/collector",
* "/env"
* ],
* "timeCreated": "2015-07-06T09:03:52.636Z"
* }
*
* @apiError(400) PrefixRequired Prefix required!.
*
* @apiError(400) HostRequired Host required!.
*
*/
router.post('/', authentication.authorized, function (req, res, next) {
async.auto({
validate: function (done) {
var err;
if (!req.body.prefix) {
err = new Error('Prefix required!');
return done(err);
}
if (!req.body.host) {
err = new Error('Host required!');
return done(err);
}
var validationObj = v.validate(req.body, appSchema);
if (validationObj.errors && validationObj.errors.length > 0) {
err = new Error('Bad format: ' + validationObj.errors[0]);
return done(err);
}
done();
},
roles: ['validate', function (done) {
var rolesArray = req.body.roles;
var routes = [];
if (rolesArray) {
rolesArray.forEach(function (role) {
role.allows.forEach(function (allow) {
var resources = allow.resources;
for (var i = 0; i < resources.length; i++) {
resources[i] = req.body.prefix + resources[i];
if (routes.indexOf(resources[i]) === -1) {
routes.push(resources[i]);
}
}
});
});
req.app.acl.allow(rolesArray, function (err) {
if (err) {
return done(err);
}
return done(null, routes);
});
} else {
done(null, routes);
}
}],
application: ['roles', function (done, results) {
var ApplicationModel = req.app.db.model('application');
ApplicationModel.create({
name: req.body.name || '',
prefix: req.body.prefix,
host: req.body.host,
autoroles: req.body.autoroles,
look: req.body.look || [],
anonymous: req.body.anonymous || [],
routes: results.roles,
owner: req.user.username
}, done);
}]
}, function (err, results) {
if (err) {
err.status = 400;
return next(err);
}
var application = results.application;
res.json(application);
});
});
/**
* @api {get} /applications/prefix/:prefix Gets the application information.
* @apiName GetApplication
* @apiGroup Applications
*
* @apiParam {String} applicationId Application id.
*
* @apiPermission admin
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "_id": "559a447831b7acec185bf513",
* "name": "My App Name",
* "prefix": "gleaner",
* "host": "localhost:3300",
* "anonymous": [],
* "timeCreated": "2015-07-06T09:03:52.636Z"
* }
*
* @apiError(400) ApplicationNotFound No application with the given user id exists.
*
*/
router.get('/prefix/:prefix', authentication.authorized, function (req, res, next) {
req.app.db.model('application').findByPrefix(req.params.prefix).select(unselectedFields).exec(function (err, application) {
if (err) {
return next(err);
}
if (!application) {
err = new Error('No application with the given application prefix exists.');
err.status = 400;
return next(err);
}
res.json(application);
});
});
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
* @api {get} /applications/:applicationId Gets the application information.
* @apiName GetApplication
* @apiGroup Applications
*
* @apiParam {String} applicationId Application id.
*
* @apiPermission admin
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "_id": "559a447831b7acec185bf513",
* "name": "My App Name",
* "prefix": "gleaner",
* "host": "localhost:3300",
* "anonymous": [],
* "timeCreated": "2015-07-06T09:03:52.636Z"
* }
*
* @apiError(400) ApplicationNotFound No application with the given user id exists.
*
*/
router.get(applicationIdRoute, authentication.authorized, function (req, res, next) {
var applicationId = req.params.applicationId || '';
req.app.db.model('application').findById(applicationId).select(unselectedFields).exec(function (err, application) {
if (err) {
return next(err);
}
if (!application) {
err = new Error('No application with the given application id exists.');
err.status = 400;
return next(err);
}
res.json(application);
});
});
/**
* @api {put} /applications/:applicationId Changes the application values.
* @apiName PutApplication
* @apiGroup Applications
*
* @apiParam {String} applicationId ApplicationId id.
* @apiParam {String} name The new name.
* @apiParam {String} prefix Application prefix.
* @apiParam {String} host Application host.
* @apiParam {String[]} [anonymous] Express-like routes for whom unidentified (anonymous) requests will be forwarded anyway.
* The routes from this array will be added only if they're not present yet.
* @apiParam {Object[]} [look] Allow access to routes for specific users.
* @apiParam {String[]} [routes] All the applications routes that are not anonymous
*
* @apiPermission admin
*
* @apiParamExample {json} Request-Example:
* {
* "name": "Gleaner App."
* }
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "_id": "559a447831b7acec185bf513",
* "name": "Gleaner App.",
* "prefix": "gleaner",
* "host": "localhost:3300",
* "anonymous": [],
* "timeCreated": "2015-07-06T09:03:52.636Z"
* }
*
* @apiError(400) InvalidApplicationId You must provide a valid application id.
*
* @apiError(400) ApplicationNotFound No application with the given application id exists.
*
*/
router.put(applicationIdRoute, authentication.authorized, function (req, res, next) {
if (!req.params.applicationId) {
var err = new Error('You must provide a valid application id');
err.status = 400;
return next(err);
}
var validationObj = v.validate(req.body, appSchema);
if (validationObj.errors && validationObj.errors.length > 0) {
var errVal = new Error('Bad format: ' + validationObj.errors[0]);
errVal.status = 400;
return next(errVal);
}
var applicationId = req.params.applicationId || '';
var query = {
_id: applicationId,
owner: req.user.username
};
var update = {
$set: {}
};
if (req.body.name) {
update.$set.name = req.body.name;
}
if (req.body.prefix) {
update.$set.prefix = req.body.prefix;
}
if (req.body.host) {
update.$set.host = req.body.host;
}
if (isArray(req.body.look)) {
update.$addToSet = {look: {$each: req.body.look.filter(Boolean)}};
}
if (isArray(req.body.anonymous)) {
update.$addToSet = {anonymous: {$each: req.body.anonymous.filter(Boolean)}};
}
var options = {
new: true,
/*
Since Mongoose 4.0.0 we can run validators
(e.g. isURL validator for the host attribute of ApplicationSchema --> /schema/application)
when performing updates with the following option.
More info. can be found here http://mongoosejs.com/docs/validation.html
*/
runValidators: true
};
req.app.db.model('application').findOneAndUpdate(query, update, options).select(unselectedFields).exec(function (err, application) {
if (err) {
err.status = 403;
return next(err);
}
if (!application) {
err = new Error('No application with the given application id exists or ' +
'you don\'t have permission to modify the given application.');
err.status = 400;
return next(err);
}
res.json(application);
});
});
/**
* @api {delete} /applications/:applicationId Removes the application.
* @apiName DeleteApplication
* @apiGroup Applications
*
* @apiParam {String} applicationId ApplicationId id.
*
* @apiPermission admin
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "message": "Success."
* }
*
* @apiError(400) ApplicationNotFound No application with the given application id exists.
*
*/
router.delete(applicationIdRoute, authentication.authorized, function (req, res, next) {
var applicationId = req.params.applicationId || '';
var query = {
_id: applicationId,
owner: req.user.username
};
req.app.db.model('application').findOneAndRemove(query, function (err, app) {
if (err) {
return next(err);
}
if (!app) {
err = new Error('No application with the given application id exists.');
err.status = 400;
return next(err);
}
app.routes.forEach(function (route) {
req.app.acl.removeResource(route);
});
res.sendDefaultSuccessMessage();
});
});
/**
* @api {put} /applications/look/:prefix Changes the application look field.
* @apiName PutApplicationLook
* @apiGroup Applications
*
* @apiParam {String} prefix Application prefix.
* @apiParam {String} key Field name to check in the body of the request.
* @apiParam {String} user The user that have access to the URL.
* @apiParam {String[]} resources The value of the key field that can use the user in the URL route.
* @apiParam {String[]} methods URL methods allowed.
* @apiParam {String} url
*
* @apiPermission admin
*
* @apiParamExample {json} Request-Example (Single-User):
* {
* "key": "_id",
* "user": "dev",
* "resources": ["id1"],
* "methods": ["post", "put"],
* "url": "/url/*"
* }
* @apiParamExample {json} Request-Example (Multiple-User):
* {
* "key": "_id",
* "users": ["u1", "u2", "u3"],
* "resources": ["id1"],
* "methods": ["post", "put"],
* "url": "/url/*"
* }
*
* @apiSuccess(200) Success.
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "_id": "559a447831b7acec185bf513",
* "name": "Gleaner App.",
* "prefix": "gleaner",
* "host": "localhost:3300",
* "anonymous": [],
* "look":[{
* "key":"_id",
* "permissions":{
* "dev":["id1","id2"]
* },
* "methods":["post","put"],
* "url":"/url/*"
* }],
* "timeCreated": "2015-07-06T09:03:52.636Z"
* }
*
* @apiError(400) InvalidApplicationId You must provide a valid application name.
*
* @apiError(400) ApplicationNotFound No application with the given application id exists.
*
*/
router.put('/look/:prefix', authentication.authorized, function (req, res, next) {
req.app.db.model('application').findByPrefix(req.params.prefix, function (err, results) {
if (err) {
return next(err);
}
var validationObj = v.validate(req.body, putLookSchema);
if (validationObj.errors && validationObj.errors.length > 0) {
var errVal = new Error('Bad format: ' + validationObj.errors[0]);
errVal.status = 400;
return next(errVal);
}
var users = [];
if (req.body.user) {
users.push(req.body.user);
}
if (req.body.users) {
users = users.concat(req.body.users);
}
var applicationId = results._id;
var query = {
_id: applicationId
};
var existKey = false;
var addNewUser = [];
var updateUser = [];
var error;
if (results.look) {
results.look.forEach(function (lookObj) {
if (lookObj.url === req.body.url) {
if (lookObj.key === req.body.key) {
if (lookObj.permissions) {
users.forEach(function(user) {
if (!lookObj.permissions[user]) {
addNewUser.push(user);
}else {
updateUser.push(user);
}
});
}
existKey = true;
} else {
error = new Error('URL registered but with a different key!');
error.status = 400;
}
}
});
}
if (error) {
return next(error);
}
var update = {};
if (!existKey) {
var objToAdd = {
key: req.body.key,
permissions: {},
methods: req.body.methods,
url: req.body.url
};
users.forEach(function(user) {
objToAdd.permissions[user] = req.body.resources;
});
update = {
$push: {
}
};
update.$push.look = objToAdd;
} else {
query['look.url'] = req.body.url;
if (updateUser.length !== 0) {
update.$addToSet = {};
updateUser.forEach(function(user) {
var resultField = 'look.$.permissions.' + user;
update.$addToSet[resultField] = { $each: req.body.resources };
});
}
if (addNewUser.length !== 0) {
update.$set = {};
addNewUser.forEach(function(user) {
var updateProp = 'look.$.permissions.' + user;
update.$set[updateProp] = req.body.resources;
});
}
}
var options = {
new: true,
/*
Since Mongoose 4.0.0 we can run validators
(e.g. isURL validator for the host attribute of ApplicationSchema --> /schema/application)
when performing updates with the following option.
More info. can be found here http://mongoosejs.com/docs/validation.html
*/
runValidators: true
};
req.app.db.model('application').findOneAndUpdate(query, update, options).select(unselectedFields).exec(function (err, application) {
if (err) {
err.status = 403;
return next(err);
}
if (!application) {
err = new Error('No application with the given application id exists or ' +
'you don\'t have permission to modify the given application.');
err.status = 400;
return next(err);
}
res.json(application.look);
});
});
});
module.exports = router; | apache-2.0 |
codestergit/swift | lib/IRGen/IRGenSIL.cpp | 187807 | //===--- IRGenSIL.cpp - Swift Per-Function IR Generation ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements basic setup and teardown for the class which
// performs IR generation for function bodies.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "irgensil"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Support/Debug.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/STLExtras.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/Types.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/InstructionUtils.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "CallEmission.h"
#include "Explosion.h"
#include "GenArchetype.h"
#include "GenBuiltin.h"
#include "GenCall.h"
#include "GenCast.h"
#include "GenClass.h"
#include "GenConstant.h"
#include "GenEnum.h"
#include "GenExistential.h"
#include "GenFunc.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenObjC.h"
#include "GenOpaque.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenStruct.h"
#include "GenTuple.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenModule.h"
#include "NativeConventionSchema.h"
#include "ReferenceTypeInfo.h"
#include "WeakTypeInfo.h"
using namespace swift;
using namespace irgen;
namespace {
class LoweredValue;
/// Represents a statically-known function as a SIL thin function value.
class StaticFunction {
/// The function reference.
llvm::Function *Function;
ForeignFunctionInfo ForeignInfo;
/// The function's native representation.
SILFunctionTypeRepresentation Rep;
public:
StaticFunction(llvm::Function *function, ForeignFunctionInfo foreignInfo,
SILFunctionTypeRepresentation rep)
: Function(function), ForeignInfo(foreignInfo), Rep(rep)
{}
llvm::Function *getFunction() const { return Function; }
SILFunctionTypeRepresentation getRepresentation() const { return Rep; }
const ForeignFunctionInfo &getForeignInfo() const { return ForeignInfo; }
llvm::Value *getExplosionValue(IRGenFunction &IGF) const;
};
/// Represents a SIL value lowered to IR, in one of these forms:
/// - an Address, corresponding to a SIL address value;
/// - an Explosion of (unmanaged) Values, corresponding to a SIL "register"; or
/// - a CallEmission for a partially-applied curried function or method.
class LoweredValue {
public:
enum class Kind {
/// The first two LoweredValue kinds correspond to a SIL address value.
///
/// The LoweredValue of an existential alloc_stack keeps an owning container
/// in addition to the address of the allocated buffer.
/// Depending on the allocated type, the container may be equal to the
/// buffer itself (for types with known sizes) or it may be the address
/// of a fixed-size container which points to the heap-allocated buffer.
/// In this case the address-part may be null, which means that the buffer
/// is not allocated yet.
ContainedAddress,
/// The LoweredValue of a resilient, generic, or loadable typed alloc_stack
/// keeps an optional stackrestore point in addition to the address of the
/// allocated buffer. For all other address values the stackrestore point is
/// just null.
/// If the stackrestore point is set (currently, this might happen for
/// opaque types: generic and resilient) the deallocation of the stack must
/// reset the stack pointer to this point.
Address,
/// The following kinds correspond to SIL non-address values.
Value_First,
/// A normal value, represented as an exploded array of llvm Values.
Explosion = Value_First,
/// A @box together with the address of the box value.
BoxWithAddress,
/// A value that represents a statically-known function symbol that
/// can be called directly, represented as a StaticFunction.
StaticFunction,
/// A value that represents an Objective-C method that must be called with
/// a form of objc_msgSend.
ObjCMethod,
Value_Last = ObjCMethod,
};
Kind kind;
private:
using ExplosionVector = SmallVector<llvm::Value *, 4>;
union {
ContainedAddress containedAddress;
StackAddress address;
OwnedAddress boxWithAddress;
struct {
ExplosionVector values;
} explosion;
StaticFunction staticFunction;
ObjCMethod objcMethod;
};
public:
/// Create an address value without a stack restore point.
LoweredValue(const Address &address)
: kind(Kind::Address), address(address)
{}
/// Create an address value with an optional stack restore point.
LoweredValue(const StackAddress &address)
: kind(Kind::Address), address(address)
{}
enum ContainerForUnallocatedAddress_t { ContainerForUnallocatedAddress };
/// Create an address value for an alloc_stack, consisting of a container and
/// a not yet allocated buffer.
LoweredValue(const Address &container, ContainerForUnallocatedAddress_t)
: kind(Kind::ContainedAddress), containedAddress(container, Address())
{}
/// Create an address value for an alloc_stack, consisting of a container and
/// the address of the allocated buffer.
LoweredValue(const ContainedAddress &address)
: kind(Kind::ContainedAddress), containedAddress(address)
{}
LoweredValue(StaticFunction &&staticFunction)
: kind(Kind::StaticFunction), staticFunction(std::move(staticFunction))
{}
LoweredValue(ObjCMethod &&objcMethod)
: kind(Kind::ObjCMethod), objcMethod(std::move(objcMethod))
{}
LoweredValue(Explosion &e)
: kind(Kind::Explosion), explosion{{}} {
auto Elts = e.claimAll();
explosion.values.append(Elts.begin(), Elts.end());
}
LoweredValue(const OwnedAddress &boxWithAddress)
: kind(Kind::BoxWithAddress), boxWithAddress(boxWithAddress)
{}
LoweredValue(LoweredValue &&lv)
: kind(lv.kind)
{
switch (kind) {
case Kind::ContainedAddress:
::new (&containedAddress) ContainedAddress(std::move(lv.containedAddress));
break;
case Kind::Address:
::new (&address) StackAddress(std::move(lv.address));
break;
case Kind::Explosion:
::new (&explosion.values) ExplosionVector(std::move(lv.explosion.values));
break;
case Kind::BoxWithAddress:
::new (&boxWithAddress) OwnedAddress(std::move(lv.boxWithAddress));
break;
case Kind::StaticFunction:
::new (&staticFunction) StaticFunction(std::move(lv.staticFunction));
break;
case Kind::ObjCMethod:
::new (&objcMethod) ObjCMethod(std::move(lv.objcMethod));
break;
}
}
LoweredValue &operator=(LoweredValue &&lv) {
assert(this != &lv);
this->~LoweredValue();
::new (this) LoweredValue(std::move(lv));
return *this;
}
bool isAddress() const {
return kind == Kind::Address && address.getAddress().isValid();
}
bool isUnallocatedAddressInBuffer() const {
return kind == Kind::ContainedAddress &&
!containedAddress.getAddress().isValid();
}
bool isValue() const {
return kind >= Kind::Value_First && kind <= Kind::Value_Last;
}
bool isBoxWithAddress() const {
return kind == Kind::BoxWithAddress;
}
Address getAddress() const {
assert(isAddress() && "not an allocated address");
return address.getAddress();
}
StackAddress getStackAddress() const {
assert(isAddress() && "not an allocated address");
return address;
}
Address getContainerOfAddress() const {
assert(kind == Kind::ContainedAddress);
assert(containedAddress.getContainer().isValid() && "address has no container");
return containedAddress.getContainer();
}
Address getAddressInContainer() const {
assert(kind == Kind::ContainedAddress);
assert(containedAddress.getContainer().isValid() &&
"address has no container");
return containedAddress.getAddress();
}
void getExplosion(IRGenFunction &IGF, Explosion &ex) const;
Explosion getExplosion(IRGenFunction &IGF) const {
Explosion e;
getExplosion(IGF, e);
return e;
}
Address getAddressOfBox() const {
assert(kind == Kind::BoxWithAddress);
return boxWithAddress.getAddress();
}
llvm::Value *getSingletonExplosion(IRGenFunction &IGF) const;
const StaticFunction &getStaticFunction() const {
assert(kind == Kind::StaticFunction && "not a static function");
return staticFunction;
}
const ObjCMethod &getObjCMethod() const {
assert(kind == Kind::ObjCMethod && "not an objc method");
return objcMethod;
}
~LoweredValue() {
switch (kind) {
case Kind::Address:
address.~StackAddress();
break;
case Kind::ContainedAddress:
containedAddress.~ContainedAddress();
break;
case Kind::Explosion:
explosion.values.~ExplosionVector();
break;
case Kind::BoxWithAddress:
boxWithAddress.~OwnedAddress();
break;
case Kind::StaticFunction:
staticFunction.~StaticFunction();
break;
case Kind::ObjCMethod:
objcMethod.~ObjCMethod();
break;
}
}
};
using PHINodeVector = llvm::TinyPtrVector<llvm::PHINode*>;
/// Represents a lowered SIL basic block. This keeps track
/// of SIL branch arguments so that they can be lowered to LLVM phi nodes.
struct LoweredBB {
llvm::BasicBlock *bb;
PHINodeVector phis;
LoweredBB() = default;
explicit LoweredBB(llvm::BasicBlock *bb, PHINodeVector &&phis)
: bb(bb), phis(std::move(phis))
{}
};
/// Visits a SIL Function and generates LLVM IR.
class IRGenSILFunction :
public IRGenFunction, public SILInstructionVisitor<IRGenSILFunction>
{
public:
llvm::DenseMap<SILValue, LoweredValue> LoweredValues;
llvm::DenseMap<SILType, LoweredValue> LoweredUndefs;
/// All alloc_ref instructions which allocate the object on the stack.
llvm::SmallPtrSet<SILInstruction *, 8> StackAllocs;
/// With closure captures it is actually possible to have two function
/// arguments that both have the same name. Until this is fixed, we need to
/// also hash the ArgNo here.
typedef std::pair<unsigned, std::pair<const SILDebugScope *, StringRef>>
StackSlotKey;
/// Keeps track of the mapping of source variables to -O0 shadow copy allocas.
llvm::SmallDenseMap<StackSlotKey, Address, 8> ShadowStackSlots;
llvm::SmallDenseMap<Decl *, SmallString<4>, 8> AnonymousVariables;
/// To avoid inserting elements into ValueDomPoints twice.
llvm::SmallDenseSet<llvm::Instruction *, 8> ValueVariables;
/// Holds the DominancePoint of values that are storage for a source variable.
SmallVector<std::pair<llvm::Instruction *, DominancePoint>, 8> ValueDomPoints;
unsigned NumAnonVars = 0;
unsigned NumCondFails = 0;
/// Accumulative amount of allocated bytes on the stack. Used to limit the
/// size for stack promoted objects.
/// We calculate it on demand, so that we don't have to do it if the
/// function does not have any stack promoted allocations.
int EstimatedStackSize = -1;
llvm::MapVector<SILBasicBlock *, LoweredBB> LoweredBBs;
// Destination basic blocks for condfail traps.
llvm::SmallVector<llvm::BasicBlock *, 8> FailBBs;
SILFunction *CurSILFn;
Address IndirectReturn;
// A cached dominance analysis.
std::unique_ptr<DominanceInfo> Dominance;
IRGenSILFunction(IRGenModule &IGM, SILFunction *f);
~IRGenSILFunction();
/// Generate IR for the SIL Function.
void emitSILFunction();
/// Calculates EstimatedStackSize.
void estimateStackSize();
void setLoweredValue(SILValue v, LoweredValue &&lv) {
auto inserted = LoweredValues.insert({v, std::move(lv)});
assert(inserted.second && "already had lowered value for sil value?!");
(void)inserted;
}
/// Create a new Address corresponding to the given SIL address value.
void setLoweredAddress(SILValue v, const Address &address) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v, address);
}
void setLoweredStackAddress(SILValue v, const StackAddress &address) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v, address);
}
void setContainerOfUnallocatedAddress(SILValue v,
const Address &buffer) {
assert(v->getType().isAddress() && "address for non-address value?!");
setLoweredValue(v,
LoweredValue(buffer, LoweredValue::ContainerForUnallocatedAddress));
}
void overwriteAllocatedAddress(SILValue v, const Address &address) {
assert(v->getType().isAddress() && "address for non-address value?!");
auto it = LoweredValues.find(v);
assert(it != LoweredValues.end() && "no existing entry for overwrite?");
assert(it->second.isUnallocatedAddressInBuffer() &&
"not an unallocated address");
it->second = ContainedAddress(it->second.getContainerOfAddress(), address);
}
void setAllocatedAddressForBuffer(SILValue v, const Address &allocedAddress);
/// Create a new Explosion corresponding to the given SIL value.
void setLoweredExplosion(SILValue v, Explosion &e) {
assert(v->getType().isObject() && "explosion for address value?!");
setLoweredValue(v, LoweredValue(e));
}
void setLoweredBox(SILValue v, const OwnedAddress &box) {
assert(v->getType().isObject() && "box for address value?!");
setLoweredValue(v, LoweredValue(box));
}
/// Create a new StaticFunction corresponding to the given SIL value.
void setLoweredStaticFunction(SILValue v,
llvm::Function *f,
SILFunctionTypeRepresentation rep,
ForeignFunctionInfo foreignInfo) {
assert(v->getType().isObject() && "function for address value?!");
assert(v->getType().is<SILFunctionType>() &&
"function for non-function value?!");
setLoweredValue(v, StaticFunction{f, foreignInfo, rep});
}
/// Create a new Objective-C method corresponding to the given SIL value.
void setLoweredObjCMethod(SILValue v, SILDeclRef method) {
assert(v->getType().isObject() && "function for address value?!");
assert(v->getType().is<SILFunctionType>() &&
"function for non-function value?!");
setLoweredValue(v, ObjCMethod{method, SILType(), false});
}
/// Create a new Objective-C method corresponding to the given SIL value that
/// starts its search from the given search type.
///
/// Unlike \c setLoweredObjCMethod, which finds the method in the actual
/// runtime type of the object, this routine starts at the static type of the
/// object and searches up the class hierarchy (toward superclasses).
///
/// \param searchType The class from which the Objective-C runtime will start
/// its search for a method.
///
/// \param startAtSuper Whether we want to start at the superclass of the
/// static type (vs. the static type itself).
void setLoweredObjCMethodBounded(SILValue v, SILDeclRef method,
SILType searchType, bool startAtSuper) {
assert(v->getType().isObject() && "function for address value?!");
assert(v->getType().is<SILFunctionType>() &&
"function for non-function value?!");
setLoweredValue(v, ObjCMethod{method, searchType, startAtSuper});
}
LoweredValue &getUndefLoweredValue(SILType t) {
auto found = LoweredUndefs.find(t);
if (found != LoweredUndefs.end())
return found->second;
auto &ti = getTypeInfo(t);
switch (t.getCategory()) {
case SILValueCategory::Address: {
Address undefAddr = ti.getAddressForPointer(
llvm::UndefValue::get(ti.getStorageType()->getPointerTo()));
LoweredUndefs.insert({t, LoweredValue(undefAddr)});
break;
}
case SILValueCategory::Object: {
auto schema = ti.getSchema();
Explosion e;
for (auto &elt : schema) {
assert(!elt.isAggregate()
&& "non-scalar element in loadable type schema?!");
e.add(llvm::UndefValue::get(elt.getScalarType()));
}
LoweredUndefs.insert({t, LoweredValue(e)});
break;
}
}
found = LoweredUndefs.find(t);
assert(found != LoweredUndefs.end());
return found->second;
}
/// Get the LoweredValue corresponding to the given SIL value, which must
/// have been lowered.
LoweredValue &getLoweredValue(SILValue v) {
if (isa<SILUndef>(v))
return getUndefLoweredValue(v->getType());
auto foundValue = LoweredValues.find(v);
assert(foundValue != LoweredValues.end() &&
"no lowered explosion for sil value!");
return foundValue->second;
}
/// Get the Address of a SIL value of address type, which must have been
/// lowered.
Address getLoweredAddress(SILValue v) {
if (getLoweredValue(v).kind == LoweredValue::Kind::Address)
return getLoweredValue(v).getAddress();
else
return getLoweredValue(v).getAddressInContainer();
}
StackAddress getLoweredStackAddress(SILValue v) {
return getLoweredValue(v).getStackAddress();
}
/// Add the unmanaged LLVM values lowered from a SIL value to an explosion.
void getLoweredExplosion(SILValue v, Explosion &e) {
getLoweredValue(v).getExplosion(*this, e);
}
/// Create an Explosion containing the unmanaged LLVM values lowered from a
/// SIL value.
Explosion getLoweredExplosion(SILValue v) {
return getLoweredValue(v).getExplosion(*this);
}
/// Return the single member of the lowered explosion for the
/// given SIL value.
llvm::Value *getLoweredSingletonExplosion(SILValue v) {
return getLoweredValue(v).getSingletonExplosion(*this);
}
LoweredBB &getLoweredBB(SILBasicBlock *bb) {
auto foundBB = LoweredBBs.find(bb);
assert(foundBB != LoweredBBs.end() && "no llvm bb for sil bb?!");
return foundBB->second;
}
StringRef getOrCreateAnonymousVarName(VarDecl *Decl) {
llvm::SmallString<4> &Name = AnonymousVariables[Decl];
if (Name.empty()) {
{
llvm::raw_svector_ostream S(Name);
S << '_' << NumAnonVars++;
}
AnonymousVariables.insert({Decl, Name});
}
return Name;
}
template <class DebugVarCarryingInst>
StringRef getVarName(DebugVarCarryingInst *i) {
StringRef Name = i->getVarInfo().Name;
// The $match variables generated by the type checker are not
// guaranteed to be unique within their scope, but they have
// unique VarDecls.
if ((Name.empty() || Name == "$match") && i->getDecl())
return getOrCreateAnonymousVarName(i->getDecl());
return Name;
}
/// At -Onone, forcibly keep all LLVM values that are tracked by
/// debug variables alive by inserting an empty inline assembler
/// expression depending on the value in the blocks dominated by the
/// value.
void emitDebugVariableRangeExtension(const SILBasicBlock *CurBB) {
if (IGM.IRGen.Opts.Optimize)
return;
for (auto &Variable : ValueDomPoints) {
auto VarDominancePoint = Variable.second;
llvm::Value *Storage = Variable.first;
if (getActiveDominancePoint() == VarDominancePoint ||
isActiveDominancePointDominatedBy(VarDominancePoint)) {
llvm::Type *ArgTys;
auto *Ty = Storage->getType();
// Vectors, Pointers and Floats are expected to fit into a register.
if (Ty->isPointerTy() || Ty->isFloatingPointTy() || Ty->isVectorTy())
ArgTys = { Ty };
else {
// If this is not a scalar or vector type, we can't handle it.
if (isa<llvm::CompositeType>(Ty))
continue;
// The storage is guaranteed to be no larger than the register width.
// Extend the storage so it would fit into a register.
llvm::Type *IntTy;
switch (IGM.getClangASTContext().getTargetInfo().getRegisterWidth()) {
case 64: IntTy = IGM.Int64Ty; break;
case 32: IntTy = IGM.Int32Ty; break;
default: llvm_unreachable("unsupported register width");
}
ArgTys = { IntTy };
Storage = Builder.CreateZExtOrBitCast(Storage, IntTy);
}
// Emit an empty inline assembler expression depending on the register.
auto *AsmFnTy = llvm::FunctionType::get(IGM.VoidTy, ArgTys, false);
auto *InlineAsm = llvm::InlineAsm::get(AsmFnTy, "", "r", true);
Builder.CreateCall(InlineAsm, Storage);
// Propagate the dbg.value intrinsics into the later basic blocks. Note
// that this shouldn't be necessary. LiveDebugValues should be doing
// this but can't in general because it currently only tracks register
// locations.
llvm::Instruction *Value = Variable.first;
auto It = llvm::BasicBlock::iterator(Value);
auto *BB = Value->getParent();
auto *CurBB = Builder.GetInsertBlock();
if (BB != CurBB)
for (auto I = std::next(It), E = BB->end(); I != E; ++I) {
auto *DVI = dyn_cast<llvm::DbgValueInst>(I);
if (DVI && DVI->getValue() == Value)
IGM.DebugInfo->getBuilder().insertDbgValueIntrinsic(
DVI->getValue(), 0, DVI->getVariable(), DVI->getExpression(),
DVI->getDebugLoc(), &*CurBB->getFirstInsertionPt());
else
// Found all dbg.value intrinsics describing this location.
break;
}
}
}
}
/// Account for bugs in LLVM.
///
/// - The LLVM type legalizer currently doesn't update debug
/// intrinsics when a large value is split up into smaller
/// pieces. Note that this heuristic as a bit too conservative
/// on 32-bit targets as it will also fire for doubles.
///
/// - CodeGen Prepare may drop dbg.values pointing to PHI instruction.
bool needsShadowCopy(llvm::Value *Storage) {
return (IGM.DataLayout.getTypeSizeInBits(Storage->getType()) >
IGM.getClangASTContext().getTargetInfo().getRegisterWidth()) ||
isa<llvm::PHINode>(Storage);
}
/// At -Onone, emit a shadow copy of an Address in an alloca, so the
/// register allocator doesn't elide the dbg.value intrinsic when
/// register pressure is high. There is a trade-off to this: With
/// shadow copies, we lose the precise lifetime.
llvm::Value *emitShadowCopy(llvm::Value *Storage,
const SILDebugScope *Scope,
StringRef Name, unsigned ArgNo,
Alignment Align = Alignment(0)) {
auto Ty = Storage->getType();
// Never emit shadow copies when optimizing, or if already on the stack.
if (IGM.IRGen.Opts.Optimize ||
isa<llvm::AllocaInst>(Storage) ||
isa<llvm::UndefValue>(Storage) ||
Ty == IGM.RefCountedPtrTy) // No debug info is emitted for refcounts.
return Storage;
// Always emit shadow copies for function arguments.
if (ArgNo == 0)
// Otherwise only if debug value range extension is not feasible.
if (!needsShadowCopy(Storage)) {
// Mark for debug value range extension unless this is a constant.
if (auto *Value = dyn_cast<llvm::Instruction>(Storage))
if (ValueVariables.insert(Value).second)
ValueDomPoints.push_back({Value, getActiveDominancePoint()});
return Storage;
}
if (Align.isZero())
Align = IGM.getPointerAlignment();
auto &Alloca = ShadowStackSlots[{ArgNo, {Scope, Name}}];
if (!Alloca.isValid())
Alloca = createAlloca(Ty, Align, Name+".addr");
ArtificialLocation AutoRestore(getDebugScope(), IGM.DebugInfo, Builder);
Builder.CreateStore(Storage, Alloca.getAddress(), Align);
return Alloca.getAddress();
}
llvm::Value *emitShadowCopy(Address Storage, const SILDebugScope *Scope,
StringRef Name, unsigned ArgNo) {
return emitShadowCopy(Storage.getAddress(), Scope, Name, ArgNo,
Storage.getAlignment());
}
void emitShadowCopy(ArrayRef<llvm::Value *> vals, const SILDebugScope *Scope,
StringRef Name, unsigned ArgNo,
llvm::SmallVectorImpl<llvm::Value *> ©) {
// Only do this at -O0.
if (IGM.IRGen.Opts.Optimize) {
copy.append(vals.begin(), vals.end());
return;
}
// Single or empty values.
if (vals.size() <= 1) {
for (auto val : vals)
copy.push_back(emitShadowCopy(val, Scope, Name, ArgNo));
return;
}
// Create a single aggregate alloca for explosions.
// TODO: why are we doing this instead of using the TypeInfo?
llvm::StructType *aggregateType = [&] {
SmallVector<llvm::Type *, 8> eltTypes;
for (auto val : vals)
eltTypes.push_back(val->getType());
return llvm::StructType::get(IGM.LLVMContext, eltTypes);
}();
auto layout = IGM.DataLayout.getStructLayout(aggregateType);
Alignment align(layout->getAlignment());
auto alloca = createAlloca(aggregateType, align, Name + ".debug");
ArtificialLocation AutoRestore(getDebugScope(), IGM.DebugInfo, Builder);
size_t i = 0;
for (auto val : vals) {
auto addr = Builder.CreateStructGEP(alloca, i,
Size(layout->getElementOffset(i)));
Builder.CreateStore(val, addr);
i++;
}
copy.push_back(alloca.getAddress());
}
/// Determine whether a generic variable has been inlined.
static bool isInlinedGeneric(VarDecl *VarDecl, const SILDebugScope *DS) {
if (!DS->InlinedCallSite)
return false;
if (VarDecl->hasType())
return VarDecl->getType()->hasArchetype();
return VarDecl->getInterfaceType()->hasTypeParameter();
}
/// Emit debug info for a function argument or a local variable.
template <typename StorageType>
void emitDebugVariableDeclaration(StorageType Storage,
DebugTypeInfo Ty,
SILType SILTy,
const SILDebugScope *DS,
VarDecl *VarDecl,
StringRef Name,
unsigned ArgNo = 0,
IndirectionKind Indirection = DirectValue) {
// Force all archetypes referenced by the type to be bound by this point.
// TODO: just make sure that we have a path to them that the debug info
// can follow.
// FIXME: The debug info type of all inlined instances of a variable must be
// the same as the type of the abstract variable.
if (isInlinedGeneric(VarDecl, DS))
return;
auto runtimeTy = getRuntimeReifiedType(IGM,
Ty.getType()->getCanonicalType());
if (!IGM.IRGen.Opts.Optimize && runtimeTy->hasArchetype())
runtimeTy.visit([&](CanType t) {
if (auto archetype = dyn_cast<ArchetypeType>(t))
emitTypeMetadataRef(archetype);
});
assert(IGM.DebugInfo && "debug info not enabled");
if (ArgNo) {
PrologueLocation AutoRestore(IGM.DebugInfo, Builder);
IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl,
Name, ArgNo, Indirection);
} else
IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl,
Name, 0, Indirection);
}
void emitFailBB() {
if (!FailBBs.empty()) {
// Move the trap basic blocks to the end of the function.
for (auto *FailBB : FailBBs) {
auto &BlockList = CurFn->getBasicBlockList();
BlockList.splice(BlockList.end(), BlockList, FailBB);
}
}
}
//===--------------------------------------------------------------------===//
// SIL instruction lowering
//===--------------------------------------------------------------------===//
void visitSILBasicBlock(SILBasicBlock *BB);
void emitErrorResultVar(SILResultInfo ErrorInfo, DebugValueInst *DbgValue);
void emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type,
llvm::Value *addr);
void visitAllocStackInst(AllocStackInst *i);
void visitAllocRefInst(AllocRefInst *i);
void visitAllocRefDynamicInst(AllocRefDynamicInst *i);
void visitAllocBoxInst(AllocBoxInst *i);
void visitProjectBoxInst(ProjectBoxInst *i);
void visitApplyInst(ApplyInst *i);
void visitTryApplyInst(TryApplyInst *i);
void visitFullApplySite(FullApplySite i);
void visitPartialApplyInst(PartialApplyInst *i);
void visitBuiltinInst(BuiltinInst *i);
void visitFunctionRefInst(FunctionRefInst *i);
void visitAllocGlobalInst(AllocGlobalInst *i);
void visitGlobalAddrInst(GlobalAddrInst *i);
void visitIntegerLiteralInst(IntegerLiteralInst *i);
void visitFloatLiteralInst(FloatLiteralInst *i);
void visitStringLiteralInst(StringLiteralInst *i);
void visitLoadInst(LoadInst *i);
void visitStoreInst(StoreInst *i);
void visitAssignInst(AssignInst *i) {
llvm_unreachable("assign is not valid in canonical SIL");
}
void visitMarkUninitializedInst(MarkUninitializedInst *i) {
llvm_unreachable("mark_uninitialized is not valid in canonical SIL");
}
void visitMarkUninitializedBehaviorInst(MarkUninitializedBehaviorInst *i) {
llvm_unreachable("mark_uninitialized_behavior is not valid in canonical SIL");
}
void visitMarkFunctionEscapeInst(MarkFunctionEscapeInst *i) {
llvm_unreachable("mark_function_escape is not valid in canonical SIL");
}
void visitLoadBorrowInst(LoadBorrowInst *i) {
llvm_unreachable("unimplemented");
}
void visitDebugValueInst(DebugValueInst *i);
void visitDebugValueAddrInst(DebugValueAddrInst *i);
void visitLoadWeakInst(LoadWeakInst *i);
void visitStoreWeakInst(StoreWeakInst *i);
void visitRetainValueInst(RetainValueInst *i);
void visitCopyValueInst(CopyValueInst *i);
void visitCopyUnownedValueInst(CopyUnownedValueInst *i) {
llvm_unreachable("unimplemented");
}
void visitReleaseValueInst(ReleaseValueInst *i);
void visitDestroyValueInst(DestroyValueInst *i);
void visitAutoreleaseValueInst(AutoreleaseValueInst *i);
void visitSetDeallocatingInst(SetDeallocatingInst *i);
void visitStructInst(StructInst *i);
void visitTupleInst(TupleInst *i);
void visitEnumInst(EnumInst *i);
void visitInitEnumDataAddrInst(InitEnumDataAddrInst *i);
void visitSelectEnumInst(SelectEnumInst *i);
void visitSelectEnumAddrInst(SelectEnumAddrInst *i);
void visitSelectValueInst(SelectValueInst *i);
void visitUncheckedEnumDataInst(UncheckedEnumDataInst *i);
void visitUncheckedTakeEnumDataAddrInst(UncheckedTakeEnumDataAddrInst *i);
void visitInjectEnumAddrInst(InjectEnumAddrInst *i);
void visitObjCProtocolInst(ObjCProtocolInst *i);
void visitMetatypeInst(MetatypeInst *i);
void visitValueMetatypeInst(ValueMetatypeInst *i);
void visitExistentialMetatypeInst(ExistentialMetatypeInst *i);
void visitTupleExtractInst(TupleExtractInst *i);
void visitTupleElementAddrInst(TupleElementAddrInst *i);
void visitStructExtractInst(StructExtractInst *i);
void visitStructElementAddrInst(StructElementAddrInst *i);
void visitRefElementAddrInst(RefElementAddrInst *i);
void visitRefTailAddrInst(RefTailAddrInst *i);
void visitClassMethodInst(ClassMethodInst *i);
void visitSuperMethodInst(SuperMethodInst *i);
void visitWitnessMethodInst(WitnessMethodInst *i);
void visitDynamicMethodInst(DynamicMethodInst *i);
void visitAllocValueBufferInst(AllocValueBufferInst *i);
void visitProjectValueBufferInst(ProjectValueBufferInst *i);
void visitDeallocValueBufferInst(DeallocValueBufferInst *i);
void visitOpenExistentialAddrInst(OpenExistentialAddrInst *i);
void visitOpenExistentialMetatypeInst(OpenExistentialMetatypeInst *i);
void visitOpenExistentialRefInst(OpenExistentialRefInst *i);
void visitOpenExistentialOpaqueInst(OpenExistentialOpaqueInst *i);
void visitInitExistentialAddrInst(InitExistentialAddrInst *i);
void visitInitExistentialOpaqueInst(InitExistentialOpaqueInst *i);
void visitInitExistentialMetatypeInst(InitExistentialMetatypeInst *i);
void visitInitExistentialRefInst(InitExistentialRefInst *i);
void visitDeinitExistentialAddrInst(DeinitExistentialAddrInst *i);
void visitDeinitExistentialOpaqueInst(DeinitExistentialOpaqueInst *i);
void visitAllocExistentialBoxInst(AllocExistentialBoxInst *i);
void visitOpenExistentialBoxInst(OpenExistentialBoxInst *i);
void visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i);
void visitDeallocExistentialBoxInst(DeallocExistentialBoxInst *i);
void visitProjectBlockStorageInst(ProjectBlockStorageInst *i);
void visitInitBlockStorageHeaderInst(InitBlockStorageHeaderInst *i);
void visitFixLifetimeInst(FixLifetimeInst *i);
void visitEndLifetimeInst(EndLifetimeInst *i) {
llvm_unreachable("unimplemented");
}
void
visitUncheckedOwnershipConversionInst(UncheckedOwnershipConversionInst *i) {
llvm_unreachable("unimplemented");
}
void visitBeginBorrowInst(BeginBorrowInst *i) {
llvm_unreachable("unimplemented");
}
void visitEndBorrowInst(EndBorrowInst *i) {
llvm_unreachable("unimplemented");
}
void visitEndBorrowArgumentInst(EndBorrowArgumentInst *i) {
llvm_unreachable("unimplemented");
}
void visitStoreBorrowInst(StoreBorrowInst *i) {
llvm_unreachable("unimplemented");
}
void visitBeginAccessInst(BeginAccessInst *i);
void visitEndAccessInst(EndAccessInst *i);
void visitUnmanagedRetainValueInst(UnmanagedRetainValueInst *i) {
llvm_unreachable("unimplemented");
}
void visitUnmanagedReleaseValueInst(UnmanagedReleaseValueInst *i) {
llvm_unreachable("unimplemented");
}
void visitUnmanagedAutoreleaseValueInst(UnmanagedAutoreleaseValueInst *i) {
llvm_unreachable("unimplemented");
}
void visitMarkDependenceInst(MarkDependenceInst *i);
void visitCopyBlockInst(CopyBlockInst *i);
void visitStrongPinInst(StrongPinInst *i);
void visitStrongUnpinInst(StrongUnpinInst *i);
void visitStrongRetainInst(StrongRetainInst *i);
void visitStrongReleaseInst(StrongReleaseInst *i);
void visitStrongRetainUnownedInst(StrongRetainUnownedInst *i);
void visitUnownedRetainInst(UnownedRetainInst *i);
void visitUnownedReleaseInst(UnownedReleaseInst *i);
void visitLoadUnownedInst(LoadUnownedInst *i);
void visitStoreUnownedInst(StoreUnownedInst *i);
void visitIsUniqueInst(IsUniqueInst *i);
void visitIsUniqueOrPinnedInst(IsUniqueOrPinnedInst *i);
void visitDeallocStackInst(DeallocStackInst *i);
void visitDeallocBoxInst(DeallocBoxInst *i);
void visitDeallocRefInst(DeallocRefInst *i);
void visitDeallocPartialRefInst(DeallocPartialRefInst *i);
void visitCopyAddrInst(CopyAddrInst *i);
void visitDestroyAddrInst(DestroyAddrInst *i);
void visitBindMemoryInst(BindMemoryInst *i);
void visitCondFailInst(CondFailInst *i);
void visitConvertFunctionInst(ConvertFunctionInst *i);
void visitThinFunctionToPointerInst(ThinFunctionToPointerInst *i);
void visitPointerToThinFunctionInst(PointerToThinFunctionInst *i);
void visitUpcastInst(UpcastInst *i);
void visitAddressToPointerInst(AddressToPointerInst *i);
void visitPointerToAddressInst(PointerToAddressInst *i);
void visitUncheckedRefCastInst(UncheckedRefCastInst *i);
void visitUncheckedRefCastAddrInst(UncheckedRefCastAddrInst *i);
void visitUncheckedAddrCastInst(UncheckedAddrCastInst *i);
void visitUncheckedTrivialBitCastInst(UncheckedTrivialBitCastInst *i);
void visitUncheckedBitwiseCastInst(UncheckedBitwiseCastInst *i);
void visitRefToRawPointerInst(RefToRawPointerInst *i);
void visitRawPointerToRefInst(RawPointerToRefInst *i);
void visitRefToUnownedInst(RefToUnownedInst *i);
void visitUnownedToRefInst(UnownedToRefInst *i);
void visitRefToUnmanagedInst(RefToUnmanagedInst *i);
void visitUnmanagedToRefInst(UnmanagedToRefInst *i);
void visitThinToThickFunctionInst(ThinToThickFunctionInst *i);
void visitThickToObjCMetatypeInst(ThickToObjCMetatypeInst *i);
void visitObjCToThickMetatypeInst(ObjCToThickMetatypeInst *i);
void visitUnconditionalCheckedCastInst(UnconditionalCheckedCastInst *i);
void visitUnconditionalCheckedCastAddrInst(UnconditionalCheckedCastAddrInst *i);
void
visitUnconditionalCheckedCastValueInst(UnconditionalCheckedCastValueInst *i);
void visitObjCMetatypeToObjectInst(ObjCMetatypeToObjectInst *i);
void visitObjCExistentialMetatypeToObjectInst(
ObjCExistentialMetatypeToObjectInst *i);
void visitRefToBridgeObjectInst(RefToBridgeObjectInst *i);
void visitBridgeObjectToRefInst(BridgeObjectToRefInst *i);
void visitBridgeObjectToWordInst(BridgeObjectToWordInst *i);
void visitIsNonnullInst(IsNonnullInst *i);
void visitIndexAddrInst(IndexAddrInst *i);
void visitTailAddrInst(TailAddrInst *i);
void visitIndexRawPointerInst(IndexRawPointerInst *i);
void visitUnreachableInst(UnreachableInst *i);
void visitBranchInst(BranchInst *i);
void visitCondBranchInst(CondBranchInst *i);
void visitReturnInst(ReturnInst *i);
void visitThrowInst(ThrowInst *i);
void visitSwitchValueInst(SwitchValueInst *i);
void visitSwitchEnumInst(SwitchEnumInst *i);
void visitSwitchEnumAddrInst(SwitchEnumAddrInst *i);
void visitDynamicMethodBranchInst(DynamicMethodBranchInst *i);
void visitCheckedCastBranchInst(CheckedCastBranchInst *i);
void visitCheckedCastValueBranchInst(CheckedCastValueBranchInst *i);
void visitCheckedCastAddrBranchInst(CheckedCastAddrBranchInst *i);
};
} // end anonymous namespace
llvm::Value *StaticFunction::getExplosionValue(IRGenFunction &IGF) const {
return IGF.Builder.CreateBitCast(Function, IGF.IGM.Int8PtrTy);
}
void LoweredValue::getExplosion(IRGenFunction &IGF, Explosion &ex) const {
switch (kind) {
case Kind::Address:
case Kind::ContainedAddress:
llvm_unreachable("not a value");
case Kind::Explosion:
for (auto *value : explosion.values)
ex.add(value);
break;
case Kind::BoxWithAddress:
ex.add(boxWithAddress.getOwner());
break;
case Kind::StaticFunction:
ex.add(staticFunction.getExplosionValue(IGF));
break;
case Kind::ObjCMethod:
ex.add(objcMethod.getExplosionValue(IGF));
break;
}
}
llvm::Value *LoweredValue::getSingletonExplosion(IRGenFunction &IGF) const {
switch (kind) {
case Kind::Address:
case Kind::ContainedAddress:
llvm_unreachable("not a value");
case Kind::Explosion:
assert(explosion.values.size() == 1);
return explosion.values[0];
case Kind::BoxWithAddress:
return boxWithAddress.getOwner();
case Kind::StaticFunction:
return staticFunction.getExplosionValue(IGF);
case Kind::ObjCMethod:
return objcMethod.getExplosionValue(IGF);
}
llvm_unreachable("bad lowered value kind!");
}
IRGenSILFunction::IRGenSILFunction(IRGenModule &IGM,
SILFunction *f)
: IRGenFunction(IGM, IGM.getAddrOfSILFunction(f, ForDefinition),
f->getDebugScope(), f->getLocation()),
CurSILFn(f) {
// Apply sanitizer attributes to the function.
// TODO: Check if the function is ASan black listed either in the external
// file or via annotations.
if (IGM.IRGen.Opts.Sanitize == SanitizerKind::Address)
CurFn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (IGM.IRGen.Opts.Sanitize == SanitizerKind::Thread) {
if (dyn_cast_or_null<DestructorDecl>(f->getDeclContext()))
// Do not report races in deinit and anything called from it
// because TSan does not observe synchronization between retain
// count dropping to '0' and the object deinitialization.
CurFn->addFnAttr("sanitize_thread_no_checking_at_run_time");
else
CurFn->addFnAttr(llvm::Attribute::SanitizeThread);
}
}
IRGenSILFunction::~IRGenSILFunction() {
assert(Builder.hasPostTerminatorIP() && "did not terminate BB?!");
// Emit the fail BB if we have one.
if (!FailBBs.empty())
emitFailBB();
DEBUG(CurFn->print(llvm::dbgs()));
}
template<typename ValueVector>
static void emitPHINodesForType(IRGenSILFunction &IGF, SILType type,
const TypeInfo &ti, unsigned predecessors,
ValueVector &phis) {
if (type.isAddress()) {
phis.push_back(IGF.Builder.CreatePHI(ti.getStorageType()->getPointerTo(),
predecessors));
} else {
// PHIs are always emitted with maximal explosion.
ExplosionSchema schema = ti.getSchema();
for (auto &elt : schema) {
if (elt.isScalar())
phis.push_back(
IGF.Builder.CreatePHI(elt.getScalarType(), predecessors));
else
phis.push_back(
IGF.Builder.CreatePHI(elt.getAggregateType()->getPointerTo(),
predecessors));
}
}
}
static PHINodeVector
emitPHINodesForBBArgs(IRGenSILFunction &IGF,
SILBasicBlock *silBB,
llvm::BasicBlock *llBB) {
PHINodeVector phis;
unsigned predecessors = std::distance(silBB->pred_begin(), silBB->pred_end());
IGF.Builder.SetInsertPoint(llBB);
if (IGF.IGM.DebugInfo) {
// Use the location of the first instruction in the basic block
// for the φ-nodes.
if (!silBB->empty()) {
SILInstruction &I = *silBB->begin();
auto DS = I.getDebugScope();
assert(DS);
IGF.IGM.DebugInfo->setCurrentLoc(IGF.Builder, DS, I.getLoc());
}
}
for (SILArgument *arg : make_range(silBB->args_begin(), silBB->args_end())) {
size_t first = phis.size();
const TypeInfo &ti = IGF.getTypeInfo(arg->getType());
emitPHINodesForType(IGF, arg->getType(), ti, predecessors, phis);
if (arg->getType().isAddress()) {
IGF.setLoweredAddress(arg,
ti.getAddressForPointer(phis.back()));
} else {
Explosion argValue;
for (llvm::PHINode *phi :
swift::make_range(phis.begin()+first, phis.end()))
argValue.add(phi);
IGF.setLoweredExplosion(arg, argValue);
}
}
// Since we return to the entry of the function, reset the location.
if (IGF.IGM.DebugInfo)
IGF.IGM.DebugInfo->clearLoc(IGF.Builder);
return phis;
}
static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF,
LoweredBB &lbb,
unsigned &phiIndex,
Explosion &argValue);
// TODO: Handle this during SIL AddressLowering.
static ArrayRef<SILArgument*> emitEntryPointIndirectReturn(
IRGenSILFunction &IGF,
SILBasicBlock *entry,
Explosion ¶ms,
CanSILFunctionType funcTy,
llvm::function_ref<bool(SILType)> requiresIndirectResult) {
// Map an indirect return for a type SIL considers loadable but still
// requires an indirect return at the IR level.
SILFunctionConventions fnConv(funcTy, IGF.getSILModule());
SILType directResultType =
IGF.CurSILFn->mapTypeIntoContext(fnConv.getSILResultType());
if (requiresIndirectResult(directResultType)) {
auto &retTI = IGF.IGM.getTypeInfo(directResultType);
IGF.IndirectReturn = retTI.getAddressForPointer(params.claimNext());
}
auto bbargs = entry->getArguments();
// Map the indirect returns if present.
unsigned numIndirectResults = fnConv.getNumIndirectSILResults();
for (unsigned i = 0; i != numIndirectResults; ++i) {
SILArgument *ret = bbargs[i];
auto &retTI = IGF.IGM.getTypeInfo(ret->getType());
IGF.setLoweredAddress(ret, retTI.getAddressForPointer(params.claimNext()));
}
return bbargs.slice(numIndirectResults);
}
static void bindParameter(IRGenSILFunction &IGF,
SILArgument *param,
Explosion &allParamValues) {
// Pull out the parameter value and its formal type.
auto ¶mTI = IGF.getTypeInfo(param->getType());
// If the SIL parameter isn't passed indirectly, we need to map it
// to an explosion.
if (param->getType().isObject()) {
Explosion paramValues;
auto &loadableTI = cast<LoadableTypeInfo>(paramTI);
// If the explosion must be passed indirectly, load the value from the
// indirect address.
auto &nativeSchema = paramTI.nativeParameterValueSchema(IGF.IGM);
if (nativeSchema.requiresIndirect()) {
Address paramAddr
= loadableTI.getAddressForPointer(allParamValues.claimNext());
loadableTI.loadAsTake(IGF, paramAddr, paramValues);
} else {
if (!nativeSchema.empty()) {
// Otherwise, we map from the native convention to the type's explosion
// schema.
Explosion nativeParam;
allParamValues.transferInto(nativeParam, nativeSchema.size());
paramValues = nativeSchema.mapFromNative(IGF.IGM, IGF, nativeParam,
param->getType());
} else {
assert(paramTI.getSchema().empty());
}
}
IGF.setLoweredExplosion(param, paramValues);
return;
}
// Okay, the type is passed indirectly in SIL, so we need to map
// it to an address.
// FIXME: that doesn't mean we should physically pass it
// indirectly at this resilience expansion. An @in or @in_guaranteed parameter
// could be passed by value in the right resilience domain.
Address paramAddr
= paramTI.getAddressForPointer(allParamValues.claimNext());
IGF.setLoweredAddress(param, paramAddr);
}
/// Emit entry point arguments for a SILFunction with the Swift calling
/// convention.
static void emitEntryPointArgumentsNativeCC(IRGenSILFunction &IGF,
SILBasicBlock *entry,
Explosion &allParamValues) {
auto funcTy = IGF.CurSILFn->getLoweredFunctionType();
// Map the indirect return if present.
ArrayRef<SILArgument *> params = emitEntryPointIndirectReturn(
IGF, entry, allParamValues, funcTy, [&](SILType retType) -> bool {
auto &schema =
IGF.IGM.getTypeInfo(retType).nativeReturnValueSchema(IGF.IGM);
return schema.requiresIndirect();
});
// The witness method CC passes Self as a final argument.
WitnessMetadata witnessMetadata;
if (funcTy->getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod) {
collectTrailingWitnessMetadata(IGF, *IGF.CurSILFn, allParamValues,
witnessMetadata);
}
// Bind the error result by popping it off the parameter list.
if (funcTy->hasErrorResult()) {
IGF.setErrorResultSlot(allParamValues.takeLast());
}
// The 'self' argument might be in the context position, which is
// now the end of the parameter list. Bind it now.
if (funcTy->hasSelfParam() &&
isSelfContextParameter(funcTy->getSelfParameter())) {
SILArgument *selfParam = params.back();
params = params.drop_back();
Explosion selfTemp;
selfTemp.add(allParamValues.takeLast());
bindParameter(IGF, selfParam, selfTemp);
// Even if we don't have a 'self', if we have an error result, we
// should have a placeholder argument here.
} else if (funcTy->hasErrorResult() ||
funcTy->getRepresentation() == SILFunctionTypeRepresentation::Thick)
{
llvm::Value *contextPtr = allParamValues.takeLast(); (void) contextPtr;
assert(contextPtr->getType() == IGF.IGM.RefCountedPtrTy);
}
// Map the remaining SIL parameters to LLVM parameters.
for (SILArgument *param : params) {
bindParameter(IGF, param, allParamValues);
}
// Bind polymorphic arguments. This can only be done after binding
// all the value parameters.
if (hasPolymorphicParameters(funcTy)) {
emitPolymorphicParameters(IGF, *IGF.CurSILFn, allParamValues,
&witnessMetadata,
[&](unsigned paramIndex) -> llvm::Value* {
SILValue parameter =
IGF.CurSILFn->getArgumentsWithoutIndirectResults()[paramIndex];
return IGF.getLoweredSingletonExplosion(parameter);
});
}
assert(allParamValues.empty() && "didn't claim all parameters!");
}
/// Emit entry point arguments for the parameters of a C function, or the
/// method parameters of an ObjC method.
static void emitEntryPointArgumentsCOrObjC(IRGenSILFunction &IGF,
SILBasicBlock *entry,
Explosion ¶ms,
CanSILFunctionType funcTy) {
// First, lower the method type.
ForeignFunctionInfo foreignInfo = IGF.IGM.getForeignFunctionInfo(funcTy);
assert(foreignInfo.ClangInfo);
auto &FI = *foreignInfo.ClangInfo;
// Okay, start processing the parameters explosion.
// First, claim all the indirect results.
ArrayRef<SILArgument*> args
= emitEntryPointIndirectReturn(IGF, entry, params, funcTy,
[&](SILType directResultType) -> bool {
return FI.getReturnInfo().isIndirect();
});
unsigned nextArgTyIdx = 0;
// Handle the arguments of an ObjC method.
if (IGF.CurSILFn->getRepresentation() ==
SILFunctionTypeRepresentation::ObjCMethod) {
// Claim the self argument from the end of the formal arguments.
SILArgument *selfArg = args.back();
args = args.slice(0, args.size() - 1);
// Set the lowered explosion for the self argument.
auto &selfTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(selfArg->getType()));
auto selfSchema = selfTI.getSchema();
assert(selfSchema.size() == 1 && "Expected self to be a single element!");
auto *selfValue = params.claimNext();
auto *bodyType = selfSchema.begin()->getScalarType();
if (selfValue->getType() != bodyType)
selfValue = IGF.coerceValue(selfValue, bodyType, IGF.IGM.DataLayout);
Explosion self;
self.add(selfValue);
IGF.setLoweredExplosion(selfArg, self);
// Discard the implicit _cmd argument.
params.claimNext();
// We've handled the self and _cmd arguments, so when we deal with
// generating explosions for the remaining arguments we can skip
// these.
nextArgTyIdx = 2;
}
assert(args.size() == (FI.arg_size() - nextArgTyIdx) &&
"Number of arguments not equal to number of argument types!");
// Generate lowered explosions for each explicit argument.
for (auto i : indices(args)) {
SILArgument *arg = args[i];
auto argTyIdx = i + nextArgTyIdx;
auto &argTI = IGF.getTypeInfo(arg->getType());
// Bitcast indirect argument pointers to the right storage type.
if (arg->getType().isAddress()) {
llvm::Value *ptr = params.claimNext();
ptr = IGF.Builder.CreateBitCast(ptr,
argTI.getStorageType()->getPointerTo());
IGF.setLoweredAddress(arg, Address(ptr, argTI.getBestKnownAlignment()));
continue;
}
auto &loadableArgTI = cast<LoadableTypeInfo>(argTI);
Explosion argExplosion;
emitForeignParameter(IGF, params, foreignInfo, argTyIdx,
arg->getType(), loadableArgTI, argExplosion);
IGF.setLoweredExplosion(arg, argExplosion);
}
assert(params.empty() && "didn't claim all parameters!");
// emitPolymorphicParameters() may create function calls, so we need
// to initialize the debug location here.
ArtificialLocation Loc(IGF.getDebugScope(), IGF.IGM.DebugInfo, IGF.Builder);
// Bind polymorphic arguments. This can only be done after binding
// all the value parameters, and must be done even for non-polymorphic
// functions because of imported Objective-C generics.
emitPolymorphicParameters(
IGF, *IGF.CurSILFn, params, nullptr,
[&](unsigned paramIndex) -> llvm::Value * {
SILValue parameter = entry->getArguments()[paramIndex];
return IGF.getLoweredSingletonExplosion(parameter);
});
}
/// Get metadata for the dynamic Self type if we have it.
static void emitLocalSelfMetadata(IRGenSILFunction &IGF) {
if (!IGF.CurSILFn->hasSelfMetadataParam())
return;
const SILArgument *selfArg = IGF.CurSILFn->getSelfMetadataArgument();
CanMetatypeType metaTy =
dyn_cast<MetatypeType>(selfArg->getType().getSwiftRValueType());
IRGenFunction::LocalSelfKind selfKind;
if (!metaTy)
selfKind = IRGenFunction::ObjectReference;
else switch (metaTy->getRepresentation()) {
case MetatypeRepresentation::Thin:
llvm_unreachable("class metatypes are never thin");
case MetatypeRepresentation::Thick:
selfKind = IRGenFunction::SwiftMetatype;
break;
case MetatypeRepresentation::ObjC:
selfKind = IRGenFunction::ObjCMetatype;
break;
}
llvm::Value *value = IGF.getLoweredExplosion(selfArg).claimNext();
IGF.setLocalSelfMetadata(value, selfKind);
}
/// Emit the definition for the given SIL constant.
void IRGenModule::emitSILFunction(SILFunction *f) {
if (f->isExternalDeclaration())
return;
PrettyStackTraceSILFunction stackTrace("emitting IR", f);
IRGenSILFunction(*this, f).emitSILFunction();
}
void IRGenSILFunction::emitSILFunction() {
DEBUG(llvm::dbgs() << "emitting SIL function: ";
CurSILFn->printName(llvm::dbgs());
llvm::dbgs() << '\n';
CurSILFn->print(llvm::dbgs()));
assert(!CurSILFn->empty() && "function has no basic blocks?!");
// Configure the dominance resolver.
// TODO: consider re-using a dom analysis from the PassManager
// TODO: consider using a cheaper analysis at -O0
setDominanceResolver([](IRGenFunction &IGF_,
DominancePoint activePoint,
DominancePoint dominatingPoint) -> bool {
IRGenSILFunction &IGF = static_cast<IRGenSILFunction&>(IGF_);
if (!IGF.Dominance) {
IGF.Dominance.reset(new DominanceInfo(IGF.CurSILFn));
}
return IGF.Dominance->dominates(dominatingPoint.as<SILBasicBlock>(),
activePoint.as<SILBasicBlock>());
});
if (IGM.DebugInfo)
IGM.DebugInfo->emitFunction(*CurSILFn, CurFn);
// Map the entry bb.
LoweredBBs[&*CurSILFn->begin()] = LoweredBB(&*CurFn->begin(), {});
// Create LLVM basic blocks for the other bbs.
for (auto bi = std::next(CurSILFn->begin()), be = CurSILFn->end(); bi != be;
++bi) {
// FIXME: Use the SIL basic block's name.
llvm::BasicBlock *llBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
auto phis = emitPHINodesForBBArgs(*this, &*bi, llBB);
CurFn->getBasicBlockList().push_back(llBB);
LoweredBBs[&*bi] = LoweredBB(llBB, std::move(phis));
}
auto entry = LoweredBBs.begin();
Builder.SetInsertPoint(entry->second.bb);
// Map the LLVM arguments to arguments on the entry point BB.
Explosion params = collectParameters();
auto funcTy = CurSILFn->getLoweredFunctionType();
switch (funcTy->getLanguage()) {
case SILFunctionLanguage::Swift:
emitEntryPointArgumentsNativeCC(*this, entry->first, params);
break;
case SILFunctionLanguage::C:
emitEntryPointArgumentsCOrObjC(*this, entry->first, params, funcTy);
break;
}
emitLocalSelfMetadata(*this);
assert(params.empty() && "did not map all llvm params to SIL params?!");
// It's really nice to be able to assume that we've already emitted
// all the values from dominating blocks --- it makes simple
// peepholing more powerful and allows us to avoid the need for
// nasty "forward-declared" values. We can do this by emitting
// blocks using a simple walk through the successor graph.
//
// We do want to preserve the original source order, but that's done
// by having previously added all the primary blocks to the LLVM
// function in their original order. As long as any secondary
// blocks are inserted after the current IP instead of at the end
// of the function, we're fine.
// Invariant: for every block in the work queue, we have visited all
// of its dominators.
llvm::SmallPtrSet<SILBasicBlock*, 8> visitedBlocks;
SmallVector<SILBasicBlock*, 8> workQueue; // really a stack
// Queue up the entry block, for which the invariant trivially holds.
visitedBlocks.insert(&*CurSILFn->begin());
workQueue.push_back(&*CurSILFn->begin());
while (!workQueue.empty()) {
auto bb = workQueue.pop_back_val();
// Emit the block.
visitSILBasicBlock(bb);
#ifndef NDEBUG
// Assert that the current IR IP (if valid) is immediately prior
// to the initial IR block for the next primary SIL block.
// It's not semantically necessary to preserve SIL block order,
// but we really should.
if (auto curBB = Builder.GetInsertBlock()) {
auto next = std::next(SILFunction::iterator(bb));
if (next != CurSILFn->end()) {
auto nextBB = LoweredBBs[&*next].bb;
assert(&*std::next(curBB->getIterator()) == nextBB &&
"lost source SIL order?");
}
}
#endif
// The immediate dominator of a successor of this block needn't be
// this block, but it has to be something which dominates this
// block. In either case, we've visited it.
//
// Therefore the invariant holds of all the successors, and we can
// queue them up if we haven't already visited them.
for (auto *succBB : bb->getSuccessorBlocks()) {
if (visitedBlocks.insert(succBB).second)
workQueue.push_back(succBB);
}
}
// If there are dead blocks in the SIL function, we might have left
// invalid blocks in the IR. Do another pass and kill them off.
for (SILBasicBlock &bb : *CurSILFn)
if (!visitedBlocks.count(&bb))
LoweredBBs[&bb].bb->eraseFromParent();
}
void IRGenSILFunction::estimateStackSize() {
if (EstimatedStackSize >= 0)
return;
// TODO: as soon as we generate alloca instructions with accurate lifetimes
// we should also do a better stack size calculation here. Currently we
// add all stack sizes even if life ranges do not overlap.
for (SILBasicBlock &BB : *CurSILFn) {
for (SILInstruction &I : BB) {
if (auto *ASI = dyn_cast<AllocStackInst>(&I)) {
const TypeInfo &type = getTypeInfo(ASI->getElementType());
if (llvm::Constant *SizeConst = type.getStaticSize(IGM)) {
auto *SizeInt = cast<llvm::ConstantInt>(SizeConst);
EstimatedStackSize += (int)SizeInt->getSExtValue();
}
}
}
}
}
void IRGenSILFunction::visitSILBasicBlock(SILBasicBlock *BB) {
// Insert into the lowered basic block.
llvm::BasicBlock *llBB = getLoweredBB(BB).bb;
Builder.SetInsertPoint(llBB);
bool InEntryBlock = BB->pred_empty();
// Set this block as the dominance point. This implicitly communicates
// with the dominance resolver configured in emitSILFunction.
DominanceScope dominance(*this, InEntryBlock ? DominancePoint::universal()
: DominancePoint(BB));
// The basic blocks are visited in a random order. Reset the debug location.
std::unique_ptr<AutoRestoreLocation> ScopedLoc;
if (InEntryBlock)
ScopedLoc = llvm::make_unique<PrologueLocation>(IGM.DebugInfo, Builder);
else
ScopedLoc = llvm::make_unique<ArtificialLocation>(
CurSILFn->getDebugScope(), IGM.DebugInfo, Builder);
// Generate the body.
bool InCleanupBlock = false;
bool KeepCurrentLocation = false;
for (auto InsnIter = BB->begin(); InsnIter != BB->end(); ++InsnIter) {
auto &I = *InsnIter;
if (IGM.DebugInfo) {
// Set the debug info location for I, if applicable.
SILLocation ILoc = I.getLoc();
auto DS = I.getDebugScope();
// Handle cleanup locations.
if (ILoc.is<CleanupLocation>()) {
// Cleanup locations point to the decl of the value that is
// being destroyed (for diagnostic generation). As far as
// the linetable is concerned, cleanups at the end of a
// lexical scope should point to the cleanup location, which
// is the location of the last instruction in the basic block.
if (!InCleanupBlock) {
InCleanupBlock = true;
// Scan ahead to see if this is the final cleanup block in
// this basic block.
auto It = InsnIter;
do ++It; while (It != BB->end() &&
It->getLoc().is<CleanupLocation>());
// We are still in the middle of a basic block?
if (It != BB->end() && !isa<TermInst>(It))
KeepCurrentLocation = true;
}
// Assign the cleanup location to this instruction.
if (!KeepCurrentLocation) {
assert(BB->getTerminator());
ILoc = BB->getTerminator()->getLoc();
DS = BB->getTerminator()->getDebugScope();
}
} else if (InCleanupBlock) {
KeepCurrentLocation = false;
InCleanupBlock = false;
}
// Until SILDebugScopes are properly serialized, bare functions
// are allowed to not have a scope.
if (!DS) {
if (CurSILFn->isBare())
DS = CurSILFn->getDebugScope();
assert(maybeScopeless(I) && "instruction has location, but no scope");
}
// Set the builder's debug location.
if (DS && !KeepCurrentLocation)
IGM.DebugInfo->setCurrentLoc(Builder, DS, ILoc);
else
// Use an artificial (line 0) location.
IGM.DebugInfo->setCurrentLoc(Builder, DS);
if (isa<TermInst>(&I))
emitDebugVariableRangeExtension(BB);
}
visit(&I);
}
assert(Builder.hasPostTerminatorIP() && "SIL bb did not terminate block?!");
}
void IRGenSILFunction::visitFunctionRefInst(FunctionRefInst *i) {
auto fn = i->getReferencedFunction();
llvm::Function *fnptr = IGM.getAddrOfSILFunction(fn, NotForDefinition);
auto foreignInfo = IGM.getForeignFunctionInfo(fn->getLoweredFunctionType());
// Store the function constant and calling
// convention as a StaticFunction so we can avoid bitcasting or thunking if
// we don't need to.
setLoweredStaticFunction(i, fnptr, fn->getRepresentation(), foreignInfo);
}
void IRGenSILFunction::visitAllocGlobalInst(AllocGlobalInst *i) {
SILGlobalVariable *var = i->getReferencedGlobal();
SILType loweredTy = var->getLoweredType();
auto &ti = getTypeInfo(loweredTy);
auto expansion = IGM.getResilienceExpansionForLayout(var);
// If the global is fixed-size in all resilience domains that can see it,
// we allocated storage for it statically, and there's nothing to do.
if (ti.isFixedSize(expansion))
return;
// Otherwise, the static storage for the global consists of a fixed-size
// buffer.
Address addr = IGM.getAddrOfSILGlobalVariable(var, ti,
NotForDefinition);
if (getSILModule().getOptions().UseCOWExistentials) {
emitAllocateValueInBuffer(*this, loweredTy, addr);
} else {
(void) ti.allocateBuffer(*this, addr, loweredTy);
}
}
void IRGenSILFunction::visitGlobalAddrInst(GlobalAddrInst *i) {
SILGlobalVariable *var = i->getReferencedGlobal();
SILType loweredTy = var->getLoweredType();
assert(loweredTy == i->getType().getObjectType());
auto &ti = getTypeInfo(loweredTy);
auto expansion = IGM.getResilienceExpansionForLayout(var);
// If the variable is empty in all resilience domains that can see it,
// don't actually emit a symbol for the global at all, just return undef.
if (ti.isKnownEmpty(expansion)) {
setLoweredAddress(i, ti.getUndefAddress());
return;
}
Address addr = IGM.getAddrOfSILGlobalVariable(var, ti,
NotForDefinition);
// If the global is fixed-size in all resilience domains that can see it,
// we allocated storage for it statically, and there's nothing to do.
if (ti.isFixedSize(expansion)) {
setLoweredAddress(i, addr);
return;
}
// Otherwise, the static storage for the global consists of a fixed-size
// buffer; project it.
if (getSILModule().getOptions().UseCOWExistentials) {
addr = emitProjectValueInBuffer(*this, loweredTy, addr);
} else {
addr = ti.projectBuffer(*this, addr, loweredTy);
}
setLoweredAddress(i, addr);
}
void IRGenSILFunction::visitMetatypeInst(swift::MetatypeInst *i) {
auto metaTy = i->getType().castTo<MetatypeType>();
Explosion e;
emitMetatypeRef(*this, metaTy, e);
setLoweredExplosion(i, e);
}
static llvm::Value *getClassBaseValue(IRGenSILFunction &IGF,
SILValue v) {
if (v->getType().isAddress()) {
auto addr = IGF.getLoweredAddress(v);
return IGF.Builder.CreateLoad(addr);
}
Explosion e = IGF.getLoweredExplosion(v);
return e.claimNext();
}
static llvm::Value *getClassMetatype(IRGenFunction &IGF,
llvm::Value *baseValue,
MetatypeRepresentation repr,
SILType instanceType) {
switch (repr) {
case MetatypeRepresentation::Thin:
llvm_unreachable("Class metatypes are never thin");
case MetatypeRepresentation::Thick:
return emitDynamicTypeOfHeapObject(IGF, baseValue, instanceType);
case MetatypeRepresentation::ObjC:
return emitHeapMetadataRefForHeapObject(IGF, baseValue, instanceType);
}
llvm_unreachable("Not a valid MetatypeRepresentation.");
}
void IRGenSILFunction::visitValueMetatypeInst(swift::ValueMetatypeInst *i) {
SILType instanceTy = i->getOperand()->getType();
auto metaTy = i->getType().castTo<MetatypeType>();
if (metaTy->getRepresentation() == MetatypeRepresentation::Thin) {
Explosion empty;
setLoweredExplosion(i, empty);
return;
}
Explosion e;
if (instanceTy.getClassOrBoundGenericClass()) {
e.add(getClassMetatype(*this,
getClassBaseValue(*this, i->getOperand()),
metaTy->getRepresentation(), instanceTy));
} else if (auto arch = instanceTy.getAs<ArchetypeType>()) {
if (arch->requiresClass()) {
e.add(getClassMetatype(*this,
getClassBaseValue(*this, i->getOperand()),
metaTy->getRepresentation(), instanceTy));
} else {
Address base = getLoweredAddress(i->getOperand());
e.add(emitDynamicTypeOfOpaqueArchetype(*this, base,
i->getOperand()->getType()));
// FIXME: We need to convert this back to an ObjC class for an
// ObjC metatype representation.
if (metaTy->getRepresentation() == MetatypeRepresentation::ObjC)
unimplemented(i->getLoc().getSourceLoc(),
"objc metatype of non-class-bounded archetype");
}
} else {
emitMetatypeRef(*this, metaTy, e);
}
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitExistentialMetatypeInst(
swift::ExistentialMetatypeInst *i) {
Explosion result;
SILValue op = i->getOperand();
SILType opType = op->getType();
switch (opType.getPreferredExistentialRepresentation(IGM.getSILModule())) {
case ExistentialRepresentation::Metatype: {
Explosion existential = getLoweredExplosion(op);
emitMetatypeOfMetatype(*this, existential, opType, result);
break;
}
case ExistentialRepresentation::Class: {
Explosion existential = getLoweredExplosion(op);
emitMetatypeOfClassExistential(*this, existential, i->getType(),
opType, result);
break;
}
case ExistentialRepresentation::Boxed: {
Explosion existential = getLoweredExplosion(op);
emitMetatypeOfBoxedExistential(*this, existential, opType, result);
break;
}
case ExistentialRepresentation::Opaque: {
Address existential = getLoweredAddress(op);
emitMetatypeOfOpaqueExistential(*this, existential, opType, result);
break;
}
case ExistentialRepresentation::None:
llvm_unreachable("Bad existential representation");
}
setLoweredExplosion(i, result);
}
static void emitApplyArgument(IRGenSILFunction &IGF,
SILValue arg,
SILType paramType,
Explosion &out) {
bool isSubstituted = (arg->getType() != paramType);
// For indirect arguments, we just need to pass a pointer.
if (paramType.isAddress()) {
// This address is of the substituted type.
auto addr = IGF.getLoweredAddress(arg);
// If a substitution is in play, just bitcast the address.
if (isSubstituted) {
auto origType = IGF.IGM.getStoragePointerType(paramType);
addr = IGF.Builder.CreateBitCast(addr, origType);
}
out.add(addr.getAddress());
return;
}
// Otherwise, it's an explosion, which we may need to translate,
// both in terms of explosion level and substitution levels.
assert(arg->getType().isObject());
// Fast path: avoid an unnecessary temporary explosion.
if (!isSubstituted) {
IGF.getLoweredExplosion(arg, out);
return;
}
Explosion temp = IGF.getLoweredExplosion(arg);
reemitAsUnsubstituted(IGF, paramType, arg->getType(),
temp, out);
}
static llvm::Value *getObjCClassForValue(IRGenSILFunction &IGF,
llvm::Value *selfValue,
CanAnyMetatypeType selfType) {
// If we have a Swift metatype, map it to the heap metadata, which
// will be the Class for an ObjC type.
switch (selfType->getRepresentation()) {
case swift::MetatypeRepresentation::ObjC:
return selfValue;
case swift::MetatypeRepresentation::Thick:
// Convert thick metatype to Objective-C metatype.
return emitClassHeapMetadataRefForMetatype(IGF, selfValue,
selfType.getInstanceType());
case swift::MetatypeRepresentation::Thin:
llvm_unreachable("Cannot convert Thin metatype to ObjC metatype");
}
llvm_unreachable("bad metatype representation");
}
static llvm::Value *emitWitnessTableForLoweredCallee(IRGenSILFunction &IGF,
CanSILFunctionType origCalleeType,
SubstitutionList subs) {
auto &M = *IGF.getSwiftModule();
llvm::Value *wtable;
if (auto *proto = origCalleeType->getDefaultWitnessMethodProtocol(M)) {
// The generic signature for a witness method with abstract Self must
// have exactly one protocol requirement.
//
// We recover the witness table from the substitution that was used to
// produce the substituted callee type.
auto subMap = origCalleeType->getGenericSignature()
->getSubstitutionMap(subs);
auto origSelfType = proto->getSelfInterfaceType()->getCanonicalType();
auto substSelfType = origSelfType.subst(subMap)->getCanonicalType();
auto conformance = *subMap.lookupConformance(origSelfType, proto);
llvm::Value *argMetadata = IGF.emitTypeMetadataRef(substSelfType);
wtable = emitWitnessTableRef(IGF, substSelfType, &argMetadata,
conformance);
} else {
// Otherwise, we have no way of knowing the original protocol or
// conformance, since the witness has a concrete self type.
//
// Protocol witnesses for concrete types are thus not allowed to touch
// the witness table; they already know all the witnesses, and we can't
// say who they are.
wtable = llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy);
}
assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy);
return wtable;
}
static CallEmission getCallEmissionForLoweredValue(IRGenSILFunction &IGF,
CanSILFunctionType origCalleeType,
CanSILFunctionType substCalleeType,
const LoweredValue &lv,
llvm::Value *selfValue,
SubstitutionList substitutions,
WitnessMetadata *witnessMetadata,
Explosion &args) {
llvm::Value *calleeFn, *calleeData;
ForeignFunctionInfo foreignInfo;
switch (lv.kind) {
case LoweredValue::Kind::StaticFunction:
calleeFn = lv.getStaticFunction().getFunction();
calleeData = selfValue;
foreignInfo = lv.getStaticFunction().getForeignInfo();
if (origCalleeType->getRepresentation()
== SILFunctionType::Representation::WitnessMethod) {
llvm::Value *wtable = emitWitnessTableForLoweredCallee(
IGF, origCalleeType, substitutions);
witnessMetadata->SelfWitnessTable = wtable;
}
break;
case LoweredValue::Kind::ObjCMethod: {
assert(selfValue);
auto &objcMethod = lv.getObjCMethod();
ObjCMessageKind kind = objcMethod.getMessageKind();
CallEmission emission =
prepareObjCMethodRootCall(IGF, objcMethod.getMethod(),
origCalleeType, substCalleeType,
substitutions, kind);
// Convert a metatype 'self' argument to the ObjC Class pointer.
// FIXME: Should be represented in SIL.
if (auto metatype = dyn_cast<AnyMetatypeType>(
origCalleeType->getSelfParameter().getType())) {
selfValue = getObjCClassForValue(IGF, selfValue, metatype);
}
addObjCMethodCallImplicitArguments(IGF, args, objcMethod.getMethod(),
selfValue,
objcMethod.getSearchType());
return emission;
}
case LoweredValue::Kind::Explosion: {
switch (origCalleeType->getRepresentation()) {
case SILFunctionType::Representation::Block: {
assert(!selfValue && "block function with self?");
// Grab the block pointer and make it the first physical argument.
llvm::Value *blockPtr = lv.getSingletonExplosion(IGF);
blockPtr = IGF.Builder.CreateBitCast(blockPtr, IGF.IGM.ObjCBlockPtrTy);
args.add(blockPtr);
// Extract the invocation pointer for blocks.
llvm::Value *invokeAddr = IGF.Builder.CreateStructGEP(
/*Ty=*/nullptr, blockPtr, 3);
calleeFn = IGF.Builder.CreateLoad(invokeAddr, IGF.IGM.getPointerAlignment());
calleeData = nullptr;
break;
}
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::CFunctionPointer:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::Closure:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::WitnessMethod:
case SILFunctionType::Representation::Thick: {
Explosion calleeValues = lv.getExplosion(IGF);
calleeFn = calleeValues.claimNext();
if (origCalleeType->getRepresentation()
== SILFunctionType::Representation::WitnessMethod) {
witnessMetadata->SelfWitnessTable = emitWitnessTableForLoweredCallee(
IGF, origCalleeType, substitutions);
}
if (origCalleeType->getRepresentation()
== SILFunctionType::Representation::Thick) {
// @convention(thick) callees are exploded as a pair
// consisting of the function and the self value.
assert(!selfValue);
calleeData = calleeValues.claimNext();
} else {
calleeData = selfValue;
}
break;
}
}
// Cast the callee pointer to the right function type.
llvm::AttributeSet attrs;
llvm::FunctionType *fnTy =
IGF.IGM.getFunctionType(origCalleeType, attrs, &foreignInfo);
calleeFn = IGF.Builder.CreateBitCast(calleeFn, fnTy->getPointerTo());
break;
}
case LoweredValue::Kind::BoxWithAddress:
llvm_unreachable("@box isn't a valid callee");
case LoweredValue::Kind::ContainedAddress:
case LoweredValue::Kind::Address:
llvm_unreachable("sil address isn't a valid callee");
}
Callee callee = Callee::forKnownFunction(origCalleeType, substCalleeType,
substitutions, calleeFn, calleeData,
foreignInfo);
CallEmission callEmission(IGF, callee);
if (IGF.CurSILFn->isThunk())
callEmission.addAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoInline);
return callEmission;
}
void IRGenSILFunction::visitBuiltinInst(swift::BuiltinInst *i) {
auto argValues = i->getArguments();
Explosion args;
for (auto argValue : argValues) {
// Builtin arguments should never be substituted, so use the value's type
// as the parameter type.
emitApplyArgument(*this, argValue, argValue->getType(), args);
}
Explosion result;
emitBuiltinCall(*this, i->getName(), i->getType(),
args, result, i->getSubstitutions());
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitApplyInst(swift::ApplyInst *i) {
visitFullApplySite(i);
}
void IRGenSILFunction::visitTryApplyInst(swift::TryApplyInst *i) {
visitFullApplySite(i);
}
void IRGenSILFunction::visitFullApplySite(FullApplySite site) {
const LoweredValue &calleeLV = getLoweredValue(site.getCallee());
auto origCalleeType = site.getOrigCalleeType();
auto substCalleeType = site.getSubstCalleeType();
auto args = site.getArguments();
SILFunctionConventions origConv(origCalleeType, getSILModule());
assert(origConv.getNumSILArguments() == args.size());
// Extract 'self' if it needs to be passed as the context parameter.
llvm::Value *selfValue = nullptr;
if (origCalleeType->hasSelfParam() &&
isSelfContextParameter(origCalleeType->getSelfParameter())) {
SILValue selfArg = args.back();
args = args.drop_back();
if (selfArg->getType().isObject()) {
selfValue = getLoweredSingletonExplosion(selfArg);
} else {
selfValue = getLoweredAddress(selfArg).getAddress();
}
}
Explosion llArgs;
WitnessMetadata witnessMetadata;
CallEmission emission =
getCallEmissionForLoweredValue(*this, origCalleeType, substCalleeType,
calleeLV, selfValue, site.getSubstitutions(),
&witnessMetadata, llArgs);
// Lower the arguments and return value in the callee's generic context.
GenericContextScope scope(IGM, origCalleeType->getGenericSignature());
// Lower the SIL arguments to IR arguments.
// Turn the formal SIL parameters into IR-gen things.
for (auto index : indices(args)) {
emitApplyArgument(*this, args[index], origConv.getSILArgumentType(index),
llArgs);
}
// Pass the generic arguments.
if (hasPolymorphicParameters(origCalleeType)) {
SubstitutionMap subMap;
if (auto genericSig = origCalleeType->getGenericSignature())
subMap = genericSig->getSubstitutionMap(site.getSubstitutions());
emitPolymorphicArguments(*this, origCalleeType, substCalleeType,
subMap, &witnessMetadata, llArgs);
}
// Add all those arguments.
emission.setArgs(llArgs, &witnessMetadata);
SILInstruction *i = site.getInstruction();
Explosion result;
emission.emitToExplosion(result);
if (isa<ApplyInst>(i)) {
setLoweredExplosion(i, result);
} else {
auto tryApplyInst = cast<TryApplyInst>(i);
// Load the error value.
SILFunctionConventions substConv(substCalleeType, getSILModule());
SILType errorType = substConv.getSILErrorType();
Address errorSlot = getErrorResultSlot(errorType);
auto errorValue = Builder.CreateLoad(errorSlot);
auto &normalDest = getLoweredBB(tryApplyInst->getNormalBB());
auto &errorDest = getLoweredBB(tryApplyInst->getErrorBB());
// Zero the error slot to maintain the invariant that it always
// contains null. This will frequently become a dead store.
auto nullError = llvm::Constant::getNullValue(errorValue->getType());
if (!tryApplyInst->getErrorBB()->getSinglePredecessorBlock()) {
// Only do that here if we can't move the store to the error block.
// See below.
Builder.CreateStore(nullError, errorSlot);
}
// If the error value is non-null, branch to the error destination.
auto hasError = Builder.CreateICmpNE(errorValue, nullError);
Builder.CreateCondBr(hasError, errorDest.bb, normalDest.bb);
// Set up the PHI nodes on the normal edge.
unsigned firstIndex = 0;
addIncomingExplosionToPHINodes(*this, normalDest, firstIndex, result);
assert(firstIndex == normalDest.phis.size());
// Set up the PHI nodes on the error edge.
assert(errorDest.phis.size() == 1);
errorDest.phis[0]->addIncoming(errorValue, Builder.GetInsertBlock());
if (tryApplyInst->getErrorBB()->getSinglePredecessorBlock()) {
// Zeroing out the error slot only in the error block increases the chance
// that it will become a dead store.
auto origBB = Builder.GetInsertBlock();
Builder.SetInsertPoint(errorDest.bb);
Builder.CreateStore(nullError, errorSlot);
Builder.SetInsertPoint(origBB);
}
}
}
/// If the value is a @convention(witness_method) function, the context
/// is the witness table that must be passed to the call.
///
/// \param v A value of possibly-polymorphic SILFunctionType.
/// \param subs This is the set of substitutions that we are going to be
/// applying to 'v'.
static std::tuple<llvm::Value*, llvm::Value*, CanSILFunctionType>
getPartialApplicationFunction(IRGenSILFunction &IGF, SILValue v,
SubstitutionList subs) {
LoweredValue &lv = IGF.getLoweredValue(v);
auto fnType = v->getType().castTo<SILFunctionType>();
switch (lv.kind) {
case LoweredValue::Kind::ContainedAddress:
case LoweredValue::Kind::Address:
llvm_unreachable("can't partially apply an address");
case LoweredValue::Kind::BoxWithAddress:
llvm_unreachable("can't partially apply a @box");
case LoweredValue::Kind::ObjCMethod:
llvm_unreachable("objc method partial application shouldn't get here");
case LoweredValue::Kind::StaticFunction: {
llvm::Value *context = nullptr;
switch (lv.getStaticFunction().getRepresentation()) {
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::Block:
case SILFunctionTypeRepresentation::ObjCMethod:
assert(false && "partial_apply of foreign functions not implemented");
break;
case SILFunctionTypeRepresentation::WitnessMethod:
context = emitWitnessTableForLoweredCallee(IGF, fnType, subs);
break;
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::Closure:
break;
}
return std::make_tuple(lv.getStaticFunction().getFunction(),
context, v->getType().castTo<SILFunctionType>());
}
case LoweredValue::Kind::Explosion: {
Explosion ex = lv.getExplosion(IGF);
llvm::Value *fn = ex.claimNext();
llvm::Value *context = nullptr;
switch (fnType->getRepresentation()) {
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::Closure:
case SILFunctionType::Representation::ObjCMethod:
break;
case SILFunctionType::Representation::WitnessMethod:
context = emitWitnessTableForLoweredCallee(IGF, fnType, subs);
break;
case SILFunctionType::Representation::CFunctionPointer:
break;
case SILFunctionType::Representation::Thick:
context = ex.claimNext();
break;
case SILFunctionType::Representation::Block:
llvm_unreachable("partial application of block not implemented");
}
return std::make_tuple(fn, context, fnType);
}
}
llvm_unreachable("Not a valid SILFunctionType.");
}
void IRGenSILFunction::visitPartialApplyInst(swift::PartialApplyInst *i) {
SILValue v(i);
// NB: We collect the arguments under the substituted type.
auto args = i->getArguments();
auto params = i->getSubstCalleeType()->getParameters();
params = params.slice(params.size() - args.size(), args.size());
Explosion llArgs;
{
// Lower the parameters in the callee's generic context.
GenericContextScope scope(IGM, i->getOrigCalleeType()->getGenericSignature());
for (auto index : indices(args)) {
assert(args[index]->getType() == IGM.silConv.getSILType(params[index]));
emitApplyArgument(*this, args[index],
IGM.silConv.getSILType(params[index]), llArgs);
}
}
auto &lv = getLoweredValue(i->getCallee());
if (lv.kind == LoweredValue::Kind::ObjCMethod) {
// Objective-C partial applications require a different path. There's no
// actual function pointer to capture, and we semantically can't cache
// dispatch, so we need to perform the message send in the partial
// application thunk.
auto &objcMethod = lv.getObjCMethod();
assert(i->getArguments().size() == 1 &&
"only partial application of objc method to self implemented");
assert(llArgs.size() == 1 &&
"objc partial_apply argument is not a single retainable pointer?!");
llvm::Value *selfVal = llArgs.claimNext();
Explosion function;
emitObjCPartialApplication(*this,
objcMethod,
i->getOrigCalleeType(),
i->getType().castTo<SILFunctionType>(),
selfVal,
i->getArguments()[0]->getType(),
function);
setLoweredExplosion(i, function);
return;
}
// Get the function value.
llvm::Value *calleeFn = nullptr;
llvm::Value *innerContext = nullptr;
CanSILFunctionType origCalleeTy;
std::tie(calleeFn, innerContext, origCalleeTy)
= getPartialApplicationFunction(*this, i->getCallee(),
i->getSubstitutions());
// Create the thunk and function value.
Explosion function;
emitFunctionPartialApplication(*this, *CurSILFn,
calleeFn, innerContext, llArgs,
params, i->getSubstitutions(),
origCalleeTy, i->getSubstCalleeType(),
i->getType().castTo<SILFunctionType>(),
function);
setLoweredExplosion(v, function);
}
void IRGenSILFunction::visitIntegerLiteralInst(swift::IntegerLiteralInst *i) {
llvm::Value *constant = emitConstantInt(IGM, i);
Explosion e;
e.add(constant);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitFloatLiteralInst(swift::FloatLiteralInst *i) {
llvm::Value *constant = emitConstantFP(IGM, i);
Explosion e;
e.add(constant);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitStringLiteralInst(swift::StringLiteralInst *i) {
llvm::Value *addr;
// Emit a load of a selector.
if (i->getEncoding() == swift::StringLiteralInst::Encoding::ObjCSelector)
addr = emitObjCSelectorRefLoad(i->getValue());
else
addr = emitAddrOfConstantString(IGM, i);
Explosion e;
e.add(addr);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitUnreachableInst(swift::UnreachableInst *i) {
Builder.CreateUnreachable();
}
static void emitReturnInst(IRGenSILFunction &IGF,
SILType resultTy,
Explosion &result) {
// The invariant on the out-parameter is that it's always zeroed, so
// there's nothing to do here.
// Even if SIL has a direct return, the IR-level calling convention may
// require an indirect return.
if (IGF.IndirectReturn.isValid()) {
auto &retTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(resultTy));
retTI.initialize(IGF, result, IGF.IndirectReturn);
IGF.Builder.CreateRetVoid();
} else {
auto funcLang = IGF.CurSILFn->getLoweredFunctionType()->getLanguage();
auto swiftCCReturn = funcLang == SILFunctionLanguage::Swift;
assert(swiftCCReturn ||
funcLang == SILFunctionLanguage::C && "Need to handle all cases");
IGF.emitScalarReturn(resultTy, result, swiftCCReturn);
}
}
void IRGenSILFunction::visitReturnInst(swift::ReturnInst *i) {
Explosion result = getLoweredExplosion(i->getOperand());
// Implicitly autorelease the return value if the function's result
// convention is autoreleased.
auto fnConv = CurSILFn->getConventions();
if (fnConv.getNumDirectSILResults() == 1
&& (fnConv.getDirectSILResults().begin()->getConvention()
== ResultConvention::Autoreleased)) {
Explosion temp;
temp.add(emitObjCAutoreleaseReturnValue(*this, result.claimNext()));
result = std::move(temp);
}
emitReturnInst(*this, i->getOperand()->getType(), result);
}
void IRGenSILFunction::visitThrowInst(swift::ThrowInst *i) {
// Store the exception to the error slot.
llvm::Value *exn = getLoweredSingletonExplosion(i->getOperand());
Builder.CreateStore(exn, getCallerErrorResultSlot());
// Create a normal return, but leaving the return value undefined.
auto fnTy = CurFn->getType()->getPointerElementType();
auto retTy = cast<llvm::FunctionType>(fnTy)->getReturnType();
if (retTy->isVoidTy()) {
Builder.CreateRetVoid();
} else {
Builder.CreateRet(llvm::UndefValue::get(retTy));
}
}
static llvm::BasicBlock *emitBBMapForSwitchValue(
IRGenSILFunction &IGF,
SmallVectorImpl<std::pair<SILValue, llvm::BasicBlock*>> &dests,
SwitchValueInst *inst) {
for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) {
auto casePair = inst->getCase(i);
dests.push_back({casePair.first, IGF.getLoweredBB(casePair.second).bb});
}
llvm::BasicBlock *defaultDest = nullptr;
if (inst->hasDefault())
defaultDest = IGF.getLoweredBB(inst->getDefaultBB()).bb;
return defaultDest;
}
static llvm::ConstantInt *
getSwitchCaseValue(IRGenFunction &IGF, SILValue val) {
if (auto *IL = dyn_cast<IntegerLiteralInst>(val)) {
return dyn_cast<llvm::ConstantInt>(emitConstantInt(IGF.IGM, IL));
}
else {
llvm_unreachable("Switch value cases should be integers");
}
}
static void
emitSwitchValueDispatch(IRGenSILFunction &IGF,
SILType ty,
Explosion &value,
ArrayRef<std::pair<SILValue, llvm::BasicBlock*>> dests,
llvm::BasicBlock *defaultDest) {
// Create an unreachable block for the default if the original SIL
// instruction had none.
bool unreachableDefault = false;
if (!defaultDest) {
unreachableDefault = true;
defaultDest = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
}
if (ty.is<BuiltinIntegerType>()) {
auto *discriminator = value.claimNext();
auto *i = IGF.Builder.CreateSwitch(discriminator, defaultDest,
dests.size());
for (auto &dest : dests)
i->addCase(getSwitchCaseValue(IGF, dest.first), dest.second);
} else {
// Get the value we're testing, which is a function.
llvm::Value *val;
llvm::BasicBlock *nextTest = nullptr;
if (ty.is<SILFunctionType>()) {
val = value.claimNext(); // Function pointer.
//values.claimNext(); // Ignore the data pointer.
} else {
llvm_unreachable("switch_value operand has an unknown type");
}
for (int i = 0, e = dests.size(); i < e; ++i) {
auto casePair = dests[i];
llvm::Value *caseval;
auto casevalue = IGF.getLoweredExplosion(casePair.first);
if (casePair.first->getType().is<SILFunctionType>()) {
caseval = casevalue.claimNext(); // Function pointer.
//values.claimNext(); // Ignore the data pointer.
} else {
llvm_unreachable("switch_value operand has an unknown type");
}
// Compare operand with a case tag value.
llvm::Value *cond = IGF.Builder.CreateICmp(llvm::CmpInst::ICMP_EQ,
val, caseval);
if (i == e -1 && !unreachableDefault) {
nextTest = nullptr;
IGF.Builder.CreateCondBr(cond, casePair.second, defaultDest);
} else {
nextTest = IGF.createBasicBlock("next-test");
IGF.Builder.CreateCondBr(cond, casePair.second, nextTest);
IGF.Builder.emitBlock(nextTest);
IGF.Builder.SetInsertPoint(nextTest);
}
}
if (nextTest) {
IGF.Builder.CreateBr(defaultDest);
}
}
if (unreachableDefault) {
IGF.Builder.emitBlock(defaultDest);
IGF.Builder.CreateUnreachable();
}
}
void IRGenSILFunction::visitSwitchValueInst(SwitchValueInst *inst) {
Explosion value = getLoweredExplosion(inst->getOperand());
// Map the SIL dest bbs to their LLVM bbs.
SmallVector<std::pair<SILValue, llvm::BasicBlock*>, 4> dests;
auto *defaultDest = emitBBMapForSwitchValue(*this, dests, inst);
emitSwitchValueDispatch(*this, inst->getOperand()->getType(),
value, dests, defaultDest);
}
// Bind an incoming explosion value to an explosion of LLVM phi node(s).
static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF,
ArrayRef<llvm::Value*> phis,
Explosion &argValue) {
llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock();
unsigned phiIndex = 0;
while (!argValue.empty())
cast<llvm::PHINode>(phis[phiIndex++])
->addIncoming(argValue.claimNext(), curBB);
assert(phiIndex == phis.size() && "explosion doesn't match number of phis");
}
// Bind an incoming explosion value to a SILArgument's LLVM phi node(s).
static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF,
LoweredBB &lbb,
unsigned &phiIndex,
Explosion &argValue) {
llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock();
while (!argValue.empty())
lbb.phis[phiIndex++]->addIncoming(argValue.claimNext(), curBB);
}
// Bind an incoming address value to a SILArgument's LLVM phi node(s).
static void addIncomingAddressToPHINodes(IRGenSILFunction &IGF,
ArrayRef<llvm::Value*> phis,
Address argValue) {
llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock();
assert(phis.size() == 1 && "more than one phi for address?!");
cast<llvm::PHINode>(phis[0])->addIncoming(argValue.getAddress(), curBB);
}
// Bind an incoming address value to a SILArgument's LLVM phi node(s).
static void addIncomingAddressToPHINodes(IRGenSILFunction &IGF,
LoweredBB &lbb,
unsigned &phiIndex,
Address argValue) {
llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock();
lbb.phis[phiIndex++]->addIncoming(argValue.getAddress(), curBB);
}
// Add branch arguments to destination phi nodes.
static void addIncomingSILArgumentsToPHINodes(IRGenSILFunction &IGF,
LoweredBB &lbb,
OperandValueArrayRef args) {
unsigned phiIndex = 0;
for (SILValue arg : args) {
const LoweredValue &lv = IGF.getLoweredValue(arg);
if (lv.isAddress()) {
addIncomingAddressToPHINodes(IGF, lbb, phiIndex, lv.getAddress());
continue;
}
Explosion argValue = lv.getExplosion(IGF);
addIncomingExplosionToPHINodes(IGF, lbb, phiIndex, argValue);
}
}
static llvm::BasicBlock *emitBBMapForSwitchEnum(
IRGenSILFunction &IGF,
SmallVectorImpl<std::pair<EnumElementDecl*, llvm::BasicBlock*>> &dests,
SwitchEnumInstBase *inst) {
for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) {
auto casePair = inst->getCase(i);
// If the destination BB accepts the case argument, set up a waypoint BB so
// we can feed the values into the argument's PHI node(s).
//
// FIXME: This is cheesy when the destination BB has only the switch
// as a predecessor.
if (!casePair.second->args_empty())
dests.push_back({casePair.first,
llvm::BasicBlock::Create(IGF.IGM.getLLVMContext())});
else
dests.push_back({casePair.first, IGF.getLoweredBB(casePair.second).bb});
}
llvm::BasicBlock *defaultDest = nullptr;
if (inst->hasDefault())
defaultDest = IGF.getLoweredBB(inst->getDefaultBB()).bb;
return defaultDest;
}
void IRGenSILFunction::visitSwitchEnumInst(SwitchEnumInst *inst) {
Explosion value = getLoweredExplosion(inst->getOperand());
// Map the SIL dest bbs to their LLVM bbs.
SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests;
llvm::BasicBlock *defaultDest
= emitBBMapForSwitchEnum(*this, dests, inst);
// Emit the dispatch.
auto &EIS = getEnumImplStrategy(IGM, inst->getOperand()->getType());
EIS.emitValueSwitch(*this, value, dests, defaultDest);
// Bind arguments for cases that want them.
for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) {
auto casePair = inst->getCase(i);
if (!casePair.second->args_empty()) {
auto waypointBB = dests[i].second;
auto &destLBB = getLoweredBB(casePair.second);
Builder.emitBlock(waypointBB);
Explosion inValue = getLoweredExplosion(inst->getOperand());
Explosion projected;
emitProjectLoadableEnum(*this, inst->getOperand()->getType(),
inValue, casePair.first, projected);
unsigned phiIndex = 0;
addIncomingExplosionToPHINodes(*this, destLBB, phiIndex, projected);
Builder.CreateBr(destLBB.bb);
}
}
}
void
IRGenSILFunction::visitSwitchEnumAddrInst(SwitchEnumAddrInst *inst) {
Address value = getLoweredAddress(inst->getOperand());
// Map the SIL dest bbs to their LLVM bbs.
SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests;
llvm::BasicBlock *defaultDest
= emitBBMapForSwitchEnum(*this, dests, inst);
// Emit the dispatch.
emitSwitchAddressOnlyEnumDispatch(*this, inst->getOperand()->getType(),
value, dests, defaultDest);
}
// FIXME: We could lower select_enum directly to LLVM select in a lot of cases.
// For now, just emit a switch and phi nodes, like a chump.
template<class C, class T>
static llvm::BasicBlock *
emitBBMapForSelect(IRGenSILFunction &IGF,
Explosion &resultPHI,
SmallVectorImpl<std::pair<T, llvm::BasicBlock*>> &BBs,
llvm::BasicBlock *&defaultBB,
SelectInstBase<C, T> *inst) {
auto origBB = IGF.Builder.GetInsertBlock();
// Set up a continuation BB and phi nodes to receive the result value.
llvm::BasicBlock *contBB = IGF.createBasicBlock("select_enum");
IGF.Builder.SetInsertPoint(contBB);
// Emit an explosion of phi node(s) to receive the value.
SmallVector<llvm::Value*, 4> phis;
auto &ti = IGF.getTypeInfo(inst->getType());
emitPHINodesForType(IGF, inst->getType(), ti,
inst->getNumCases() + inst->hasDefault(),
phis);
resultPHI.add(phis);
IGF.Builder.SetInsertPoint(origBB);
auto addIncoming = [&](SILValue value) {
if (value->getType().isAddress()) {
addIncomingAddressToPHINodes(IGF, resultPHI.getAll(),
IGF.getLoweredAddress(value));
} else {
Explosion ex = IGF.getLoweredExplosion(value);
addIncomingExplosionToPHINodes(IGF, resultPHI.getAll(), ex);
}
};
for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) {
auto casePair = inst->getCase(i);
// Create a basic block destination for this case.
llvm::BasicBlock *destBB = IGF.createBasicBlock("");
IGF.Builder.emitBlock(destBB);
// Feed the corresponding result into the phi nodes.
addIncoming(casePair.second);
// Jump immediately to the continuation.
IGF.Builder.CreateBr(contBB);
BBs.push_back(std::make_pair(casePair.first, destBB));
}
if (inst->hasDefault()) {
defaultBB = IGF.createBasicBlock("");
IGF.Builder.emitBlock(defaultBB);
addIncoming(inst->getDefaultResult());
IGF.Builder.CreateBr(contBB);
} else {
defaultBB = nullptr;
}
IGF.Builder.emitBlock(contBB);
IGF.Builder.SetInsertPoint(origBB);
return contBB;
}
// Try to map the value of a select_enum directly to an int type with a simple
// cast from the tag value to the result type. Optionally also by adding a
// constant offset.
// This is useful, e.g. for rawValue or hashValue of C-like enums.
static llvm::Value *
mapTriviallyToInt(IRGenSILFunction &IGF, const EnumImplStrategy &EIS, SelectEnumInst *inst) {
// All cases must be covered
if (inst->hasDefault())
return nullptr;
auto &ti = IGF.getTypeInfo(inst->getType());
ExplosionSchema schema = ti.getSchema();
// Check if the select_enum's result is a single integer scalar.
if (schema.size() != 1)
return nullptr;
if (!schema[0].isScalar())
return nullptr;
llvm::Type *type = schema[0].getScalarType();
llvm::IntegerType *resultType = dyn_cast<llvm::IntegerType>(type);
if (!resultType)
return nullptr;
// Check if the case values directly map to the tag values, maybe with a
// constant offset.
APInt commonOffset;
bool offsetValid = false;
for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) {
auto casePair = inst->getCase(i);
int64_t index = EIS.getDiscriminatorIndex(casePair.first);
if (index < 0)
return nullptr;
IntegerLiteralInst *intLit = dyn_cast<IntegerLiteralInst>(casePair.second);
if (!intLit)
return nullptr;
APInt caseValue = intLit->getValue();
APInt offset = caseValue - index;
if (offsetValid) {
if (offset != commonOffset)
return nullptr;
} else {
commonOffset = offset;
offsetValid = true;
}
}
// Ask the enum implementation strategy to extract the enum tag as an integer
// value.
Explosion enumValue = IGF.getLoweredExplosion(inst->getEnumOperand());
llvm::Value *result = EIS.emitExtractDiscriminator(IGF, enumValue);
if (!result) {
(void)enumValue.claimAll();
return nullptr;
}
// Cast to the result type.
result = IGF.Builder.CreateIntCast(result, resultType, false);
if (commonOffset != 0) {
// The offset, if any.
auto *offsetConst = llvm::ConstantInt::get(resultType, commonOffset);
result = IGF.Builder.CreateAdd(result, offsetConst);
}
return result;
}
template <class C, class T>
static LoweredValue
getLoweredValueForSelect(IRGenSILFunction &IGF,
Explosion &result, SelectInstBase<C, T> *inst) {
if (inst->getType().isAddress())
// FIXME: Loses potentially better alignment info we might have.
return LoweredValue(Address(result.claimNext(),
IGF.getTypeInfo(inst->getType()).getBestKnownAlignment()));
return LoweredValue(result);
}
static void emitSingleEnumMemberSelectResult(IRGenSILFunction &IGF,
SelectEnumInstBase *inst,
llvm::Value *isTrue,
Explosion &result) {
assert((inst->getNumCases() == 1 && inst->hasDefault()) ||
(inst->getNumCases() == 2 && !inst->hasDefault()));
// Extract the true values.
auto trueValue = inst->getCase(0).second;
SmallVector<llvm::Value*, 4> TrueValues;
if (trueValue->getType().isAddress()) {
TrueValues.push_back(IGF.getLoweredAddress(trueValue).getAddress());
} else {
Explosion ex = IGF.getLoweredExplosion(trueValue);
while (!ex.empty())
TrueValues.push_back(ex.claimNext());
}
// Extract the false values.
auto falseValue =
inst->hasDefault() ? inst->getDefaultResult() : inst->getCase(1).second;
SmallVector<llvm::Value*, 4> FalseValues;
if (falseValue->getType().isAddress()) {
FalseValues.push_back(IGF.getLoweredAddress(falseValue).getAddress());
} else {
Explosion ex = IGF.getLoweredExplosion(falseValue);
while (!ex.empty())
FalseValues.push_back(ex.claimNext());
}
assert(TrueValues.size() == FalseValues.size() &&
"explosions didn't produce same element count?");
for (unsigned i = 0, e = FalseValues.size(); i != e; ++i) {
auto *TV = TrueValues[i], *FV = FalseValues[i];
// It is pretty common to select between zero and 1 as the result of the
// select. Instead of emitting an obviously dumb select, emit nothing or
// a zext.
if (auto *TC = dyn_cast<llvm::ConstantInt>(TV))
if (auto *FC = dyn_cast<llvm::ConstantInt>(FV))
if (TC->isOne() && FC->isZero()) {
result.add(IGF.Builder.CreateZExtOrBitCast(isTrue, TV->getType()));
continue;
}
result.add(IGF.Builder.CreateSelect(isTrue, TV, FalseValues[i]));
}
}
void IRGenSILFunction::visitSelectEnumInst(SelectEnumInst *inst) {
auto &EIS = getEnumImplStrategy(IGM, inst->getEnumOperand()->getType());
Explosion result;
if (llvm::Value *R = mapTriviallyToInt(*this, EIS, inst)) {
result.add(R);
} else if ((inst->getNumCases() == 1 && inst->hasDefault()) ||
(inst->getNumCases() == 2 && !inst->hasDefault())) {
// If this is testing for one case, do simpler codegen. This is
// particularly common when testing optionals.
Explosion value = getLoweredExplosion(inst->getEnumOperand());
auto isTrue = EIS.emitValueCaseTest(*this, value, inst->getCase(0).first);
emitSingleEnumMemberSelectResult(*this, inst, isTrue, result);
} else {
Explosion value = getLoweredExplosion(inst->getEnumOperand());
// Map the SIL dest bbs to their LLVM bbs.
SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests;
llvm::BasicBlock *defaultDest;
llvm::BasicBlock *contBB
= emitBBMapForSelect(*this, result, dests, defaultDest, inst);
// Emit the dispatch.
EIS.emitValueSwitch(*this, value, dests, defaultDest);
// emitBBMapForSelectEnum set up a continuation block and phi nodes to
// receive the result.
Builder.SetInsertPoint(contBB);
}
setLoweredValue(inst,
getLoweredValueForSelect(*this, result, inst));
}
void IRGenSILFunction::visitSelectEnumAddrInst(SelectEnumAddrInst *inst) {
Address value = getLoweredAddress(inst->getEnumOperand());
Explosion result;
if ((inst->getNumCases() == 1 && inst->hasDefault()) ||
(inst->getNumCases() == 2 && !inst->hasDefault())) {
auto &EIS = getEnumImplStrategy(IGM, inst->getEnumOperand()->getType());
// If this is testing for one case, do simpler codegen. This is
// particularly common when testing optionals.
auto isTrue = EIS.emitIndirectCaseTest(*this,
inst->getEnumOperand()->getType(),
value, inst->getCase(0).first);
emitSingleEnumMemberSelectResult(*this, inst, isTrue, result);
} else {
// Map the SIL dest bbs to their LLVM bbs.
SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests;
llvm::BasicBlock *defaultDest;
llvm::BasicBlock *contBB
= emitBBMapForSelect(*this, result, dests, defaultDest, inst);
// Emit the dispatch.
emitSwitchAddressOnlyEnumDispatch(*this, inst->getEnumOperand()->getType(),
value, dests, defaultDest);
// emitBBMapForSelectEnum set up a phi node to receive the result.
Builder.SetInsertPoint(contBB);
}
setLoweredValue(inst,
getLoweredValueForSelect(*this, result, inst));
}
void IRGenSILFunction::visitSelectValueInst(SelectValueInst *inst) {
Explosion value = getLoweredExplosion(inst->getOperand());
// Map the SIL dest bbs to their LLVM bbs.
SmallVector<std::pair<SILValue, llvm::BasicBlock*>, 4> dests;
llvm::BasicBlock *defaultDest;
Explosion result;
auto *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst);
// Emit the dispatch.
emitSwitchValueDispatch(*this, inst->getOperand()->getType(), value, dests,
defaultDest);
// emitBBMapForSelectEnum set up a continuation block and phi nodes to
// receive the result.
Builder.SetInsertPoint(contBB);
setLoweredValue(inst,
getLoweredValueForSelect(*this, result, inst));
}
void IRGenSILFunction::visitDynamicMethodBranchInst(DynamicMethodBranchInst *i){
LoweredBB &hasMethodBB = getLoweredBB(i->getHasMethodBB());
LoweredBB &noMethodBB = getLoweredBB(i->getNoMethodBB());
// Emit the respondsToSelector: call.
StringRef selector;
llvm::SmallString<64> selectorBuffer;
if (auto fnDecl = dyn_cast<FuncDecl>(i->getMember().getDecl()))
selector = fnDecl->getObjCSelector().getString(selectorBuffer);
else if (auto var = dyn_cast<AbstractStorageDecl>(i->getMember().getDecl()))
selector = var->getObjCGetterSelector().getString(selectorBuffer);
else
llvm_unreachable("Unhandled dynamic method branch query");
llvm::Value *object = getLoweredExplosion(i->getOperand()).claimNext();
if (object->getType() != IGM.ObjCPtrTy)
object = Builder.CreateBitCast(object, IGM.ObjCPtrTy);
llvm::Value *loadSel = emitObjCSelectorRefLoad(selector);
llvm::Value *respondsToSelector
= emitObjCSelectorRefLoad("respondsToSelector:");
llvm::Constant *messenger = IGM.getObjCMsgSendFn();
llvm::Type *argTys[] = {
IGM.ObjCPtrTy,
IGM.Int8PtrTy,
IGM.Int8PtrTy,
};
auto respondsToSelectorTy = llvm::FunctionType::get(IGM.Int1Ty,
argTys,
/*isVarArg*/ false)
->getPointerTo();
messenger = llvm::ConstantExpr::getBitCast(messenger,
respondsToSelectorTy);
llvm::CallInst *call = Builder.CreateCall(messenger,
{object, respondsToSelector, loadSel});
call->setDoesNotThrow();
// FIXME: Assume (probably safely) that the hasMethodBB has only us as a
// predecessor, and cannibalize its bb argument so we can represent is as an
// ObjCMethod lowered value. This is hella gross but saves us having to
// implement ObjCMethod-to-Explosion lowering and creating a thunk we don't
// want.
assert(std::next(i->getHasMethodBB()->pred_begin())
== i->getHasMethodBB()->pred_end()
&& "lowering dynamic_method_br with multiple preds for destination "
"not implemented");
// Kill the existing lowered value for the bb arg and its phi nodes.
SILValue methodArg = i->getHasMethodBB()->args_begin()[0];
Explosion formerLLArg = getLoweredExplosion(methodArg);
for (llvm::Value *val : formerLLArg.claimAll()) {
auto phi = cast<llvm::PHINode>(val);
assert(phi->getNumIncomingValues() == 0 && "phi already used");
phi->removeFromParent();
delete phi;
}
LoweredValues.erase(methodArg);
// Replace the lowered value with an ObjCMethod lowering.
setLoweredObjCMethod(methodArg, i->getMember());
// Create the branch.
Builder.CreateCondBr(call, hasMethodBB.bb, noMethodBB.bb);
}
void IRGenSILFunction::visitBranchInst(swift::BranchInst *i) {
LoweredBB &lbb = getLoweredBB(i->getDestBB());
addIncomingSILArgumentsToPHINodes(*this, lbb, i->getArgs());
Builder.CreateBr(lbb.bb);
}
void IRGenSILFunction::visitCondBranchInst(swift::CondBranchInst *i) {
LoweredBB &trueBB = getLoweredBB(i->getTrueBB());
LoweredBB &falseBB = getLoweredBB(i->getFalseBB());
llvm::Value *condValue =
getLoweredExplosion(i->getCondition()).claimNext();
addIncomingSILArgumentsToPHINodes(*this, trueBB, i->getTrueArgs());
addIncomingSILArgumentsToPHINodes(*this, falseBB, i->getFalseArgs());
Builder.CreateCondBr(condValue, trueBB.bb, falseBB.bb);
}
void IRGenSILFunction::visitRetainValueInst(swift::RetainValueInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
Explosion out;
cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType()))
.copy(*this, in, out, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
(void)out.claimAll();
}
void IRGenSILFunction::visitCopyValueInst(swift::CopyValueInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
Explosion out;
cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType()))
.copy(*this, in, out, getDefaultAtomicity());
setLoweredExplosion(i, out);
}
// TODO: Implement this more generally for arbitrary values. Currently the
// SIL verifier restricts it to single-refcounted-pointer types.
void IRGenSILFunction::visitAutoreleaseValueInst(swift::AutoreleaseValueInst *i)
{
Explosion in = getLoweredExplosion(i->getOperand());
auto val = in.claimNext();
emitObjCAutoreleaseCall(val);
}
void IRGenSILFunction::visitSetDeallocatingInst(SetDeallocatingInst *i) {
auto *ARI = dyn_cast<AllocRefInst>(i->getOperand());
if (ARI && StackAllocs.count(ARI)) {
// A small peep-hole optimization: If the operand is allocated on stack and
// there is no "significant" code between the set_deallocating and the final
// dealloc_ref, the set_deallocating is not required.
// %0 = alloc_ref [stack]
// ...
// set_deallocating %0 // not needed
// // code which does not depend on the RC_DEALLOCATING_FLAG flag.
// dealloc_ref %0 // not needed (stems from the inlined deallocator)
// ...
// dealloc_ref [stack] %0
SILBasicBlock::iterator Iter(i);
SILBasicBlock::iterator End = i->getParent()->end();
for (++Iter; Iter != End; ++Iter) {
SILInstruction *I = &*Iter;
if (auto *DRI = dyn_cast<DeallocRefInst>(I)) {
if (DRI->getOperand() == ARI) {
// The set_deallocating is followed by a dealloc_ref -> we can ignore
// it.
return;
}
}
// Assume that any instruction with side-effects may depend on the
// RC_DEALLOCATING_FLAG flag.
if (I->mayHaveSideEffects())
break;
}
}
Explosion lowered = getLoweredExplosion(i->getOperand());
emitNativeSetDeallocating(lowered.claimNext());
}
void IRGenSILFunction::visitReleaseValueInst(swift::ReleaseValueInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType()))
.consume(*this, in, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
void IRGenSILFunction::visitDestroyValueInst(swift::DestroyValueInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType()))
.consume(*this, in, getDefaultAtomicity());
}
void IRGenSILFunction::visitStructInst(swift::StructInst *i) {
Explosion out;
for (SILValue elt : i->getElements())
out.add(getLoweredExplosion(elt).claimAll());
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitTupleInst(swift::TupleInst *i) {
Explosion out;
for (SILValue elt : i->getElements())
out.add(getLoweredExplosion(elt).claimAll());
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitEnumInst(swift::EnumInst *i) {
Explosion data = (i->hasOperand())
? getLoweredExplosion(i->getOperand())
: Explosion();
Explosion out;
emitInjectLoadableEnum(*this, i->getType(), i->getElement(), data, out);
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitInitEnumDataAddrInst(swift::InitEnumDataAddrInst *i) {
Address enumAddr = getLoweredAddress(i->getOperand());
Address dataAddr = emitProjectEnumAddressForStore(*this,
i->getOperand()->getType(),
enumAddr,
i->getElement());
setLoweredAddress(i, dataAddr);
}
void IRGenSILFunction::visitUncheckedEnumDataInst(swift::UncheckedEnumDataInst *i) {
Explosion enumVal = getLoweredExplosion(i->getOperand());
Explosion data;
emitProjectLoadableEnum(*this, i->getOperand()->getType(),
enumVal, i->getElement(), data);
setLoweredExplosion(i, data);
}
void IRGenSILFunction::visitUncheckedTakeEnumDataAddrInst(swift::UncheckedTakeEnumDataAddrInst *i) {
Address enumAddr = getLoweredAddress(i->getOperand());
Address dataAddr = emitDestructiveProjectEnumAddressForLoad(*this,
i->getOperand()->getType(),
enumAddr,
i->getElement());
setLoweredAddress(i, dataAddr);
}
void IRGenSILFunction::visitInjectEnumAddrInst(swift::InjectEnumAddrInst *i) {
Address enumAddr = getLoweredAddress(i->getOperand());
emitStoreEnumTagToAddress(*this, i->getOperand()->getType(),
enumAddr, i->getElement());
}
void IRGenSILFunction::visitTupleExtractInst(swift::TupleExtractInst *i) {
Explosion fullTuple = getLoweredExplosion(i->getOperand());
Explosion output;
SILType baseType = i->getOperand()->getType();
projectTupleElementFromExplosion(*this,
baseType,
fullTuple,
i->getFieldNo(),
output);
(void)fullTuple.claimAll();
setLoweredExplosion(i, output);
}
void IRGenSILFunction::visitTupleElementAddrInst(swift::TupleElementAddrInst *i)
{
Address base = getLoweredAddress(i->getOperand());
SILType baseType = i->getOperand()->getType();
Address field = projectTupleElementAddress(*this, base, baseType,
i->getFieldNo());
setLoweredAddress(i, field);
}
void IRGenSILFunction::visitStructExtractInst(swift::StructExtractInst *i) {
Explosion operand = getLoweredExplosion(i->getOperand());
Explosion lowered;
SILType baseType = i->getOperand()->getType();
projectPhysicalStructMemberFromExplosion(*this,
baseType,
operand,
i->getField(),
lowered);
(void)operand.claimAll();
setLoweredExplosion(i, lowered);
}
void IRGenSILFunction::visitStructElementAddrInst(
swift::StructElementAddrInst *i) {
Address base = getLoweredAddress(i->getOperand());
SILType baseType = i->getOperand()->getType();
Address field = projectPhysicalStructMemberAddress(*this, base, baseType,
i->getField());
setLoweredAddress(i, field);
}
void IRGenSILFunction::visitRefElementAddrInst(swift::RefElementAddrInst *i) {
Explosion base = getLoweredExplosion(i->getOperand());
llvm::Value *value = base.claimNext();
SILType baseTy = i->getOperand()->getType();
Address field = projectPhysicalClassMemberAddress(*this,
value,
baseTy,
i->getType(),
i->getField())
.getAddress();
setLoweredAddress(i, field);
}
void IRGenSILFunction::visitRefTailAddrInst(RefTailAddrInst *i) {
SILValue Ref = i->getOperand();
llvm::Value *RefValue = getLoweredExplosion(Ref).claimNext();
Address TailAddr = emitTailProjection(*this, RefValue, Ref->getType(),
i->getTailType());
setLoweredAddress(i, TailAddr);
}
static bool isInvariantAddress(SILValue v) {
auto root = getUnderlyingAddressRoot(v);
if (auto ptrRoot = dyn_cast<PointerToAddressInst>(root)) {
return ptrRoot->isInvariant();
}
// TODO: We could be more aggressive about considering addresses based on
// `let` variables as invariant when the type of the address is known not to
// have any sharably-mutable interior storage (in other words, no weak refs,
// atomics, etc.)
return false;
}
void IRGenSILFunction::visitLoadInst(swift::LoadInst *i) {
Explosion lowered;
Address source = getLoweredAddress(i->getOperand());
SILType objType = i->getType().getObjectType();
const auto &typeInfo = cast<LoadableTypeInfo>(getTypeInfo(objType));
switch (i->getOwnershipQualifier()) {
case LoadOwnershipQualifier::Unqualified:
case LoadOwnershipQualifier::Trivial:
case LoadOwnershipQualifier::Take:
typeInfo.loadAsTake(*this, source, lowered);
break;
case LoadOwnershipQualifier::Copy:
typeInfo.loadAsCopy(*this, source, lowered);
break;
}
if (isInvariantAddress(i->getOperand())) {
// It'd be better to push this down into `loadAs` methods, perhaps...
for (auto value : lowered.getAll())
if (auto load = dyn_cast<llvm::LoadInst>(value))
setInvariantLoad(load);
}
setLoweredExplosion(i, lowered);
}
void IRGenSILFunction::visitStoreInst(swift::StoreInst *i) {
Explosion source = getLoweredExplosion(i->getSrc());
Address dest = getLoweredAddress(i->getDest());
SILType objType = i->getSrc()->getType().getObjectType();
const auto &typeInfo = cast<LoadableTypeInfo>(getTypeInfo(objType));
switch (i->getOwnershipQualifier()) {
case StoreOwnershipQualifier::Unqualified:
case StoreOwnershipQualifier::Init:
case StoreOwnershipQualifier::Trivial:
typeInfo.initialize(*this, source, dest);
break;
case StoreOwnershipQualifier::Assign:
typeInfo.assign(*this, source, dest);
break;
}
}
/// Emit the artificial error result argument.
void IRGenSILFunction::emitErrorResultVar(SILResultInfo ErrorInfo,
DebugValueInst *DbgValue) {
// We don't need a shadow error variable for debugging on ABI's that return
// swifterror in a register.
if (IGM.IsSwiftErrorInRegister)
return;
auto ErrorResultSlot = getErrorResultSlot(IGM.silConv.getSILType(ErrorInfo));
SILDebugVariable Var = DbgValue->getVarInfo();
auto Storage = emitShadowCopy(ErrorResultSlot.getAddress(), getDebugScope(),
Var.Name, Var.ArgNo);
DebugTypeInfo DTI(nullptr, nullptr, ErrorInfo.getType(),
ErrorResultSlot->getType(), IGM.getPointerSize(),
IGM.getPointerAlignment());
IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, DTI, getDebugScope(),
nullptr, Var.Name, Var.ArgNo,
IndirectValue, ArtificialValue);
}
void IRGenSILFunction::visitDebugValueInst(DebugValueInst *i) {
if (!IGM.DebugInfo)
return;
auto SILVal = i->getOperand();
if (isa<SILUndef>(SILVal)) {
// We cannot track the location of inlined error arguments because it has no
// representation in SIL.
if (!i->getDebugScope()->InlinedCallSite &&
i->getVarInfo().Name == "$error") {
auto funcTy = CurSILFn->getLoweredFunctionType();
emitErrorResultVar(funcTy->getErrorResult(), i);
}
return;
}
StringRef Name = getVarName(i);
DebugTypeInfo DbgTy;
SILType SILTy = SILVal->getType();
auto RealTy = SILVal->getType().getSwiftRValueType();
if (VarDecl *Decl = i->getDecl()) {
DbgTy = DebugTypeInfo::getLocalVariable(
CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl,
RealTy, getTypeInfo(SILVal->getType()), /*Unwrap=*/false);
} else if (i->getFunction()->isBare() &&
!SILTy.hasArchetype() && !Name.empty()) {
// Preliminary support for .sil debug information.
DbgTy = DebugTypeInfo::getFromTypeInfo(CurSILFn->getDeclContext(),
CurSILFn->getGenericEnvironment(),
RealTy, getTypeInfo(SILTy));
} else
return;
// Put the value into a stack slot at -Onone.
llvm::SmallVector<llvm::Value *, 8> Copy;
Explosion e = getLoweredExplosion(SILVal);
unsigned ArgNo = i->getVarInfo().ArgNo;
emitShadowCopy(e.claimAll(), i->getDebugScope(), Name, ArgNo, Copy);
emitDebugVariableDeclaration(Copy, DbgTy, SILTy, i->getDebugScope(),
i->getDecl(), Name, ArgNo);
}
void IRGenSILFunction::visitDebugValueAddrInst(DebugValueAddrInst *i) {
if (!IGM.DebugInfo)
return;
VarDecl *Decl = i->getDecl();
if (!Decl)
return;
auto SILVal = i->getOperand();
if (isa<SILUndef>(SILVal))
return;
StringRef Name = getVarName(i);
auto Addr = getLoweredAddress(SILVal).getAddress();
SILType SILTy = SILVal->getType();
auto RealType = SILTy.getSwiftRValueType();
if (SILTy.isAddress())
RealType = CanInOutType::get(RealType);
// Unwrap implicitly indirect types and types that are passed by
// reference only at the SIL level and below.
//
// FIXME: Should this check if the lowered SILType is address only
// instead? Otherwise optionals of archetypes etc will still have
// 'Unwrap' set to false.
bool Unwrap =
i->getVarInfo().Constant ||
SILTy.is<ArchetypeType>();
auto DbgTy = DebugTypeInfo::getLocalVariable(
CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl,
RealType, getTypeInfo(SILVal->getType()), Unwrap);
// Put the value's address into a stack slot at -Onone and emit a debug
// intrinsic.
unsigned ArgNo = i->getVarInfo().ArgNo;
emitDebugVariableDeclaration(
emitShadowCopy(Addr, i->getDebugScope(), Name, ArgNo), DbgTy,
i->getType(), i->getDebugScope(), Decl, Name, ArgNo,
DbgTy.isImplicitlyIndirect() ? DirectValue : IndirectValue);
}
void IRGenSILFunction::visitLoadWeakInst(swift::LoadWeakInst *i) {
Address source = getLoweredAddress(i->getOperand());
auto &weakTI = cast<WeakTypeInfo>(getTypeInfo(i->getOperand()->getType()));
Explosion result;
if (i->isTake()) {
weakTI.weakTakeStrong(*this, source, result);
} else {
weakTI.weakLoadStrong(*this, source, result);
}
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitStoreWeakInst(swift::StoreWeakInst *i) {
Explosion source = getLoweredExplosion(i->getSrc());
Address dest = getLoweredAddress(i->getDest());
auto &weakTI = cast<WeakTypeInfo>(getTypeInfo(i->getDest()->getType()));
if (i->isInitializationOfDest()) {
weakTI.weakInit(*this, source, dest);
} else {
weakTI.weakAssign(*this, source, dest);
}
}
void IRGenSILFunction::visitFixLifetimeInst(swift::FixLifetimeInst *i) {
if (i->getOperand()->getType().isAddress()) {
// Just pass in the address to fix lifetime if we have one. We will not do
// anything to it so nothing bad should happen.
emitFixLifetime(getLoweredAddress(i->getOperand()).getAddress());
return;
}
// Handle objects.
Explosion in = getLoweredExplosion(i->getOperand());
cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType()))
.fixLifetime(*this, in);
}
void IRGenSILFunction::visitMarkDependenceInst(swift::MarkDependenceInst *i) {
// Dependency-marking is purely for SIL. Just forward the input as
// the result.
SILValue value = i->getValue();
if (value->getType().isAddress()) {
setLoweredAddress(i, getLoweredAddress(value));
} else {
Explosion temp = getLoweredExplosion(value);
setLoweredExplosion(i, temp);
}
}
void IRGenSILFunction::visitCopyBlockInst(CopyBlockInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
llvm::Value *copied = emitBlockCopyCall(lowered.claimNext());
Explosion result;
result.add(copied);
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitStrongPinInst(swift::StrongPinInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
llvm::Value *object = lowered.claimNext();
llvm::Value *pinHandle =
emitNativeTryPin(object, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
Explosion result;
result.add(pinHandle);
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitStrongUnpinInst(swift::StrongUnpinInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
llvm::Value *pinHandle = lowered.claimNext();
emitNativeUnpin(pinHandle, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
void IRGenSILFunction::visitStrongRetainInst(swift::StrongRetainInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
auto &ti = cast<ReferenceTypeInfo>(getTypeInfo(i->getOperand()->getType()));
ti.strongRetain(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
void IRGenSILFunction::visitStrongReleaseInst(swift::StrongReleaseInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
auto &ti = cast<ReferenceTypeInfo>(getTypeInfo(i->getOperand()->getType()));
ti.strongRelease(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
/// Given a SILType which is a ReferenceStorageType, return the type
/// info for the underlying reference type.
static const ReferenceTypeInfo &getReferentTypeInfo(IRGenFunction &IGF,
SILType silType) {
auto type = silType.castTo<ReferenceStorageType>().getReferentType();
return cast<ReferenceTypeInfo>(IGF.getTypeInfoForLowered(type));
}
void IRGenSILFunction::
visitStrongRetainUnownedInst(swift::StrongRetainUnownedInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType());
ti.strongRetainUnowned(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
void IRGenSILFunction::visitUnownedRetainInst(swift::UnownedRetainInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType());
ti.unownedRetain(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
void IRGenSILFunction::visitUnownedReleaseInst(swift::UnownedReleaseInst *i) {
Explosion lowered = getLoweredExplosion(i->getOperand());
auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType());
ti.unownedRelease(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic
: irgen::Atomicity::NonAtomic);
}
void IRGenSILFunction::visitLoadUnownedInst(swift::LoadUnownedInst *i) {
Address source = getLoweredAddress(i->getOperand());
auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType());
Explosion result;
if (i->isTake()) {
ti.unownedTakeStrong(*this, source, result);
} else {
ti.unownedLoadStrong(*this, source, result);
}
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitStoreUnownedInst(swift::StoreUnownedInst *i) {
Explosion source = getLoweredExplosion(i->getSrc());
Address dest = getLoweredAddress(i->getDest());
auto &ti = getReferentTypeInfo(*this, i->getDest()->getType());
if (i->isInitializationOfDest()) {
ti.unownedInit(*this, source, dest);
} else {
ti.unownedAssign(*this, source, dest);
}
}
static bool hasReferenceSemantics(IRGenSILFunction &IGF,
SILType silType) {
auto operType = silType.getSwiftRValueType();
auto valueType = operType->getAnyOptionalObjectType();
auto objType = valueType ? valueType : operType;
return (objType->mayHaveSuperclass()
|| objType->isClassExistentialType()
|| objType->is<BuiltinNativeObjectType>()
|| objType->is<BuiltinBridgeObjectType>()
|| objType->is<BuiltinUnknownObjectType>());
}
static llvm::Value *emitIsUnique(IRGenSILFunction &IGF, SILValue operand,
SourceLoc loc, bool checkPinned) {
if (!hasReferenceSemantics(IGF, operand->getType())) {
llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration(
&IGF.IGM.Module, llvm::Intrinsic::ID::trap);
IGF.Builder.CreateCall(trapIntrinsic, {});
return llvm::UndefValue::get(IGF.IGM.Int1Ty);
}
auto &operTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(operand->getType()));
LoadedRef ref =
operTI.loadRefcountedPtr(IGF, loc, IGF.getLoweredAddress(operand));
return
IGF.emitIsUniqueCall(ref.getValue(), loc, ref.isNonNull(), checkPinned);
}
void IRGenSILFunction::visitIsUniqueInst(swift::IsUniqueInst *i) {
llvm::Value *result = emitIsUnique(*this, i->getOperand(),
i->getLoc().getSourceLoc(), false);
Explosion out;
out.add(result);
setLoweredExplosion(i, out);
}
void IRGenSILFunction::
visitIsUniqueOrPinnedInst(swift::IsUniqueOrPinnedInst *i) {
llvm::Value *result = emitIsUnique(*this, i->getOperand(),
i->getLoc().getSourceLoc(), true);
Explosion out;
out.add(result);
setLoweredExplosion(i, out);
}
static bool tryDeferFixedSizeBufferInitialization(IRGenSILFunction &IGF,
SILInstruction *allocInst,
const TypeInfo &ti,
Address fixedSizeBuffer,
const llvm::Twine &name) {
// There's no point in doing this for fixed-sized types, since we'll allocate
// an appropriately-sized buffer for them statically.
if (ti.isFixedSize())
return false;
// TODO: More interesting dominance analysis could be done here to see
// if the alloc_stack is dominated by copy_addrs into it on all paths.
// For now, check only that the copy_addr is the first use within the same
// block.
for (auto ii = std::next(allocInst->getIterator()),
ie = std::prev(allocInst->getParent()->end());
ii != ie; ++ii) {
auto *inst = &*ii;
// Does this instruction use the allocation? If not, continue.
auto Ops = inst->getAllOperands();
if (std::none_of(Ops.begin(), Ops.end(),
[allocInst](const Operand &Op) {
return Op.get() == allocInst;
}))
continue;
// Is this a copy?
auto *copy = dyn_cast<swift::CopyAddrInst>(inst);
if (!copy)
return false;
// Destination must be the allocation.
if (copy->getDest() != SILValue(allocInst))
return false;
// Copy must be an initialization.
if (!copy->isInitializationOfDest())
return false;
// We can defer to this initialization. Allocate the fixed-size buffer
// now, but don't allocate the value inside it.
if (!fixedSizeBuffer.getAddress()) {
fixedSizeBuffer = IGF.createFixedSizeBufferAlloca(name);
IGF.Builder.CreateLifetimeStart(fixedSizeBuffer,
getFixedBufferSize(IGF.IGM));
}
IGF.setContainerOfUnallocatedAddress(allocInst, fixedSizeBuffer);
return true;
}
return false;
}
void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i,
const TypeInfo &type,
llvm::Value *addr) {
VarDecl *Decl = i->getDecl();
if (IGM.DebugInfo && Decl) {
// Ignore compiler-generated patterns but not optional bindings.
if (auto *Pattern = Decl->getParentPattern())
if (Pattern->isImplicit() &&
Pattern->getKind() != PatternKind::OptionalSome)
return;
SILType SILTy = i->getType();
auto RealType = SILTy.getSwiftRValueType();
auto DbgTy = DebugTypeInfo::getLocalVariable(
CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl,
RealType, type, false);
StringRef Name = getVarName(i);
if (auto DS = i->getDebugScope())
emitDebugVariableDeclaration(addr, DbgTy, SILTy, DS, Decl, Name,
i->getVarInfo().ArgNo);
}
}
void IRGenSILFunction::visitAllocStackInst(swift::AllocStackInst *i) {
const TypeInfo &type = getTypeInfo(i->getElementType());
// Derive name from SIL location.
VarDecl *Decl = i->getDecl();
StringRef dbgname;
# ifndef NDEBUG
// If this is a DEBUG build, use pretty names for the LLVM IR.
dbgname = getVarName(i);
# endif
(void) Decl;
bool isEntryBlock =
i->getParentBlock() == i->getFunction()->getEntryBlock();
auto addr =
type.allocateStack(*this, i->getElementType(), isEntryBlock, dbgname);
emitDebugInfoForAllocStack(i, type, addr.getAddress().getAddress());
setLoweredStackAddress(i, addr);
}
static void
buildTailArrays(IRGenSILFunction &IGF,
SmallVectorImpl<std::pair<SILType, llvm::Value *>> &TailArrays,
AllocRefInstBase *ARI) {
auto Types = ARI->getTailAllocatedTypes();
auto Counts = ARI->getTailAllocatedCounts();
for (unsigned Idx = 0, NumTypes = Types.size(); Idx < NumTypes; ++Idx) {
Explosion ElemCount = IGF.getLoweredExplosion(Counts[Idx].get());
TailArrays.push_back({Types[Idx], ElemCount.claimNext()});
}
}
void IRGenSILFunction::visitAllocRefInst(swift::AllocRefInst *i) {
int StackAllocSize = -1;
if (i->canAllocOnStack()) {
estimateStackSize();
// Is there enough space for stack allocation?
StackAllocSize = IGM.IRGen.Opts.StackPromotionSizeLimit - EstimatedStackSize;
}
SmallVector<std::pair<SILType, llvm::Value *>, 4> TailArrays;
buildTailArrays(*this, TailArrays, i);
llvm::Value *alloced = emitClassAllocation(*this, i->getType(), i->isObjC(),
StackAllocSize, TailArrays);
if (StackAllocSize >= 0) {
// Remember that this alloc_ref allocates the object on the stack.
StackAllocs.insert(i);
EstimatedStackSize += StackAllocSize;
}
Explosion e;
e.add(alloced);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitAllocRefDynamicInst(swift::AllocRefDynamicInst *i) {
SmallVector<std::pair<SILType, llvm::Value *>, 4> TailArrays;
buildTailArrays(*this, TailArrays, i);
Explosion metadata = getLoweredExplosion(i->getMetatypeOperand());
auto metadataValue = metadata.claimNext();
llvm::Value *alloced = emitClassAllocationDynamic(*this, metadataValue,
i->getType(), i->isObjC(),
TailArrays);
Explosion e;
e.add(alloced);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitDeallocStackInst(swift::DeallocStackInst *i) {
auto allocatedType = i->getOperand()->getType();
const TypeInfo &allocatedTI = getTypeInfo(allocatedType);
StackAddress stackAddr = getLoweredStackAddress(i->getOperand());
allocatedTI.deallocateStack(*this, stackAddr, allocatedType);
}
void IRGenSILFunction::visitDeallocRefInst(swift::DeallocRefInst *i) {
// Lower the operand.
Explosion self = getLoweredExplosion(i->getOperand());
auto selfValue = self.claimNext();
auto *ARI = dyn_cast<AllocRefInst>(i->getOperand());
if (!i->canAllocOnStack()) {
if (ARI && StackAllocs.count(ARI)) {
// We can ignore dealloc_refs (without [stack]) for stack allocated
// objects.
//
// %0 = alloc_ref [stack]
// ...
// dealloc_ref %0 // not needed (stems from the inlined deallocator)
// ...
// dealloc_ref [stack] %0
return;
}
auto classType = i->getOperand()->getType();
emitClassDeallocation(*this, classType, selfValue);
return;
}
// It's a dealloc_ref [stack]. Even if the alloc_ref did not allocate the
// object on the stack, we don't have to deallocate it, because it is
// deallocated in the final release.
assert(ARI->canAllocOnStack());
if (StackAllocs.count(ARI)) {
if (IGM.IRGen.Opts.EmitStackPromotionChecks) {
selfValue = Builder.CreateBitCast(selfValue, IGM.RefCountedPtrTy);
emitVerifyEndOfLifetimeCall(selfValue);
} else {
// This has two purposes:
// 1. Tell LLVM the lifetime of the allocated stack memory.
// 2. Avoid tail-call optimization which may convert the call to the final
// release to a jump, which is done after the stack frame is
// destructed.
Builder.CreateLifetimeEnd(selfValue);
}
}
}
void IRGenSILFunction::visitDeallocPartialRefInst(swift::DeallocPartialRefInst *i) {
Explosion self = getLoweredExplosion(i->getInstance());
auto selfValue = self.claimNext();
Explosion metadata = getLoweredExplosion(i->getMetatype());
auto metadataValue = metadata.claimNext();
auto classType = i->getInstance()->getType();
emitPartialClassDeallocation(*this, classType, selfValue, metadataValue);
}
void IRGenSILFunction::visitDeallocBoxInst(swift::DeallocBoxInst *i) {
Explosion owner = getLoweredExplosion(i->getOperand());
llvm::Value *ownerPtr = owner.claimNext();
auto boxTy = i->getOperand()->getType().castTo<SILBoxType>();
emitDeallocateBox(*this, ownerPtr, boxTy);
}
void IRGenSILFunction::visitAllocBoxInst(swift::AllocBoxInst *i) {
assert(i->getBoxType()->getLayout()->getFields().size() == 1
&& "multi field boxes not implemented yet");
const TypeInfo &type = getTypeInfo(i->getBoxType()
->getFieldType(IGM.getSILModule(), 0));
// Derive name from SIL location.
VarDecl *Decl = i->getDecl();
StringRef Name = getVarName(i);
StringRef DbgName =
# ifndef NDEBUG
// If this is a DEBUG build, use pretty names for the LLVM IR.
Name;
# else
"";
# endif
auto boxTy = i->getType().castTo<SILBoxType>();
OwnedAddress boxWithAddr = emitAllocateBox(*this, boxTy,
CurSILFn->getGenericEnvironment(),
DbgName);
setLoweredBox(i, boxWithAddr);
if (IGM.DebugInfo && Decl) {
// FIXME: This is a workaround to not produce local variables for
// capture list arguments like "[weak self]". The better solution
// would be to require all variables to be described with a
// SILDebugValue(Addr) and then not describe capture list
// arguments.
if (Name == IGM.Context.Id_self.str())
return;
assert(i->getBoxType()->getLayout()->getFields().size() == 1
&& "box for a local variable should only have one field");
auto SILTy = i->getBoxType()->getFieldType(IGM.getSILModule(), 0);
auto RealType = SILTy.getSwiftRValueType();
if (SILTy.isAddress())
RealType = CanInOutType::get(RealType);
auto DbgTy = DebugTypeInfo::getLocalVariable(
CurSILFn->getDeclContext(), CurSILFn->getGenericEnvironment(), Decl,
RealType, type, /*Unwrap=*/false);
if (isInlinedGeneric(Decl, i->getDebugScope()))
return;
IGM.DebugInfo->emitVariableDeclaration(
Builder,
emitShadowCopy(boxWithAddr.getAddress(), i->getDebugScope(), Name, 0),
DbgTy, i->getDebugScope(), Decl, Name, 0,
DbgTy.isImplicitlyIndirect() ? DirectValue : IndirectValue);
}
}
void IRGenSILFunction::visitProjectBoxInst(swift::ProjectBoxInst *i) {
auto boxTy = i->getOperand()->getType().castTo<SILBoxType>();
const LoweredValue &val = getLoweredValue(i->getOperand());
if (val.isBoxWithAddress()) {
// The operand is an alloc_box. We can directly reuse the address.
setLoweredAddress(i, val.getAddressOfBox());
} else {
// The slow-path: we have to emit code to get from the box to it's
// value address.
Explosion box = val.getExplosion(*this);
auto addr = emitProjectBox(*this, box.claimNext(), boxTy);
setLoweredAddress(i, addr);
}
}
static void emitBeginAccess(IRGenSILFunction &IGF, BeginAccessInst *access,
Address addr) {
switch (access->getEnforcement()) {
case SILAccessEnforcement::Unknown:
llvm_unreachable("unknown access enforcement in IRGen!");
case SILAccessEnforcement::Static:
case SILAccessEnforcement::Unsafe:
// nothing to do
return;
case SILAccessEnforcement::Dynamic:
// TODO
return;
}
llvm_unreachable("bad access enforcement");
}
static void emitEndAccess(IRGenSILFunction &IGF, BeginAccessInst *access) {
switch (access->getEnforcement()) {
case SILAccessEnforcement::Unknown:
llvm_unreachable("unknown access enforcement in IRGen!");
case SILAccessEnforcement::Static:
case SILAccessEnforcement::Unsafe:
// nothing to do
return;
case SILAccessEnforcement::Dynamic:
// TODO
return;
}
llvm_unreachable("bad access enforcement");
}
void IRGenSILFunction::visitBeginAccessInst(BeginAccessInst *i) {
Address addr = getLoweredAddress(i->getOperand());
emitBeginAccess(*this, i, addr);
setLoweredAddress(i, addr);
}
void IRGenSILFunction::visitEndAccessInst(EndAccessInst *i) {
emitEndAccess(*this, i->getBeginAccess());
}
void IRGenSILFunction::visitConvertFunctionInst(swift::ConvertFunctionInst *i) {
// This instruction is specified to be a no-op.
Explosion temp = getLoweredExplosion(i->getOperand());
setLoweredExplosion(i, temp);
}
void IRGenSILFunction::visitThinFunctionToPointerInst(
swift::ThinFunctionToPointerInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
llvm::Value *fn = in.claimNext();
fn = Builder.CreateBitCast(fn, IGM.Int8PtrTy);
Explosion out;
out.add(fn);
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitPointerToThinFunctionInst(
swift::PointerToThinFunctionInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
llvm::Value *fn = in.claimNext();
fn = Builder.CreateBitCast(fn, IGM.FunctionPtrTy);
Explosion out;
out.add(fn);
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitAddressToPointerInst(swift::AddressToPointerInst *i)
{
Explosion to;
llvm::Value *addrValue = getLoweredAddress(i->getOperand()).getAddress();
if (addrValue->getType() != IGM.Int8PtrTy)
addrValue = Builder.CreateBitCast(addrValue, IGM.Int8PtrTy);
to.add(addrValue);
setLoweredExplosion(i, to);
}
// Ignores the isStrict flag because Swift TBAA is not lowered into LLVM IR.
void IRGenSILFunction::visitPointerToAddressInst(swift::PointerToAddressInst *i)
{
Explosion from = getLoweredExplosion(i->getOperand());
llvm::Value *ptrValue = from.claimNext();
auto &ti = getTypeInfo(i->getType());
llvm::Type *destType = ti.getStorageType()->getPointerTo();
ptrValue = Builder.CreateBitCast(ptrValue, destType);
setLoweredAddress(i,
ti.getAddressForPointer(ptrValue));
}
static void emitPointerCastInst(IRGenSILFunction &IGF,
SILValue src,
SILValue dest,
const TypeInfo &ti) {
Explosion from = IGF.getLoweredExplosion(src);
llvm::Value *ptrValue = from.claimNext();
// The input may have witness tables or other additional data, but the class
// reference is always first.
(void)from.claimAll();
auto schema = ti.getSchema();
assert(schema.size() == 1
&& schema[0].isScalar()
&& "pointer schema is not a single scalar?!");
auto castToType = schema[0].getScalarType();
// A retainable pointer representation may be wrapped in an optional, so we
// need to provide inttoptr/ptrtoint in addition to bitcast.
ptrValue = IGF.Builder.CreateBitOrPointerCast(ptrValue, castToType);
Explosion to;
to.add(ptrValue);
IGF.setLoweredExplosion(dest, to);
}
void IRGenSILFunction::visitUncheckedRefCastInst(
swift::UncheckedRefCastInst *i) {
auto &ti = getTypeInfo(i->getType());
emitPointerCastInst(*this, i->getOperand(), i, ti);
}
// TODO: Although runtime checks are not required, we get them anyway when
// asking the runtime to perform this cast. If this is a performance impact, we
// can add a CheckedCastMode::Unchecked.
void IRGenSILFunction::
visitUncheckedRefCastAddrInst(swift::UncheckedRefCastAddrInst *i) {
Address dest = getLoweredAddress(i->getDest());
Address src = getLoweredAddress(i->getSrc());
emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(),
i->getConsumptionKind(), CheckedCastMode::Unconditional);
}
void IRGenSILFunction::visitUncheckedAddrCastInst(
swift::UncheckedAddrCastInst *i) {
auto addr = getLoweredAddress(i->getOperand());
auto &ti = getTypeInfo(i->getType());
auto result = Builder.CreateBitCast(addr,ti.getStorageType()->getPointerTo());
setLoweredAddress(i, result);
}
static bool isStructurallySame(const llvm::Type *T1, const llvm::Type *T2) {
if (T1 == T2) return true;
if (auto *S1 = dyn_cast<llvm::StructType>(T1))
if (auto *S2 = dyn_cast<llvm::StructType>(T2))
return S1->isLayoutIdentical(const_cast<llvm::StructType*>(S2));
return false;
}
// Emit a trap in the event a type does not match expected layout constraints.
//
// We can hit this case in specialized functions even for correct user code.
// If the user dynamically checks for correct type sizes in the generic
// function, a specialized function can contain the (not executed) bitcast
// with mismatching fixed sizes.
// Usually llvm can eliminate this code again because the user's safety
// check should be constant foldable on llvm level.
static void emitTrapAndUndefValue(IRGenSILFunction &IGF,
Explosion &in,
Explosion &out,
const LoadableTypeInfo &outTI) {
llvm::BasicBlock *failBB =
llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
IGF.Builder.CreateBr(failBB);
IGF.FailBBs.push_back(failBB);
IGF.Builder.emitBlock(failBB);
llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration(
&IGF.IGM.Module, llvm::Intrinsic::ID::trap);
IGF.Builder.CreateCall(trapIntrinsic, {});
IGF.Builder.CreateUnreachable();
llvm::BasicBlock *contBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
IGF.Builder.emitBlock(contBB);
(void)in.claimAll();
for (auto schema : outTI.getSchema())
out.add(llvm::UndefValue::get(schema.getScalarType()));
}
static void emitUncheckedValueBitCast(IRGenSILFunction &IGF,
SourceLoc loc,
Explosion &in,
const LoadableTypeInfo &inTI,
Explosion &out,
const LoadableTypeInfo &outTI) {
// If the transfer is doable bitwise, and if the elements of the explosion are
// the same type, then just transfer the elements.
if (inTI.isBitwiseTakable(ResilienceExpansion::Maximal) &&
outTI.isBitwiseTakable(ResilienceExpansion::Maximal) &&
isStructurallySame(inTI.getStorageType(), outTI.getStorageType())) {
in.transferInto(out, in.size());
return;
}
// TODO: We could do bitcasts entirely in the value domain in some cases, but
// for simplicity, let's just always go through the stack for now.
// Create the allocation.
auto inStorage = IGF.createAlloca(inTI.getStorageType(),
std::max(inTI.getFixedAlignment(),
outTI.getFixedAlignment()),
"bitcast");
auto maxSize = std::max(inTI.getFixedSize(), outTI.getFixedSize());
IGF.Builder.CreateLifetimeStart(inStorage, maxSize);
// Store the 'in' value.
inTI.initialize(IGF, in, inStorage);
// Load the 'out' value as the destination type.
auto outStorage = IGF.Builder.CreateBitCast(inStorage,
outTI.getStorageType()->getPointerTo());
outTI.loadAsTake(IGF, outStorage, out);
IGF.Builder.CreateLifetimeEnd(inStorage, maxSize);
return;
}
static void emitValueBitwiseCast(IRGenSILFunction &IGF,
SourceLoc loc,
Explosion &in,
const LoadableTypeInfo &inTI,
Explosion &out,
const LoadableTypeInfo &outTI) {
// Unfortunately, we can't check this invariant until we get to IRGen, since
// the AST and SIL don't know anything about type layout.
if (inTI.getFixedSize() < outTI.getFixedSize()) {
emitTrapAndUndefValue(IGF, in, out, outTI);
return;
}
emitUncheckedValueBitCast(IGF, loc, in, inTI, out, outTI);
}
void IRGenSILFunction::visitUncheckedTrivialBitCastInst(
swift::UncheckedTrivialBitCastInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
Explosion out;
emitValueBitwiseCast(*this, i->getLoc().getSourceLoc(),
in, cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())),
out, cast<LoadableTypeInfo>(getTypeInfo(i->getType())));
setLoweredExplosion(i, out);
}
void IRGenSILFunction::
visitUncheckedBitwiseCastInst(swift::UncheckedBitwiseCastInst *i) {
Explosion in = getLoweredExplosion(i->getOperand());
Explosion out;
emitValueBitwiseCast(*this, i->getLoc().getSourceLoc(),
in, cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())),
out, cast<LoadableTypeInfo>(getTypeInfo(i->getType())));
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitRefToRawPointerInst(
swift::RefToRawPointerInst *i) {
auto &ti = getTypeInfo(i->getType());
emitPointerCastInst(*this, i->getOperand(), i, ti);
}
void IRGenSILFunction::visitRawPointerToRefInst(swift::RawPointerToRefInst *i) {
auto &ti = getTypeInfo(i->getType());
emitPointerCastInst(*this, i->getOperand(), i, ti);
}
// SIL scalar conversions which never change the IR type.
// FIXME: Except for optionals, which get bit-packed into an integer.
static void trivialRefConversion(IRGenSILFunction &IGF,
SILValue input,
SILValue result) {
Explosion temp = IGF.getLoweredExplosion(input);
auto &inputTI = IGF.getTypeInfo(input->getType());
auto &resultTI = IGF.getTypeInfo(result->getType());
// If the types are the same, forward the existing value.
if (inputTI.getStorageType() == resultTI.getStorageType()) {
IGF.setLoweredExplosion(result, temp);
return;
}
auto schema = resultTI.getSchema();
Explosion out;
for (auto schemaElt : schema) {
auto resultTy = schemaElt.getScalarType();
llvm::Value *value = temp.claimNext();
if (value->getType() == resultTy) {
// Nothing to do. This happens with the unowned conversions.
} else if (resultTy->isPointerTy()) {
value = IGF.Builder.CreateIntToPtr(value, resultTy);
} else {
value = IGF.Builder.CreatePtrToInt(value, resultTy);
}
out.add(value);
}
IGF.setLoweredExplosion(result, out);
}
// SIL scalar conversions which never change the IR type.
// FIXME: Except for optionals, which get bit-packed into an integer.
#define NOOP_CONVERSION(KIND) \
void IRGenSILFunction::visit##KIND##Inst(swift::KIND##Inst *i) { \
::trivialRefConversion(*this, i->getOperand(), i); \
}
NOOP_CONVERSION(UnownedToRef)
NOOP_CONVERSION(RefToUnowned)
NOOP_CONVERSION(UnmanagedToRef)
NOOP_CONVERSION(RefToUnmanaged)
#undef NOOP_CONVERSION
void IRGenSILFunction::visitThinToThickFunctionInst(
swift::ThinToThickFunctionInst *i) {
// Take the incoming function pointer and add a null context pointer to it.
Explosion from = getLoweredExplosion(i->getOperand());
Explosion to;
to.add(from.claimNext());
to.add(IGM.RefCountedNull);
setLoweredExplosion(i, to);
}
void IRGenSILFunction::visitThickToObjCMetatypeInst(ThickToObjCMetatypeInst *i){
Explosion from = getLoweredExplosion(i->getOperand());
llvm::Value *swiftMeta = from.claimNext();
CanType instanceType(i->getType().castTo<AnyMetatypeType>().getInstanceType());
Explosion to;
llvm::Value *classPtr =
emitClassHeapMetadataRefForMetatype(*this, swiftMeta, instanceType);
to.add(Builder.CreateBitCast(classPtr, IGM.ObjCClassPtrTy));
setLoweredExplosion(i, to);
}
void IRGenSILFunction::visitObjCToThickMetatypeInst(
ObjCToThickMetatypeInst *i) {
Explosion from = getLoweredExplosion(i->getOperand());
llvm::Value *classPtr = from.claimNext();
// Fetch the metadata for that class.
Explosion to;
auto metadata = emitObjCMetadataRefForMetadata(*this, classPtr);
to.add(metadata);
setLoweredExplosion(i, to);
}
void IRGenSILFunction::visitUnconditionalCheckedCastInst(
swift::UnconditionalCheckedCastInst *i) {
Explosion value = getLoweredExplosion(i->getOperand());
Explosion ex;
emitScalarCheckedCast(*this, value, i->getOperand()->getType(), i->getType(),
CheckedCastMode::Unconditional, ex);
setLoweredExplosion(i, ex);
}
void IRGenSILFunction::visitObjCMetatypeToObjectInst(
ObjCMetatypeToObjectInst *i){
// Bitcast the @objc metatype reference, which is already an ObjC object, to
// the destination type.
Explosion from = getLoweredExplosion(i->getOperand());
llvm::Value *value = from.claimNext();
value = Builder.CreateBitCast(value, IGM.UnknownRefCountedPtrTy);
Explosion to;
to.add(value);
setLoweredExplosion(i, to);
}
void IRGenSILFunction::visitObjCExistentialMetatypeToObjectInst(
ObjCExistentialMetatypeToObjectInst *i){
// Bitcast the @objc metatype reference, which is already an ObjC object, to
// the destination type. The metatype may carry additional witness tables we
// can drop.
Explosion from = getLoweredExplosion(i->getOperand());
llvm::Value *value = from.claimNext();
(void)from.claimAll();
value = Builder.CreateBitCast(value, IGM.UnknownRefCountedPtrTy);
Explosion to;
to.add(value);
setLoweredExplosion(i, to);
}
void IRGenSILFunction::visitObjCProtocolInst(ObjCProtocolInst *i) {
// Get the protocol reference.
llvm::Value *protoRef = emitReferenceToObjCProtocol(*this, i->getProtocol());
// Bitcast it to the class reference type.
protoRef = Builder.CreateBitCast(protoRef,
getTypeInfo(i->getType()).getStorageType());
Explosion ex;
ex.add(protoRef);
setLoweredExplosion(i, ex);
}
void IRGenSILFunction::visitRefToBridgeObjectInst(
swift::RefToBridgeObjectInst *i) {
Explosion refEx = getLoweredExplosion(i->getConverted());
llvm::Value *ref = refEx.claimNext();
Explosion bitsEx = getLoweredExplosion(i->getBitsOperand());
llvm::Value *bits = bitsEx.claimNext();
// Mask the bits into the pointer representation.
llvm::Value *val = Builder.CreatePtrToInt(ref, IGM.SizeTy);
val = Builder.CreateOr(val, bits);
val = Builder.CreateIntToPtr(val, IGM.BridgeObjectPtrTy);
Explosion resultEx;
resultEx.add(val);
setLoweredExplosion(i, resultEx);
}
void IRGenSILFunction::visitBridgeObjectToRefInst(
swift::BridgeObjectToRefInst *i) {
Explosion boEx = getLoweredExplosion(i->getConverted());
llvm::Value *bo = boEx.claimNext();
Explosion resultEx;
auto &refTI = getTypeInfo(i->getType());
llvm::Type *refType = refTI.getSchema()[0].getScalarType();
// If the value is an ObjC tagged pointer, pass it through verbatim.
llvm::BasicBlock *taggedCont = nullptr,
*tagged = nullptr,
*notTagged = nullptr;
llvm::Value *taggedRef = nullptr;
llvm::Value *boBits = nullptr;
ClassDecl *Cl = i->getType().getClassOrBoundGenericClass();
if (IGM.TargetInfo.hasObjCTaggedPointers() &&
(!Cl || !isKnownNotTaggedPointer(IGM, Cl))) {
boBits = Builder.CreatePtrToInt(bo, IGM.SizeTy);
APInt maskValue = IGM.TargetInfo.ObjCPointerReservedBits.asAPInt();
llvm::Value *mask = llvm::ConstantInt::get(IGM.getLLVMContext(), maskValue);
llvm::Value *reserved = Builder.CreateAnd(boBits, mask);
llvm::Value *cond = Builder.CreateICmpEQ(reserved,
llvm::ConstantInt::get(IGM.SizeTy, 0));
tagged = createBasicBlock("tagged-pointer"),
notTagged = createBasicBlock("not-tagged-pointer");
taggedCont = createBasicBlock("tagged-cont");
Builder.CreateCondBr(cond, notTagged, tagged);
Builder.emitBlock(tagged);
taggedRef = Builder.CreateBitCast(bo, refType);
Builder.CreateBr(taggedCont);
// If it's not a tagged pointer, mask off the spare bits.
Builder.emitBlock(notTagged);
}
// Mask off the spare bits (if they exist).
auto &spareBits = IGM.getHeapObjectSpareBits();
llvm::Value *result;
if (spareBits.any()) {
APInt maskValue = ~spareBits.asAPInt();
if (!boBits)
boBits = Builder.CreatePtrToInt(bo, IGM.SizeTy);
llvm::Value *mask = llvm::ConstantInt::get(IGM.getLLVMContext(), maskValue);
llvm::Value *masked = Builder.CreateAnd(boBits, mask);
result = Builder.CreateIntToPtr(masked, refType);
} else {
result = Builder.CreateBitCast(bo, refType);
}
if (taggedCont) {
Builder.CreateBr(taggedCont);
Builder.emitBlock(taggedCont);
auto phi = Builder.CreatePHI(refType, 2);
phi->addIncoming(taggedRef, tagged);
phi->addIncoming(result, notTagged);
result = phi;
}
resultEx.add(result);
setLoweredExplosion(i, resultEx);
}
void IRGenSILFunction::visitBridgeObjectToWordInst(
swift::BridgeObjectToWordInst *i) {
Explosion boEx = getLoweredExplosion(i->getConverted());
llvm::Value *val = boEx.claimNext();
val = Builder.CreatePtrToInt(val, IGM.SizeTy);
Explosion wordEx;
wordEx.add(val);
setLoweredExplosion(i, wordEx);
}
void IRGenSILFunction::visitUnconditionalCheckedCastAddrInst(
swift::UnconditionalCheckedCastAddrInst *i) {
Address dest = getLoweredAddress(i->getDest());
Address src = getLoweredAddress(i->getSrc());
emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(),
i->getConsumptionKind(), CheckedCastMode::Unconditional);
}
void IRGenSILFunction::visitUnconditionalCheckedCastValueInst(
swift::UnconditionalCheckedCastValueInst *i) {
llvm_unreachable("unsupported instruction during IRGen");
}
void IRGenSILFunction::visitCheckedCastValueBranchInst(
swift::CheckedCastValueBranchInst *i) {
llvm_unreachable("unsupported instruction during IRGen");
}
void IRGenSILFunction::visitCheckedCastBranchInst(
swift::CheckedCastBranchInst *i) {
SILType destTy = i->getCastType();
FailableCastResult castResult;
Explosion ex;
if (i->isExact()) {
auto operand = i->getOperand();
Explosion source = getLoweredExplosion(operand);
castResult = emitClassIdenticalCast(*this, source.claimNext(),
operand->getType(), destTy);
} else {
Explosion value = getLoweredExplosion(i->getOperand());
emitScalarCheckedCast(*this, value, i->getOperand()->getType(),
i->getCastType(), CheckedCastMode::Conditional, ex);
auto val = ex.claimNext();
castResult.casted = val;
llvm::Value *nil =
llvm::ConstantPointerNull::get(cast<llvm::PointerType>(val->getType()));
castResult.succeeded = Builder.CreateICmpNE(val, nil);
}
// Branch on the success of the cast.
// All cast operations currently return null on failure.
auto &successBB = getLoweredBB(i->getSuccessBB());
llvm::Type *toTy = IGM.getTypeInfo(destTy).getStorageType();
if (toTy->isPointerTy())
castResult.casted = Builder.CreateBitCast(castResult.casted, toTy);
Builder.CreateCondBr(castResult.succeeded,
successBB.bb,
getLoweredBB(i->getFailureBB()).bb);
// Feed the cast result into the nonnull branch.
unsigned phiIndex = 0;
Explosion ex2;
ex2.add(castResult.casted);
ex2.add(ex.claimAll());
addIncomingExplosionToPHINodes(*this, successBB, phiIndex, ex2);
}
void IRGenSILFunction::visitCheckedCastAddrBranchInst(
swift::CheckedCastAddrBranchInst *i) {
Address dest = getLoweredAddress(i->getDest());
Address src = getLoweredAddress(i->getSrc());
llvm::Value *castSucceeded =
emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(),
i->getConsumptionKind(), CheckedCastMode::Conditional);
Builder.CreateCondBr(castSucceeded,
getLoweredBB(i->getSuccessBB()).bb,
getLoweredBB(i->getFailureBB()).bb);
}
void IRGenSILFunction::visitIsNonnullInst(swift::IsNonnullInst *i) {
// Get the value we're testing, which may be a function, an address or an
// instance pointer.
llvm::Value *val;
const LoweredValue &lv = getLoweredValue(i->getOperand());
if (i->getOperand()->getType().is<SILFunctionType>()) {
Explosion values = lv.getExplosion(*this);
val = values.claimNext(); // Function pointer.
values.claimNext(); // Ignore the data pointer.
} else if (lv.isAddress()) {
val = lv.getAddress().getAddress();
} else {
Explosion values = lv.getExplosion(*this);
val = values.claimNext();
}
// Check that the result isn't null.
auto *valTy = cast<llvm::PointerType>(val->getType());
llvm::Value *result = Builder.CreateICmp(llvm::CmpInst::ICMP_NE,
val, llvm::ConstantPointerNull::get(valTy));
Explosion out;
out.add(result);
setLoweredExplosion(i, out);
}
void IRGenSILFunction::visitUpcastInst(swift::UpcastInst *i) {
auto toTy = getTypeInfo(i->getType()).getSchema()[0].getScalarType();
// If we have an address, just bitcast, don't explode.
if (i->getOperand()->getType().isAddress()) {
Address fromAddr = getLoweredAddress(i->getOperand());
llvm::Value *toValue = Builder.CreateBitCast(
fromAddr.getAddress(), toTy->getPointerTo());
Address Addr(toValue, fromAddr.getAlignment());
setLoweredAddress(i, Addr);
return;
}
Explosion from = getLoweredExplosion(i->getOperand());
Explosion to;
assert(from.size() == 1 && "class should explode to single value");
llvm::Value *fromValue = from.claimNext();
to.add(Builder.CreateBitCast(fromValue, toTy));
setLoweredExplosion(i, to);
}
void IRGenSILFunction::visitIndexAddrInst(swift::IndexAddrInst *i) {
Address base = getLoweredAddress(i->getBase());
Explosion indexValues = getLoweredExplosion(i->getIndex());
llvm::Value *index = indexValues.claimNext();
auto baseTy = i->getBase()->getType();
auto &ti = getTypeInfo(baseTy);
Address dest = ti.indexArray(*this, base, index, baseTy);
setLoweredAddress(i, dest);
}
void IRGenSILFunction::visitTailAddrInst(swift::TailAddrInst *i) {
Address base = getLoweredAddress(i->getBase());
Explosion indexValues = getLoweredExplosion(i->getIndex());
llvm::Value *index = indexValues.claimNext();
SILType baseTy = i->getBase()->getType();
const TypeInfo &baseTI = getTypeInfo(baseTy);
Address dest = baseTI.indexArray(*this, base, index, baseTy);
const TypeInfo &TailTI = getTypeInfo(i->getTailType());
dest = TailTI.roundUpToTypeAlignment(*this, dest, i->getTailType());
llvm::Type *destType = TailTI.getStorageType()->getPointerTo();
dest = Builder.CreateBitCast(dest, destType);
setLoweredAddress(i, dest);
}
void IRGenSILFunction::visitIndexRawPointerInst(swift::IndexRawPointerInst *i) {
Explosion baseValues = getLoweredExplosion(i->getBase());
llvm::Value *base = baseValues.claimNext();
Explosion indexValues = getLoweredExplosion(i->getIndex());
llvm::Value *index = indexValues.claimNext();
// We don't expose a non-inbounds GEP operation.
llvm::Value *destValue = Builder.CreateInBoundsGEP(base, index);
Explosion result;
result.add(destValue);
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitAllocValueBufferInst(
swift::AllocValueBufferInst *i) {
Address buffer = getLoweredAddress(i->getOperand());
auto valueType = i->getValueType();
Address value;
if (getSILModule().getOptions().UseCOWExistentials) {
value = emitAllocateValueInBuffer(*this, valueType, buffer);
} else {
value = getTypeInfo(valueType).allocateBuffer(*this, buffer, valueType);
}
setLoweredAddress(i, value);
}
void IRGenSILFunction::visitProjectValueBufferInst(
swift::ProjectValueBufferInst *i) {
Address buffer = getLoweredAddress(i->getOperand());
auto valueType = i->getValueType();
Address value;
if (getSILModule().getOptions().UseCOWExistentials) {
value = emitProjectValueInBuffer(*this, valueType, buffer);
} else {
value = getTypeInfo(valueType).projectBuffer(*this, buffer, valueType);
}
setLoweredAddress(i, value);
}
void IRGenSILFunction::visitDeallocValueBufferInst(
swift::DeallocValueBufferInst *i) {
Address buffer = getLoweredAddress(i->getOperand());
auto valueType = i->getValueType();
if (getSILModule().getOptions().UseCOWExistentials) {
emitDeallocateValueInBuffer(*this, valueType, buffer);
return;
}
getTypeInfo(valueType).deallocateBuffer(*this, buffer, valueType);
}
void IRGenSILFunction::visitInitExistentialAddrInst(swift::InitExistentialAddrInst *i) {
Address container = getLoweredAddress(i->getOperand());
SILType destType = i->getOperand()->getType();
Address buffer = emitOpaqueExistentialContainerInit(*this,
container,
destType,
i->getFormalConcreteType(),
i->getLoweredConcreteType(),
i->getConformances());
auto srcType = i->getLoweredConcreteType();
auto &srcTI = getTypeInfo(srcType);
// Allocate a COW box for the value if necessary.
if (getSILModule().getOptions().UseCOWExistentials) {
auto *genericEnv = CurSILFn->getGenericEnvironment();
setLoweredAddress(i, emitAllocateBoxedOpaqueExistentialBuffer(
*this, destType, srcType, container, genericEnv));
return;
}
// See if we can defer initialization of the buffer to a copy_addr into it.
if (tryDeferFixedSizeBufferInitialization(*this, i, srcTI, buffer, ""))
return;
// Allocate in the destination fixed-size buffer.
Address address = srcTI.allocateBuffer(*this, buffer, srcType);
setLoweredAddress(i, address);
}
void IRGenSILFunction::visitInitExistentialOpaqueInst(
swift::InitExistentialOpaqueInst *i) {
llvm_unreachable("unsupported instruction during IRGen");
}
void IRGenSILFunction::visitInitExistentialMetatypeInst(
InitExistentialMetatypeInst *i) {
Explosion metatype = getLoweredExplosion(i->getOperand());
Explosion result;
emitExistentialMetatypeContainer(*this,
result, i->getType(),
metatype.claimNext(),
i->getOperand()->getType(),
i->getConformances());
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitInitExistentialRefInst(InitExistentialRefInst *i) {
Explosion instance = getLoweredExplosion(i->getOperand());
Explosion result;
emitClassExistentialContainer(*this,
result, i->getType(),
instance.claimNext(),
i->getFormalConcreteType(),
i->getOperand()->getType(),
i->getConformances());
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitDeinitExistentialAddrInst(
swift::DeinitExistentialAddrInst *i) {
Address container = getLoweredAddress(i->getOperand());
// Deallocate the COW box for the value if necessary.
if (getSILModule().getOptions().UseCOWExistentials) {
emitDeallocateBoxedOpaqueExistentialBuffer(
*this, i->getOperand()->getType(), container);
return;
}
emitOpaqueExistentialContainerDeinit(*this, container,
i->getOperand()->getType());
}
void IRGenSILFunction::visitDeinitExistentialOpaqueInst(
swift::DeinitExistentialOpaqueInst *i) {
llvm_unreachable("unsupported instruction during IRGen");
}
void IRGenSILFunction::visitOpenExistentialAddrInst(OpenExistentialAddrInst *i) {
SILType baseTy = i->getOperand()->getType();
Address base = getLoweredAddress(i->getOperand());
auto openedArchetype = cast<ArchetypeType>(
i->getType().getSwiftRValueType());
// Insert a copy of the boxed value for COW semantics if necessary.
if (getSILModule().getOptions().UseCOWExistentials) {
auto accessKind = i->getAccessKind();
Address object = emitOpaqueBoxedExistentialProjection(
*this, accessKind, base, baseTy, openedArchetype);
setLoweredAddress(i, object);
return;
}
Address object = emitOpaqueExistentialProjection(*this, base, baseTy,
openedArchetype);
setLoweredAddress(i, object);
}
void IRGenSILFunction::visitOpenExistentialRefInst(OpenExistentialRefInst *i) {
SILType baseTy = i->getOperand()->getType();
Explosion base = getLoweredExplosion(i->getOperand());
auto openedArchetype = cast<ArchetypeType>(
i->getType().getSwiftRValueType());
Explosion result;
llvm::Value *instance
= emitClassExistentialProjection(*this, base, baseTy,
openedArchetype);
result.add(instance);
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitOpenExistentialMetatypeInst(
OpenExistentialMetatypeInst *i) {
SILType baseTy = i->getOperand()->getType();
Explosion base = getLoweredExplosion(i->getOperand());
auto openedTy = i->getType().getSwiftRValueType();
llvm::Value *metatype =
emitExistentialMetatypeProjection(*this, base, baseTy, openedTy);
Explosion result;
result.add(metatype);
setLoweredExplosion(i, result);
}
void IRGenSILFunction::visitOpenExistentialOpaqueInst(
OpenExistentialOpaqueInst *i) {
llvm_unreachable("unsupported instruction during IRGen");
}
void IRGenSILFunction::visitProjectBlockStorageInst(ProjectBlockStorageInst *i){
// TODO
Address block = getLoweredAddress(i->getOperand());
Address capture = projectBlockStorageCapture(*this, block,
i->getOperand()->getType().castTo<SILBlockStorageType>());
setLoweredAddress(i, capture);
}
void IRGenSILFunction::visitInitBlockStorageHeaderInst(
InitBlockStorageHeaderInst *i) {
auto addr = getLoweredAddress(i->getBlockStorage());
// We currently only support static invoke functions.
auto &invokeVal = getLoweredValue(i->getInvokeFunction());
llvm::Function *invokeFn = nullptr;
ForeignFunctionInfo foreignInfo;
if (invokeVal.kind != LoweredValue::Kind::StaticFunction) {
IGM.unimplemented(i->getLoc().getSourceLoc(),
"non-static block invoke function");
} else {
invokeFn = invokeVal.getStaticFunction().getFunction();
foreignInfo = invokeVal.getStaticFunction().getForeignInfo();
}
assert(foreignInfo.ClangInfo && "no clang info for block function?");
// Initialize the header.
emitBlockHeader(*this, addr,
i->getBlockStorage()->getType().castTo<SILBlockStorageType>(),
invokeFn, i->getInvokeFunction()->getType().castTo<SILFunctionType>(),
foreignInfo);
// Cast the storage to the block type to produce the result value.
llvm::Value *asBlock = Builder.CreateBitCast(addr.getAddress(),
IGM.ObjCBlockPtrTy);
Explosion e;
e.add(asBlock);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitAllocExistentialBoxInst(AllocExistentialBoxInst *i){
OwnedAddress boxWithAddr =
emitBoxedExistentialContainerAllocation(*this, i->getExistentialType(),
i->getFormalConcreteType(),
i->getConformances());
setLoweredBox(i, boxWithAddr);
}
void IRGenSILFunction::visitDeallocExistentialBoxInst(
DeallocExistentialBoxInst *i) {
Explosion box = getLoweredExplosion(i->getOperand());
emitBoxedExistentialContainerDeallocation(*this, box,
i->getOperand()->getType(),
i->getConcreteType());
}
void IRGenSILFunction::visitOpenExistentialBoxInst(OpenExistentialBoxInst *i) {
Explosion box = getLoweredExplosion(i->getOperand());
auto openedArchetype = cast<ArchetypeType>(i->getType().getSwiftRValueType());
auto addr = emitOpenExistentialBox(*this, box, i->getOperand()->getType(),
openedArchetype);
setLoweredAddress(i, addr);
}
void
IRGenSILFunction::visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i) {
const LoweredValue &val = getLoweredValue(i->getOperand());
if (val.isBoxWithAddress()) {
// The operand is an alloc_existential_box.
// We can directly reuse the address.
setLoweredAddress(i, val.getAddressOfBox());
} else {
Explosion box = getLoweredExplosion(i->getOperand());
auto caddr = emitBoxedExistentialProjection(*this, box,
i->getOperand()->getType(),
i->getType().getSwiftRValueType());
setLoweredAddress(i, caddr.getAddress());
}
}
void IRGenSILFunction::visitDynamicMethodInst(DynamicMethodInst *i) {
assert(i->getMember().isForeign && "dynamic_method requires [objc] method");
setLoweredObjCMethod(i, i->getMember());
return;
}
void IRGenSILFunction::visitWitnessMethodInst(swift::WitnessMethodInst *i) {
// For Objective-C classes we need to arrange for a msgSend
// to happen when the method is called.
if (i->getMember().isForeign) {
setLoweredObjCMethod(i, i->getMember());
return;
}
CanType baseTy = i->getLookupType();
ProtocolConformanceRef conformance = i->getConformance();
SILDeclRef member = i->getMember();
// It would be nice if this weren't discarded.
llvm::Value *baseMetadataCache = nullptr;
Explosion lowered;
emitWitnessMethodValue(*this, baseTy, &baseMetadataCache,
member, conformance, lowered);
setLoweredExplosion(i, lowered);
}
void IRGenSILFunction::setAllocatedAddressForBuffer(SILValue v,
const Address &allocedAddress) {
overwriteAllocatedAddress(v, allocedAddress);
// Emit the debug info for the variable if any.
if (auto allocStack = dyn_cast<AllocStackInst>(v)) {
emitDebugInfoForAllocStack(allocStack, getTypeInfo(v->getType()),
allocedAddress.getAddress());
}
}
void IRGenSILFunction::visitCopyAddrInst(swift::CopyAddrInst *i) {
SILType addrTy = i->getSrc()->getType();
const TypeInfo &addrTI = getTypeInfo(addrTy);
Address src = getLoweredAddress(i->getSrc());
// See whether we have a deferred fixed-size buffer initialization.
auto &loweredDest = getLoweredValue(i->getDest());
if (loweredDest.isUnallocatedAddressInBuffer()) {
// We should never have a deferred initialization with COW existentials.
assert(!getSILModule().getOptions().UseCOWExistentials &&
"Should never have an unallocated buffer and COW existentials");
assert(i->isInitializationOfDest()
&& "need to initialize an unallocated buffer");
Address cont = loweredDest.getContainerOfAddress();
if (i->isTakeOfSrc()) {
Address addr = addrTI.initializeBufferWithTake(*this, cont, src, addrTy);
setAllocatedAddressForBuffer(i->getDest(), addr);
} else {
Address addr = addrTI.initializeBufferWithCopy(*this, cont, src, addrTy);
setAllocatedAddressForBuffer(i->getDest(), addr);
}
} else {
Address dest = loweredDest.getAddress();
if (i->isInitializationOfDest()) {
if (i->isTakeOfSrc()) {
addrTI.initializeWithTake(*this, dest, src, addrTy);
} else {
addrTI.initializeWithCopy(*this, dest, src, addrTy);
}
} else {
if (i->isTakeOfSrc()) {
addrTI.assignWithTake(*this, dest, src, addrTy);
} else {
addrTI.assignWithCopy(*this, dest, src, addrTy);
}
}
}
}
// This is a no-op because we do not lower Swift TBAA info to LLVM IR, and it
// does not produce any values.
void IRGenSILFunction::visitBindMemoryInst(swift::BindMemoryInst *) {}
void IRGenSILFunction::visitDestroyAddrInst(swift::DestroyAddrInst *i) {
SILType addrTy = i->getOperand()->getType();
const TypeInfo &addrTI = getTypeInfo(addrTy);
// Otherwise, do the normal thing.
Address base = getLoweredAddress(i->getOperand());
addrTI.destroy(*this, base, addrTy);
}
void IRGenSILFunction::visitCondFailInst(swift::CondFailInst *i) {
Explosion e = getLoweredExplosion(i->getOperand());
llvm::Value *cond = e.claimNext();
// Emit individual fail blocks so that we can map the failure back to a source
// line.
llvm::BasicBlock *failBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
llvm::BasicBlock *contBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
Builder.CreateCondBr(cond, failBB, contBB);
Builder.emitBlock(failBB);
if (IGM.IRGen.Opts.Optimize) {
// Emit unique side-effecting inline asm calls in order to eliminate
// the possibility that an LLVM optimization or code generation pass
// will merge these blocks back together again. We emit an empty asm
// string with the side-effect flag set, and with a unique integer
// argument for each cond_fail we see in the function.
llvm::IntegerType *asmArgTy = IGM.Int32Ty;
llvm::Type *argTys = { asmArgTy };
llvm::FunctionType *asmFnTy =
llvm::FunctionType::get(IGM.VoidTy, argTys, false /* = isVarArg */);
llvm::InlineAsm *inlineAsm =
llvm::InlineAsm::get(asmFnTy, "", "n", true /* = SideEffects */);
Builder.CreateCall(inlineAsm,
llvm::ConstantInt::get(asmArgTy, NumCondFails++));
}
// Emit the trap instruction.
llvm::Function *trapIntrinsic =
llvm::Intrinsic::getDeclaration(&IGM.Module, llvm::Intrinsic::ID::trap);
Builder.CreateCall(trapIntrinsic, {});
Builder.CreateUnreachable();
Builder.emitBlock(contBB);
FailBBs.push_back(failBB);
}
void IRGenSILFunction::visitSuperMethodInst(swift::SuperMethodInst *i) {
if (i->getMember().isForeign) {
setLoweredObjCMethodBounded(i, i->getMember(),
i->getOperand()->getType(),
/*startAtSuper=*/true);
return;
}
auto base = getLoweredExplosion(i->getOperand());
auto baseType = i->getOperand()->getType();
llvm::Value *baseValue = base.claimNext();
auto method = i->getMember();
auto methodType = i->getType().castTo<SILFunctionType>();
llvm::Value *fnValue = emitVirtualMethodValue(*this, baseValue,
baseType,
method, methodType,
/*useSuperVTable*/ true);
fnValue = Builder.CreateBitCast(fnValue, IGM.Int8PtrTy);
Explosion e;
e.add(fnValue);
setLoweredExplosion(i, e);
}
void IRGenSILFunction::visitClassMethodInst(swift::ClassMethodInst *i) {
// For Objective-C classes we need to arrange for a msgSend
// to happen when the method is called.
if (i->getMember().isForeign) {
setLoweredObjCMethod(i, i->getMember());
return;
}
Explosion base = getLoweredExplosion(i->getOperand());
llvm::Value *baseValue = base.claimNext();
SILDeclRef method = i->getMember();
auto methodType = i->getType().castTo<SILFunctionType>();
// For Swift classes, get the method implementation from the vtable.
// FIXME: better explosion kind, map as static.
llvm::Value *fnValue = emitVirtualMethodValue(*this, baseValue,
i->getOperand()->getType(),
method, methodType,
/*useSuperVTable*/ false);
fnValue = Builder.CreateBitCast(fnValue, IGM.Int8PtrTy);
Explosion e;
e.add(fnValue);
setLoweredExplosion(i, e);
}
void IRGenModule::emitSILStaticInitializers() {
SmallVector<SILFunction *, 8> StaticInitializers;
for (SILGlobalVariable &Global : getSILModule().getSILGlobals()) {
if (!Global.getInitializer())
continue;
auto *IRGlobal =
Module.getGlobalVariable(Global.getName(), true /* = AllowLocal */);
// A check for multi-threaded compilation: Is this the llvm module where the
// global is defined and not only referenced (or not referenced at all).
if (!IRGlobal || !IRGlobal->hasInitializer())
continue;
auto *InitValue = Global.getValueOfStaticInitializer();
// Set the IR global's initializer to the constant for this SIL
// struct.
if (auto *SI = dyn_cast<StructInst>(InitValue)) {
IRGlobal->setInitializer(emitConstantStruct(*this, SI));
continue;
}
// Set the IR global's initializer to the constant for this SIL
// tuple.
auto *TI = cast<TupleInst>(InitValue);
IRGlobal->setInitializer(emitConstantTuple(*this, TI));
}
}
| apache-2.0 |
Ramzi-Alqrainy/SELK | solr-4.10.0/docs/solr-core/org/apache/solr/search/class-use/BitDocSet.html | 6924 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Tue Aug 26 20:50:07 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.search.BitDocSet (Solr 4.10.0 API)</title>
<meta name="date" content="2014-08-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.search.BitDocSet (Solr 4.10.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/search/BitDocSet.html" title="class in org.apache.solr.search">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/search/class-use/BitDocSet.html" target="_top">Frames</a></li>
<li><a href="BitDocSet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.search.BitDocSet" class="title">Uses of Class<br>org.apache.solr.search.BitDocSet</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/solr/search/BitDocSet.html" title="class in org.apache.solr.search">BitDocSet</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.solr.search">org.apache.solr.search</a></td>
<td class="colLast">
<div class="block">
APIs and classes for <a href="../../../../../org/apache/solr/search/QParserPlugin.html" title="class in org.apache.solr.search">parsing</a> and <a href="../../../../../org/apache/solr/search/SolrIndexSearcher.html" title="class in org.apache.solr.search">processing</a> search requests</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.solr.search">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/solr/search/BitDocSet.html" title="class in org.apache.solr.search">BitDocSet</a> in <a href="../../../../../org/apache/solr/search/package-summary.html">org.apache.solr.search</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/solr/search/package-summary.html">org.apache.solr.search</a> that return <a href="../../../../../org/apache/solr/search/BitDocSet.html" title="class in org.apache.solr.search">BitDocSet</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../org/apache/solr/search/BitDocSet.html" title="class in org.apache.solr.search">BitDocSet</a></code></td>
<td class="colLast"><span class="strong">BitDocSet.</span><code><strong><a href="../../../../../org/apache/solr/search/BitDocSet.html#clone()">clone</a></strong>()</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/search/BitDocSet.html" title="class in org.apache.solr.search">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/search/class-use/BitDocSet.html" target="_top">Frames</a></li>
<li><a href="BitDocSet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| apache-2.0 |
malakasilva/carbon-event-processing | components/adaptors/event-input-adaptor/org.wso2.carbon.event.input.adaptor.kafka/src/main/java/org/wso2/carbon/event/input/adaptor/kafka/internal/ds/ConsumerKafkaServiceDS.java | 2647 | /*
* Copyright (c) 2005-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.event.input.adaptor.kafka.internal.ds;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.event.input.adaptor.core.InputEventAdaptorFactory;
import org.wso2.carbon.event.input.adaptor.kafka.KafkaEventAdaptorFactory;
import org.wso2.carbon.utils.ConfigurationContextService;
/**
* @scr.component name="input.Kafka.EventAdaptorService.component" immediate="true"
* @scr.reference name="configurationcontext.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="0..1"
* policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
*/
public class ConsumerKafkaServiceDS {
private static final Log log = LogFactory.getLog(ConsumerKafkaServiceDS.class);
/**
* initialize the agent service here service here.
*
* @param context
*/
protected void activate(ComponentContext context) {
try {
InputEventAdaptorFactory testInEventAdaptorFactory = new KafkaEventAdaptorFactory();
context.getBundleContext().registerService(InputEventAdaptorFactory.class.getName(), testInEventAdaptorFactory, null);
log.info("Successfully deployed the KafkaConsumer input event adaptor service");
} catch (RuntimeException e) {
log.error("Can not create the KafkaConsumer input event adaptor service ", e);
}
}
protected void setConfigurationContextService(
ConfigurationContextService configurationContextService) {
KafkaEventAdaptorServiceHolder.registerConfigurationContextService(configurationContextService);
}
protected void unsetConfigurationContextService(
ConfigurationContextService configurationContextService) {
KafkaEventAdaptorServiceHolder.unregisterConfigurationContextService(configurationContextService);
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.