repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
polyfractal/elasticsearch
plugins/discovery-gce/src/main/java/org/elasticsearch/cloud/gce/GceComputeServiceImpl.java
10521
/* * 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.cloud.gce; import com.google.api.client.googleapis.compute.ComputeCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.compute.Compute; import com.google.api.services.compute.model.Instance; import com.google.api.services.compute.model.InstanceList; import org.elasticsearch.SpecialPermission; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cloud.gce.network.GceNameResolver; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.discovery.gce.RetryHttpInitializerWrapper; import java.io.IOException; import java.net.URL; import java.security.AccessController; import java.security.GeneralSecurityException; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; public class GceComputeServiceImpl extends AbstractLifecycleComponent<GceComputeService> implements GceComputeService { private final String project; private final List<String> zones; // Forcing Google Token API URL as set in GCE SDK to // http://metadata/computeMetadata/v1/instance/service-accounts/default/token // See https://developers.google.com/compute/docs/metadata#metadataserver public static final String GCE_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance"; public static final String TOKEN_SERVER_ENCODED_URL = GCE_METADATA_URL + "/service-accounts/default/token"; @Override public Collection<Instance> instances() { logger.debug("get instances for project [{}], zones [{}]", project, zones); final List<Instance> instances = zones.stream().map((zoneId) -> { try { // hack around code messiness in GCE code // TODO: get this fixed SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); } InstanceList instanceList = AccessController.doPrivileged(new PrivilegedExceptionAction<InstanceList>() { @Override public InstanceList run() throws Exception { Compute.Instances.List list = client().instances().list(project, zoneId); return list.execute(); } }); // assist type inference return instanceList.isEmpty() ? Collections.<Instance>emptyList() : instanceList.getItems(); } catch (PrivilegedActionException e) { logger.warn("Problem fetching instance list for zone {}", zoneId); logger.debug("Full exception:", e); // assist type inference return Collections.<Instance>emptyList(); } }).reduce(new ArrayList<>(), (a, b) -> { a.addAll(b); return a; }); if (instances.isEmpty()) { logger.warn("disabling GCE discovery. Can not get list of nodes"); } return instances; } @Override public String metadata(String metadataPath) throws IOException { String urlMetadataNetwork = GCE_METADATA_URL + "/" + metadataPath; logger.debug("get metadata from [{}]", urlMetadataNetwork); final URL url = new URL(urlMetadataNetwork); HttpHeaders headers; try { // hack around code messiness in GCE code // TODO: get this fixed SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); } headers = AccessController.doPrivileged(new PrivilegedExceptionAction<HttpHeaders>() { @Override public HttpHeaders run() throws IOException { return new HttpHeaders(); } }); GenericUrl genericUrl = AccessController.doPrivileged(new PrivilegedAction<GenericUrl>() { @Override public GenericUrl run() { return new GenericUrl(url); } }); // This is needed to query meta data: https://cloud.google.com/compute/docs/metadata headers.put("Metadata-Flavor", "Google"); HttpResponse response; response = getGceHttpTransport().createRequestFactory() .buildGetRequest(genericUrl) .setHeaders(headers) .execute(); String metadata = response.parseAsString(); logger.debug("metadata found [{}]", metadata); return metadata; } catch (Exception e) { throw new IOException("failed to fetch metadata from [" + urlMetadataNetwork + "]", e); } } private Compute client; private TimeValue refreshInterval = null; private long lastRefresh; /** Global instance of the HTTP transport. */ private HttpTransport gceHttpTransport; /** Global instance of the JSON factory. */ private JsonFactory gceJsonFactory; @Inject public GceComputeServiceImpl(Settings settings, NetworkService networkService) { super(settings); this.project = settings.get(Fields.PROJECT); String[] zoneList = settings.getAsArray(Fields.ZONE); this.zones = Arrays.asList(zoneList); networkService.addCustomNameResolver(new GceNameResolver(settings, this)); } protected synchronized HttpTransport getGceHttpTransport() throws GeneralSecurityException, IOException { if (gceHttpTransport == null) { gceHttpTransport = GoogleNetHttpTransport.newTrustedTransport(); } return gceHttpTransport; } public synchronized Compute client() { if (refreshInterval != null && refreshInterval.millis() != 0) { if (client != null && (refreshInterval.millis() < 0 || (System.currentTimeMillis() - lastRefresh) < refreshInterval.millis())) { if (logger.isTraceEnabled()) logger.trace("using cache to retrieve client"); return client; } lastRefresh = System.currentTimeMillis(); } try { gceJsonFactory = new JacksonFactory(); logger.info("starting GCE discovery service"); ComputeCredential credential = new ComputeCredential.Builder(getGceHttpTransport(), gceJsonFactory) .setTokenServerEncodedUrl(TOKEN_SERVER_ENCODED_URL) .build(); // hack around code messiness in GCE code // TODO: get this fixed SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); } AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws IOException { credential.refreshToken(); return null; } }); logger.debug("token [{}] will expire in [{}] s", credential.getAccessToken(), credential.getExpiresInSeconds()); if (credential.getExpiresInSeconds() != null) { refreshInterval = TimeValue.timeValueSeconds(credential.getExpiresInSeconds() - 1); } boolean ifRetry = settings.getAsBoolean(Fields.RETRY, true); Compute.Builder builder = new Compute.Builder(getGceHttpTransport(), gceJsonFactory, null) .setApplicationName(Fields.VERSION); if (ifRetry) { int maxWait = settings.getAsInt(Fields.MAXWAIT, -1); RetryHttpInitializerWrapper retryHttpInitializerWrapper; if (maxWait > 0) { retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, maxWait); } else { retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential); } builder.setHttpRequestInitializer(retryHttpInitializerWrapper); } else { builder.setHttpRequestInitializer(credential); } this.client = builder.build(); } catch (Exception e) { logger.warn("unable to start GCE discovery service", e); throw new IllegalArgumentException("unable to start GCE discovery service", e); } return this.client; } @Override protected void doStart() throws ElasticsearchException { } @Override protected void doStop() throws ElasticsearchException { if (gceHttpTransport != null) { try { gceHttpTransport.shutdown(); } catch (IOException e) { logger.warn("unable to shutdown GCE Http Transport", e); } gceHttpTransport = null; } } @Override protected void doClose() throws ElasticsearchException { } }
apache-2.0
yurloc/drools
drools-compiler/src/test/java/org/drools/integrationtests/CepEspTest.java
105840
package org.drools.integrationtests; import org.drools.ClockType; import org.drools.CommonTestMethodBase; import org.drools.OrderEvent; import org.drools.RuleBaseConfiguration; import org.drools.Sensor; import org.drools.StockTick; import org.drools.StockTickInterface; import org.drools.audit.WorkingMemoryFileLogger; import org.drools.base.ClassObjectType; import org.drools.base.evaluators.TimeIntervalParser; import org.drools.common.EventFactHandle; import org.drools.common.InternalFactHandle; import org.drools.common.InternalRuleBase; import org.drools.common.InternalWorkingMemory; import org.drools.core.util.DroolsStreamUtils; import org.drools.impl.KnowledgeBaseImpl; import org.drools.impl.StatefulKnowledgeSessionImpl; import org.drools.reteoo.ObjectTypeNode; import org.drools.rule.EntryPoint; import org.drools.rule.Rule; import org.drools.rule.TypeDeclaration; import org.drools.spi.ObjectType; import org.drools.time.SessionPseudoClock; import org.drools.time.impl.DurationTimer; import org.drools.time.impl.PseudoClockScheduler; import org.junit.Assert; import org.junit.Test; import org.kie.KieBaseConfiguration; import org.kie.KnowledgeBase; import org.kie.KnowledgeBaseFactory; import org.kie.builder.KnowledgeBuilder; import org.kie.builder.KnowledgeBuilderFactory; import org.kie.conf.EqualityBehaviorOption; import org.kie.conf.EventProcessingOption; import org.kie.definition.KnowledgePackage; import org.kie.event.rule.AfterMatchFiredEvent; import org.kie.event.rule.AgendaEventListener; import org.kie.event.rule.MatchCreatedEvent; import org.kie.io.ResourceFactory; import org.kie.io.ResourceType; import org.kie.runtime.KieSessionConfiguration; import org.kie.runtime.StatefulKnowledgeSession; import org.kie.runtime.conf.ClockTypeOption; import org.kie.runtime.rule.FactHandle; import org.kie.runtime.rule.Match; import org.kie.runtime.rule.SessionEntryPoint; import org.kie.time.SessionClock; import org.mockito.ArgumentCaptor; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class CepEspTest extends CommonTestMethodBase { @Test public void testComplexTimestamp() { String rule = ""; rule += "package " + Message.class.getPackage().getName() + "\n" + "declare " + Message.class.getCanonicalName() + "\n" + " @role( event ) \n" + " @timestamp( getProperties().get( 'timestamp' )-1 ) \n" + " @duration( getProperties().get( 'duration' )+1 ) \n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString( rule ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); Message msg = new Message(); Properties props = new Properties(); props.put( "timestamp", new Integer( 99 ) ); props.put( "duration", new Integer( 52 ) ); msg.setProperties( props ); EventFactHandle efh = (EventFactHandle) ksession.insert( msg ); assertEquals( 98, efh.getStartTimestamp() ); assertEquals( 53, efh.getDuration() ); } @Test public void testEventAssertion() throws Exception { // read in the source KnowledgeBase kbase = loadKnowledgeBase( "test_CEP_SimpleEventAssertion.drl" ); KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption( ClockTypeOption.get( "pseudo" ) ); StatefulKnowledgeSession session = createKnowledgeSession(kbase, conf); SessionPseudoClock clock = (SessionPseudoClock) session.<SessionClock>getSessionClock(); final List results = new ArrayList(); session.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 10000 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 10010 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, 10100 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, 11000 ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); clock.advanceTime( 10, TimeUnit.SECONDS ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); clock.advanceTime( 30, TimeUnit.SECONDS ); InternalFactHandle handle3 = (InternalFactHandle) session.insert( tick3 ); clock.advanceTime( 20, TimeUnit.SECONDS ); InternalFactHandle handle4 = (InternalFactHandle) session.insert( tick4 ); clock.advanceTime( 10, TimeUnit.SECONDS ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); session.fireAllRules(); assertEquals( 2, ((List) session.getGlobal( "results" )).size() ); } @SuppressWarnings("unchecked") @Test public void testPackageSerializationWithEvents() throws Exception { // read in the source KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newInputStreamResource( getClass().getResourceAsStream( "test_CEP_SimpleEventAssertion.drl" ) ), ResourceType.DRL ); // get the package Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); assertEquals( 2, pkgs.size() ); // serialize the package byte[] serializedPkg = DroolsStreamUtils.streamOut( pkgs ); pkgs = (Collection<KnowledgePackage>) DroolsStreamUtils.streamIn( serializedPkg ); // create the kbase KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages( pkgs ); // create the session KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); StatefulKnowledgeSession session = createKnowledgeSession(kbase, conf); final List<StockTick> results = new ArrayList<StockTick>(); session.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 10000 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 10010 ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); session.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( tick2, results.get( 0 ) ); } @Test public void testEventAssertionWithDuration() throws Exception { KnowledgeBase kbase = loadKnowledgeBase( "test_CEP_SimpleEventAssertionWithDuration.drl" ); KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession session = createKnowledgeSession(kbase, conf); final List results = new ArrayList(); session.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 10000, 5 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 11000, 10 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, 12000, 8 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, 13000, 7 ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); InternalFactHandle handle3 = (InternalFactHandle) session.insert( tick3 ); InternalFactHandle handle4 = (InternalFactHandle) session.insert( tick4 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); EventFactHandle eh1 = (EventFactHandle) handle1; EventFactHandle eh2 = (EventFactHandle) handle2; EventFactHandle eh3 = (EventFactHandle) handle3; EventFactHandle eh4 = (EventFactHandle) handle4; assertEquals( tick1.getTime(), eh1.getStartTimestamp() ); assertEquals( tick2.getTime(), eh2.getStartTimestamp() ); assertEquals( tick3.getTime(), eh3.getStartTimestamp() ); assertEquals( tick4.getTime(), eh4.getStartTimestamp() ); assertEquals( tick1.getDuration(), eh1.getDuration() ); assertEquals( tick2.getDuration(), eh2.getDuration() ); assertEquals( tick3.getDuration(), eh3.getDuration() ); assertEquals( tick4.getDuration(), eh4.getDuration() ); session.fireAllRules(); assertEquals( 2, results.size() ); } @Test public void testEventAssertionWithDateTimestamp() throws Exception { KnowledgeBase kbase = loadKnowledgeBase( "test_CEP_SimpleEventAssertionWithDateTimestamp.drl" ); KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession session = createKnowledgeSession(kbase, conf); final List results = new ArrayList(); session.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 10000, 5 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 11000, 10 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, 12000, 8 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, 13000, 7 ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); InternalFactHandle handle3 = (InternalFactHandle) session.insert( tick3 ); InternalFactHandle handle4 = (InternalFactHandle) session.insert( tick4 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); EventFactHandle eh1 = (EventFactHandle) handle1; EventFactHandle eh2 = (EventFactHandle) handle2; EventFactHandle eh3 = (EventFactHandle) handle3; EventFactHandle eh4 = (EventFactHandle) handle4; assertEquals( tick1.getTime(), eh1.getStartTimestamp() ); assertEquals( tick2.getTime(), eh2.getStartTimestamp() ); assertEquals( tick3.getTime(), eh3.getStartTimestamp() ); assertEquals( tick4.getTime(), eh4.getStartTimestamp() ); session.fireAllRules(); assertEquals( 2, results.size() ); } @Test public void testEventExpiration() throws Exception { KnowledgeBase kbase = loadKnowledgeBase( "test_CEP_EventExpiration.drl" ); // read in the source TypeDeclaration factType = ((InternalRuleBase)((KnowledgeBaseImpl)kbase).ruleBase).getTypeDeclaration( StockTick.class ); final TimeIntervalParser parser = new TimeIntervalParser(); assertEquals( parser.parse( "1h30m" )[0].longValue(), factType.getExpirationOffset() ); } @Test public void testEventExpiration2() throws Exception { // read in the source KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kbc.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBase( kbc, "test_CEP_EventExpiration2.drl" ); final InternalRuleBase internal = (InternalRuleBase) ((KnowledgeBaseImpl)kbase).ruleBase; final TimeIntervalParser parser = new TimeIntervalParser(); Map<ObjectType, ObjectTypeNode> objectTypeNodes = internal.getRete().getObjectTypeNodes( EntryPoint.DEFAULT ); ObjectTypeNode node = objectTypeNodes.get( new ClassObjectType( StockTick.class ) ); assertNotNull( node ); // the expiration policy @expires(10m) should override the temporal operator usage assertEquals( parser.parse( "10m" )[0].longValue() + 1, node.getExpirationOffset() ); } @Test public void testEventExpiration3() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_EventExpiration3.drl" ); final InternalRuleBase internal = (InternalRuleBase) ((KnowledgeBaseImpl)kbase).ruleBase; final TimeIntervalParser parser = new TimeIntervalParser(); Map<ObjectType, ObjectTypeNode> objectTypeNodes = internal.getRete().getObjectTypeNodes( EntryPoint.DEFAULT ); ObjectTypeNode node = objectTypeNodes.get( new ClassObjectType( StockTick.class ) ); assertNotNull( node ); // the expiration policy @expires(10m) should override the temporal operator usage assertEquals( parser.parse( "10m" )[0].longValue() + 1, node.getExpirationOffset() ); } @Test public void testEventExpiration4() throws Exception { // read in the source final KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_EventExpiration4.drl" ); final KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( "pseudo" ) ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase, sconf); SessionEntryPoint eventStream = ksession.getEntryPoint( "Event Stream" ); SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); final List results = new ArrayList(); ksession.setGlobal( "results", results ); EventFactHandle handle1 = (EventFactHandle) eventStream.insert( new StockTick( 1, "ACME", 50, System.currentTimeMillis(), 3 ) ); ksession.fireAllRules(); clock.advanceTime( 11, TimeUnit.SECONDS ); /** clock.advance() will put the event expiration in the queue to be executed, but it has to wait for a "thread" to do that so we fire rules again here to get that alternative could run fireUntilHalt() **/ ksession.fireAllRules(); assertTrue( results.size() == 1 ); assertTrue( handle1.isExpired() ); assertFalse( ksession.getFactHandles().contains( handle1 ) ); } @Test public void testTimeRelationalOperators() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_TimeRelationalOperators.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); final PseudoClockScheduler clock = (PseudoClockScheduler) wm.getSessionClock(); clock.setStartupTime( 1000 ); final List results_coincides = new ArrayList(); final List results_before = new ArrayList(); final List results_after = new ArrayList(); final List results_meets = new ArrayList(); final List results_met_by = new ArrayList(); final List results_overlaps = new ArrayList(); final List results_overlapped_by = new ArrayList(); final List results_during = new ArrayList(); final List results_includes = new ArrayList(); final List results_starts = new ArrayList(); final List results_started_by = new ArrayList(); final List results_finishes = new ArrayList(); final List results_finished_by = new ArrayList(); wm.setGlobal( "results_coincides", results_coincides ); wm.setGlobal( "results_before", results_before ); wm.setGlobal( "results_after", results_after ); wm.setGlobal( "results_meets", results_meets ); wm.setGlobal( "results_met_by", results_met_by ); wm.setGlobal( "results_overlaps", results_overlaps ); wm.setGlobal( "results_overlapped_by", results_overlapped_by ); wm.setGlobal( "results_during", results_during ); wm.setGlobal( "results_includes", results_includes ); wm.setGlobal( "results_starts", results_starts ); wm.setGlobal( "results_started_by", results_started_by ); wm.setGlobal( "results_finishes", results_finishes ); wm.setGlobal( "results_finished_by", results_finished_by ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, System.currentTimeMillis(), 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, System.currentTimeMillis(), 5 ); StockTickInterface tick5 = new StockTick( 5, "ACME", 10, System.currentTimeMillis(), 5 ); StockTickInterface tick6 = new StockTick( 6, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick7 = new StockTick( 7, "ACME", 10, System.currentTimeMillis(), 5 ); StockTickInterface tick8 = new StockTick( 8, "ACME", 10, System.currentTimeMillis(), 3 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle3 = (InternalFactHandle) wm.insert( tick3 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle handle4 = (InternalFactHandle) wm.insert( tick4 ); InternalFactHandle handle5 = (InternalFactHandle) wm.insert( tick5 ); clock.advanceTime( 1, TimeUnit.MILLISECONDS ); InternalFactHandle handle6 = (InternalFactHandle) wm.insert( tick6 ); InternalFactHandle handle7 = (InternalFactHandle) wm.insert( tick7 ); clock.advanceTime( 2, TimeUnit.MILLISECONDS ); InternalFactHandle handle8 = (InternalFactHandle) wm.insert( tick8 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertNotNull( handle5 ); assertNotNull( handle6 ); assertNotNull( handle7 ); assertNotNull( handle8 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); assertTrue( handle6.isEvent() ); assertTrue( handle7.isEvent() ); assertTrue( handle8.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 1, results_coincides.size() ); assertEquals( tick5, results_coincides.get( 0 ) ); assertEquals( 1, results_before.size() ); assertEquals( tick2, results_before.get( 0 ) ); assertEquals( 1, results_after.size() ); assertEquals( tick3, results_after.get( 0 ) ); assertEquals( 1, results_meets.size() ); assertEquals( tick3, results_meets.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_met_by.size() ); assertEquals( tick2, results_met_by.get( 0 ) ); assertEquals( 1, results_overlaps.size() ); assertEquals( tick4, results_overlaps.get( 0 ) ); assertEquals( 1, results_overlapped_by.size() ); assertEquals( tick8, results_overlapped_by.get( 0 ) ); assertEquals( 1, results_during.size() ); assertEquals( tick6, results_during.get( 0 ) ); assertEquals( 1, results_includes.size() ); assertEquals( tick4, results_includes.get( 0 ) ); assertEquals( 1, results_starts.size() ); assertEquals( tick6, results_starts.get( 0 ) ); assertEquals( 1, results_started_by.size() ); assertEquals( tick7, results_started_by.get( 0 ) ); assertEquals( 1, results_finishes.size() ); assertEquals( tick8, results_finishes.get( 0 ) ); assertEquals( 1, results_finished_by.size() ); assertEquals( tick7, results_finished_by.get( 0 ) ); } @Test public void testBeforeOperator() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_BeforeOperator.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = createKnowledgeSession( kbase, sconf ); final PseudoClockScheduler clock = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); clock.setStartupTime( 1000 ); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, System.currentTimeMillis(), 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, System.currentTimeMillis(), 5 ); StockTickInterface tick5 = new StockTick( 5, "ACME", 10, System.currentTimeMillis(), 5 ); StockTickInterface tick6 = new StockTick( 6, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick7 = new StockTick( 7, "ACME", 10, System.currentTimeMillis(), 5 ); StockTickInterface tick8 = new StockTick( 8, "ACME", 10, System.currentTimeMillis(), 3 ); ksession.insert( tick1 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); ksession.insert( tick2 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); ksession.insert( tick3 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); ksession.insert( tick4 ); ksession.insert( tick5 ); clock.advanceTime( 1, TimeUnit.MILLISECONDS ); ksession.insert( tick6 ); ksession.insert( tick7 ); clock.advanceTime( 2, TimeUnit.MILLISECONDS ); ksession.insert( tick8 ); ArgumentCaptor<MatchCreatedEvent> arg = ArgumentCaptor.forClass( MatchCreatedEvent.class ); verify( ael ).matchCreated(arg.capture()); assertThat( arg.getValue().getMatch().getRule().getName(), is( "before" ) ); ksession.fireAllRules(); verify( ael ).afterMatchFired(any(AfterMatchFiredEvent.class)); } @Test public void testComplexOperator() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_ComplexOperator.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = createKnowledgeSession( kbase, sconf ); final PseudoClockScheduler clock = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); clock.setStartupTime( 1000 ); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 0, 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 4, 3 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, 8, 3 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, 12, 5 ); StockTickInterface tick5 = new StockTick( 5, "ACME", 10, 12, 5 ); StockTickInterface tick6 = new StockTick( 6, "ACME", 10, 13, 3 ); StockTickInterface tick7 = new StockTick( 7, "ACME", 10, 13, 5 ); StockTickInterface tick8 = new StockTick( 8, "ACME", 10, 15, 3 ); ksession.insert( tick1 ); ksession.insert( tick2 ); ksession.insert( tick3 ); ksession.insert( tick4 ); ksession.insert( tick5 ); ksession.insert( tick6 ); ksession.insert( tick7 ); ksession.insert( tick8 ); ArgumentCaptor<MatchCreatedEvent> arg = ArgumentCaptor.forClass( MatchCreatedEvent.class ); verify( ael ).matchCreated(arg.capture()); assertThat( arg.getValue().getMatch().getRule().getName(), is( "before" ) ); ksession.fireAllRules(); verify( ael ).afterMatchFired(any(AfterMatchFiredEvent.class)); } @Test public void testMetByOperator() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_MetByOperator.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = createKnowledgeSession( kbase, sconf ); final PseudoClockScheduler clock = (PseudoClockScheduler) ksession.<PseudoClockScheduler>getSessionClock(); clock.setStartupTime( 1000 ); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, System.currentTimeMillis(), 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, System.currentTimeMillis(), 5 ); StockTickInterface tick5 = new StockTick( 5, "ACME", 10, System.currentTimeMillis(), 5 ); StockTickInterface tick6 = new StockTick( 6, "ACME", 10, System.currentTimeMillis(), 3 ); StockTickInterface tick7 = new StockTick( 7, "ACME", 10, System.currentTimeMillis(), 5 ); StockTickInterface tick8 = new StockTick( 8, "ACME", 10, System.currentTimeMillis(), 3 ); InternalFactHandle fh1 = (InternalFactHandle) ksession.insert( tick1 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); InternalFactHandle fh2 = (InternalFactHandle) ksession.insert( tick2 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); ksession.insert( tick3 ); clock.advanceTime( 4, TimeUnit.MILLISECONDS ); ksession.insert( tick4 ); ksession.insert( tick5 ); clock.advanceTime( 1, TimeUnit.MILLISECONDS ); ksession.insert( tick6 ); ksession.insert( tick7 ); clock.advanceTime( 2, TimeUnit.MILLISECONDS ); ksession.insert( tick8 ); ArgumentCaptor<MatchCreatedEvent> arg = ArgumentCaptor.forClass( MatchCreatedEvent.class ); verify( ael ).matchCreated(arg.capture()); Match activation = arg.getValue().getMatch(); assertThat( activation.getRule().getName(), is( "metby" ) ); ksession.fireAllRules(); ArgumentCaptor<AfterMatchFiredEvent> aaf = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); verify( ael ).afterMatchFired(aaf.capture()); assertThat( (InternalFactHandle) aaf.getValue().getMatch().getFactHandles().toArray()[0], is( fh2 ) ); } @Test public void testAfterOnArbitraryDates() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_AfterOperatorDates.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); final List< ? > results = new ArrayList<Object>(); wm.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 100000, // arbitrary timestamp 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 104000, // 4 seconds after DROO 3 ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( tick1, results.get( 0 ) ); assertEquals( tick2, results.get( 1 ) ); assertEquals( tick1, results.get( 2 ) ); assertEquals( tick2, results.get( 3 ) ); } @Test public void testBeforeOnArbitraryDates() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_BeforeOperatorDates.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); final List< ? > results = new ArrayList<Object>(); wm.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 104000, // arbitrary timestamp 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 100000, // 4 seconds after DROO 3 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( tick1, results.get( 0 ) ); assertEquals( tick2, results.get( 1 ) ); assertEquals( tick1, results.get( 2 ) ); assertEquals( tick2, results.get( 3 ) ); } @Test public void testCoincidesOnArbitraryDates() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_CoincidesOperatorDates.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); final List< ? > results = new ArrayList<Object>(); wm.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 100000, // arbitrary timestamp 3 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 100050, // 50 milliseconds after DROO 3 ); InternalFactHandle handle1 = (InternalFactHandle) wm.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) wm.insert( tick2 ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( tick1, results.get( 0 ) ); assertEquals( tick2, results.get( 1 ) ); assertEquals( tick1, results.get( 2 ) ); assertEquals( tick2, results.get( 3 ) ); } @Test public void testSimpleTimeWindow() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_SimpleTimeWindow.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); List results = new ArrayList(); wm.setGlobal( "results", results ); // how to initialize the clock? // how to configure the clock? SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock(); clock.advanceTime( 5, TimeUnit.SECONDS ); // 5 seconds EventFactHandle handle1 = (EventFactHandle) wm.insert( new OrderEvent( "1", "customer A", 70 ) ); assertEquals( 5000, handle1.getStartTimestamp() ); assertEquals( 0, handle1.getDuration() ); // wm = SerializationHelper.getSerialisedStatefulSession( wm ); // results = (List) wm.getGlobal( "results" ); // clock = (SessionPseudoClock) wm.getSessionClock(); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 70, ((Number) results.get( 0 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle2 = (EventFactHandle) wm.insert( new OrderEvent( "2", "customer A", 60 ) ); assertEquals( 15000, handle2.getStartTimestamp() ); assertEquals( 0, handle2.getDuration() ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( 65, ((Number) results.get( 1 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle3 = (EventFactHandle) wm.insert( new OrderEvent( "3", "customer A", 50 ) ); assertEquals( 25000, handle3.getStartTimestamp() ); assertEquals( 0, handle3.getDuration() ); wm.fireAllRules(); assertEquals( 3, results.size() ); assertEquals( 60, ((Number) results.get( 2 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle4 = (EventFactHandle) wm.insert( new OrderEvent( "4", "customer A", 25 ) ); assertEquals( 35000, handle4.getStartTimestamp() ); assertEquals( 0, handle4.getDuration() ); wm.fireAllRules(); // first event should have expired, making average under the rule threshold, so no additional rule fire assertEquals( 3, results.size() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle5 = (EventFactHandle) wm.insert( new OrderEvent( "5", "customer A", 70 ) ); assertEquals( 45000, handle5.getStartTimestamp() ); assertEquals( 0, handle5.getDuration() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); // still under the threshold, so no fire assertEquals( 3, results.size() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds EventFactHandle handle6 = (EventFactHandle) wm.insert( new OrderEvent( "6", "customer A", 115 ) ); assertEquals( 55000, handle6.getStartTimestamp() ); assertEquals( 0, handle6.getDuration() ); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( 70, ((Number) results.get( 3 )).intValue() ); } @Test public void testSimpleLengthWindow() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_SimpleLengthWindow.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); final List results = new ArrayList(); wm.setGlobal( "results", results ); EventFactHandle handle1 = (EventFactHandle) wm.insert( new OrderEvent( "1", "customer A", 70 ) ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 70, ((Number) results.get( 0 )).intValue() ); // assert new data EventFactHandle handle2 = (EventFactHandle) wm.insert( new OrderEvent( "2", "customer A", 60 ) ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( 65, ((Number) results.get( 1 )).intValue() ); // assert new data EventFactHandle handle3 = (EventFactHandle) wm.insert( new OrderEvent( "3", "customer A", 50 ) ); wm.fireAllRules(); assertEquals( 3, results.size() ); assertEquals( 60, ((Number) results.get( 2 )).intValue() ); // assert new data EventFactHandle handle4 = (EventFactHandle) wm.insert( new OrderEvent( "4", "customer A", 25 ) ); wm.fireAllRules(); // first event should have expired, making average under the rule threshold, so no additional rule fire assertEquals( 3, results.size() ); // assert new data EventFactHandle handle5 = (EventFactHandle) wm.insert( new OrderEvent( "5", "customer A", 70 ) ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); // still under the threshold, so no fire assertEquals( 3, results.size() ); // assert new data EventFactHandle handle6 = (EventFactHandle) wm.insert( new OrderEvent( "6", "customer A", 115 ) ); wm.fireAllRules(); assertEquals( 4, results.size() ); assertEquals( 70, ((Number) results.get( 3 )).intValue() ); } @Test public void testDelayingNot() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_DelayingNot.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); final Rule rule = (Rule) kbase.getRule( "org.drools", "Delaying Not" ); assertEquals( 10000, ((DurationTimer) rule.getTimer()).getDuration() ); final List results = new ArrayList(); wm.setGlobal( "results", results ); SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock(); clock.advanceTime( 10, TimeUnit.SECONDS ); StockTickInterface st1O = new StockTick( 1, "DROO", 100, clock.getCurrentTime() ); EventFactHandle st1 = (EventFactHandle) wm.insert( st1O ); wm.fireAllRules(); // should not fire, because it must wait 10 seconds assertEquals( 0, results.size() ); clock.advanceTime( 5, TimeUnit.SECONDS ); EventFactHandle st2 = (EventFactHandle) wm.insert( new StockTick( 1, "DROO", 80, clock.getCurrentTime() ) ); wm.fireAllRules(); // should still not fire, because it must wait 5 more seconds, and st2 has lower price (80) assertEquals( 0, results.size() ); // assert new data wm.fireAllRules(); clock.advanceTime( 6, TimeUnit.SECONDS ); wm.fireAllRules(); // should fire, because waited for 10 seconds and no other event arrived with a price increase assertEquals( 1, results.size() ); assertEquals( st1O, results.get( 0 ) ); } @Test public void testDelayingNot2() throws Exception { String str = "package org.drools\n" + "declare A @role(event) symbol : String end\n" + "declare B @role(event) symbol : String end\n" + "rule Setup when\n" + "then\n" + " insert( new A() );\n" + "end\n" + "rule X\n" + "when\n" + " $a : A() and not( B( this after $a ) )\n" + "then\n" + "end\n"; KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBaseFromString( conf, str ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); // rule X should not be delayed as the delay would be infinite int rules = ksession.fireAllRules(); assertEquals( 2, rules ); } @Test public void testDelayingNotWithPreEpochClock() throws Exception { String str = "package org.drools\n" + "declare A @role(event) symbol : String end\n" + "declare B @role(event) symbol : String end\n" + "rule Setup when\n" + "then\n" + " insert( new A() );\n" + "end\n" + "rule X\n" + "when\n" + " $a : A() and not( B( this after $a ) )\n" + "then\n" + "end\n"; KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBaseFromString( conf, str ); KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); ksconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase, ksconf); // Getting a pre-epoch date (i.e., before 1970) Calendar ts = Calendar.getInstance(); ts.set( 1900, 1, 1 ); // Initializing the clock to that date SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( ts.getTimeInMillis(), TimeUnit.MILLISECONDS ); // rule X should not be delayed as the delay would be infinite int rules = ksession.fireAllRules(); assertEquals( 2, rules ); } // @Test @Ignore // public void testTransactionCorrelation() throws Exception { // // read in the source // final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_TransactionCorrelation.drl" ) ); // final RuleBase ruleBase = loadRuleBase( reader ); // // final WorkingMemory wm = ruleBase.newStatefulSession(); // final List results = new ArrayList(); // // wm.setGlobal( "results", // results ); // // // } @Test public void testIdleTime() throws Exception { // read in the source KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newInputStreamResource( getClass().getResourceAsStream( "test_CEP_SimpleEventAssertion.drl" ) ), ResourceType.DRL ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption( ClockTypeOption.get( "pseudo" ) ); StatefulKnowledgeSession session = createKnowledgeSession(kbase, conf); InternalWorkingMemory iwm = ((StatefulKnowledgeSessionImpl) session).session; SessionPseudoClock clock = (SessionPseudoClock) session.<SessionClock>getSessionClock(); final List results = new ArrayList(); session.setGlobal( "results", results ); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 10000 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 10010 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, 10100 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, 11000 ); assertEquals( 0, iwm.getIdleTime() ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); clock.advanceTime( 10, TimeUnit.SECONDS ); assertEquals( 10000, iwm.getIdleTime() ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); assertEquals( 0, iwm.getIdleTime() ); clock.advanceTime( 15, TimeUnit.SECONDS ); assertEquals( 15000, iwm.getIdleTime() ); clock.advanceTime( 15, TimeUnit.SECONDS ); assertEquals( 30000, iwm.getIdleTime() ); InternalFactHandle handle3 = (InternalFactHandle) session.insert( tick3 ); assertEquals( 0, iwm.getIdleTime() ); clock.advanceTime( 20, TimeUnit.SECONDS ); InternalFactHandle handle4 = (InternalFactHandle) session.insert( tick4 ); clock.advanceTime( 10, TimeUnit.SECONDS ); assertNotNull( handle1 ); assertNotNull( handle2 ); assertNotNull( handle3 ); assertNotNull( handle4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); assertEquals( 10000, iwm.getIdleTime() ); session.fireAllRules(); assertEquals( 0, iwm.getIdleTime() ); assertEquals( 2, ((List) session.getGlobal( "results" )).size() ); } @Test public void testIdleTimeAndTimeToNextJob() throws Exception { // read in the source KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_SimpleTimeWindow.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession wm = createKnowledgeSession( kbase, sconf ); WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger( wm ); File testTmpDir = new File( "target/test-tmp/" ); testTmpDir.mkdirs(); logger.setFileName( "target/test-tmp/testIdleTimeAndTimeToNextJob-audit" ); try { List results = new ArrayList(); wm.setGlobal( "results", results ); InternalWorkingMemory iwm = (InternalWorkingMemory) ((StatefulKnowledgeSessionImpl)wm).session; // how to initialize the clock? // how to configure the clock? SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock(); clock.advanceTime( 5, TimeUnit.SECONDS ); // 5 seconds // there is no next job, so returns -1 assertEquals( -1, iwm.getTimeToNextJob() ); wm.insert( new OrderEvent( "1", "customer A", 70 ) ); assertEquals( 0, iwm.getIdleTime() ); // now, there is a next job in 30 seconds: expire the event assertEquals( 30000, iwm.getTimeToNextJob() ); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 70, ((Number) results.get( 0 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds // next job is in 20 seconds: expire the event assertEquals( 20000, iwm.getTimeToNextJob() ); wm.insert( new OrderEvent( "2", "customer A", 60 ) ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( 65, ((Number) results.get( 1 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds // next job is in 10 seconds: expire the event assertEquals( 10000, iwm.getTimeToNextJob() ); wm.insert( new OrderEvent( "3", "customer A", 50 ) ); wm.fireAllRules(); assertEquals( 3, results.size() ); assertEquals( 60, ((Number) results.get( 2 )).intValue() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds // advancing clock time will cause events to expire assertEquals( 0, iwm.getIdleTime() ); // next job is in 10 seconds: expire another event //assertEquals( 10000, iwm.getTimeToNextJob()); wm.insert( new OrderEvent( "4", "customer A", 25 ) ); wm.fireAllRules(); // first event should have expired, making average under the rule threshold, so no additional rule fire assertEquals( 3, results.size() ); // advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds wm.insert( new OrderEvent( "5", "customer A", 70 ) ); assertEquals( 0, iwm.getIdleTime() ); // wm = SerializationHelper.serializeObject(wm); wm.fireAllRules(); // still under the threshold, so no fire assertEquals( 3, results.size() ); } finally { logger.writeToDisk(); } } @Test public void testCollectWithWindows() throws Exception { final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kbconf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase = loadKnowledgeBase( kbconf, "test_CEP_CollectWithWindows.drl" ); KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); ksconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase, ksconf); WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger( ksession ); File testTmpDir = new File( "target/test-tmp/" ); testTmpDir.mkdirs(); logger.setFileName( "target/test-tmp/testCollectWithWindows-audit" ); List<Number> timeResults = new ArrayList<Number>(); List<Number> lengthResults = new ArrayList<Number>(); ksession.setGlobal( "timeResults", timeResults ); ksession.setGlobal( "lengthResults", lengthResults ); SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); try { // First interaction clock.advanceTime( 5, TimeUnit.SECONDS ); // 5 seconds ksession.insert( new OrderEvent( "1", "customer A", 70 ) ); ksession.fireAllRules(); assertEquals( 1, timeResults.size() ); assertEquals( 1, timeResults.get( 0 ).intValue() ); assertEquals( 1, lengthResults.size() ); assertEquals( 1, lengthResults.get( 0 ).intValue() ); // Second interaction: advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds ksession.insert( new OrderEvent( "2", "customer A", 60 ) ); ksession.fireAllRules(); assertEquals( 2, timeResults.size() ); assertEquals( 2, timeResults.get( 1 ).intValue() ); assertEquals( 2, lengthResults.size() ); assertEquals( 2, lengthResults.get( 1 ).intValue() ); // Third interaction: advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds ksession.insert( new OrderEvent( "3", "customer A", 50 ) ); ksession.fireAllRules(); assertEquals( 3, timeResults.size() ); assertEquals( 3, timeResults.get( 2 ).intValue() ); assertEquals( 3, lengthResults.size() ); assertEquals( 3, lengthResults.get( 2 ).intValue() ); // Fourth interaction: advance clock and assert new data clock.advanceTime( 10, TimeUnit.SECONDS ); // 10 seconds ksession.insert( new OrderEvent( "4", "customer A", 25 ) ); ksession.fireAllRules(); // first event should have expired now assertEquals( 4, timeResults.size() ); assertEquals( 3, timeResults.get( 3 ).intValue() ); assertEquals( 4, lengthResults.size() ); assertEquals( 3, lengthResults.get( 3 ).intValue() ); // Fifth interaction: advance clock and assert new data clock.advanceTime( 5, TimeUnit.SECONDS ); // 10 seconds ksession.insert( new OrderEvent( "5", "customer A", 70 ) ); ksession.fireAllRules(); assertEquals( 5, timeResults.size() ); assertEquals( 4, timeResults.get( 4 ).intValue() ); assertEquals( 5, lengthResults.size() ); assertEquals( 3, lengthResults.get( 4 ).intValue() ); } finally { logger.writeToDisk(); } } @Test public void testPseudoSchedulerRemoveJobTest() { String str = "import org.drools.integrationtests.CepEspTest.A\n"; str += "declare A\n"; str += " @role( event )\n"; str += "end\n"; str += "rule A\n"; str += "when\n"; str += " $a : A()\n"; str += " not A(this after [1s,10s] $a)\n"; str += "then\n"; str += "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newReaderResource( new StringReader( str ) ), ResourceType.DRL ); assertFalse( kbuilder.getErrors().toString(), kbuilder.hasErrors() ); KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); config.setOption( EventProcessingOption.STREAM ); KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sessionConfig.setOption( ClockTypeOption.get( "pseudo" ) ); KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase( config ); knowledgeBase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession( sessionConfig, KnowledgeBaseFactory.newEnvironment() ); PseudoClockScheduler pseudoClock = ksession.<PseudoClockScheduler>getSessionClock(); FactHandle h = ksession.insert( new A() ); ksession.retract( h ); } public static class A implements Serializable { } public static class Message { private Properties properties; public Properties getProperties() { return properties; } public void setProperties( Properties properties ) { this.properties = properties; } } @Test public void testStreamModeNoSerialization() throws IOException, ClassNotFoundException { final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kbconf.setOption( EventProcessingOption.STREAM ); final KnowledgeBase kbase1 = loadKnowledgeBase( kbconf, "test_CEP_StreamMode.drl" ); KnowledgeBase kbase2 = (KnowledgeBase) DroolsStreamUtils.streamIn( DroolsStreamUtils.streamOut( kbase1 ), null ); final StatefulKnowledgeSession ksession1 = kbase1.newStatefulKnowledgeSession(); AgendaEventListener ael1 = mock( AgendaEventListener.class ); ksession1.addEventListener( ael1 ); final StatefulKnowledgeSession ksession2 = kbase2.newStatefulKnowledgeSession(); AgendaEventListener ael2 = mock( AgendaEventListener.class ); ksession2.addEventListener( ael2 ); // ------------- // first, check the non-serialized session // ------------- ksession1.insert( new Sensor( 10, 10 ) ); ksession1.fireAllRules(); ArgumentCaptor<AfterMatchFiredEvent> aafe1 = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); verify( ael1, times( 1 ) ).afterMatchFired(aafe1.capture()); List<AfterMatchFiredEvent> events1 = aafe1.getAllValues(); assertThat( events1.get( 0 ).getMatch().getDeclarationValue( "$avg" ), is( (Object) 10 ) ); ksession1.insert( new Sensor( 20, 20 ) ); ksession1.fireAllRules(); verify( ael1, times( 2 ) ).afterMatchFired(aafe1.capture()); assertThat( events1.get( 1 ).getMatch().getDeclarationValue( "$avg" ), is( (Object) 15 ) ); ksession1.insert( new Sensor( 30, 30 ) ); ksession1.fireAllRules(); verify( ael1, times( 3 ) ).afterMatchFired(aafe1.capture()); assertThat( events1.get( 2 ).getMatch().getDeclarationValue( "$avg" ), is( (Object) 25 ) ); ksession1.dispose(); // ------------- // now we check the serialized session // ------------- ArgumentCaptor<AfterMatchFiredEvent> aafe2 = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); ksession2.insert( new Sensor( 10, 10 ) ); ksession2.fireAllRules(); verify( ael2, times( 1 ) ).afterMatchFired(aafe2.capture()); List<AfterMatchFiredEvent> events2 = aafe2.getAllValues(); assertThat( events2.get( 0 ).getMatch().getDeclarationValue( "$avg" ), is( (Object) 10 ) ); ksession2.insert( new Sensor( 20, 20 ) ); ksession2.fireAllRules(); verify( ael2, times( 2 ) ).afterMatchFired(aafe2.capture()); assertThat( events2.get( 1 ).getMatch().getDeclarationValue( "$avg" ), is( (Object) 15 ) ); ksession2.insert( new Sensor( 30, 30 ) ); ksession2.fireAllRules(); verify( ael2, times( 3 ) ).afterMatchFired(aafe2.capture()); assertThat( events2.get( 2 ).getMatch().getDeclarationValue( "$avg" ), is( (Object) 25 ) ); ksession2.dispose(); } @Test public void testIdentityAssertBehaviorOnEntryPoints() throws IOException, ClassNotFoundException { StockTickInterface st1 = new StockTick( 1, "RHT", 10, 10 ); StockTickInterface st2 = new StockTick( 1, "RHT", 10, 10 ); StockTickInterface st3 = new StockTick( 2, "RHT", 15, 20 ); final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kbconf.setOption( EventProcessingOption.STREAM ); kbconf.setOption( EqualityBehaviorOption.IDENTITY ); final KnowledgeBase kbase1 = loadKnowledgeBase( kbconf, "test_CEP_AssertBehaviorOnEntryPoints.drl" ); final StatefulKnowledgeSession ksession = kbase1.newStatefulKnowledgeSession(); AgendaEventListener ael1 = mock( AgendaEventListener.class ); ksession.addEventListener( ael1 ); SessionEntryPoint ep1 = ksession.getEntryPoint( "stocktick stream" ); FactHandle fh1 = ep1.insert( st1 ); FactHandle fh1_2 = ep1.insert( st1 ); FactHandle fh2 = ep1.insert( st2 ); FactHandle fh3 = ep1.insert( st3 ); assertSame( fh1, fh1_2 ); assertNotSame( fh1, fh2 ); assertNotSame( fh1, fh3 ); assertNotSame( fh2, fh3 ); ksession.fireAllRules(); // must have fired 3 times, one for each event identity verify( ael1, times( 3 ) ).afterMatchFired(any(AfterMatchFiredEvent.class)); ksession.dispose(); } @Test public void testEqualityAssertBehaviorOnEntryPoints() throws IOException, ClassNotFoundException { StockTickInterface st1 = new StockTick( 1, "RHT", 10, 10 ); StockTickInterface st2 = new StockTick( 1, "RHT", 10, 10 ); StockTickInterface st3 = new StockTick( 2, "RHT", 15, 20 ); final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kbconf.setOption( EventProcessingOption.STREAM ); kbconf.setOption( EqualityBehaviorOption.EQUALITY ); final KnowledgeBase kbase1 = loadKnowledgeBase( kbconf, "test_CEP_AssertBehaviorOnEntryPoints.drl" ); final StatefulKnowledgeSession ksession1 = kbase1.newStatefulKnowledgeSession(); AgendaEventListener ael1 = mock( AgendaEventListener.class ); ksession1.addEventListener( ael1 ); SessionEntryPoint ep1 = ksession1.getEntryPoint( "stocktick stream" ); FactHandle fh1 = ep1.insert( st1 ); FactHandle fh1_2 = ep1.insert( st1 ); FactHandle fh2 = ep1.insert( st2 ); FactHandle fh3 = ep1.insert( st3 ); assertSame( fh1, fh1_2 ); assertSame( fh1, fh2 ); assertNotSame( fh1, fh3 ); ksession1.fireAllRules(); // must have fired 2 times, one for each event equality verify( ael1, times( 2 ) ).afterMatchFired(any(AfterMatchFiredEvent.class)); ksession1.dispose(); } @Test public void testEventDeclarationForInterfaces() throws Exception { // read in the source final KnowledgeBase kbase = loadKnowledgeBase( "test_CEP_EventInterfaces.drl" ); StatefulKnowledgeSession session = createKnowledgeSession(kbase); StockTickInterface tick1 = new StockTick( 1, "DROO", 50, 10000 ); StockTickInterface tick2 = new StockTick( 2, "ACME", 10, 10010 ); StockTickInterface tick3 = new StockTick( 3, "ACME", 10, 10100 ); StockTickInterface tick4 = new StockTick( 4, "DROO", 50, 11000 ); InternalFactHandle handle1 = (InternalFactHandle) session.insert( tick1 ); InternalFactHandle handle2 = (InternalFactHandle) session.insert( tick2 ); InternalFactHandle handle3 = (InternalFactHandle) session.insert( tick3 ); InternalFactHandle handle4 = (InternalFactHandle) session.insert( tick4 ); assertTrue( handle1.isEvent() ); assertTrue( handle2.isEvent() ); assertTrue( handle3.isEvent() ); assertTrue( handle4.isEvent() ); } @Test public void testTemporalOperators() throws Exception { // read in the source final RuleBaseConfiguration kbconf = new RuleBaseConfiguration(); kbconf.setEventProcessingMode( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBase( kbconf, "test_CEP_TemporalOperators.drl" ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); ksession.insert( new StockTick( 1, "A", 10, 1000 ) ); } @Test public void testTemporalOperators2() throws Exception { // read in the source final RuleBaseConfiguration kbconf = new RuleBaseConfiguration(); kbconf.setEventProcessingMode( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBase( kbconf, "test_CEP_TemporalOperators2.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase, sconf); SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); SessionEntryPoint ep = ksession.getEntryPoint( "X" ); clock.advanceTime( 1000, TimeUnit.SECONDS ); ep.insert( new StockTick( 1, "A", 10, clock.getCurrentTime() ) ); clock.advanceTime( 8, TimeUnit.SECONDS ); ep.insert( new StockTick( 2, "B", 10, clock.getCurrentTime() ) ); clock.advanceTime( 8, TimeUnit.SECONDS ); ep.insert( new StockTick( 3, "B", 10, clock.getCurrentTime() ) ); clock.advanceTime( 8, TimeUnit.SECONDS ); int rules = ksession.fireAllRules(); assertEquals( 2, rules ); } @Test public void testTemporalOperatorsInfinity() throws Exception { // read in the source final RuleBaseConfiguration kbconf = new RuleBaseConfiguration(); kbconf.setEventProcessingMode( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBase( kbconf, "test_CEP_TemporalOperators3.drl" ); KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession( sconf, null ); SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); SessionEntryPoint ep = ksession.getEntryPoint( "X" ); clock.advanceTime( 1000, TimeUnit.SECONDS ); ep.insert( new StockTick( 1, "A", 10, clock.getCurrentTime() ) ); clock.advanceTime( 8, TimeUnit.SECONDS ); ep.insert( new StockTick( 2, "B", 10, clock.getCurrentTime() ) ); clock.advanceTime( 8, TimeUnit.SECONDS ); ep.insert( new StockTick( 3, "B", 10, clock.getCurrentTime() ) ); clock.advanceTime( 8, TimeUnit.SECONDS ); int rules = ksession.fireAllRules(); assertEquals( 3, rules ); } @Test public void testMultipleSlidingWindows() throws IOException, ClassNotFoundException { String str = "declare A\n" + " @role( event )\n" + " id : int\n" + "end\n" + "declare B\n" + " @role( event )\n" + " id : int\n" + "end\n" + "rule launch\n" + "when\n" + "then\n" + " insert( new A( 1 ) );\n" + " insert( new A( 2 ) );\n" + " insert( new B( 1 ) );\n" + " insert( new A( 3 ) );\n" + " insert( new B( 2 ) );\n" + "end\n" + "rule \"ab\"\n" + "when\n" + " A( $a : id ) over window:length( 1 )\n" + " B( $b : id ) over window:length( 1 )\n" + "then\n" + " //System.out.println(\"AB: ( \"+$a+\", \"+$b+\" )\");\n" + "end\n" + "rule \"ba\"\n" + "when\n" + " B( $b : id ) over window:length( 1 )\n" + " A( $a : id ) over window:length( 1 )\n" + "then\n" + " //System.out.println(\"BA: ( \"+$b+\", \"+$a+\" )\");\n" + "end"; KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); config.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBaseFromString( config, str ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); ksession.fireAllRules(); ArgumentCaptor<AfterMatchFiredEvent> captor = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); verify( ael, times( 7 ) ).afterMatchFired(captor.capture()); List<AfterMatchFiredEvent> values = captor.getAllValues(); // first rule Match act = values.get( 0 ).getMatch(); assertThat( act.getRule().getName(), is( "launch" ) ); // second rule act = values.get( 1 ).getMatch(); assertThat( act.getRule().getName(), is( "ba" ) ); assertThat( ((Number) act.getDeclarationValue( "$a" )).intValue(), is( 3 ) ); assertThat( ((Number) act.getDeclarationValue( "$b" )).intValue(), is( 2 ) ); // third rule act = values.get( 2 ).getMatch(); assertThat( act.getRule().getName(), is( "ab" ) ); assertThat( ((Number) act.getDeclarationValue( "$a" )).intValue(), is( 3 ) ); assertThat( ((Number) act.getDeclarationValue( "$b" )).intValue(), is( 2 ) ); // fourth rule act = values.get( 3 ).getMatch(); assertThat( act.getRule().getName(), is( "ba" ) ); assertThat( ((Number) act.getDeclarationValue( "$a" )).intValue(), is( 3 ) ); assertThat( ((Number) act.getDeclarationValue( "$b" )).intValue(), is( 1 ) ); // fifth rule act = values.get( 4 ).getMatch(); assertThat( act.getRule().getName(), is( "ab" ) ); assertThat( ((Number) act.getDeclarationValue( "$a" )).intValue(), is( 3 ) ); assertThat( ((Number) act.getDeclarationValue( "$b" )).intValue(), is( 1 ) ); // sixth rule act = values.get( 5 ).getMatch(); assertThat( act.getRule().getName(), is( "ba" ) ); assertThat( ((Number) act.getDeclarationValue( "$a" )).intValue(), is( 2 ) ); assertThat( ((Number) act.getDeclarationValue( "$b" )).intValue(), is( 1 ) ); // seventh rule act = values.get( 6 ).getMatch(); assertThat( act.getRule().getName(), is( "ab" ) ); assertThat( ((Number) act.getDeclarationValue( "$a" )).intValue(), is( 2 ) ); assertThat( ((Number) act.getDeclarationValue( "$b" )).intValue(), is( 1 ) ); } @Test public void testCloudModeExpiration() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, InterruptedException { String str = "package org.drools.cloud\n" + "import org.drools.*\n" + "declare Event\n" + " @role ( event )\n" + " name : String\n" + " value : Object\n" + "end\n" + "declare AnotherEvent\n" + " @role ( event )\n" + " message : String\n" + " type : String\n" + "end\n" + "declare StockTick\n" + " @role ( event )\n" + "end\n" + "rule \"two events\"\n" + " when\n" + " Event( value != null ) from entry-point X\n" + " StockTick( company != null ) from entry-point X\n" + " then\n" + "end"; KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); config.setOption( EventProcessingOption.CLOUD ); KnowledgeBase kbase = loadKnowledgeBaseFromString( config, str ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); SessionEntryPoint ep = ksession.getEntryPoint( "X" ); ep.insert( new StockTick( 1, "RHT", 10, 1000 ) ); int rulesFired = ksession.fireAllRules(); assertEquals( 0, rulesFired ); org.kie.definition.type.FactType event = kbase.getFactType( "org.drools.cloud", "Event" ); Object e1 = event.newInstance(); event.set( e1, "name", "someKey" ); event.set( e1, "value", "someValue" ); ep.insert( e1 ); rulesFired = ksession.fireAllRules(); assertEquals( 1, rulesFired ); // let some time be spent Thread.currentThread().sleep( 1000 ); // check both events are still in memory as we are running in CLOUD mode assertEquals( 2, ep.getFactCount() ); } @Test public void testSalienceWithEventsPseudoClock() throws IOException, ClassNotFoundException { String str = "package org.drools\n" + "declare StockTick\n" + " @role ( event )\n" + "end\n" + "rule R1 salience 1000\n" + " when\n" + " $s1 : StockTick( company == 'RHT' )\n" + " $s2 : StockTick( company == 'ACME', this after[0s,1m] $s1 )\n" + " then\n" + "end\n" + "rule R2 salience 1000\n" + " when\n" + " $s1 : StockTick( company == 'RHT' )\n" + " not StockTick( company == 'ACME', this after[0s,1m] $s1 )\n" + " then\n" + "end\n" + "rule R3 salience 100\n" + " when\n" + " $s2 : StockTick( company == 'ACME' )\n" + " then\n" + "end\n"; KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); config.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBaseFromString( config, str ); KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); ksconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession( ksconf, null ); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); clock.advanceTime( 1000000, TimeUnit.MILLISECONDS ); ksession.insert( new StockTick( 1, "RHT", 10, 1000 ) ); clock.advanceTime( 5, TimeUnit.SECONDS ); ksession.insert( new StockTick( 2, "RHT", 10, 1000 ) ); clock.advanceTime( 5, TimeUnit.SECONDS ); ksession.insert( new StockTick( 3, "RHT", 10, 1000 ) ); clock.advanceTime( 5, TimeUnit.SECONDS ); ksession.insert( new StockTick( 4, "ACME", 10, 1000 ) ); clock.advanceTime( 5, TimeUnit.SECONDS ); int rulesFired = ksession.fireAllRules(); assertEquals( 4, rulesFired ); ArgumentCaptor<AfterMatchFiredEvent> captor = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); verify( ael, times( 4 ) ).afterMatchFired(captor.capture()); List<AfterMatchFiredEvent> aafe = captor.getAllValues(); Assert.assertThat( aafe.get( 0 ).getMatch().getRule().getName(), is( "R1" ) ); Assert.assertThat( aafe.get( 1 ).getMatch().getRule().getName(), is( "R1" ) ); Assert.assertThat( aafe.get( 2 ).getMatch().getRule().getName(), is( "R1" ) ); Assert.assertThat( aafe.get( 3 ).getMatch().getRule().getName(), is( "R3" ) ); } @Test public void testSalienceWithEventsRealtimeClock() throws IOException, ClassNotFoundException, InterruptedException { String str = "package org.drools\n" + "declare StockTick\n" + " @role ( event )\n" + "end\n" + "rule R1 salience 1000\n" + " when\n" + " $s1 : StockTick( company == 'RHT' )\n" + " $s2 : StockTick( company == 'ACME', this after[0s,1m] $s1 )\n" + " then\n" + "end\n" + "rule R2 salience 1000\n" + " when\n" + " $s1 : StockTick( company == 'RHT' )\n" + " not StockTick( company == 'ACME', this after[0s,1m] $s1 )\n" + " then\n" + "end\n" + "rule R3 salience 100\n" + " when\n" + " $s2 : StockTick( company == 'ACME' )\n" + " then\n" + "end\n"; KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); config.setOption( EventProcessingOption.STREAM ); KnowledgeBase kbase = loadKnowledgeBaseFromString( config, str ); KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); ksconf.setOption( ClockTypeOption.get( ClockType.REALTIME_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession( ksconf, null ); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); ksession.insert( new StockTick( 1, "RHT", 10, 1000 ) ); ksession.insert( new StockTick( 2, "RHT", 10, 1000 ) ); ksession.insert( new StockTick( 3, "RHT", 10, 1000 ) ); // sleep for 2 secs Thread.currentThread().sleep( 2000 ); ksession.insert( new StockTick( 4, "ACME", 10, 1000 ) ); // sleep for 1 sec Thread.currentThread().sleep( 1000 ); int rulesFired = ksession.fireAllRules(); assertEquals( 4, rulesFired ); ArgumentCaptor<AfterMatchFiredEvent> captor = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); verify( ael, times( 4 ) ).afterMatchFired(captor.capture()); List<AfterMatchFiredEvent> aafe = captor.getAllValues(); Assert.assertThat( aafe.get( 0 ).getMatch().getRule().getName(), is( "R1" ) ); Assert.assertThat( aafe.get( 1 ).getMatch().getRule().getName(), is( "R1" ) ); Assert.assertThat( aafe.get( 2 ).getMatch().getRule().getName(), is( "R1" ) ); Assert.assertThat( aafe.get( 3 ).getMatch().getRule().getName(), is( "R3" ) ); } @Test public void testExpireEventOnEndTimestamp() throws Exception { // DROOLS-40 String str = "package org.drools;\n" + "\n" + "import org.drools.StockTick;\n" + "\n" + "global java.util.List resultsAfter;\n" + "\n" + "declare StockTick\n" + " @role( event )\n" + " @duration( duration )\n" + "end\n" + "\n" + "rule \"after[60,80]\"\n" + "when\n" + "$a : StockTick( company == \"DROO\" )\n" + "$b : StockTick( company == \"ACME\", this after[60,80] $a )\n" + "then\n" + " resultsAfter.add( $b );\n" + "end"; KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); config.setOption(EventProcessingOption.STREAM); KnowledgeBase kbase = loadKnowledgeBaseFromString(config, str); KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(conf, null); PseudoClockScheduler clock = (PseudoClockScheduler) ksession.getSessionClock(); List<StockTick> resultsAfter = new ArrayList<StockTick>(); ksession.setGlobal("resultsAfter", resultsAfter); // inserting new StockTick with duration 30 at time 0 => rule // after[60,80] should fire when ACME lasts at 100-120 ksession.insert(new StockTick(1, "DROO", 0, 0, 30)); clock.advanceTime(100, TimeUnit.MILLISECONDS); ksession.insert(new StockTick(2, "ACME", 0, 0, 20)); ksession.fireAllRules(); assertEquals(1, resultsAfter.size()); } }
apache-2.0
spepping/fop-cs
src/java/org/apache/fop/afp/AFPImageObjectInfo.java
3503
/* * 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. */ /* $Id$ */ package org.apache.fop.afp; /** * A list of parameters associated with an image */ public class AFPImageObjectInfo extends AFPDataObjectInfo { /** number of bits per pixel used */ private int bitsPerPixel; /** is this a color image? */ private boolean color; /** compression type if any */ private int compression = -1; private boolean subtractive; /** * Default constructor */ public AFPImageObjectInfo() { super(); } /** * Sets the number of bits per pixel * * @param bitsPerPixel the number of bits per pixel */ public void setBitsPerPixel(int bitsPerPixel) { this.bitsPerPixel = bitsPerPixel; } /** * Sets if this image is color * * @param color true if this is a color image */ public void setColor(boolean color) { this.color = color; } /** * Returns the number of bits used per pixel * * @return the number of bits used per pixel */ public int getBitsPerPixel() { return bitsPerPixel; } /** * Returns true if this is a color image * * @return true if this is a color image */ public boolean isColor() { return color; } /** * Returns true if this image uses compression * * @return true if this image uses compression */ public boolean hasCompression() { return compression != -1; } /** * Returns the compression type * * @return the compression type */ public int getCompression() { return compression; } /** * Sets the compression used with this image * * @param compression the type of compression used with this image */ public void setCompression(int compression) { this.compression = compression; } /** * Set either additive or subtractive mode (used for ASFLAG). * @param subtractive true for subtractive mode, false for additive mode */ public void setSubtractive(boolean subtractive) { this.subtractive = subtractive; } /** * Indicates whether additive or subtractive mode is set. * @return true for subtractive mode, false for additive mode */ public boolean isSubtractive() { return subtractive; } /** {@inheritDoc} */ @Override public String toString() { return "AFPImageObjectInfo{" + super.toString() + ", compression=" + compression + ", color=" + color + ", bitsPerPixel=" + bitsPerPixel + ", " + (isSubtractive() ? "subtractive" : "additive") + "}"; } }
apache-2.0
alain898/distributed-search-cache
src/main/java/com/alain898/dscache/cache/collection/IBlock.java
278
package com.alain898.dscache.cache.collection; /** * Created by alain on 16/8/16. */ public interface IBlock<E> extends Iterable<E> { int size(); boolean isEmpty(); E get(int index); boolean add(E e); E set(int index, E element); void clear(); }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p307/Production6141.java
2132
package org.gradle.test.performance.mediummonolithicjavaproject.p307; import org.gradle.test.performance.mediummonolithicjavaproject.p306.Production6138; import org.gradle.test.performance.mediummonolithicjavaproject.p306.Production6139; public class Production6141 { private Production6138 property0; public Production6138 getProperty0() { return property0; } public void setProperty0(Production6138 value) { property0 = value; } private Production6139 property1; public Production6139 getProperty1() { return property1; } public void setProperty1(Production6139 value) { property1 = value; } private Production6140 property2; public Production6140 getProperty2() { return property2; } public void setProperty2(Production6140 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
apache-2.0
junkerm/specmate
bundles/specmate-migration-test/src/com/specmate/migration/test/objectadded/testmodel/artefact/impl/SketchImpl.java
62398
/** */ package com.specmate.migration.test.objectadded.testmodel.artefact.impl; import com.specmate.migration.test.objectadded.testmodel.artefact.ArtefactPackage; import com.specmate.migration.test.objectadded.testmodel.artefact.Sketch; import com.specmate.migration.test.objectadded.testmodel.base.BasePackage; import com.specmate.migration.test.objectadded.testmodel.base.IContainer; import com.specmate.migration.test.objectadded.testmodel.base.IContentElement; import com.specmate.migration.test.objectadded.testmodel.base.IID; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Sketch</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#isTested <em>Tested</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getId <em>Id</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getContents <em>Contents</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getByteVar1 <em>Byte Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getByteVar2 <em>Byte Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getByteVar3 <em>Byte Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getByteVar4 <em>Byte Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getByteVar5 <em>Byte Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getShortVar1 <em>Short Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getShortVar2 <em>Short Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getShortVar3 <em>Short Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getShortVar4 <em>Short Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getShortVar5 <em>Short Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getIntVar1 <em>Int Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getIntVar2 <em>Int Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getIntVar3 <em>Int Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getIntVar4 <em>Int Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getIntVar5 <em>Int Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getCharVar1 <em>Char Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getCharVar2 <em>Char Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getCharVar3 <em>Char Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getCharVar4 <em>Char Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getCharVar5 <em>Char Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getLongVar1 <em>Long Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getLongVar2 <em>Long Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getLongVar3 <em>Long Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getLongVar4 <em>Long Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getLongVar5 <em>Long Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getFloatVar1 <em>Float Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getFloatVar2 <em>Float Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getFloatVar3 <em>Float Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getFloatVar4 <em>Float Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getFloatVar5 <em>Float Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getDoubleVar1 <em>Double Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getDoubleVar2 <em>Double Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getDoubleVar3 <em>Double Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getDoubleVar4 <em>Double Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getDoubleVar5 <em>Double Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#isBooleanVar1 <em>Boolean Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#isBooleanVar2 <em>Boolean Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#isBooleanVar3 <em>Boolean Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#isBooleanVar4 <em>Boolean Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#isBooleanVar5 <em>Boolean Var5</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getStringVar1 <em>String Var1</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getStringVar2 <em>String Var2</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getStringVar3 <em>String Var3</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getStringVar4 <em>String Var4</em>}</li> * <li>{@link com.specmate.migration.test.objectadded.testmodel.artefact.impl.SketchImpl#getStringVar5 <em>String Var5</em>}</li> * </ul> * * @generated */ public class SketchImpl extends MinimalEObjectImpl.Container implements Sketch { /** * The default value of the '{@link #isTested() <em>Tested</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isTested() * @generated * @ordered */ protected static final boolean TESTED_EDEFAULT = false; /** * The default value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected static final String ID_EDEFAULT = null; /** * The default value of the '{@link #getByteVar1() <em>Byte Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getByteVar1() * @generated * @ordered */ protected static final byte BYTE_VAR1_EDEFAULT = 0x00; /** * The default value of the '{@link #getByteVar2() <em>Byte Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getByteVar2() * @generated * @ordered */ protected static final byte BYTE_VAR2_EDEFAULT = 0x00; /** * The default value of the '{@link #getByteVar3() <em>Byte Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getByteVar3() * @generated * @ordered */ protected static final byte BYTE_VAR3_EDEFAULT = 0x00; /** * The default value of the '{@link #getByteVar4() <em>Byte Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getByteVar4() * @generated * @ordered */ protected static final byte BYTE_VAR4_EDEFAULT = 0x00; /** * The default value of the '{@link #getByteVar5() <em>Byte Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getByteVar5() * @generated * @ordered */ protected static final byte BYTE_VAR5_EDEFAULT = 0x00; /** * The default value of the '{@link #getShortVar1() <em>Short Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShortVar1() * @generated * @ordered */ protected static final short SHORT_VAR1_EDEFAULT = 0; /** * The default value of the '{@link #getShortVar2() <em>Short Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShortVar2() * @generated * @ordered */ protected static final short SHORT_VAR2_EDEFAULT = 0; /** * The default value of the '{@link #getShortVar3() <em>Short Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShortVar3() * @generated * @ordered */ protected static final short SHORT_VAR3_EDEFAULT = 0; /** * The default value of the '{@link #getShortVar4() <em>Short Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShortVar4() * @generated * @ordered */ protected static final short SHORT_VAR4_EDEFAULT = 0; /** * The default value of the '{@link #getShortVar5() <em>Short Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShortVar5() * @generated * @ordered */ protected static final short SHORT_VAR5_EDEFAULT = 0; /** * The default value of the '{@link #getIntVar1() <em>Int Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIntVar1() * @generated * @ordered */ protected static final int INT_VAR1_EDEFAULT = 0; /** * The default value of the '{@link #getIntVar2() <em>Int Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIntVar2() * @generated * @ordered */ protected static final int INT_VAR2_EDEFAULT = 0; /** * The default value of the '{@link #getIntVar3() <em>Int Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIntVar3() * @generated * @ordered */ protected static final int INT_VAR3_EDEFAULT = 0; /** * The default value of the '{@link #getIntVar4() <em>Int Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIntVar4() * @generated * @ordered */ protected static final int INT_VAR4_EDEFAULT = 0; /** * The default value of the '{@link #getIntVar5() <em>Int Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIntVar5() * @generated * @ordered */ protected static final int INT_VAR5_EDEFAULT = 0; /** * The default value of the '{@link #getCharVar1() <em>Char Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCharVar1() * @generated * @ordered */ protected static final char CHAR_VAR1_EDEFAULT = '\u0000'; /** * The default value of the '{@link #getCharVar2() <em>Char Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCharVar2() * @generated * @ordered */ protected static final char CHAR_VAR2_EDEFAULT = '\u0000'; /** * The default value of the '{@link #getCharVar3() <em>Char Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCharVar3() * @generated * @ordered */ protected static final char CHAR_VAR3_EDEFAULT = '\u0000'; /** * The default value of the '{@link #getCharVar4() <em>Char Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCharVar4() * @generated * @ordered */ protected static final char CHAR_VAR4_EDEFAULT = '\u0000'; /** * The default value of the '{@link #getCharVar5() <em>Char Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCharVar5() * @generated * @ordered */ protected static final char CHAR_VAR5_EDEFAULT = '\u0000'; /** * The default value of the '{@link #getLongVar1() <em>Long Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLongVar1() * @generated * @ordered */ protected static final long LONG_VAR1_EDEFAULT = 0L; /** * The default value of the '{@link #getLongVar2() <em>Long Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLongVar2() * @generated * @ordered */ protected static final long LONG_VAR2_EDEFAULT = 0L; /** * The default value of the '{@link #getLongVar3() <em>Long Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLongVar3() * @generated * @ordered */ protected static final long LONG_VAR3_EDEFAULT = 0L; /** * The default value of the '{@link #getLongVar4() <em>Long Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLongVar4() * @generated * @ordered */ protected static final long LONG_VAR4_EDEFAULT = 0L; /** * The default value of the '{@link #getLongVar5() <em>Long Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLongVar5() * @generated * @ordered */ protected static final long LONG_VAR5_EDEFAULT = 0L; /** * The default value of the '{@link #getFloatVar1() <em>Float Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatVar1() * @generated * @ordered */ protected static final float FLOAT_VAR1_EDEFAULT = 0.0F; /** * The default value of the '{@link #getFloatVar2() <em>Float Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatVar2() * @generated * @ordered */ protected static final float FLOAT_VAR2_EDEFAULT = 0.0F; /** * The default value of the '{@link #getFloatVar3() <em>Float Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatVar3() * @generated * @ordered */ protected static final float FLOAT_VAR3_EDEFAULT = 0.0F; /** * The default value of the '{@link #getFloatVar4() <em>Float Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatVar4() * @generated * @ordered */ protected static final float FLOAT_VAR4_EDEFAULT = 0.0F; /** * The default value of the '{@link #getFloatVar5() <em>Float Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatVar5() * @generated * @ordered */ protected static final float FLOAT_VAR5_EDEFAULT = 0.0F; /** * The default value of the '{@link #getDoubleVar1() <em>Double Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDoubleVar1() * @generated * @ordered */ protected static final double DOUBLE_VAR1_EDEFAULT = 0.0; /** * The default value of the '{@link #getDoubleVar2() <em>Double Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDoubleVar2() * @generated * @ordered */ protected static final double DOUBLE_VAR2_EDEFAULT = 0.0; /** * The default value of the '{@link #getDoubleVar3() <em>Double Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDoubleVar3() * @generated * @ordered */ protected static final double DOUBLE_VAR3_EDEFAULT = 0.0; /** * The default value of the '{@link #getDoubleVar4() <em>Double Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDoubleVar4() * @generated * @ordered */ protected static final double DOUBLE_VAR4_EDEFAULT = 0.0; /** * The default value of the '{@link #getDoubleVar5() <em>Double Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDoubleVar5() * @generated * @ordered */ protected static final double DOUBLE_VAR5_EDEFAULT = 0.0; /** * The default value of the '{@link #isBooleanVar1() <em>Boolean Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBooleanVar1() * @generated * @ordered */ protected static final boolean BOOLEAN_VAR1_EDEFAULT = false; /** * The default value of the '{@link #isBooleanVar2() <em>Boolean Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBooleanVar2() * @generated * @ordered */ protected static final boolean BOOLEAN_VAR2_EDEFAULT = false; /** * The default value of the '{@link #isBooleanVar3() <em>Boolean Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBooleanVar3() * @generated * @ordered */ protected static final boolean BOOLEAN_VAR3_EDEFAULT = false; /** * The default value of the '{@link #isBooleanVar4() <em>Boolean Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBooleanVar4() * @generated * @ordered */ protected static final boolean BOOLEAN_VAR4_EDEFAULT = false; /** * The default value of the '{@link #isBooleanVar5() <em>Boolean Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isBooleanVar5() * @generated * @ordered */ protected static final boolean BOOLEAN_VAR5_EDEFAULT = false; /** * The default value of the '{@link #getStringVar1() <em>String Var1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStringVar1() * @generated * @ordered */ protected static final String STRING_VAR1_EDEFAULT = null; /** * The default value of the '{@link #getStringVar2() <em>String Var2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStringVar2() * @generated * @ordered */ protected static final String STRING_VAR2_EDEFAULT = null; /** * The default value of the '{@link #getStringVar3() <em>String Var3</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStringVar3() * @generated * @ordered */ protected static final String STRING_VAR3_EDEFAULT = null; /** * The default value of the '{@link #getStringVar4() <em>String Var4</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStringVar4() * @generated * @ordered */ protected static final String STRING_VAR4_EDEFAULT = null; /** * The default value of the '{@link #getStringVar5() <em>String Var5</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStringVar5() * @generated * @ordered */ protected static final String STRING_VAR5_EDEFAULT = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SketchImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ArtefactPackage.Literals.SKETCH; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected int eStaticFeatureCount() { return 0; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isTested() { return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__TESTED, BasePackage.Literals.ITESTABLE__TESTED, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTested(boolean newTested) { eDynamicSet(ArtefactPackage.SKETCH__TESTED, BasePackage.Literals.ITESTABLE__TESTED, newTested); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getId() { return (String)eDynamicGet(ArtefactPackage.SKETCH__ID, BasePackage.Literals.IID__ID, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setId(String newId) { eDynamicSet(ArtefactPackage.SKETCH__ID, BasePackage.Literals.IID__ID, newId); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") public EList<IContentElement> getContents() { return (EList<IContentElement>)eDynamicGet(ArtefactPackage.SKETCH__CONTENTS, BasePackage.Literals.ICONTAINER__CONTENTS, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public byte getByteVar1() { return (Byte)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR1, ArtefactPackage.Literals.SKETCH__BYTE_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setByteVar1(byte newByteVar1) { eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR1, ArtefactPackage.Literals.SKETCH__BYTE_VAR1, newByteVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public byte getByteVar2() { return (Byte)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR2, ArtefactPackage.Literals.SKETCH__BYTE_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setByteVar2(byte newByteVar2) { eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR2, ArtefactPackage.Literals.SKETCH__BYTE_VAR2, newByteVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public byte getByteVar3() { return (Byte)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR3, ArtefactPackage.Literals.SKETCH__BYTE_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setByteVar3(byte newByteVar3) { eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR3, ArtefactPackage.Literals.SKETCH__BYTE_VAR3, newByteVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public byte getByteVar4() { return (Byte)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR4, ArtefactPackage.Literals.SKETCH__BYTE_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setByteVar4(byte newByteVar4) { eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR4, ArtefactPackage.Literals.SKETCH__BYTE_VAR4, newByteVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public byte getByteVar5() { return (Byte)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR5, ArtefactPackage.Literals.SKETCH__BYTE_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setByteVar5(byte newByteVar5) { eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR5, ArtefactPackage.Literals.SKETCH__BYTE_VAR5, newByteVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public short getShortVar1() { return (Short)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR1, ArtefactPackage.Literals.SKETCH__SHORT_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setShortVar1(short newShortVar1) { eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR1, ArtefactPackage.Literals.SKETCH__SHORT_VAR1, newShortVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public short getShortVar2() { return (Short)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR2, ArtefactPackage.Literals.SKETCH__SHORT_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setShortVar2(short newShortVar2) { eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR2, ArtefactPackage.Literals.SKETCH__SHORT_VAR2, newShortVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public short getShortVar3() { return (Short)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR3, ArtefactPackage.Literals.SKETCH__SHORT_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setShortVar3(short newShortVar3) { eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR3, ArtefactPackage.Literals.SKETCH__SHORT_VAR3, newShortVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public short getShortVar4() { return (Short)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR4, ArtefactPackage.Literals.SKETCH__SHORT_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setShortVar4(short newShortVar4) { eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR4, ArtefactPackage.Literals.SKETCH__SHORT_VAR4, newShortVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public short getShortVar5() { return (Short)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR5, ArtefactPackage.Literals.SKETCH__SHORT_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setShortVar5(short newShortVar5) { eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR5, ArtefactPackage.Literals.SKETCH__SHORT_VAR5, newShortVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getIntVar1() { return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR1, ArtefactPackage.Literals.SKETCH__INT_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIntVar1(int newIntVar1) { eDynamicSet(ArtefactPackage.SKETCH__INT_VAR1, ArtefactPackage.Literals.SKETCH__INT_VAR1, newIntVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getIntVar2() { return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR2, ArtefactPackage.Literals.SKETCH__INT_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIntVar2(int newIntVar2) { eDynamicSet(ArtefactPackage.SKETCH__INT_VAR2, ArtefactPackage.Literals.SKETCH__INT_VAR2, newIntVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getIntVar3() { return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR3, ArtefactPackage.Literals.SKETCH__INT_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIntVar3(int newIntVar3) { eDynamicSet(ArtefactPackage.SKETCH__INT_VAR3, ArtefactPackage.Literals.SKETCH__INT_VAR3, newIntVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getIntVar4() { return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR4, ArtefactPackage.Literals.SKETCH__INT_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIntVar4(int newIntVar4) { eDynamicSet(ArtefactPackage.SKETCH__INT_VAR4, ArtefactPackage.Literals.SKETCH__INT_VAR4, newIntVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getIntVar5() { return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR5, ArtefactPackage.Literals.SKETCH__INT_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIntVar5(int newIntVar5) { eDynamicSet(ArtefactPackage.SKETCH__INT_VAR5, ArtefactPackage.Literals.SKETCH__INT_VAR5, newIntVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public char getCharVar1() { return (Character)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR1, ArtefactPackage.Literals.SKETCH__CHAR_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCharVar1(char newCharVar1) { eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR1, ArtefactPackage.Literals.SKETCH__CHAR_VAR1, newCharVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public char getCharVar2() { return (Character)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR2, ArtefactPackage.Literals.SKETCH__CHAR_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCharVar2(char newCharVar2) { eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR2, ArtefactPackage.Literals.SKETCH__CHAR_VAR2, newCharVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public char getCharVar3() { return (Character)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR3, ArtefactPackage.Literals.SKETCH__CHAR_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCharVar3(char newCharVar3) { eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR3, ArtefactPackage.Literals.SKETCH__CHAR_VAR3, newCharVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public char getCharVar4() { return (Character)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR4, ArtefactPackage.Literals.SKETCH__CHAR_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCharVar4(char newCharVar4) { eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR4, ArtefactPackage.Literals.SKETCH__CHAR_VAR4, newCharVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public char getCharVar5() { return (Character)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR5, ArtefactPackage.Literals.SKETCH__CHAR_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCharVar5(char newCharVar5) { eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR5, ArtefactPackage.Literals.SKETCH__CHAR_VAR5, newCharVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getLongVar1() { return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR1, ArtefactPackage.Literals.SKETCH__LONG_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLongVar1(long newLongVar1) { eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR1, ArtefactPackage.Literals.SKETCH__LONG_VAR1, newLongVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getLongVar2() { return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR2, ArtefactPackage.Literals.SKETCH__LONG_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLongVar2(long newLongVar2) { eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR2, ArtefactPackage.Literals.SKETCH__LONG_VAR2, newLongVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getLongVar3() { return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR3, ArtefactPackage.Literals.SKETCH__LONG_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLongVar3(long newLongVar3) { eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR3, ArtefactPackage.Literals.SKETCH__LONG_VAR3, newLongVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getLongVar4() { return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR4, ArtefactPackage.Literals.SKETCH__LONG_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLongVar4(long newLongVar4) { eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR4, ArtefactPackage.Literals.SKETCH__LONG_VAR4, newLongVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getLongVar5() { return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR5, ArtefactPackage.Literals.SKETCH__LONG_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLongVar5(long newLongVar5) { eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR5, ArtefactPackage.Literals.SKETCH__LONG_VAR5, newLongVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getFloatVar1() { return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR1, ArtefactPackage.Literals.SKETCH__FLOAT_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFloatVar1(float newFloatVar1) { eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR1, ArtefactPackage.Literals.SKETCH__FLOAT_VAR1, newFloatVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getFloatVar2() { return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR2, ArtefactPackage.Literals.SKETCH__FLOAT_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFloatVar2(float newFloatVar2) { eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR2, ArtefactPackage.Literals.SKETCH__FLOAT_VAR2, newFloatVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getFloatVar3() { return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR3, ArtefactPackage.Literals.SKETCH__FLOAT_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFloatVar3(float newFloatVar3) { eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR3, ArtefactPackage.Literals.SKETCH__FLOAT_VAR3, newFloatVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getFloatVar4() { return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR4, ArtefactPackage.Literals.SKETCH__FLOAT_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFloatVar4(float newFloatVar4) { eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR4, ArtefactPackage.Literals.SKETCH__FLOAT_VAR4, newFloatVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getFloatVar5() { return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR5, ArtefactPackage.Literals.SKETCH__FLOAT_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFloatVar5(float newFloatVar5) { eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR5, ArtefactPackage.Literals.SKETCH__FLOAT_VAR5, newFloatVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getDoubleVar1() { return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR1, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoubleVar1(double newDoubleVar1) { eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR1, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR1, newDoubleVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getDoubleVar2() { return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR2, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoubleVar2(double newDoubleVar2) { eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR2, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR2, newDoubleVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getDoubleVar3() { return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR3, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoubleVar3(double newDoubleVar3) { eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR3, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR3, newDoubleVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getDoubleVar4() { return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR4, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoubleVar4(double newDoubleVar4) { eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR4, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR4, newDoubleVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getDoubleVar5() { return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR5, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoubleVar5(double newDoubleVar5) { eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR5, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR5, newDoubleVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isBooleanVar1() { return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR1, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBooleanVar1(boolean newBooleanVar1) { eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR1, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR1, newBooleanVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isBooleanVar2() { return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR2, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBooleanVar2(boolean newBooleanVar2) { eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR2, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR2, newBooleanVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isBooleanVar3() { return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR3, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBooleanVar3(boolean newBooleanVar3) { eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR3, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR3, newBooleanVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isBooleanVar4() { return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR4, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBooleanVar4(boolean newBooleanVar4) { eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR4, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR4, newBooleanVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isBooleanVar5() { return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR5, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBooleanVar5(boolean newBooleanVar5) { eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR5, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR5, newBooleanVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getStringVar1() { return (String)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR1, ArtefactPackage.Literals.SKETCH__STRING_VAR1, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStringVar1(String newStringVar1) { eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR1, ArtefactPackage.Literals.SKETCH__STRING_VAR1, newStringVar1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getStringVar2() { return (String)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR2, ArtefactPackage.Literals.SKETCH__STRING_VAR2, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStringVar2(String newStringVar2) { eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR2, ArtefactPackage.Literals.SKETCH__STRING_VAR2, newStringVar2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getStringVar3() { return (String)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR3, ArtefactPackage.Literals.SKETCH__STRING_VAR3, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStringVar3(String newStringVar3) { eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR3, ArtefactPackage.Literals.SKETCH__STRING_VAR3, newStringVar3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getStringVar4() { return (String)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR4, ArtefactPackage.Literals.SKETCH__STRING_VAR4, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStringVar4(String newStringVar4) { eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR4, ArtefactPackage.Literals.SKETCH__STRING_VAR4, newStringVar4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getStringVar5() { return (String)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR5, ArtefactPackage.Literals.SKETCH__STRING_VAR5, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStringVar5(String newStringVar5) { eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR5, ArtefactPackage.Literals.SKETCH__STRING_VAR5, newStringVar5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ArtefactPackage.SKETCH__CONTENTS: return ((InternalEList<?>)getContents()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ArtefactPackage.SKETCH__TESTED: return isTested(); case ArtefactPackage.SKETCH__ID: return getId(); case ArtefactPackage.SKETCH__CONTENTS: return getContents(); case ArtefactPackage.SKETCH__BYTE_VAR1: return getByteVar1(); case ArtefactPackage.SKETCH__BYTE_VAR2: return getByteVar2(); case ArtefactPackage.SKETCH__BYTE_VAR3: return getByteVar3(); case ArtefactPackage.SKETCH__BYTE_VAR4: return getByteVar4(); case ArtefactPackage.SKETCH__BYTE_VAR5: return getByteVar5(); case ArtefactPackage.SKETCH__SHORT_VAR1: return getShortVar1(); case ArtefactPackage.SKETCH__SHORT_VAR2: return getShortVar2(); case ArtefactPackage.SKETCH__SHORT_VAR3: return getShortVar3(); case ArtefactPackage.SKETCH__SHORT_VAR4: return getShortVar4(); case ArtefactPackage.SKETCH__SHORT_VAR5: return getShortVar5(); case ArtefactPackage.SKETCH__INT_VAR1: return getIntVar1(); case ArtefactPackage.SKETCH__INT_VAR2: return getIntVar2(); case ArtefactPackage.SKETCH__INT_VAR3: return getIntVar3(); case ArtefactPackage.SKETCH__INT_VAR4: return getIntVar4(); case ArtefactPackage.SKETCH__INT_VAR5: return getIntVar5(); case ArtefactPackage.SKETCH__CHAR_VAR1: return getCharVar1(); case ArtefactPackage.SKETCH__CHAR_VAR2: return getCharVar2(); case ArtefactPackage.SKETCH__CHAR_VAR3: return getCharVar3(); case ArtefactPackage.SKETCH__CHAR_VAR4: return getCharVar4(); case ArtefactPackage.SKETCH__CHAR_VAR5: return getCharVar5(); case ArtefactPackage.SKETCH__LONG_VAR1: return getLongVar1(); case ArtefactPackage.SKETCH__LONG_VAR2: return getLongVar2(); case ArtefactPackage.SKETCH__LONG_VAR3: return getLongVar3(); case ArtefactPackage.SKETCH__LONG_VAR4: return getLongVar4(); case ArtefactPackage.SKETCH__LONG_VAR5: return getLongVar5(); case ArtefactPackage.SKETCH__FLOAT_VAR1: return getFloatVar1(); case ArtefactPackage.SKETCH__FLOAT_VAR2: return getFloatVar2(); case ArtefactPackage.SKETCH__FLOAT_VAR3: return getFloatVar3(); case ArtefactPackage.SKETCH__FLOAT_VAR4: return getFloatVar4(); case ArtefactPackage.SKETCH__FLOAT_VAR5: return getFloatVar5(); case ArtefactPackage.SKETCH__DOUBLE_VAR1: return getDoubleVar1(); case ArtefactPackage.SKETCH__DOUBLE_VAR2: return getDoubleVar2(); case ArtefactPackage.SKETCH__DOUBLE_VAR3: return getDoubleVar3(); case ArtefactPackage.SKETCH__DOUBLE_VAR4: return getDoubleVar4(); case ArtefactPackage.SKETCH__DOUBLE_VAR5: return getDoubleVar5(); case ArtefactPackage.SKETCH__BOOLEAN_VAR1: return isBooleanVar1(); case ArtefactPackage.SKETCH__BOOLEAN_VAR2: return isBooleanVar2(); case ArtefactPackage.SKETCH__BOOLEAN_VAR3: return isBooleanVar3(); case ArtefactPackage.SKETCH__BOOLEAN_VAR4: return isBooleanVar4(); case ArtefactPackage.SKETCH__BOOLEAN_VAR5: return isBooleanVar5(); case ArtefactPackage.SKETCH__STRING_VAR1: return getStringVar1(); case ArtefactPackage.SKETCH__STRING_VAR2: return getStringVar2(); case ArtefactPackage.SKETCH__STRING_VAR3: return getStringVar3(); case ArtefactPackage.SKETCH__STRING_VAR4: return getStringVar4(); case ArtefactPackage.SKETCH__STRING_VAR5: return getStringVar5(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ArtefactPackage.SKETCH__TESTED: setTested((Boolean)newValue); return; case ArtefactPackage.SKETCH__ID: setId((String)newValue); return; case ArtefactPackage.SKETCH__CONTENTS: getContents().clear(); getContents().addAll((Collection<? extends IContentElement>)newValue); return; case ArtefactPackage.SKETCH__BYTE_VAR1: setByteVar1((Byte)newValue); return; case ArtefactPackage.SKETCH__BYTE_VAR2: setByteVar2((Byte)newValue); return; case ArtefactPackage.SKETCH__BYTE_VAR3: setByteVar3((Byte)newValue); return; case ArtefactPackage.SKETCH__BYTE_VAR4: setByteVar4((Byte)newValue); return; case ArtefactPackage.SKETCH__BYTE_VAR5: setByteVar5((Byte)newValue); return; case ArtefactPackage.SKETCH__SHORT_VAR1: setShortVar1((Short)newValue); return; case ArtefactPackage.SKETCH__SHORT_VAR2: setShortVar2((Short)newValue); return; case ArtefactPackage.SKETCH__SHORT_VAR3: setShortVar3((Short)newValue); return; case ArtefactPackage.SKETCH__SHORT_VAR4: setShortVar4((Short)newValue); return; case ArtefactPackage.SKETCH__SHORT_VAR5: setShortVar5((Short)newValue); return; case ArtefactPackage.SKETCH__INT_VAR1: setIntVar1((Integer)newValue); return; case ArtefactPackage.SKETCH__INT_VAR2: setIntVar2((Integer)newValue); return; case ArtefactPackage.SKETCH__INT_VAR3: setIntVar3((Integer)newValue); return; case ArtefactPackage.SKETCH__INT_VAR4: setIntVar4((Integer)newValue); return; case ArtefactPackage.SKETCH__INT_VAR5: setIntVar5((Integer)newValue); return; case ArtefactPackage.SKETCH__CHAR_VAR1: setCharVar1((Character)newValue); return; case ArtefactPackage.SKETCH__CHAR_VAR2: setCharVar2((Character)newValue); return; case ArtefactPackage.SKETCH__CHAR_VAR3: setCharVar3((Character)newValue); return; case ArtefactPackage.SKETCH__CHAR_VAR4: setCharVar4((Character)newValue); return; case ArtefactPackage.SKETCH__CHAR_VAR5: setCharVar5((Character)newValue); return; case ArtefactPackage.SKETCH__LONG_VAR1: setLongVar1((Long)newValue); return; case ArtefactPackage.SKETCH__LONG_VAR2: setLongVar2((Long)newValue); return; case ArtefactPackage.SKETCH__LONG_VAR3: setLongVar3((Long)newValue); return; case ArtefactPackage.SKETCH__LONG_VAR4: setLongVar4((Long)newValue); return; case ArtefactPackage.SKETCH__LONG_VAR5: setLongVar5((Long)newValue); return; case ArtefactPackage.SKETCH__FLOAT_VAR1: setFloatVar1((Float)newValue); return; case ArtefactPackage.SKETCH__FLOAT_VAR2: setFloatVar2((Float)newValue); return; case ArtefactPackage.SKETCH__FLOAT_VAR3: setFloatVar3((Float)newValue); return; case ArtefactPackage.SKETCH__FLOAT_VAR4: setFloatVar4((Float)newValue); return; case ArtefactPackage.SKETCH__FLOAT_VAR5: setFloatVar5((Float)newValue); return; case ArtefactPackage.SKETCH__DOUBLE_VAR1: setDoubleVar1((Double)newValue); return; case ArtefactPackage.SKETCH__DOUBLE_VAR2: setDoubleVar2((Double)newValue); return; case ArtefactPackage.SKETCH__DOUBLE_VAR3: setDoubleVar3((Double)newValue); return; case ArtefactPackage.SKETCH__DOUBLE_VAR4: setDoubleVar4((Double)newValue); return; case ArtefactPackage.SKETCH__DOUBLE_VAR5: setDoubleVar5((Double)newValue); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR1: setBooleanVar1((Boolean)newValue); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR2: setBooleanVar2((Boolean)newValue); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR3: setBooleanVar3((Boolean)newValue); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR4: setBooleanVar4((Boolean)newValue); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR5: setBooleanVar5((Boolean)newValue); return; case ArtefactPackage.SKETCH__STRING_VAR1: setStringVar1((String)newValue); return; case ArtefactPackage.SKETCH__STRING_VAR2: setStringVar2((String)newValue); return; case ArtefactPackage.SKETCH__STRING_VAR3: setStringVar3((String)newValue); return; case ArtefactPackage.SKETCH__STRING_VAR4: setStringVar4((String)newValue); return; case ArtefactPackage.SKETCH__STRING_VAR5: setStringVar5((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ArtefactPackage.SKETCH__TESTED: setTested(TESTED_EDEFAULT); return; case ArtefactPackage.SKETCH__ID: setId(ID_EDEFAULT); return; case ArtefactPackage.SKETCH__CONTENTS: getContents().clear(); return; case ArtefactPackage.SKETCH__BYTE_VAR1: setByteVar1(BYTE_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__BYTE_VAR2: setByteVar2(BYTE_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__BYTE_VAR3: setByteVar3(BYTE_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__BYTE_VAR4: setByteVar4(BYTE_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__BYTE_VAR5: setByteVar5(BYTE_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__SHORT_VAR1: setShortVar1(SHORT_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__SHORT_VAR2: setShortVar2(SHORT_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__SHORT_VAR3: setShortVar3(SHORT_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__SHORT_VAR4: setShortVar4(SHORT_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__SHORT_VAR5: setShortVar5(SHORT_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__INT_VAR1: setIntVar1(INT_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__INT_VAR2: setIntVar2(INT_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__INT_VAR3: setIntVar3(INT_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__INT_VAR4: setIntVar4(INT_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__INT_VAR5: setIntVar5(INT_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__CHAR_VAR1: setCharVar1(CHAR_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__CHAR_VAR2: setCharVar2(CHAR_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__CHAR_VAR3: setCharVar3(CHAR_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__CHAR_VAR4: setCharVar4(CHAR_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__CHAR_VAR5: setCharVar5(CHAR_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__LONG_VAR1: setLongVar1(LONG_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__LONG_VAR2: setLongVar2(LONG_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__LONG_VAR3: setLongVar3(LONG_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__LONG_VAR4: setLongVar4(LONG_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__LONG_VAR5: setLongVar5(LONG_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__FLOAT_VAR1: setFloatVar1(FLOAT_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__FLOAT_VAR2: setFloatVar2(FLOAT_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__FLOAT_VAR3: setFloatVar3(FLOAT_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__FLOAT_VAR4: setFloatVar4(FLOAT_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__FLOAT_VAR5: setFloatVar5(FLOAT_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__DOUBLE_VAR1: setDoubleVar1(DOUBLE_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__DOUBLE_VAR2: setDoubleVar2(DOUBLE_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__DOUBLE_VAR3: setDoubleVar3(DOUBLE_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__DOUBLE_VAR4: setDoubleVar4(DOUBLE_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__DOUBLE_VAR5: setDoubleVar5(DOUBLE_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR1: setBooleanVar1(BOOLEAN_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR2: setBooleanVar2(BOOLEAN_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR3: setBooleanVar3(BOOLEAN_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR4: setBooleanVar4(BOOLEAN_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__BOOLEAN_VAR5: setBooleanVar5(BOOLEAN_VAR5_EDEFAULT); return; case ArtefactPackage.SKETCH__STRING_VAR1: setStringVar1(STRING_VAR1_EDEFAULT); return; case ArtefactPackage.SKETCH__STRING_VAR2: setStringVar2(STRING_VAR2_EDEFAULT); return; case ArtefactPackage.SKETCH__STRING_VAR3: setStringVar3(STRING_VAR3_EDEFAULT); return; case ArtefactPackage.SKETCH__STRING_VAR4: setStringVar4(STRING_VAR4_EDEFAULT); return; case ArtefactPackage.SKETCH__STRING_VAR5: setStringVar5(STRING_VAR5_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ArtefactPackage.SKETCH__TESTED: return isTested() != TESTED_EDEFAULT; case ArtefactPackage.SKETCH__ID: return ID_EDEFAULT == null ? getId() != null : !ID_EDEFAULT.equals(getId()); case ArtefactPackage.SKETCH__CONTENTS: return !getContents().isEmpty(); case ArtefactPackage.SKETCH__BYTE_VAR1: return getByteVar1() != BYTE_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__BYTE_VAR2: return getByteVar2() != BYTE_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__BYTE_VAR3: return getByteVar3() != BYTE_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__BYTE_VAR4: return getByteVar4() != BYTE_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__BYTE_VAR5: return getByteVar5() != BYTE_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__SHORT_VAR1: return getShortVar1() != SHORT_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__SHORT_VAR2: return getShortVar2() != SHORT_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__SHORT_VAR3: return getShortVar3() != SHORT_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__SHORT_VAR4: return getShortVar4() != SHORT_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__SHORT_VAR5: return getShortVar5() != SHORT_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__INT_VAR1: return getIntVar1() != INT_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__INT_VAR2: return getIntVar2() != INT_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__INT_VAR3: return getIntVar3() != INT_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__INT_VAR4: return getIntVar4() != INT_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__INT_VAR5: return getIntVar5() != INT_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__CHAR_VAR1: return getCharVar1() != CHAR_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__CHAR_VAR2: return getCharVar2() != CHAR_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__CHAR_VAR3: return getCharVar3() != CHAR_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__CHAR_VAR4: return getCharVar4() != CHAR_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__CHAR_VAR5: return getCharVar5() != CHAR_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__LONG_VAR1: return getLongVar1() != LONG_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__LONG_VAR2: return getLongVar2() != LONG_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__LONG_VAR3: return getLongVar3() != LONG_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__LONG_VAR4: return getLongVar4() != LONG_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__LONG_VAR5: return getLongVar5() != LONG_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__FLOAT_VAR1: return getFloatVar1() != FLOAT_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__FLOAT_VAR2: return getFloatVar2() != FLOAT_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__FLOAT_VAR3: return getFloatVar3() != FLOAT_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__FLOAT_VAR4: return getFloatVar4() != FLOAT_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__FLOAT_VAR5: return getFloatVar5() != FLOAT_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__DOUBLE_VAR1: return getDoubleVar1() != DOUBLE_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__DOUBLE_VAR2: return getDoubleVar2() != DOUBLE_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__DOUBLE_VAR3: return getDoubleVar3() != DOUBLE_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__DOUBLE_VAR4: return getDoubleVar4() != DOUBLE_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__DOUBLE_VAR5: return getDoubleVar5() != DOUBLE_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__BOOLEAN_VAR1: return isBooleanVar1() != BOOLEAN_VAR1_EDEFAULT; case ArtefactPackage.SKETCH__BOOLEAN_VAR2: return isBooleanVar2() != BOOLEAN_VAR2_EDEFAULT; case ArtefactPackage.SKETCH__BOOLEAN_VAR3: return isBooleanVar3() != BOOLEAN_VAR3_EDEFAULT; case ArtefactPackage.SKETCH__BOOLEAN_VAR4: return isBooleanVar4() != BOOLEAN_VAR4_EDEFAULT; case ArtefactPackage.SKETCH__BOOLEAN_VAR5: return isBooleanVar5() != BOOLEAN_VAR5_EDEFAULT; case ArtefactPackage.SKETCH__STRING_VAR1: return STRING_VAR1_EDEFAULT == null ? getStringVar1() != null : !STRING_VAR1_EDEFAULT.equals(getStringVar1()); case ArtefactPackage.SKETCH__STRING_VAR2: return STRING_VAR2_EDEFAULT == null ? getStringVar2() != null : !STRING_VAR2_EDEFAULT.equals(getStringVar2()); case ArtefactPackage.SKETCH__STRING_VAR3: return STRING_VAR3_EDEFAULT == null ? getStringVar3() != null : !STRING_VAR3_EDEFAULT.equals(getStringVar3()); case ArtefactPackage.SKETCH__STRING_VAR4: return STRING_VAR4_EDEFAULT == null ? getStringVar4() != null : !STRING_VAR4_EDEFAULT.equals(getStringVar4()); case ArtefactPackage.SKETCH__STRING_VAR5: return STRING_VAR5_EDEFAULT == null ? getStringVar5() != null : !STRING_VAR5_EDEFAULT.equals(getStringVar5()); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == IID.class) { switch (derivedFeatureID) { case ArtefactPackage.SKETCH__ID: return BasePackage.IID__ID; default: return -1; } } if (baseClass == IContentElement.class) { switch (derivedFeatureID) { default: return -1; } } if (baseClass == IContainer.class) { switch (derivedFeatureID) { case ArtefactPackage.SKETCH__CONTENTS: return BasePackage.ICONTAINER__CONTENTS; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == IID.class) { switch (baseFeatureID) { case BasePackage.IID__ID: return ArtefactPackage.SKETCH__ID; default: return -1; } } if (baseClass == IContentElement.class) { switch (baseFeatureID) { default: return -1; } } if (baseClass == IContainer.class) { switch (baseFeatureID) { case BasePackage.ICONTAINER__CONTENTS: return ArtefactPackage.SKETCH__CONTENTS; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } } //SketchImpl
apache-2.0
userByHu/coolweatherbyhu
app/src/main/java/hu/learn/coolweatherbyhu/util/HttpUtil.java
430
package hu.learn.coolweatherbyhu.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by Administrator on 2017/7/29. */ public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback){ OkHttpClient client =new OkHttpClient(); Request request=new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
apache-2.0
fxdyx/develnext
jphp-gui-designer-ext/src/main/java/org/develnext/jphp/gui/designer/classes/FileSystemWatcher.java
2763
package org.develnext.jphp.gui.designer.classes; import org.develnext.jphp.gui.designer.GuiDesignerExtension; import php.runtime.Memory; import php.runtime.annotation.Reflection.Abstract; import php.runtime.annotation.Reflection.Name; import php.runtime.annotation.Reflection.Namespace; import php.runtime.annotation.Reflection.Signature; import php.runtime.env.Environment; import php.runtime.lang.BaseObject; import php.runtime.memory.ArrayMemory; import php.runtime.reflection.ClassEntity; import java.io.IOException; import java.nio.file.*; @Namespace(GuiDesignerExtension.NS) public class FileSystemWatcher extends BaseObject { protected WatchService watchService; protected Path folder; public FileSystemWatcher(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature public void __construct(String path) throws IOException { folder = Paths.get(path); watchService = FileSystems.getDefault().newWatchService(); folder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW ); } @Signature public void close() throws IOException { watchService.close(); } @Signature public WrapWatchKey take(Environment env) throws InterruptedException { return new WrapWatchKey(env, folder, watchService.take()); } @Abstract @Name("WatchFileKey") @Namespace(GuiDesignerExtension.NS) public static class WrapWatchKey extends BaseObject { private Path path; private WatchKey wrappedObject; public WrapWatchKey(Environment env, Path path, WatchKey wrappedObject) { super(env); this.path = path; this.wrappedObject = wrappedObject; } public WrapWatchKey(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature public boolean reset() { return wrappedObject.reset(); } @Signature public void cancel() { wrappedObject.cancel(); } @Signature public Memory pollEvents() { ArrayMemory result = new ArrayMemory(); for (WatchEvent<?> event : wrappedObject.pollEvents()) { Memory item = result.refOfPush(); item.refOfIndex("kind").assign(event.kind().name()); item.refOfIndex("context").assign(path.toString() + "/" + event.context().toString()); item.refOfIndex("count").assign(event.count()); } return result.toConstant(); } } }
apache-2.0
Bananeweizen/cgeo
tests/src-android/cgeo/geocaching/connector/trackable/GeokretyConnectorTest.java
4918
package cgeo.geocaching.connector.trackable; import static org.assertj.core.api.Java6Assertions.assertThat; import cgeo.geocaching.models.Trackable; import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase; import cgeo.geocaching.test.R; import java.util.List; import org.xml.sax.InputSource; /** * test for {@link GeokretyConnector} */ public class GeokretyConnectorTest extends AbstractResourceInstrumentationTestCase { public static void testCanHandleTrackable() { assertThat(getConnector().canHandleTrackable("GK82A2")).isTrue(); assertThat(getConnector().canHandleTrackable("TB1234")).isFalse(); assertThat(getConnector().canHandleTrackable("UNKNOWN")).isFalse(); assertThat(getConnector().canHandleTrackable("GKXYZ1")).isFalse(); // non hex assertThat(getConnector().canHandleTrackable("GKXYZ1", TrackableBrand.GEOKRETY)).isTrue(); // non hex, but match secret codes pattern assertThat(getConnector().canHandleTrackable("123456", TrackableBrand.GEOKRETY)).isTrue(); // Secret code assertThat(getConnector().canHandleTrackable("012345", TrackableBrand.GEOKRETY)).isFalse(); // blacklisted 0/O assertThat(getConnector().canHandleTrackable("ABCDEF", TrackableBrand.GEOKRETY)).isTrue(); // Secret code assertThat(getConnector().canHandleTrackable("LMNOPQ", TrackableBrand.GEOKRETY)).isFalse(); // blacklisted 0/O assertThat(getConnector().canHandleTrackable("GC1234")).isFalse(); assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.UNKNOWN)).isFalse(); assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.TRAVELBUG)).isFalse(); assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.GEOKRETY)).isTrue(); } public static void testGetTrackableCodeFromUrl() throws Exception { assertThat(getConnector().getTrackableCodeFromUrl("http://www.geokrety.org/konkret.php?id=46464")).isEqualTo("GKB580"); assertThat(getConnector().getTrackableCodeFromUrl("https://www.geokrety.org/konkret.php?id=46464")).isEqualTo("GKB580"); assertThat(getConnector().getTrackableCodeFromUrl("http://geokrety.org/konkret.php?id=46465")).isEqualTo("GKB581"); assertThat(getConnector().getTrackableCodeFromUrl("https://geokrety.org/konkret.php?id=46465")).isEqualTo("GKB581"); } public static void testGeocode() throws Exception { assertThat(GeokretyConnector.geocode(46464)).isEqualTo("GKB580"); } public static void testGetId() throws Exception { assertThat(GeokretyConnector.getId("GKB581")).isEqualTo(46465); } public void testGetUrl() throws Exception { final List<Trackable> trackables = GeokretyParser.parse(new InputSource(getResourceStream(R.raw.geokret141_xml))); assertThat(trackables).hasSize(2); assertThat(trackables.get(0).getUrl()).isEqualTo("https://geokrety.org/konkret.php?id=46464"); assertThat(trackables.get(1).getUrl()).isEqualTo("https://geokrety.org/konkret.php?id=46465"); } public void testSearchTrackable() throws Exception { final Trackable geokret = GeokretyConnector.searchTrackable("GKB580"); assertThat(geokret).isNotNull(); assert geokret != null; assertThat(geokret.getBrand()).isEqualTo(TrackableBrand.GEOKRETY); assertThat(geokret.getName()).isEqualTo("c:geo One"); assertThat(geokret.getDetails()).isEqualTo("GeoKret for the c:geo project :)<br />DO NOT MOVE"); assertThat(geokret.getOwner()).isEqualTo("kumy"); assertThat(geokret.isMissing()).isTrue(); assertThat(geokret.isLoggable()).isTrue(); assertThat(geokret.getSpottedName()).isEqualTo("OX5BRQK"); assertThat(geokret.getSpottedType()).isEqualTo(Trackable.SPOTTED_CACHE); } public void testSearchTrackables() throws Exception { // here it is assumed that: // * cache OX5BRQK contains these 2 objects only... // * objects never been moved // * GK website always return list in the same order final List<Trackable> trackables = new GeokretyConnector().searchTrackables("OX5BRQK"); assertThat(trackables).hasSize(2); assertThat(trackables).extracting("name").containsOnly("c:geo One", "c:geo Two"); } public void testGetIconBrand() throws Exception { final List<Trackable> trackables = GeokretyParser.parse(new InputSource(getResourceStream(R.raw.geokret141_xml))); assertThat(trackables).hasSize(2); assertThat(trackables).extracting("brand").containsOnly(TrackableBrand.GEOKRETY, TrackableBrand.GEOKRETY); } private static GeokretyConnector getConnector() { return new GeokretyConnector(); } public static void testRecommendGeocode() throws Exception { assertThat(getConnector().recommendLogWithGeocode()).isTrue(); } }
apache-2.0
google/floody
server/src/main/java/com/google/floody/service/GtmRequestWriter.java
3813
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.floody.service; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.floody.model.FloodyBundle; import com.google.floody.model.GtmExport; import com.google.floody.model.GtmFloodlightActivity; import com.google.floody.model.SheetFloody; import com.google.floody.protobuf.GtmOperations.GtmExportRequest; import com.google.floody.transforms.SheetFloodyToGtmFloodlightActivityTransformer; /** Service to create a {@link GtmExport} object and store it in Datastore. */ @AutoValue public abstract class GtmRequestWriter { abstract FloodyBundle bundle(); abstract long floodlightConfigurationId(); abstract ObjectifySaverService<GtmExport> saverService(); abstract GtmExportRequest operationRequest(); abstract String requesterEmail(); @AutoValue.Builder public abstract static class Builder { public abstract Builder setBundle(FloodyBundle value); public abstract Builder setFloodlightConfigurationId(long floodlightConfigurationId); public abstract Builder setSaverService(ObjectifySaverService<GtmExport> value); public abstract Builder setOperationRequest(GtmExportRequest value); public abstract Builder setRequesterEmail(String value); public abstract GtmRequestWriter build(); public final GtmRequestWriter forRequest(GtmExportRequest request, String requesterEmail) { return setOperationRequest(request).setRequesterEmail(requesterEmail).build(); } } public static Builder builder() { return new AutoValue_GtmRequestWriter.Builder(); } public FloodyBundleManager sync() { var exportMaker = new GtmExportMaker(); var updatedFloodies = bundle().getFloodies().stream().map(exportMaker::processFloody).collect(toImmutableSet()); saverService().save(exportMaker.make()); return FloodyBundleManager.builder() .setFloodlightConfigurationId(floodlightConfigurationId()) .setBundle(bundle().withFloodies(updatedFloodies)) .build(); } private class GtmExportMaker { private final ImmutableCollection.Builder<GtmFloodlightActivity> selectedFloodiesBuilder; public GtmExportMaker() { this.selectedFloodiesBuilder = ImmutableList.builder(); } private SheetFloody processFloody(SheetFloody floody) { if (!floody.isToBeUpdated()) { return floody; } selectedFloodiesBuilder.add(SheetFloodyToGtmFloodlightActivityTransformer.transform(floody)); return floody.toBuilder().setToBeUpdated(false).build(); } private GtmExport make() { return GtmExport.builder() .setGtmContainerId(operationRequest().getGtmContainerId()) .setApproverEmails(operationRequest().getApproverEmailsList()) .setSpreadsheetId(operationRequest().getSpreadsheetId()) .setRequesterMessage(operationRequest().getRequesterMessage()) .setFloodlightActivities(selectedFloodiesBuilder.build()) .setRequesterEmail(requesterEmail()) .setActionInformation(null) .build(); } } }
apache-2.0
microprofile/microprofile-config
api/src/main/java/org/eclipse/microprofile/config/Config.java
14308
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * 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. * * Contributors: * 2011-12-28 - Mark Struberg & Gerhard Petracek * Initially authored in Apache DeltaSpike as ConfigResolver fb0131106481f0b9a8fd * 2015-04-30 - Ron Smeral * Typesafe Config authored in Apache DeltaSpike 25b2b8cc0c955a28743f * 2016-07-14 - Mark Struberg * Extracted the Config part out of Apache DeltaSpike and proposed as Microprofile-Config * 2016-11-14 - Emily Jiang / IBM Corp * Experiments with separate methods per type, JavaDoc, method renaming * 2018-04-04 - Mark Struberg, Manfred Huber, Alex Falb, Gerhard Petracek * ConfigSnapshot added. Initially authored in Apache DeltaSpike fdd1e3dcd9a12ceed831dd * Additional reviews and feedback by Tomas Langer. */ package org.eclipse.microprofile.config; import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.Converter; /** * Resolves the property value by searching through all configured {@link ConfigSource ConfigSources}. If the same * property is specified in multiple {@link ConfigSource ConfigSources}, the value in the {@link ConfigSource} with the * highest ordinal will be used. * <p> * If multiple {@link ConfigSource ConfigSources} are specified with the same ordinal, the * {@link ConfigSource#getName()} will be used for sorting. * <p> * The config objects produced via the injection model {@code @Inject Config} are guaranteed to be serializable, while * the programmatically created ones are not required to be serializable. * <p> * If one or more converters are registered for a class of a requested value then the registered * {@link org.eclipse.microprofile.config.spi.Converter} which has the highest {@code @jakarta.annotation.Priority} is * used to convert the string value retrieved from the config sources. * * <h2>Usage</h2> * * <p> * For accessing the config you can use the {@link ConfigProvider}: * * <pre> * public void doSomething() { * Config cfg = ConfigProvider.getConfig(); * String archiveUrl = cfg.getValue("my.project.archive.endpoint", String.class); * Integer archivePort = cfg.getValue("my.project.archive.port", Integer.class); * } * </pre> * * <p> * It is also possible to inject the Config if a DI container is available: * * <pre> * public class MyService { * &#064;Inject * private Config config; * } * </pre> * * <p> * See {@link #getValue(String, Class)} and {@link #getOptionalValue(String, Class)} for accessing a configured value. * * <p> * Configured values can also be accessed via injection. See * {@link org.eclipse.microprofile.config.inject.ConfigProperty} for more information. * * @author <a href="mailto:struberg@apache.org">Mark Struberg</a> * @author <a href="mailto:gpetracek@apache.org">Gerhard Petracek</a> * @author <a href="mailto:rsmeral@apache.org">Ron Smeral</a> * @author <a href="mailto:emijiang@uk.ibm.com">Emily Jiang</a> * @author <a href="mailto:gunnar@hibernate.org">Gunnar Morling</a> */ @org.osgi.annotation.versioning.ProviderType public interface Config { /** * The value of the property specifies a single active profile. */ String PROFILE = "mp.config.profile"; /** * The value of the property determines whether the property expression is enabled or disabled. The value * <code>false</code> means the property expression is disabled, while <code>true</code> means enabled. * * By default, the value is set to <code>true</code>. */ String PROPERTY_EXPRESSIONS_ENABLED = "mp.config.property.expressions.enabled"; /** * Return the resolved property value with the specified type for the specified property name from the underlying * {@linkplain ConfigSource configuration sources}. * <p> * The configuration value is not guaranteed to be cached by the implementation, and may be expensive to compute; * therefore, if the returned value is intended to be frequently used, callers should consider storing rather than * recomputing it. * <p> * The result of this method is identical to the result of calling * {@code getOptionalValue(propertyName, propertyType).get()}. In particular, If the given property name or the * value element of this property does not exist, the {@link java.util.NoSuchElementException} is thrown. This * method never returns {@code null}. * * @param <T> * The property type * @param propertyName * The configuration property name * @param propertyType * The type into which the resolved property value should get converted * @return the resolved property value as an instance of the requested type (not {@code null}) * @throws IllegalArgumentException * if the property cannot be converted to the specified type * @throws java.util.NoSuchElementException * if the property is not defined or is defined as an empty string or the converter returns {@code null} */ <T> T getValue(String propertyName, Class<T> propertyType); /** * Return the {@link ConfigValue} for the specified property name from the underlying {@linkplain ConfigSource * configuration source}. The lookup of the configuration is performed immediately, meaning that calls to * {@link ConfigValue} will always yield the same results. * <p> * The configuration value is not guaranteed to be cached by the implementation, and may be expensive to compute; * therefore, if the returned value is intended to be frequently used, callers should consider storing rather than * recomputing it. * <p> * A {@link ConfigValue} is always returned even if a property name cannot be found. In this case, every method in * {@link ConfigValue} returns {@code null} except for {@link ConfigValue#getName()}, which includes the original * property name being looked up. * * @param propertyName * The configuration property name * @return the resolved property value as a {@link ConfigValue} */ ConfigValue getConfigValue(String propertyName); /** * Return the resolved property values with the specified type for the specified property name from the underlying * {@linkplain ConfigSource configuration sources}. * <p> * The configuration values are not guaranteed to be cached by the implementation, and may be expensive to compute; * therefore, if the returned values are intended to be frequently used, callers should consider storing rather than * recomputing them. * * @param <T> * The property type * @param propertyName * The configuration property name * @param propertyType * The type into which the resolved property values should get converted * @return the resolved property values as a list of instances of the requested type * @throws java.lang.IllegalArgumentException * if the property values cannot be converted to the specified type * @throws java.util.NoSuchElementException * if the property isn't present in the configuration or is defined as an empty string or the converter * returns {@code null} */ default <T> List<T> getValues(String propertyName, Class<T> propertyType) { @SuppressWarnings("unchecked") Class<T[]> arrayType = (Class<T[]>) Array.newInstance(propertyType, 0).getClass(); return Arrays.asList(getValue(propertyName, arrayType)); } /** * Return the resolved property value with the specified type for the specified property name from the underlying * {@linkplain ConfigSource configuration sources}. * <p> * The configuration value is not guaranteed to be cached by the implementation, and may be expensive to compute; * therefore, if the returned value is intended to be frequently used, callers should consider storing rather than * recomputing it. * <p> * If this method is used very often then consider to locally store the configured value. * * @param <T> * The property type * @param propertyName * The configuration property name * @param propertyType * The type into which the resolved property value should be converted * @return The resolved property value as an {@code Optional} wrapping the requested type * * @throws IllegalArgumentException * if the property cannot be converted to the specified type */ <T> Optional<T> getOptionalValue(String propertyName, Class<T> propertyType); /** * Return the resolved property values with the specified type for the specified property name from the underlying * {@linkplain ConfigSource configuration sources}. * <p> * The configuration values are not guaranteed to be cached by the implementation, and may be expensive to compute; * therefore, if the returned values are intended to be frequently used, callers should consider storing rather than * recomputing them. * * @param <T> * The property type * @param propertyName * The configuration property name * @param propertyType * The type into which the resolved property values should be converted * @return The resolved property values as an {@code Optional} wrapping a list of the requested type * * @throws java.lang.IllegalArgumentException * if the property cannot be converted to the specified type */ default <T> Optional<List<T>> getOptionalValues(String propertyName, Class<T> propertyType) { @SuppressWarnings("unchecked") Class<T[]> arrayType = (Class<T[]>) Array.newInstance(propertyType, 0).getClass(); return getOptionalValue(propertyName, arrayType).map(Arrays::asList); } /** * Returns a sequence of configuration property names. The order of the returned property names is unspecified. * <p> * The returned property names are unique; that is, if a name is returned once by a given iteration, it will not be * returned again during that same iteration. * <p> * There is no guarantee about the completeness or currency of the names returned, nor is there any guarantee that a * name that is returned by the iterator will resolve to a non-empty value or be found in any configuration source * associated with the configuration; for example, it is allowed for this method to return an empty set always. * However, the implementation <em>should</em> return a set of names that is useful to a user that wishes to browse * the configuration. * <p> * It is implementation-defined whether the returned names reflect a point-in-time "snapshot" of names, or an * aggregation of multiple point-in-time "snapshots", or a more dynamic view of the available property names. * Implementations are not required to return the same sequence of names on each iteration; however, the produced * {@link java.util.Iterator Iterator} must adhere to the contract of that class, and must not return any more * elements once its {@link java.util.Iterator#hasNext() hasNext()} method returns {@code false}. * <p> * The returned instance is thread safe and may be iterated concurrently. The individual iterators are not * thread-safe. * * @return the names of all configured keys of the underlying configuration */ Iterable<String> getPropertyNames(); /** * Return all of the currently registered {@linkplain ConfigSource configuration sources} for this configuration. * <p> * The returned sources will be sorted by descending ordinal value and name, which can be iterated in a thread-safe * manner. The {@link java.lang.Iterable Iterable} contains a fixed number of {@linkplain ConfigSource configuration * sources}, determined at application start time, and the config sources themselves may be static or dynamic. * * @return the configuration sources */ Iterable<ConfigSource> getConfigSources(); /** * Return the {@link Converter} used by this instance to produce instances of the specified type from string values. * * @param <T> * the conversion type * @param forType * the type to be produced by the converter * @return an {@link Optional} containing the converter, or empty if no converter is available for the specified * type */ <T> Optional<Converter<T>> getConverter(Class<T> forType); /** * Returns an instance of the specific class, to allow access to the provider specific API. * <p> * If the MP Config provider implementation does not support the specified class, a {@link IllegalArgumentException} * is thrown. * <p> * Unwrapping to the provider specific API may lead to non-portable behaviour. * * @param type * Class representing the type to unwrap to * @param <T> * The type to unwrap to * @return An instance of the given type * @throws IllegalArgumentException * If the current provider does not support unwrapping to the given type */ <T> T unwrap(Class<T> type); }
apache-2.0
brainysmith/shibboleth-common
src/main/java/edu/internet2/middleware/shibboleth/common/config/metadata/AbstractReloadingMetadataProviderBeanDefinitionParser.java
7847
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID 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 edu.internet2.middleware.shibboleth.common.config.metadata; import javax.xml.datatype.Duration; import org.opensaml.xml.util.DatatypeHelper; import org.opensaml.xml.util.XMLHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; import edu.internet2.middleware.shibboleth.common.config.SpringConfigurationUtils; /** Base class for metadata providers that reload their metadata. */ public abstract class AbstractReloadingMetadataProviderBeanDefinitionParser extends AbstractMetadataProviderBeanDefinitionParser { /** Class logger. */ private final Logger log = LoggerFactory.getLogger(AbstractReloadingMetadataProviderBeanDefinitionParser.class); /** {@inheritDoc} */ protected void doParse(Element config, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doParse(config, parserContext, builder); String taskTimerRef = getTaskTimerRef(config); log.debug("Metadata provider using task timer: {}", taskTimerRef); builder.addConstructorArgReference(taskTimerRef); float refreshDelayFactor = getRefreshDelayFactor(config); log.debug("Metadata provider refresh delay factor: {}", refreshDelayFactor); builder.addPropertyValue("refreshDelayFactor", refreshDelayFactor); long minRefreshDelay = getMinRefreshDelay(config); log.debug("Metadata provider min refresh delay: {}ms", minRefreshDelay); builder.addPropertyValue("minRefreshDelay", minRefreshDelay); long maxRefreshDelay = getMaxRefreshDelay(config); log.debug("Metadata provider max refresh delay: {}ms", maxRefreshDelay); builder.addPropertyValue("maxRefreshDelay", maxRefreshDelay); } /** * Gets the default parser pool reference for the metadata provider. * * @param config metadata provider configuration element * * @return parser pool reference */ protected String getParserPoolRef(Element config) { String parserPoolRef = null; if (config.hasAttributeNS(null, "parerPoolRef")) { parserPoolRef = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "parserPoolRef")); } if (parserPoolRef == null) { parserPoolRef = "shibboleth.ParserPool"; } return parserPoolRef; } /** * Gets the default task timer reference for the metadata provider. * * @param config metadata provider configuration element * * @return task timer reference */ protected String getTaskTimerRef(Element config) { String taskTimerRef = null; if (config.hasAttributeNS(null, "taskTimerRef")) { taskTimerRef = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "taskTimerRef")); } if (taskTimerRef == null) { taskTimerRef = "shibboleth.TaskTimer"; } return taskTimerRef; } /** * Gets the refresh delay factor for the metadata provider. * * @param config provider configuration element * * @return refresh delay factor */ protected float getRefreshDelayFactor(Element config) { float delayFactor = 0.75f; if (config.hasAttributeNS(null, "refreshDelayFactor")) { String factorString = config.getAttributeNS(null, "refreshDelayFactor"); try { delayFactor = Float.parseFloat(factorString); } catch (NumberFormatException e) { log.error("Metadata provider had invalid refreshDelayFactor value '{}', using default value", factorString); } } if (delayFactor <= 0.0 || delayFactor >= 1.0) { log.error("Metadata provider had invalid refreshDelayFactor value '{}', using default value", delayFactor); delayFactor = 0.75f; } return delayFactor; } /** * Gets the maximum refresh delay for the metadata provider. * * @param config provider configuration element * * @return the maximum refresh delay, in milliseconds */ protected long getMaxRefreshDelay(Element config) { long maxRefreshDelay = 14400000L; if (config.hasAttributeNS(null, "cacheDuration")) { int cacheDuration = Integer.parseInt(config.getAttributeNS(null, "cacheDuration")); maxRefreshDelay = cacheDuration * 1000; log.warn("Metadata provider cacheDuration attribute is deprecated, use maxRefreshDelay=\"{}\" instead.", XMLHelper.getDataTypeFactory().newDuration(maxRefreshDelay).toString()); } if (config.hasAttributeNS(null, "maxCacheDuration")) { int cacheDuration = Integer.parseInt(config.getAttributeNS(null, "maxCacheDuration")); Duration duration = XMLHelper.getDataTypeFactory().newDuration(cacheDuration * 1000); log.warn("Metadata provider maxCacheDuration attribute is deprecated, use maxRefreshDelay=\"{}\" instead.", duration.toString()); } if (config.hasAttributeNS(null, "maxRefreshDelay")) { String delayString = config.getAttributeNS(null, "maxRefreshDelay"); try { maxRefreshDelay = SpringConfigurationUtils.parseDurationToMillis("maxRefreshDelay", delayString, 1); } catch (NumberFormatException e) { log.error("Metadata provider had invalid maxRefreshDelay value '{}', using default value", delayString); } } if (maxRefreshDelay <= 0) { log.error("Metadata provider had invalid maxRefreshDelay value '{}', using default value", maxRefreshDelay); maxRefreshDelay = 14400000L; } return maxRefreshDelay; } /** * Gets the minimum refresh delay for the metadata provider. * * @param config provider configuration element * * @return the minimum refresh delay, in milliseconds */ protected long getMinRefreshDelay(Element config) { long minRefreshDelay = 300000L; if (config.hasAttributeNS(null, "minRefreshDelay")) { String delayString = config.getAttributeNS(null, "minRefreshDelay"); try { minRefreshDelay = SpringConfigurationUtils.parseDurationToMillis("minRefreshDelay", delayString, 1); } catch (NumberFormatException e) { log.error("Metadata provider had invalid minRefreshDelay value '{}', using default value", delayString); } } if (minRefreshDelay <= 0) { log.error("Metadata provider had invalid minRefreshDelay value '{}', using default value", minRefreshDelay); minRefreshDelay = 300000L; } return minRefreshDelay; } }
apache-2.0
red6/pdfcompare
src/test/java/de/redsix/pdfcompare/CompareResultImplTest.java
2691
package de.redsix.pdfcompare; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import de.redsix.pdfcompare.env.SimpleEnvironment; import org.junit.jupiter.api.Test; import java.awt.image.BufferedImage; import java.util.Map; class CompareResultImplTest { @Test public void addEqualPagesAreStored() { CompareResultImpl compareResult = new CompareResultImpl(); compareResult.setEnvironment(new SimpleEnvironment()); ImageWithDimension image = new ImageWithDimension(new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY), 0.0f, 0.0f); compareResult.addPage(new PageDiffCalculator(0, 0), 1, image, image, image); assertThat(compareResult.hasImages(), is(true)); compareResult.addPage(new PageDiffCalculator(new PageArea(2)), 2, image, image, image); assertThat(compareResult.hasImages(), is(true)); assertThat(compareResult.getNumberOfPages(), is(2)); assertThat(compareResult.diffImages.size(), is(2)); } @Test public void addEqualPagesAreNotStored() { CompareResultImpl compareResult = new CompareResultImpl(); compareResult.setEnvironment(new SimpleEnvironment().setAddEqualPagesToResult(false)); ImageWithDimension image = new ImageWithDimension(new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY), 0.0f, 0.0f); compareResult.addPage(new PageDiffCalculator(0, 0), 1, image, image, image); assertThat(compareResult.hasImages(), is(false)); compareResult.addPage(new PageDiffCalculator(new PageArea(2)), 2, image, image, image); assertThat(compareResult.hasImages(), is(true)); assertThat(compareResult.getNumberOfPages(), is(1)); assertThat(compareResult.diffImages.size(), is(1)); } @Test public void mapsDiffPercentagesCorrectly() { CompareResultImpl compareResult = new CompareResultImpl(); compareResult.setEnvironment(new SimpleEnvironment()); ImageWithDimension image = new ImageWithDimension(new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY), 0.0f, 0.0f); PageDiffCalculator pageWithDiff = new PageDiffCalculator(5, 0); pageWithDiff.diffFound(); PageDiffCalculator pageWithoutDiff = new PageDiffCalculator(10, 0); compareResult.addPage(pageWithDiff, 1, image, image, image); compareResult.addPage(pageWithoutDiff, 2, image, image, image); Map<Integer, Double> result = compareResult.getPageDiffsInPercent(); assertThat(result, hasEntry(1, 20.0)); assertThat(result, hasEntry(2, 0.0)); } }
apache-2.0
0blivi0n/oblivion-bin-client-java
src/main/java/net/uiqui/oblivion/bin/client/api/APIClient.java
7475
/* * 0blivi0n-cache * ============== * Java BIN Client * * Copyright (C) 2015 Joaquim Rocha <jrocha@gmailbox.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.uiqui.oblivion.bin.client.api; import java.io.IOException; import java.util.List; import java.util.Map; import net.uiqui.oblivion.bin.client.error.CacheException; import net.uiqui.oblivion.bin.client.model.Caches; import net.uiqui.oblivion.bin.client.model.Nodes; import net.uiqui.oblivion.bin.client.model.Server; import net.uiqui.oblivion.mercury.Mercury; import net.uiqui.oblivion.mercury.api.JSON; import net.uiqui.oblivion.mercury.api.MercuryRequest; import net.uiqui.oblivion.mercury.api.MercuryResponse; import net.uiqui.oblivion.mercury.api.Proplist; import net.uiqui.oblivion.mercury.api.Resource; public class APIClient { private Mercury client = null; public APIClient(final String server, final int port, final int refreshInterval) { final OblibionCluster cluster = new OblibionCluster(this, server, port, refreshInterval); this.client = new Mercury(cluster); } public List<String> caches() throws IOException, CacheException { final String[] resource = Resource.build("caches"); final Map<String, Object> params = Proplist.build("sort", true); final MercuryRequest request = MercuryRequest.build("GET", resource, params); final MercuryResponse response = call(request); if (response.status() == 200) { final JSON json = response.payload(); final List<JSON> caches = json.value("caches"); return Caches.cacheNames(caches); } else { throw error(response); } } public void flush(final String cache) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys"); final MercuryRequest request = MercuryRequest.build("DELETE", resource); final MercuryResponse response = call(request); if (response.status() != 202) { throw error(response); } } public long size(final String cache) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys"); final MercuryRequest request = MercuryRequest.build("GET", resource); final MercuryResponse response = call(request); if (response.status() == 200) { return response.payload(); } else { throw error(response); } } public List<String> keys(final String cache) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys"); final Map<String, Object> params = Proplist.build("list", true); final MercuryRequest request = MercuryRequest.build("GET", resource, params); final MercuryResponse response = call(request); if (response.status() == 200) { final JSON json = response.payload(); return json.value("keys"); } else { throw error(response); } } public long put(final String cache, final String key, final Object value) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys", key); final MercuryRequest request = MercuryRequest.build("PUT", resource, value); return store(request); } public long put(final String cache, final String key, final Object value, long version) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys", key); final Map<String, Object> params = Proplist.build("version", version); final MercuryRequest request = MercuryRequest.build("PUT", resource, params, value); return store(request); } private long store(final MercuryRequest request) throws IOException, CacheException { final MercuryResponse response = call(request); if (response.status() == 201) { final Map<String, Object> params = response.params(); return (Long) params.get("version"); } else { throw error(response); } } public void delete(final String cache, final String key) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys", key); final MercuryRequest request = MercuryRequest.build("DELETE", resource); remove(request); } public void delete(final String cache, final String key, long version) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys", key); final Map<String, Object> params = Proplist.build("version", version); final MercuryRequest request = MercuryRequest.build("DELETE", resource, params); remove(request); } private void remove(final MercuryRequest request) throws IOException, CacheException { final MercuryResponse response = call(request); if (response.status() != 200) { throw error(response); } } public long version(final String cache, final String key) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys", key); final MercuryRequest request = MercuryRequest.build("VERSION", resource); final MercuryResponse response = call(request); if (response.status() == 200) { final Map<String, Object> params = response.params(); return (Long) params.get("version"); } else { throw error(response); } } public Response get(final String cache, final String key) throws IOException, CacheException { final String[] resource = Resource.build("caches", cache, "keys", key); final MercuryRequest request = MercuryRequest.build("GET", resource); final MercuryResponse response = call(request); if (response.status() == 200) { final Map<String, Object> params = response.params(); final Long version = (Long) params.get("version"); return new Response(response.payload(), version); } else if (response.status() == 404) { return null; } else { throw error(response); } } protected List<Server> nodes() throws IOException, CacheException { final String[] resource = Resource.build("nodes"); final MercuryRequest request = MercuryRequest.build("GET", resource); final MercuryResponse response = call(request); if (response.status() == 200) { final JSON json = response.payload(); final List<JSON> nodes = json.value("nodes"); return Nodes.onlineNodes(nodes); } else { throw error(response); } } public String systemVersion() throws IOException, CacheException { final String[] resource = Resource.build("system"); final MercuryRequest request = MercuryRequest.build("GET", resource); final MercuryResponse response = call(request); if (response.status() == 200) { final JSON json = response.payload(); return json.value("version"); } else { throw error(response); } } private MercuryResponse call(final MercuryRequest request) throws IOException { try { return client.call(request); } catch (Exception e) { throw new IOException("Error executing remote call", e); } } private CacheException error(final MercuryResponse response) { final JSON json = response.payload(); return CacheException.build(response.status(), json); } }
apache-2.0
jittagornp/cpe4235
orm/hr/src/main/java/com/pamarin/cpe4235/hr/service/impl/EmployeeServiceImpl.java
1342
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pamarin.cpe4235.hr.service.impl; import com.pamarin.cpe4235.hr.model.Employee; import com.pamarin.cpe4235.hr.repo.EmployeeRepo; import com.pamarin.cpe4235.hr.service.EmployeeService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * * @author anonymous */ @Service @Transactional public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepo repo; private boolean isEmpty(String str) { return str == null || str.isEmpty(); } @Override public List<Employee> searchByName(String keyword) { if (isEmpty(keyword)) { return repo.findAllEmployees(); } return repo.searchByName("%" + keyword + "%"); } @Override public void delete(Employee employee) { if (employee != null) { repo.delete(employee.getId()); } } @Override public Employee save(Employee employee) { //// return repo.save(employee); ///// } }
apache-2.0
iWay7/Helpers
helpers/src/main/java/site/iway/helpers/ActionTimer.java
3751
package site.iway.helpers; import android.content.Context; import java.util.LinkedList; import java.util.List; public class ActionTimer { public static abstract class Action { private volatile String mTag; private volatile long mRunTime; public Action(String tag) { if (tag == null) throw new RuntimeException("Tag of the action can not be null."); mTag = tag; } public String getTag() { return mTag; } public long getRunTime() { return mRunTime; } public void setRunTime(long runTime) { mRunTime = runTime; } public void setRunTimeDelayed(long delay) { mRunTime = System.currentTimeMillis() + delay; } public void schedule() { addAction(this); } public abstract void run(Context context); } private static final Object sSynchronizer = new Object(); private static Context sApplicationContext; private static List<Action> sActions = new LinkedList<>(); private static Thread sThread = new Thread() { public void run() { while (true) { List<Action> actions = new LinkedList<>(); synchronized (sSynchronizer) { actions.addAll(sActions); } long now = System.currentTimeMillis(); for (Action action : actions) { long runTime = action.getRunTime(); if (now >= runTime) { removeAction(action); action.run(sApplicationContext); } } try { Thread.sleep(1000); } catch (InterruptedException e) { // nothing } } } }; public static void initialize(Context context) { sApplicationContext = context; sThread.start(); } public static void addAction(Action action) { synchronized (sSynchronizer) { String tag = action.getTag(); if (tag == null) { throw new RuntimeException("Action tag can not be null."); } if (hasAction(tag)) { throw new RuntimeException("Action with tag " + tag + " already existed."); } sActions.add(action); } } public static void removeAction(Action action) { synchronized (sSynchronizer) { sActions.remove(action); } } public static void removeAction(String tag) { synchronized (sSynchronizer) { int size = sActions.size(); for (int i = size - 1; i >= 0; i--) { Action action = sActions.get(i); String actionTag = action.getTag(); if (actionTag == null) { if (tag == null) { sActions.remove(i); } } else { if (actionTag.equals(tag)) { sActions.remove(i); } } } } } public static boolean hasAction(Action action) { synchronized (sSynchronizer) { return sActions.contains(action); } } public static boolean hasAction(String tag) { synchronized (sSynchronizer) { for (Action action : sActions) { String actionTag = action.getTag(); if (actionTag.equals(tag)) { return true; } } return false; } } }
apache-2.0
openfurther/further-open-precompile
further-precompile/datasources/OpenMRS-OMOP-Reference/further-open-datasources/ds-omop/src/test/java/edu/utah/further/ds/omop/model/v2/domain/UTestMarshallOmopV2.java
3712
/** * Copyright (C) [2013] [The FURTHeR Project] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.further.ds.omop.model.v2.domain; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; import java.math.BigDecimal; import javax.xml.bind.JAXBException; import org.junit.Test; import edu.utah.further.core.api.collections.CollectionUtil; import edu.utah.further.core.api.xml.XmlService; import edu.utah.further.core.test.annotation.UnitTest; import edu.utah.further.core.xml.jaxb.XmlServiceImpl; import edu.utah.further.ds.omop.model.v2.domain.ConditionEra; import edu.utah.further.ds.omop.model.v2.domain.ConditionOccurrence; import edu.utah.further.ds.omop.model.v2.domain.DrugEra; import edu.utah.further.ds.omop.model.v2.domain.DrugExposure; import edu.utah.further.ds.omop.model.v2.domain.Observation; import edu.utah.further.ds.omop.model.v2.domain.ObservationPeriod; import edu.utah.further.ds.omop.model.v2.domain.Person; import edu.utah.further.ds.omop.model.v2.domain.ProcedureOccurrence; import edu.utah.further.ds.omop.model.v2.domain.VisitOccurrence; /** * ... * <p> * -----------------------------------------------------------------------------------<br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <further@utah.edu>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author N. Dustin Schultz {@code <dustin.schultz@utah.edu>} * @version Apr 24, 2013 */ @UnitTest public class UTestMarshallOmopV2 { @Test public void marshalPerson() throws JAXBException { final Person person = new Person(); person.setId(new Long(1)); person.setGenderConceptId(new BigDecimal(1)); person.setLocationConceptId(new BigDecimal(1)); person.setRaceConceptId(new BigDecimal(1)); person.setSourceGenderCode("Male"); person.setSourceLocationCode("Moon"); person.setSourceRaceCode("Blue"); person.setSourcePersonKey("key"); person.setYearOfBirth(new BigDecimal(2013)); person.setConditionEras(CollectionUtil.<ConditionEra> newList()); person.setConditionOccurrences(CollectionUtil.<ConditionOccurrence> newList()); person.setDrugEras(CollectionUtil.<DrugEra> newList()); person.setDrugExposures(CollectionUtil.<DrugExposure> newList()); person.setObservations(CollectionUtil.<Observation> newList()); person.setObservationPeriods(CollectionUtil.<ObservationPeriod> newList()); person.setProcedureOccurrences(CollectionUtil.<ProcedureOccurrence> newList()); person.setVisitOccurrences(CollectionUtil.<VisitOccurrence> newList()); final XmlService service = new XmlServiceImpl(); final String result = service.marshal(person); assertThat(result, containsString("<Person")); assertThat(result, containsString("</Person>")); assertThat(result, containsString("Male")); assertThat(result, containsString("Moon")); assertThat(result, containsString("Blue")); assertThat(result, containsString("key")); assertThat(result, containsString("2013")); } }
apache-2.0
a8658438/DataAnalysis
DataAnalysis/src/main/java/com/minstone/util/Result.java
3854
package com.minstone.util; import java.util.List; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * 淘淘商城自定义响应结构 */ public class Result { // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); // 响应业务状态 private Integer status; // 响应消息 private String msg; // 响应中的数据 private Object data; public static Result build(Integer status, String msg, Object data) { return new Result(status, msg, data); } public static Result ok(Object data) { return new Result(data); } public static Result ok() { return new Result(null); } public Result() { } public static Result build(Integer status, String msg) { return new Result(status, msg, null); } public Result(Integer status, String msg, Object data) { this.status = status; this.msg = msg; this.data = data; } public Result(Object data) { this.status = 200; this.msg = "OK"; this.data = data; } // public Boolean isOK() { // return this.status == 200; // } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } /** * 将json结果集转化为TaotaoResult对象 * * @param jsonData json数据 * @param clazz TaotaoResult中的object类型 * @return */ public static Result formatToPojo(String jsonData, Class<?> clazz) { try { if (clazz == null) { return MAPPER.readValue(jsonData, Result.class); } MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNode data = jsonNode.get("data"); Object obj = null; if (clazz != null) { if (data.isObject()) { obj = MAPPER.readValue(data.traverse(), clazz); } else if (data.isTextual()) { obj = MAPPER.readValue(data.asText(), clazz); } } return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 没有object对象的转化 * * @param json * @return */ public static Result format(String json) { try { return MAPPER.readValue(json, Result.class); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Object是集合转化 * * @param jsonData json数据 * @param clazz 集合中的类型 * @return */ public static Result formatToList(String jsonData, Class<?> clazz) { try { JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNode data = jsonNode.get("data"); Object obj = null; if (data.isArray() && data.size() > 0) { obj = MAPPER.readValue(data.traverse(), MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); } return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); } catch (Exception e) { return null; } } }
apache-2.0
ur6lad/stroke-taglib
src/test/java/ua/co/ur6lad/stroke/ProductBeanTest.java
8903
package ua.co.ur6lad.stroke; /* * Copyright 2015 Vitaliy Berdinskikh * * 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 static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ProductBeanTest { private static final String ANOTHER_PRODUCT_ID = "product99"; private static final String CATEGORY_ID = "category1"; private static final int EQUAL = 0; private static final int EVENT_1 = 13; private static final int EVENT_2 = 27; private static final int EVENT_3 = -1; private static final String EVENT_VALUE_1 = "fge"; private static final String EVENT_VALUE_2 = "opqrst"; private static final String EVENT_VALUE_3 = "xyz"; private static final int KEY_AND_VALUE = 2; private static final int LESS_THAN = -1; private static final String PAGE_NAME = "pageName"; private static final String PRODUCT_ID = "product2"; private static final int PRODUCT_STRING_SIZE = 6; private static final String QUANTITY = "quantity3"; private static final String TOTAL_COST = "totalCost4"; private static final int TWO = 2; private static final int VARIABLE_1 = 1; private static final int VARIABLE_2 = 0; private static final String VARIABLE_VALUE_1 = "last"; private static final String VARIABLE_VALUE_2 = "zero"; @Mock private ProductBean anotherBean; private ProductBean bean; /* Equals */ @Test public void alienObject() { bean.setProduct(PRODUCT_ID); assertFalse("Different beans", bean.equals(VARIABLE_VALUE_1)); } @Test public void beanWithNullProduct() { bean.setProduct(PRODUCT_ID); assertFalse("Bean with null product", bean.equals(anotherBean)); } @Test public void differentBeans() { bean.setProduct(PRODUCT_ID); when(anotherBean.getProduct()).thenReturn(ANOTHER_PRODUCT_ID); assertFalse("Different beans", bean.equals(anotherBean)); verify(anotherBean).getProduct(); } @Test public void equalBeans() { bean.setProduct(PRODUCT_ID); when(anotherBean.getProduct()).thenReturn(PRODUCT_ID); assertTrue("Equal beans", bean.equals(anotherBean)); verify(anotherBean).getProduct(); } @Test public void nullBean() { ProductBean nullBean = null; bean.setProduct(PRODUCT_ID); assertFalse("Null bean", bean.equals(nullBean)); } @Test public void whenProductIsNull() { when(anotherBean.getProduct()).thenReturn(ANOTHER_PRODUCT_ID); assertFalse("Bean with null product", bean.equals(anotherBean)); } /* toString() */ @Test public void beanToString() throws UnsupportedVariableException { List<String> variables; String[] splittedTestString, variable; String testString; Map<String, String> expectedEvents = new LinkedHashMap<String, String>(); Map<String, String> expectedVariables = new LinkedHashMap<String, String>(); expectedEvents.put("event" + EVENT_1, EVENT_VALUE_1); expectedEvents.put("event" + EVENT_3, EVENT_VALUE_3); expectedEvents.put("event" + EVENT_2, EVENT_VALUE_2); expectedVariables.put("eVar" + VARIABLE_1, VARIABLE_VALUE_1); expectedVariables.put("eVar" + VARIABLE_2, VARIABLE_VALUE_2); bean.setCategory(CATEGORY_ID); bean.addVariable(new OmniVariable.Conversion(VARIABLE_1), VARIABLE_VALUE_1); bean.addVariable(new OmniVariable.Conversion(VARIABLE_2), VARIABLE_VALUE_2); bean.addVariable(new OmniVariable.Event(EVENT_1), EVENT_VALUE_1); bean.addVariable(new OmniVariable.Event(EVENT_2), EVENT_VALUE_2); bean.addVariable(new OmniVariable.Event(EVENT_3), EVENT_VALUE_3); bean.setProduct(PRODUCT_ID); bean.setQuantity(QUANTITY); bean.setTotalCost(TOTAL_COST); testString = bean.toString(); assertNotNull("String exists", testString); splittedTestString = testString.split(";"); assertEquals("Product string parts", PRODUCT_STRING_SIZE, splittedTestString.length); assertEquals("Category", CATEGORY_ID, splittedTestString[0]); assertEquals("Product", PRODUCT_ID, splittedTestString[1]); assertEquals("Quantity", QUANTITY, splittedTestString[2]); assertEquals("Total cost", TOTAL_COST, splittedTestString[3]); variables = Arrays.asList(splittedTestString[4].split("\\|")); for (String eventString : variables) { variable = eventString.split("="); assertEquals("Event: key and value", KEY_AND_VALUE, variable.length); assertEquals("Event", expectedEvents.get(variable[0]), variable[1]); expectedEvents.remove(variable[0]); } assertTrue("All events are found", expectedEvents.isEmpty()); variables = Arrays.asList(splittedTestString[5].split("\\|")); for (String variableString : variables) { variable = variableString.split("="); assertEquals("Conversion variable: key and value", KEY_AND_VALUE, variable.length); assertEquals("Conversion variable", expectedVariables.get(variable[0]), variable[1]); expectedVariables.remove(variable[0]); } assertTrue("All conversion variables are found", expectedVariables.isEmpty()); } @Test public void emptyBeanToString() { String testString = null; testString = bean.toString(); assertNotNull("String exists", testString); assertEquals("Product string", ";;;;;", testString); } /* hashCode() */ @Test public void hashCodeAndEmptyProduct() { assertNotNull("Hashcode of the empty bean", bean.hashCode()); } @Test public void hashCodeAndProduct() { bean.setProduct(PRODUCT_ID); assertEquals("Hashcode equals number's one", PRODUCT_ID.hashCode(), bean.hashCode()); } /* Compare */ @Test public void compareBeanWithNullProduct() { bean.setProduct(PRODUCT_ID); assertEquals("Compare with a bean with null product", EQUAL, bean.compareTo(anotherBean)); } @Test public void compareDifferentBeans() { bean.setProduct(PRODUCT_ID); when(anotherBean.getProduct()).thenReturn(ANOTHER_PRODUCT_ID); assertTrue("Different beans", LESS_THAN >= bean.compareTo(anotherBean)); verify(anotherBean, times(TWO)).getProduct(); } @Test public void compareEqualBeans() { bean.setProduct(PRODUCT_ID); when(anotherBean.getProduct()).thenReturn(PRODUCT_ID); assertEquals("Compare equal beans", EQUAL, bean.compareTo(anotherBean)); verify(anotherBean, times(TWO)).getProduct(); } @Test public void compareNullBean() { ProductBean nullBean = null; bean.setProduct(PRODUCT_ID); assertEquals("Compare with the null bean", EQUAL, bean.compareTo(nullBean)); } @Test public void compareWhenProductIsNull() { when(anotherBean.getProduct()).thenReturn(ANOTHER_PRODUCT_ID); assertEquals("Compare when the bean with null product", EQUAL, bean.compareTo(anotherBean)); } /* Unsupported variable types */ @Test(expected=UnsupportedVariableException.class) public void unsupportedHierarchy() throws UnsupportedVariableException { OmniVariable.Hierarchy variable = new OmniVariable.Hierarchy(VARIABLE_1); bean.addVariable(variable, VARIABLE_VALUE_1); } @Test(expected=UnsupportedVariableException.class) public void unsupportedStandardVariable() throws UnsupportedVariableException { OmniVariable.Standard variable = new OmniVariable.Standard(PAGE_NAME); bean.addVariable(variable, VARIABLE_VALUE_1); } @Test(expected=UnsupportedVariableException.class) public void unsupportedTrafficTraffic() throws UnsupportedVariableException { OmniVariable.Traffic variable = new OmniVariable.Traffic(VARIABLE_1); bean.addVariable(variable, VARIABLE_VALUE_1); } @Test(expected=UnsupportedVariableException.class) public void unsupportedVariableSet() throws UnsupportedVariableException { OmniVariable.Event variable = new OmniVariable.Event(VARIABLE_1); bean.addVariable(variable); } @Before public void setUp() throws Exception { bean = new ProductBean(); } }
apache-2.0
liangminhua/cordova-plugin-posprinter
src/android/PosPrinter.java
11551
package cordova.plugin.posprinter; /** * cordova-plugin-posprinter * Created by BEN on 2016/8/25. */ import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Build; import android.os.IBinder; import android.util.Log; import net.posprinter.posprinterface.IMyBinder; import net.posprinter.posprinterface.UiExecute; import net.posprinter.service.PosprinterService; import net.posprinter.utils.RoundQueue; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; /** * This class echoes a string called from JavaScript. */ public class PosPrinter extends CordovaPlugin { boolean isConnect = false; IMyBinder binder; ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { binder = (IMyBinder) iBinder; } @Override public void onServiceDisconnected(ComponentName componentName) { } }; BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); CallbackContext scanCallback = null; CallbackContext enableCallback = null; BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent JSONObject callbackJsonObject = new JSONObject(); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); addProperty(callbackJsonObject, Constant.DEVICE_NAME, device.getName()); addProperty(callbackJsonObject, Constant.DEVICE_BLUETOOTH_ADDRESS, device.getAddress()); addProperty(callbackJsonObject, Constant.BOND_STATE, device.getBondState()); sendUpdate(scanCallback, callbackJsonObject); // Logs if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Log.i("PosPrinter", device.getName() + "\n" + device.getAddress() + "\n" + device.getType()); } } } }; @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); // Enable Bluetooth Callback if (Constant.REQUEST_ENABLE_BT == requestCode) { if (resultCode == Constant.RESULT_OK) { enableCallback.success(); } else { enableCallback.error(Constant.REQUEST_ENABLE_BT_FAIL); } } } @Override public void onDestroy() { super.onDestroy(); if (bluetoothAdapter != null) cordova.getActivity().unregisterReceiver(bluetoothReceiver); if (conn != null) cordova.getActivity().unbindService(conn); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("initialize")) { initialize(callbackContext); return true; } if (action.equals("getBluetoothState")) { getBluetoothState(callbackContext); return true; } if (action.equals("enableBluetooth")) { enableBluetooth(callbackContext); return true; } if (action.equals("disableBluetooth")) { disableBluetooth(callbackContext); return true; } if (action.equals("scanBluetoothDevice")) { scanBluetoothDevice(callbackContext); return true; } if (action.equals("stopScanBluetoothDevices")) { stopScanBluetoothDevices(callbackContext); return true; } if (action.equals("connectUsb")) { String usbPathName = args.getString(0); connectUsb(usbPathName, callbackContext); return true; } if (action.equals("connectBluetooth")) { String address = args.getString(0); connectBluetooth(address, callbackContext); return true; } if (action.equals("connectNet")) { String ip = args.getString(0); int port = args.optInt(1, 9100); connectNet(ip, port, callbackContext); return true; } if (action.equals("disconnectCurrentPort")) { disconnectCurrentPort(callbackContext); return true; } if (action.equals("write")) { byte[] data = new byte[args.length()]; for (int index = 0; index < args.length(); ++index) { data[index] = (byte) args.getInt(index); } write(data, callbackContext); return true; } if (action.equals("read")) { read(callbackContext); return true; } return false; } private void initialize(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { Intent intent = new Intent(cordova.getActivity(), PosprinterService.class); Context context = cordova.getActivity().getApplicationContext(); context.bindService(intent, conn, Context.BIND_AUTO_CREATE); if (callbackContext != null) callbackContext.success(); } }); } private void getBluetoothState(CallbackContext callbackContext) { if (BluetoothAdapter.STATE_ON != bluetoothAdapter.getState()) { callbackContext.success(1); } else { callbackContext.success(0); } } private void stopScanBluetoothDevices(final CallbackContext callbackContext) { bluetoothAdapter.cancelDiscovery(); callbackContext.success(); } private void enableBluetooth(final CallbackContext callbackContext) { if (!bluetoothAdapter.isEnabled()) { enableCallback = callbackContext; Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); cordova.getActivity().startActivityForResult(intent, Constant.REQUEST_ENABLE_BT); } } private void disableBluetooth(final CallbackContext callbackContext) { boolean result = bluetoothAdapter.disable(); if (result) { callbackContext.success(); } else { callbackContext.error(Constant.DISABLE_BLUETOOTH_FAIL); } } private void scanBluetoothDevice(CallbackContext callbackContext) { scanCallback = callbackContext; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); cordova.getActivity().registerReceiver(bluetoothReceiver, filter); boolean result = bluetoothAdapter.startDiscovery(); if (!result) { callbackContext.error(Constant.SCAN_BLUETOOTHDEVICE_FAIL); } } private void connectUsb(String usbPathName, final CallbackContext callbackContext) { binder.connectUsbPort(cordova.getActivity().getApplicationContext(), usbPathName, new UiExecute() { @Override public void onsucess() { isConnect = true; final PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); binder.acceptdatafromprinter(new UiExecute() { @Override public void onsucess() { } @Override public void onfailed() { isConnect = false; callbackContext.error(Constant.USB_DISCONNECT); } }); } @Override public void onfailed() { callbackContext.error(Constant.USB_CONNECT_FAIL); } }); } private void connectBluetooth(String bluetoothAddress, final CallbackContext callbackContext) { if (bluetoothAdapter.isEnabled()) { binder.connectBtPort(bluetoothAddress, new UiExecute() { @Override public void onsucess() { isConnect = true; final PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); binder.acceptdatafromprinter(new UiExecute() { @Override public void onsucess() { } @Override public void onfailed() { callbackContext.error(Constant.BLUETOOTH_DISCONNECT); } }); } @Override public void onfailed() { isConnect = false; callbackContext.error(Constant.BLUETOOTH_CONNECT_FAIL); } }); } else { callbackContext.error(Constant.REQUEST_ENABLE_BT_FAIL); } } private void connectNet(String ipAddress, int port, final CallbackContext callbackContext) { binder.connectNetPort(ipAddress, port, new UiExecute() { @Override public void onsucess() { isConnect = true; final PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); binder.acceptdatafromprinter(new UiExecute() { @Override public void onsucess() { } @Override public void onfailed() { isConnect = false; callbackContext.error(Constant.NET_DISCONNECT); } }); } @Override public void onfailed() { callbackContext.error(Constant.NET_CONNECT_FAIL); } }); } private void disconnectCurrentPort(final CallbackContext callbackContext) { if (isConnect) { binder.disconnectCurrentPort(new UiExecute() { @Override public void onsucess() { callbackContext.success(); } @Override public void onfailed() { callbackContext.error(Constant.DISCONNECT_FAIL); } }); } else { callbackContext.error(Constant.NOT_CONNECT); } } private void write(byte[] data, final CallbackContext callbackContext) { if (isConnect) { binder.write(data, new UiExecute() { @Override public void onsucess() { callbackContext.success(); } @Override public void onfailed() { callbackContext.error(Constant.WRITE_FAIL); } }); } else { callbackContext.error(Constant.NOT_CONNECT); } } private void read(CallbackContext callbackContext) { RoundQueue<byte[]> readBuffer = binder.readBuffer(); byte[] data = readBuffer.getLast(); String res = Arrays.toString(data); Log.i("PosPrinter", "data=" + res); callbackContext.success(res); } /** * Create a new plugin result and send it back to JavaScript * * @param obj the printer info to set as navigator.connection */ private void sendUpdate(CallbackContext callbackContext, JSONObject obj) { if (callbackContext != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, obj); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } } //General Helpers private void addProperty(JSONObject obj, String key, Object value) { //Believe exception only occurs when adding duplicate keys, so just ignore it try { if (value == null) { obj.put(key, JSONObject.NULL); } else { obj.put(key, value); } } catch (JSONException e) { Log.e("PosPrinter", e.getMessage()); } } }
apache-2.0
googleapis/java-translate
proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/GetGlossaryRequestOrBuilder.java
1573
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/translate/v3/translation_service.proto package com.google.cloud.translate.v3; public interface GetGlossaryRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.translation.v3.GetGlossaryRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The name of the glossary to retrieve. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * Required. The name of the glossary to retrieve. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); }
apache-2.0
anjalshireesh/gluster-ovirt-poc
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/DiskImageDAODbFacadeImpl.java
38353
package org.ovirt.engine.core.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskInterface; import org.ovirt.engine.core.common.businessentities.DiskType; import org.ovirt.engine.core.common.businessentities.ImageStatus; import org.ovirt.engine.core.common.businessentities.PropagateErrors; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.image_vm_map_id; import org.ovirt.engine.core.common.businessentities.image_vm_pool_map; import org.ovirt.engine.core.common.businessentities.stateless_vm_image_map; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.DbFacadeUtils; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; /** * <code>DiskImageDAODbFacadeImpl</code> provides an implementation of {@link DiskImageDAO} that uses previously * developed code from {@link DbFacade}. * * */ public class DiskImageDAODbFacadeImpl extends BaseDAODbFacade implements DiskImageDAO { @Override public DiskImage get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_guid", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setactive((Boolean) rs.getObject("active")); entity.setvm_guid(Guid.createGuidFromString(rs .getString("vm_guid"))); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeRead("GetImageByImageGuid", mapper, parameterSource); } @Override public DiskImage getSnapshotById(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_guid", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeRead("GetSnapshotByGuid", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<DiskImage> getAllForVm(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vm_guid", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setactive((Boolean) rs.getObject("active")); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setvm_guid(Guid.createGuidFromString(rs .getString("vm_guid"))); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeReadList("GetImagesByVmGuid", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<DiskImage> getAllSnapshotsForParent(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("parent_guid", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeReadList("GetSnapshotByParentGuid", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<DiskImage> getAllSnapshotsForStorageDomain(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("storage_domain_id", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeReadList("GetSnapshotsByStorageDomainId", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<DiskImage> getAllSnapshotsForVmSnapshot(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("vm_snapshot_id", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeReadList("GetSnapshotsByVmSnapshotId", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<DiskImage> getAllSnapshotsForImageGroup(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_group_id", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeReadList("GetSnapshotsByImageGroupId", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<DiskImage> getAll() { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource(); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setactual_size(rs.getLong("actual_size")); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setstorage_path(rs.getString("storage_path")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs .getString("storage_pool_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); entity.setread_rate(rs.getInt("read_rate")); entity.setwrite_rate(rs.getInt("write_rate")); return entity; } }; return getCallsHandler().executeReadList("GetAllFromImages", mapper, parameterSource); } @Override public void save(DiskImage image) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("creation_date", image.getcreation_date()) .addValue("description", image.getdescription()) .addValue("image_guid", image.getId()) .addValue("internal_drive_mapping", image.getinternal_drive_mapping()) .addValue("it_guid", image.getit_guid()) .addValue("size", image.getsize()) .addValue("ParentId", image.getParentId()) .addValue("imageStatus", image.getimageStatus()) .addValue("lastModified", image.getlastModified()) .addValue("app_list", image.getappList()) .addValue("storage_id", image.getstorage_id()) .addValue("vm_snapshot_id", image.getvm_snapshot_id()) .addValue("volume_type", image.getvolume_type()) .addValue("volume_format", image.getvolume_format()) .addValue("disk_type", image.getdisk_type()) .addValue("image_group_id", image.getimage_group_id()) .addValue("disk_interface", image.getdisk_interface()) .addValue("boot", image.getboot()) .addValue("wipe_after_delete", image.getwipe_after_delete()) .addValue("propagate_errors", image.getpropagate_errors()); getCallsHandler().executeModification("InsertImage", parameterSource); } @Override public void update(DiskImage image) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("creation_date", image.getcreation_date()) .addValue("description", image.getdescription()) .addValue("image_guid", image.getId()) .addValue("internal_drive_mapping", image.getinternal_drive_mapping()) .addValue("it_guid", image.getit_guid()) .addValue("size", image.getsize()) .addValue("ParentId", image.getParentId()) .addValue("imageStatus", image.getimageStatus()) .addValue("lastModified", image.getlastModified()) .addValue("app_list", image.getappList()) .addValue("storage_id", image.getstorage_id()) .addValue("vm_snapshot_id", image.getvm_snapshot_id()) .addValue("volume_type", image.getvolume_type()) .addValue("volume_format", image.getvolume_format()) .addValue("disk_type", image.getdisk_type()) .addValue("image_group_id", image.getimage_group_id()) .addValue("disk_interface", image.getdisk_interface()) .addValue("boot", image.getboot()) .addValue("wipe_after_delete", image.getwipe_after_delete()) .addValue("propagate_errors", image.getpropagate_errors()); getCallsHandler().executeModification("UpdateImage", parameterSource); } @Override public void remove(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_guid", id); getCallsHandler().executeModification("DeleteImage", parameterSource); } @Override public void removeAllForVmId(Guid id) { List<Guid> imagesList = new ArrayList<Guid>(); for (DiskImage image : getAllForVm(id)) { imagesList.add(image.getId()); } // TODO this will be fixed when we have ORM and object relationships for (Guid guid : imagesList) { DbFacade.getInstance().getImageVmMapDAO().remove(new image_vm_map_id(guid, id)); } } @Override public image_vm_pool_map getImageVmPoolMapByImageId(Guid imageId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_guid", imageId); ParameterizedRowMapper<image_vm_pool_map> mapper = new ParameterizedRowMapper<image_vm_pool_map>() { @Override public image_vm_pool_map mapRow(ResultSet rs, int rowNum) throws SQLException { image_vm_pool_map entity = new image_vm_pool_map(); entity.setimage_guid(Guid.createGuidFromString(rs.getString("image_guid"))); entity.setinternal_drive_mapping(rs.getString("internal_drive_mapping")); entity.setvm_guid(Guid.createGuidFromString(rs.getString("vm_guid"))); return entity; } }; return getCallsHandler().executeRead("Getimage_vm_pool_mapByimage_guid", mapper, parameterSource); } @Override public void addImageVmPoolMap(image_vm_pool_map map) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_guid", map.getimage_guid()).addValue("internal_drive_mapping", map.getinternal_drive_mapping()).addValue( "vm_guid", map.getvm_guid()); getCallsHandler().executeModification("Insertimage_vm_pool_map", parameterSource); } @Override public void removeImageVmPoolMap(Guid imageId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_guid", imageId); getCallsHandler().executeModification("Deleteimage_vm_pool_map", parameterSource); } @SuppressWarnings("unchecked") @Override public List<image_vm_pool_map> getImageVmPoolMapByVmId(Guid vmId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vm_guid", vmId); ParameterizedRowMapper<image_vm_pool_map> mapper = new ParameterizedRowMapper<image_vm_pool_map>() { @Override public image_vm_pool_map mapRow(ResultSet rs, int rowNum) throws SQLException { image_vm_pool_map entity = new image_vm_pool_map(); entity.setimage_guid(Guid.createGuidFromString(rs.getString("image_guid"))); entity.setinternal_drive_mapping(rs.getString("internal_drive_mapping")); entity.setvm_guid(Guid.createGuidFromString(rs.getString("vm_guid"))); return entity; } }; return getCallsHandler().executeReadList("Getimage_vm_pool_mapByvm_guid", mapper, parameterSource); } @Override public stateless_vm_image_map getStatelessVmImageMapForImageId(Guid imageId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_guid", imageId); ParameterizedRowMapper<stateless_vm_image_map> mapper = new ParameterizedRowMapper<stateless_vm_image_map>() { @Override public stateless_vm_image_map mapRow(ResultSet rs, int rowNum) throws SQLException { stateless_vm_image_map entity = new stateless_vm_image_map(); entity.setimage_guid(Guid.createGuidFromString(rs.getString("image_guid"))); entity.setinternal_drive_mapping(rs.getString("internal_drive_mapping")); entity.setvm_guid(Guid.createGuidFromString(rs.getString("vm_guid"))); return entity; } }; return getCallsHandler().executeRead("Getstateless_vm_image_mapByimage_guid", mapper, parameterSource); } @Override public void addStatelessVmImageMap(stateless_vm_image_map map) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_guid", map.getimage_guid()).addValue("internal_drive_mapping", map.getinternal_drive_mapping()).addValue( "vm_guid", map.getvm_guid()); getCallsHandler().executeModification("Insertstateless_vm_image_map", parameterSource); } @Override public void removeStatelessVmImageMap(Guid imageId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_guid", imageId); getCallsHandler().executeModification("Deletestateless_vm_image_map", parameterSource); } @SuppressWarnings("unchecked") @Override public List<stateless_vm_image_map> getAllStatelessVmImageMapsForVm(Guid vmId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vm_guid", vmId); ParameterizedRowMapper<stateless_vm_image_map> mapper = new ParameterizedRowMapper<stateless_vm_image_map>() { @Override public stateless_vm_image_map mapRow(ResultSet rs, int rowNum) throws SQLException { stateless_vm_image_map entity = new stateless_vm_image_map(); entity.setimage_guid(Guid.createGuidFromString(rs.getString("image_guid"))); entity.setinternal_drive_mapping(rs.getString("internal_drive_mapping")); entity.setvm_guid(Guid.createGuidFromString(rs.getString("vm_guid"))); return entity; } }; return getCallsHandler().executeReadList("Getstateless_vm_image_mapByvm_guid", mapper, parameterSource); } @Override public DiskImage getAncestor(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_guid", id); ParameterizedRowMapper<DiskImage> mapper = new ParameterizedRowMapper<DiskImage>() { @Override public DiskImage mapRow(ResultSet rs, int rowNum) throws SQLException { DiskImage entity = new DiskImage(); entity.setcreation_date(DbFacadeUtils.fromDate(rs .getTimestamp("creation_date"))); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs .getString("image_guid"))); entity.setinternal_drive_mapping(rs .getString("internal_drive_mapping")); entity.setit_guid(Guid.createGuidFromString(rs .getString("it_guid"))); entity.setsize(rs.getLong("size")); entity.setParentId(Guid.createGuidFromString(rs .getString("ParentId"))); entity.setimageStatus(ImageStatus.forValue(rs .getInt("imageStatus"))); entity.setlastModified(DbFacadeUtils.fromDate(rs .getTimestamp("lastModified"))); entity.setappList(rs.getString("app_list")); entity.setstorage_id(NGuid.createGuidFromString(rs .getString("storage_id"))); entity.setvm_snapshot_id(NGuid.createGuidFromString(rs .getString("vm_snapshot_id"))); entity.setvolume_type(VolumeType.forValue(rs .getInt("volume_type"))); entity.setvolume_format(VolumeFormat.forValue(rs .getInt("volume_format"))); entity.setdisk_type(DiskType.forValue(rs.getInt("disk_type"))); entity.setimage_group_id(Guid.createGuidFromString(rs .getString("image_group_id"))); entity.setdisk_interface(DiskInterface.forValue(rs .getInt("disk_interface"))); entity.setboot(rs.getBoolean("boot")); entity.setwipe_after_delete(rs.getBoolean("wipe_after_delete")); entity.setpropagate_errors(PropagateErrors.forValue(rs .getInt("propagate_errors"))); return entity; } }; return getCallsHandler().executeRead("GetAncestralImageByImageGuid", mapper, parameterSource); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/AWSXRayClientBuilder.java
2261
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.xray; import javax.annotation.Generated; import com.amazonaws.ClientConfigurationFactory; import com.amazonaws.annotation.NotThreadSafe; import com.amazonaws.client.builder.AwsSyncClientBuilder; import com.amazonaws.client.AwsSyncClientParams; /** * Fluent builder for {@link com.amazonaws.services.xray.AWSXRay}. Use of the builder is preferred over using * constructors of the client class. **/ @NotThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") public final class AWSXRayClientBuilder extends AwsSyncClientBuilder<AWSXRayClientBuilder, AWSXRay> { private static final ClientConfigurationFactory CLIENT_CONFIG_FACTORY = new ClientConfigurationFactory(); /** * @return Create new instance of builder with all defaults set. */ public static AWSXRayClientBuilder standard() { return new AWSXRayClientBuilder(); } /** * @return Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} and * {@link com.amazonaws.regions.DefaultAwsRegionProviderChain} chain */ public static AWSXRay defaultClient() { return standard().build(); } private AWSXRayClientBuilder() { super(CLIENT_CONFIG_FACTORY); } /** * Construct a synchronous implementation of AWSXRay using the current builder configuration. * * @param params * Current builder configuration represented as a parameter object. * @return Fully configured implementation of AWSXRay. */ @Override protected AWSXRay build(AwsSyncClientParams params) { return new AWSXRayClient(params); } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/RingbufferHeadSequenceCodec.java
4090
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.protocol.codec; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.Generated; import com.hazelcast.client.impl.protocol.codec.builtin.*; import com.hazelcast.client.impl.protocol.codec.custom.*; import javax.annotation.Nullable; import static com.hazelcast.client.impl.protocol.ClientMessage.*; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*; /* * This file is auto-generated by the Hazelcast Client Protocol Code Generator. * To change this file, edit the templates or the protocol * definitions on the https://github.com/hazelcast/hazelcast-client-protocol * and regenerate it. */ /** * Returns the sequence of the head. The head is the side of the ringbuffer where the oldest items in the ringbuffer * are found. If the RingBuffer is empty, the head will be one more than the tail. * The initial value of the head is 0 (1 more than tail). */ @Generated("c8236b60173dd504e6bf72cc5c047d71") public final class RingbufferHeadSequenceCodec { //hex: 0x170300 public static final int REQUEST_MESSAGE_TYPE = 1508096; //hex: 0x170301 public static final int RESPONSE_MESSAGE_TYPE = 1508097; private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES; private static final int RESPONSE_RESPONSE_FIELD_OFFSET = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES; private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_RESPONSE_FIELD_OFFSET + LONG_SIZE_IN_BYTES; private RingbufferHeadSequenceCodec() { } public static ClientMessage encodeRequest(java.lang.String name) { ClientMessage clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(true); clientMessage.setOperationName("Ringbuffer.HeadSequence"); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE); encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1); clientMessage.add(initialFrame); StringCodec.encode(clientMessage, name); return clientMessage; } /** * Name of the Ringbuffer */ public static java.lang.String decodeRequest(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); //empty initial frame iterator.next(); return StringCodec.decode(iterator); } public static ClientMessage encodeResponse(long response) { ClientMessage clientMessage = ClientMessage.createForEncode(); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE); encodeLong(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET, response); clientMessage.add(initialFrame); return clientMessage; } /** * the sequence of the head */ public static long decodeResponse(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); ClientMessage.Frame initialFrame = iterator.next(); return decodeLong(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET); } }
apache-2.0
android-art-intel/marshmallow
art-extension/opttests/src/OptimizationTests/ShortLeafMethodsInlining/InvokeDirect_rsub_int_001/Test.java
861
/* * Copyright (C) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package OptimizationTests.ShortLeafMethodsInlining.InvokeDirect_rsub_int_001; class Test { public int shim(int jj){ return simple_method(jj); } private int simple_method(int jj) { jj = 32767 - jj; return jj; } }
apache-2.0
srijeyanthan/hops
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestListCorruptFileBlocks.java
21357
/** * 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.hadoop.hdfs.server.namenode; import org.apache.commons.logging.Log; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.hdfs.BlockMissingException; import org.apache.hadoop.hdfs.CorruptFileBlockIterator; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.util.StringUtils; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Collection; import java.util.Random; import static org.junit.Assert.assertTrue; /** * This class tests the listCorruptFileBlocks API. * We create 3 files; intentionally delete their blocks * Use listCorruptFileBlocks to validate that we get the list of corrupt * files/blocks; also test the "paging" support by calling the API * with a block # from a previous call and validate that the subsequent * blocks/files are also returned. */ public class TestListCorruptFileBlocks { static Log LOG = NameNode.stateChangeLog; /** * check if nn.getCorruptFiles() returns a file that has corrupted blocks */ @Test(timeout = 300000) public void testListCorruptFilesCorruptedBlock() throws Exception { MiniDFSCluster cluster = null; Random random = new Random(); try { Configuration conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1); // datanode scans directories conf.setInt(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 3 * 1000); // datanode sends block reports cluster = new MiniDFSCluster.Builder(conf).build(); FileSystem fs = cluster.getFileSystem(); // create two files with one block each DFSTestUtil util = new DFSTestUtil.Builder(). setName("testCorruptFilesCorruptedBlock").setNumFiles(2). setMaxLevels(1).setMaxSize(512).build(); util.createFiles(fs, "/srcdat10"); // fetch bad file list from namenode. There should be none. final NameNode namenode = cluster.getNameNode(); Collection<FSNamesystem.CorruptFileBlockInfo> badFiles = namenode. getNamesystem().listCorruptFileBlocks("/", null); assertTrue( "Namenode has " + badFiles.size() + " corrupt files. Expecting None.", badFiles.size() == 0); // Now deliberately corrupt one block String bpid = cluster.getNamesystem().getBlockPoolId(); File storageDir = cluster.getInstanceStorageDir(0, 1); File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid); assertTrue("data directory does not exist", data_dir.exists()); File[] blocks = data_dir.listFiles(); assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0)); for (int idx = 0; idx < blocks.length; idx++) { if (blocks[idx].getName().startsWith("blk_") && blocks[idx].getName().endsWith(".meta")) { // // shorten .meta file // RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw"); FileChannel channel = file.getChannel(); long position = channel.size() - 2; int length = 2; byte[] buffer = new byte[length]; random.nextBytes(buffer); channel.write(ByteBuffer.wrap(buffer), position); file.close(); LOG.info("Deliberately corrupting file " + blocks[idx].getName() + " at offset " + position + " length " + length); // read all files to trigger detection of corrupted replica try { util.checkFiles(fs, "/srcdat10"); } catch (BlockMissingException e) { System.out.println("Received BlockMissingException as expected."); } catch (IOException e) { assertTrue( "Corrupted replicas not handled properly. Expecting BlockMissingException " + " but received IOException " + e, false); } break; } } // fetch bad file list from namenode. There should be one file. badFiles = namenode.getNamesystem().listCorruptFileBlocks("/", null); LOG.info("Namenode has bad files. " + badFiles.size()); assertTrue("Namenode has " + badFiles.size() + " bad files. Expecting 1.", badFiles.size() == 1); util.cleanup(fs, "/srcdat10"); } finally { if (cluster != null) { cluster.shutdown(); } } } /** * Check that listCorruptFileBlocks works while the namenode is still in * safemode. */ @Test(timeout = 300000) public void testListCorruptFileBlocksInSafeMode() throws Exception { MiniDFSCluster cluster = null; Random random = new Random(); try { Configuration conf = new HdfsConfiguration(); // datanode scans directories conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1); // datanode sends block reports conf.setInt(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 3 * 1000); // never leave safemode automatically conf.setFloat(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, 1.5f); // start populating repl queues immediately conf.setFloat(DFSConfigKeys.DFS_NAMENODE_REPL_QUEUE_THRESHOLD_PCT_KEY, 0f); cluster = new MiniDFSCluster.Builder(conf).waitSafeMode(false).build(); cluster.getNameNodeRpc() .setSafeMode(HdfsConstants.SafeModeAction.SAFEMODE_LEAVE, false); FileSystem fs = cluster.getFileSystem(); // create two files with one block each DFSTestUtil util = new DFSTestUtil.Builder(). setName("testListCorruptFileBlocksInSafeMode").setNumFiles(2). setMaxLevels(1).setMaxSize(512).build(); util.createFiles(fs, "/srcdat10"); // fetch bad file list from namenode. There should be none. Collection<FSNamesystem.CorruptFileBlockInfo> badFiles = cluster.getNameNode().getNamesystem() .listCorruptFileBlocks("/", null); assertTrue( "Namenode has " + badFiles.size() + " corrupt files. Expecting None.", badFiles.size() == 0); // Now deliberately corrupt one block File storageDir = cluster.getInstanceStorageDir(0, 0); File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, cluster.getNamesystem().getBlockPoolId()); assertTrue("data directory does not exist", data_dir.exists()); File[] blocks = data_dir.listFiles(); assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length > 0)); for (int idx = 0; idx < blocks.length; idx++) { if (blocks[idx].getName().startsWith("blk_") && blocks[idx].getName().endsWith(".meta")) { // // shorten .meta file // RandomAccessFile file = new RandomAccessFile(blocks[idx], "rw"); FileChannel channel = file.getChannel(); long position = channel.size() - 2; int length = 2; byte[] buffer = new byte[length]; random.nextBytes(buffer); channel.write(ByteBuffer.wrap(buffer), position); file.close(); LOG.info("Deliberately corrupting file " + blocks[idx].getName() + " at offset " + position + " length " + length); // read all files to trigger detection of corrupted replica try { util.checkFiles(fs, "/srcdat10"); } catch (BlockMissingException e) { System.out.println("Received BlockMissingException as expected."); } catch (IOException e) { assertTrue("Corrupted replicas not handled properly. " + "Expecting BlockMissingException " + " but received IOException " + e, false); } break; } } // fetch bad file list from namenode. There should be one file. badFiles = cluster.getNameNode().getNamesystem(). listCorruptFileBlocks("/", null); LOG.info("Namenode has bad files. " + badFiles.size()); assertTrue("Namenode has " + badFiles.size() + " bad files. Expecting 1.", badFiles.size() == 1); // restart namenode cluster.restartNameNode(0); fs = cluster.getFileSystem(); // wait until replication queues have been initialized while (!cluster.getNameNode().namesystem.isPopulatingReplQueues()) { try { LOG.info("waiting for replication queues"); Thread.sleep(1000); } catch (InterruptedException ignore) { } } // read all files to trigger detection of corrupted replica try { util.checkFiles(fs, "/srcdat10"); } catch (BlockMissingException e) { System.out.println("Received BlockMissingException as expected."); } catch (IOException e) { assertTrue("Corrupted replicas not handled properly. " + "Expecting BlockMissingException " + " but received IOException " + e, false); } // fetch bad file list from namenode. There should be one file. badFiles = cluster.getNameNode().getNamesystem(). listCorruptFileBlocks("/", null); LOG.info("Namenode has bad files. " + badFiles.size()); assertTrue("Namenode has " + badFiles.size() + " bad files. Expecting 1.", badFiles.size() == 1); // check that we are still in safe mode assertTrue("Namenode is not in safe mode", cluster.getNameNode().isInSafeMode()); // now leave safe mode so that we can clean up cluster.getNameNodeRpc() .setSafeMode(HdfsConstants.SafeModeAction.SAFEMODE_LEAVE, false); util.cleanup(fs, "/srcdat10"); } catch (Exception e) { LOG.error(StringUtils.stringifyException(e)); throw e; } finally { if (cluster != null) { cluster.shutdown(); } } } // deliberately remove blocks from a file and validate the list-corrupt-file-blocks API @Test(timeout = 300000) public void testlistCorruptFileBlocks() throws Exception { Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000); conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1); // datanode scans // directories FileSystem fs = null; MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitActive(); fs = cluster.getFileSystem(); DFSTestUtil util = new DFSTestUtil.Builder(). setName("testGetCorruptFiles").setNumFiles(3).setMaxLevels(1). setMaxSize(1024).build(); util.createFiles(fs, "/corruptData"); final NameNode namenode = cluster.getNameNode(); Collection<FSNamesystem.CorruptFileBlockInfo> corruptFileBlocks = namenode.getNamesystem().listCorruptFileBlocks("/corruptData", null); int numCorrupt = corruptFileBlocks.size(); assertTrue(numCorrupt == 0); // delete the blocks String bpid = cluster.getNamesystem().getBlockPoolId(); for (int i = 0; i < 4; i++) { for (int j = 0; j <= 1; j++) { File storageDir = cluster.getInstanceStorageDir(i, j); File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid); File[] blocks = data_dir.listFiles(); if (blocks == null) { continue; } for (int idx = 0; idx < blocks.length; idx++) { if (!blocks[idx].getName().startsWith("blk_")) { continue; } LOG.info("Deliberately removing file " + blocks[idx].getName()); assertTrue("Cannot remove file.", blocks[idx].delete()); } } } int count = 0; corruptFileBlocks = namenode.getNamesystem(). listCorruptFileBlocks("/corruptData", null); numCorrupt = corruptFileBlocks.size(); while (numCorrupt < 3) { Thread.sleep(1000); corruptFileBlocks = namenode.getNamesystem() .listCorruptFileBlocks("/corruptData", null); numCorrupt = corruptFileBlocks.size(); count++; if (count > 30) { break; } } // Validate we get all the corrupt files LOG.info("Namenode has bad files. " + numCorrupt); assertTrue(numCorrupt == 3); // test the paging here FSNamesystem.CorruptFileBlockInfo[] cfb = corruptFileBlocks.toArray(new FSNamesystem.CorruptFileBlockInfo[0]); // now get the 2nd and 3rd file that is corrupt String[] cookie = new String[]{"1"}; Collection<FSNamesystem.CorruptFileBlockInfo> nextCorruptFileBlocks = namenode.getNamesystem() .listCorruptFileBlocks("/corruptData", cookie); FSNamesystem.CorruptFileBlockInfo[] ncfb = nextCorruptFileBlocks .toArray(new FSNamesystem.CorruptFileBlockInfo[0]); numCorrupt = nextCorruptFileBlocks.size(); assertTrue(numCorrupt == 2); assertTrue(ncfb[0].block.getBlockName() .equalsIgnoreCase(cfb[1].block.getBlockName())); corruptFileBlocks = namenode.getNamesystem() .listCorruptFileBlocks("/corruptData", cookie); numCorrupt = corruptFileBlocks.size(); assertTrue(numCorrupt == 0); // Do a listing on a dir which doesn't have any corrupt blocks and // validate util.createFiles(fs, "/goodData"); corruptFileBlocks = namenode.getNamesystem().listCorruptFileBlocks("/goodData", null); numCorrupt = corruptFileBlocks.size(); assertTrue(numCorrupt == 0); util.cleanup(fs, "/corruptData"); util.cleanup(fs, "/goodData"); } finally { if (cluster != null) { cluster.shutdown(); } } } private int countPaths(RemoteIterator<Path> iter) throws IOException { int i = 0; while (iter.hasNext()) { LOG.info("PATH: " + iter.next().toUri().getPath()); i++; } return i; } /** * test listCorruptFileBlocks in DistributedFileSystem */ @Test(timeout = 300000) public void testlistCorruptFileBlocksDFS() throws Exception { Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000); conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1); // datanode scans // directories FileSystem fs = null; MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitActive(); fs = cluster.getFileSystem(); DistributedFileSystem dfs = (DistributedFileSystem) fs; DFSTestUtil util = new DFSTestUtil.Builder(). setName("testGetCorruptFiles").setNumFiles(3). setMaxLevels(1).setMaxSize(1024).build(); util.createFiles(fs, "/corruptData"); RemoteIterator<Path> corruptFileBlocks = dfs.listCorruptFileBlocks(new Path("/corruptData")); int numCorrupt = countPaths(corruptFileBlocks); assertTrue(numCorrupt == 0); // delete the blocks String bpid = cluster.getNamesystem().getBlockPoolId(); // For loop through number of datadirectories per datanode (2) for (int i = 0; i < 2; i++) { File storageDir = cluster.getInstanceStorageDir(0, i); File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid); File[] blocks = data_dir.listFiles(); if (blocks == null) { continue; } for (int idx = 0; idx < blocks.length; idx++) { if (!blocks[idx].getName().startsWith("blk_")) { continue; } LOG.info("Deliberately removing file " + blocks[idx].getName()); assertTrue("Cannot remove file.", blocks[idx].delete()); } } int count = 0; corruptFileBlocks = dfs.listCorruptFileBlocks(new Path("/corruptData")); numCorrupt = countPaths(corruptFileBlocks); while (numCorrupt < 3) { Thread.sleep(1000); corruptFileBlocks = dfs.listCorruptFileBlocks(new Path("/corruptData")); numCorrupt = countPaths(corruptFileBlocks); count++; if (count > 30) { break; } } // Validate we get all the corrupt files LOG.info("Namenode has bad files. " + numCorrupt); assertTrue(numCorrupt == 3); util.cleanup(fs, "/corruptData"); util.cleanup(fs, "/goodData"); } finally { if (cluster != null) { cluster.shutdown(); } } } /** * Test if NN.listCorruptFiles() returns the right number of results. * Also, test that DFS.listCorruptFileBlocks can make multiple successive * calls. */ @Test(timeout = 300000) public void testMaxCorruptFiles() throws Exception { MiniDFSCluster cluster = null; try { Configuration conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 15); // datanode scans directories conf.setInt(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 3 * 1000); // datanode sends block reports cluster = new MiniDFSCluster.Builder(conf).build(); FileSystem fs = cluster.getFileSystem(); final int maxCorruptFileBlocks = FSNamesystem.DEFAULT_MAX_CORRUPT_FILEBLOCKS_RETURNED; // create 110 files with one block each DFSTestUtil util = new DFSTestUtil.Builder().setName("testMaxCorruptFiles"). setNumFiles(maxCorruptFileBlocks * 3).setMaxLevels(1) .setMaxSize(512). build(); util.createFiles(fs, "/srcdat2", (short) 1); util.waitReplication(fs, "/srcdat2", (short) 1); // verify that there are no bad blocks. final NameNode namenode = cluster.getNameNode(); Collection<FSNamesystem.CorruptFileBlockInfo> badFiles = namenode. getNamesystem().listCorruptFileBlocks("/srcdat2", null); assertTrue( "Namenode has " + badFiles.size() + " corrupt files. Expecting none.", badFiles.size() == 0); // Now deliberately blocks from all files final String bpid = cluster.getNamesystem().getBlockPoolId(); for (int i = 0; i < 4; i++) { for (int j = 0; j <= 1; j++) { File storageDir = cluster.getInstanceStorageDir(i, j); File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid); LOG.info("Removing files from " + data_dir); File[] blocks = data_dir.listFiles(); if (blocks == null) { continue; } for (int idx = 0; idx < blocks.length; idx++) { if (!blocks[idx].getName().startsWith("blk_")) { continue; } assertTrue("Cannot remove file.", blocks[idx].delete()); } } } badFiles = namenode.getNamesystem().listCorruptFileBlocks("/srcdat2", null); while (badFiles.size() < maxCorruptFileBlocks) { LOG.info("# of corrupt files is: " + badFiles.size()); Thread.sleep(10000); badFiles = namenode.getNamesystem(). listCorruptFileBlocks("/srcdat2", null); } badFiles = namenode.getNamesystem(). listCorruptFileBlocks("/srcdat2", null); LOG.info("Namenode has bad files. " + badFiles.size()); assertTrue("Namenode has " + badFiles.size() + " bad files. Expecting " + maxCorruptFileBlocks + ".", badFiles.size() == maxCorruptFileBlocks); CorruptFileBlockIterator iter = (CorruptFileBlockIterator) fs .listCorruptFileBlocks(new Path("/srcdat2")); int corruptPaths = countPaths(iter); assertTrue("Expected more than " + maxCorruptFileBlocks + " corrupt file blocks but got " + corruptPaths, corruptPaths > maxCorruptFileBlocks); assertTrue("Iterator should have made more than 1 call but made " + iter.getCallsMade(), iter.getCallsMade() > 1); util.cleanup(fs, "/srcdat2"); } finally { if (cluster != null) { cluster.shutdown(); } } } }
apache-2.0
welterde/ewok
com/planet_ink/coffee_mud/Items/Weapons/Quarterstaff.java
2118
package com.planet_ink.coffee_mud.Items.Weapons; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ public class Quarterstaff extends StdWeapon { public String ID(){ return "Quarterstaff";} public Quarterstaff() { super(); setName("a wooden quarterstaff"); setDisplayText("a wooden quarterstaff lies in the corner of the room."); setDescription("It`s long and wooden, just like a quarterstaff ought to be."); baseEnvStats().setAbility(0); baseEnvStats().setLevel(0); baseEnvStats.setWeight(4); baseEnvStats().setAttackAdjustment(0); baseEnvStats().setDamage(3); baseGoldValue=1; recoverEnvStats(); wornLogicalAnd=true; material=RawMaterial.RESOURCE_OAK; properWornBitmap=Wearable.WORN_HELD|Wearable.WORN_WIELD; weaponType=TYPE_BASHING; weaponClassification=Weapon.CLASS_STAFF; } }
apache-2.0
grgrzybek/karaf
itests/test/src/test/java/org/apache/karaf/itests/examples/WebSocketExampleTest.java
4334
/* * 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.karaf.itests.examples; import org.apache.karaf.itests.KarafTestSupport; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.StatusCode; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.junit.Test; import org.junit.runner.RunWith; 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.osgi.framework.Bundle; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class WebSocketExampleTest extends KarafTestSupport { @Test(timeout = 60000) public void test() throws Exception { featureService.installFeature("scr"); featureService.installFeature("http"); featureService.installFeature("jetty"); Bundle bundle = bundleContext.installBundle("mvn:org.apache.karaf.examples/karaf-websocket-example/" + System.getProperty("karaf.version")); bundle.start(); String httpList = executeCommand("http:list"); while (!httpList.contains("Deployed")) { Thread.sleep(1000); httpList = executeCommand("http:list"); } System.out.println(httpList); WebSocketClient client = new WebSocketClient(); SimpleSocket socket = new SimpleSocket(); client.start(); URI uri = new URI("ws://localhost:" + getHttpPort() + "/example-websocket"); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect(socket, uri, request); socket.awaitClose(10, TimeUnit.SECONDS); assertTrue(socket.messages.size() > 0); assertEquals("Hello World", socket.messages.get(0)); client.stop(); } @WebSocket public class SimpleSocket { private final CountDownLatch closeLatch; private Session session; public final List<String> messages; public SimpleSocket() { this.messages = new ArrayList<>(); this.closeLatch = new CountDownLatch(1); } public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException { return this.closeLatch.await(duration, unit); } @OnWebSocketClose public void onClose(int statusCode, String reason) { System.out.println("Closing websocket client"); session.close(StatusCode.NORMAL, "I'm done"); this.session = null; this.closeLatch.countDown(); // trigger latch } @OnWebSocketConnect public void onConnect(Session session) { System.out.println("Connecting websocket client"); this.session = session; } @OnWebSocketMessage public void onMessage(String msg) { System.out.println("Received websocket message: " + msg); messages.add(msg); } } }
apache-2.0
wseemann/ServeStream
app/src/main/java/net/sourceforge/servestream/activity/SetAlarmActivity.java
2000
/* * ServeStream: A HTTP stream browser/player for Android * Copyright 2014 William Seemann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.servestream.activity; import net.sourceforge.servestream.fragment.SetAlarmFragment; import net.sourceforge.servestream.preference.UserPreferences; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.view.MenuItem; public class SetAlarmActivity extends ActionBarActivity { @Override public void onCreate(Bundle savedInstanceState) { setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); if (savedInstanceState == null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.add(android.R.id.content, new SetAlarmFragment()); transaction.commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { SetAlarmFragment fragment = (SetAlarmFragment) getSupportFragmentManager().findFragmentById(android.R.id.content); fragment.onBackPressed(); } }
apache-2.0
g977284333/KwZxing
src/com/kw_support/zxing/camera/PreviewCallback.java
1222
package com.kw_support.zxing.camera; import android.graphics.Point; import android.hardware.Camera; import android.os.Handler; import android.os.Message; import android.util.Log; final class PreviewCallback implements Camera.PreviewCallback { private static final String TAG = PreviewCallback.class.getSimpleName(); private final CameraConfigurationManager mConfigManager; private Handler mPreviewHandler; private int mPreviewMessage; PreviewCallback(CameraConfigurationManager configManager) { this.mConfigManager = configManager; } public void setHandler(Handler previewHandler, int previewMessage) { this.mPreviewHandler = previewHandler; this.mPreviewMessage = previewMessage; } @Override public void onPreviewFrame(byte[] data, Camera camera) { Point cameraResolution = mConfigManager.getCameraResolution(); Handler thePreviewHandler = mPreviewHandler; if (cameraResolution != null && thePreviewHandler != null) { Message message = thePreviewHandler.obtainMessage(mPreviewMessage, cameraResolution.x, cameraResolution.y, data); message.sendToTarget(); mPreviewHandler = null; } else { Log.d(TAG, "Got preview callback, but no handler or resolution available"); } } }
apache-2.0
eposse/osate2-agcl
org.osate.xtext.aadl2.agcl.analysis/src/org/osate/xtext/aadl2/agcl/analysis/verifiers/VerifiersPackage.java
110972
/** * Copyright (c) 2014 Ernesto Posse * * 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. * * @author Ernesto Posse * @version 0.1 */ package org.osate.xtext.aadl2.agcl.analysis.verifiers; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; /** * <!-- begin-user-doc --> * The <b>Package</b> for the model. * It contains accessors for the meta objects to represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each operation of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerifiersFactory * @model kind="package" * @generated */ public interface VerifiersPackage extends EPackage { /** * The package name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNAME = "verifiers"; /** * The package namespace URI. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_URI = "http://verifiers/1.0"; /** * The package namespace name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_PREFIX = "org.osate.xtext.aadl2.agcl.analysis.verifiers"; /** * The singleton instance of the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ VerifiersPackage eINSTANCE = org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl.init(); /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult <em>Verification Result</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getVerificationResult() * @generated */ int VERIFICATION_RESULT = 0; /** * The number of structural features of the '<em>Verification Result</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_RESULT_FEATURE_COUNT = 0; /** * The number of operations of the '<em>Verification Result</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_RESULT_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.PositiveImpl <em>Positive</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.PositiveImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getPositive() * @generated */ int POSITIVE = 1; /** * The number of structural features of the '<em>Positive</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int POSITIVE_FEATURE_COUNT = VERIFICATION_RESULT_FEATURE_COUNT + 0; /** * The number of operations of the '<em>Positive</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int POSITIVE_OPERATION_COUNT = VERIFICATION_RESULT_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NegativeImpl <em>Negative</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NegativeImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNegative() * @generated */ int NEGATIVE = 2; /** * The feature id for the '<em><b>Counterexample</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NEGATIVE__COUNTEREXAMPLE = VERIFICATION_RESULT_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Negative</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NEGATIVE_FEATURE_COUNT = VERIFICATION_RESULT_FEATURE_COUNT + 1; /** * The number of operations of the '<em>Negative</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NEGATIVE_OPERATION_COUNT = VERIFICATION_RESULT_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Model <em>Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Model * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModel() * @generated */ int MODEL = 3; /** * The feature id for the '<em><b>Model</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL__MODEL = 0; /** * The feature id for the '<em><b>Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL__CONTEXT = 1; /** * The number of structural features of the '<em>Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_FEATURE_COUNT = 2; /** * The operation id for the '<em>Text</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL___TEXT__OBJECT = 0; /** * The number of operations of the '<em>Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_OPERATION_COUNT = 1; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification <em>Specification</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getSpecification() * @generated */ int SPECIFICATION = 4; /** * The feature id for the '<em><b>Spec</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION__SPEC = 0; /** * The feature id for the '<em><b>Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION__CONTEXT = 1; /** * The number of structural features of the '<em>Specification</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION_FEATURE_COUNT = 2; /** * The operation id for the '<em>Text</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION___TEXT__OBJECT = 0; /** * The number of operations of the '<em>Specification</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION_OPERATION_COUNT = 1; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.CounterExampleImpl <em>Counter Example</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.CounterExampleImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getCounterExample() * @generated */ int COUNTER_EXAMPLE = 5; /** * The number of structural features of the '<em>Counter Example</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COUNTER_EXAMPLE_FEATURE_COUNT = 0; /** * The number of operations of the '<em>Counter Example</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COUNTER_EXAMPLE_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.UniversalModel <em>Universal Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.UniversalModel * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getUniversalModel() * @generated */ int UNIVERSAL_MODEL = 6; /** * The feature id for the '<em><b>Model</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNIVERSAL_MODEL__MODEL = MODEL__MODEL; /** * The feature id for the '<em><b>Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNIVERSAL_MODEL__CONTEXT = MODEL__CONTEXT; /** * The number of structural features of the '<em>Universal Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNIVERSAL_MODEL_FEATURE_COUNT = MODEL_FEATURE_COUNT + 0; /** * The operation id for the '<em>Text</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNIVERSAL_MODEL___TEXT__OBJECT = MODEL___TEXT__OBJECT; /** * The number of operations of the '<em>Universal Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNIVERSAL_MODEL_OPERATION_COUNT = MODEL_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerImpl <em>Model Checker</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModelChecker() * @generated */ int MODEL_CHECKER = 7; /** * The feature id for the '<em><b>Resource Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER__RESOURCE_CONTEXT = 0; /** * The feature id for the '<em><b>Results</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER__RESULTS = 1; /** * The feature id for the '<em><b>Verification Units</b></em>' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER__VERIFICATION_UNITS = 2; /** * The feature id for the '<em><b>Viewpoint Collection</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER__VIEWPOINT_COLLECTION = 3; /** * The feature id for the '<em><b>Component Collection</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER__COMPONENT_COLLECTION = 4; /** * The number of structural features of the '<em>Model Checker</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_FEATURE_COUNT = 5; /** * The operation id for the '<em>Set Up</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___SET_UP__RESOURCE = 0; /** * The operation id for the '<em>Make Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___MAKE_VERIFICATION_UNIT__MODEL_SPECIFICATION_VIEWPOINT_COMPONENT = 1; /** * The operation id for the '<em>Make Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___MAKE_VERIFICATION_UNIT__SPECIFICATION_VIEWPOINT_COMPONENT = 2; /** * The operation id for the '<em>Check Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___CHECK_VERIFICATION_UNIT__VERIFICATIONUNIT = 3; /** * The operation id for the '<em>Prepare Input</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___PREPARE_INPUT__VERIFICATIONUNIT = 4; /** * The operation id for the '<em>Call External</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___CALL_EXTERNAL__MODELCHECKERINPUT = 5; /** * The operation id for the '<em>Process Output</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___PROCESS_OUTPUT__MODELCHECKEROUTPUT = 6; /** * The operation id for the '<em>Add Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___ADD_VERIFICATION_UNIT__VERIFICATIONUNIT = 7; /** * The operation id for the '<em>Remove Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___REMOVE_VERIFICATION_UNIT__STRING = 8; /** * The operation id for the '<em>Get Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___GET_VERIFICATION_UNIT__STRING = 9; /** * The operation id for the '<em>Check All</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER___CHECK_ALL = 10; /** * The number of operations of the '<em>Model Checker</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_OPERATION_COUNT = 11; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelCheckerImpl <em>Nu SMV Model Checker</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelCheckerImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVModelChecker() * @generated */ int NU_SMV_MODEL_CHECKER = 8; /** * The feature id for the '<em><b>Resource Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER__RESOURCE_CONTEXT = MODEL_CHECKER__RESOURCE_CONTEXT; /** * The feature id for the '<em><b>Results</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER__RESULTS = MODEL_CHECKER__RESULTS; /** * The feature id for the '<em><b>Verification Units</b></em>' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER__VERIFICATION_UNITS = MODEL_CHECKER__VERIFICATION_UNITS; /** * The feature id for the '<em><b>Viewpoint Collection</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER__VIEWPOINT_COLLECTION = MODEL_CHECKER__VIEWPOINT_COLLECTION; /** * The feature id for the '<em><b>Component Collection</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER__COMPONENT_COLLECTION = MODEL_CHECKER__COMPONENT_COLLECTION; /** * The number of structural features of the '<em>Nu SMV Model Checker</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER_FEATURE_COUNT = MODEL_CHECKER_FEATURE_COUNT + 0; /** * The operation id for the '<em>Set Up</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___SET_UP__RESOURCE = MODEL_CHECKER___SET_UP__RESOURCE; /** * The operation id for the '<em>Make Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___MAKE_VERIFICATION_UNIT__MODEL_SPECIFICATION_VIEWPOINT_COMPONENT = MODEL_CHECKER___MAKE_VERIFICATION_UNIT__MODEL_SPECIFICATION_VIEWPOINT_COMPONENT; /** * The operation id for the '<em>Make Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___MAKE_VERIFICATION_UNIT__SPECIFICATION_VIEWPOINT_COMPONENT = MODEL_CHECKER___MAKE_VERIFICATION_UNIT__SPECIFICATION_VIEWPOINT_COMPONENT; /** * The operation id for the '<em>Check Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___CHECK_VERIFICATION_UNIT__VERIFICATIONUNIT = MODEL_CHECKER___CHECK_VERIFICATION_UNIT__VERIFICATIONUNIT; /** * The operation id for the '<em>Prepare Input</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___PREPARE_INPUT__VERIFICATIONUNIT = MODEL_CHECKER___PREPARE_INPUT__VERIFICATIONUNIT; /** * The operation id for the '<em>Call External</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___CALL_EXTERNAL__MODELCHECKERINPUT = MODEL_CHECKER___CALL_EXTERNAL__MODELCHECKERINPUT; /** * The operation id for the '<em>Process Output</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___PROCESS_OUTPUT__MODELCHECKEROUTPUT = MODEL_CHECKER___PROCESS_OUTPUT__MODELCHECKEROUTPUT; /** * The operation id for the '<em>Add Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___ADD_VERIFICATION_UNIT__VERIFICATIONUNIT = MODEL_CHECKER___ADD_VERIFICATION_UNIT__VERIFICATIONUNIT; /** * The operation id for the '<em>Remove Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___REMOVE_VERIFICATION_UNIT__STRING = MODEL_CHECKER___REMOVE_VERIFICATION_UNIT__STRING; /** * The operation id for the '<em>Get Verification Unit</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___GET_VERIFICATION_UNIT__STRING = MODEL_CHECKER___GET_VERIFICATION_UNIT__STRING; /** * The operation id for the '<em>Check All</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER___CHECK_ALL = MODEL_CHECKER___CHECK_ALL; /** * The number of operations of the '<em>Nu SMV Model Checker</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_CHECKER_OPERATION_COUNT = MODEL_CHECKER_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerInputImpl <em>Model Checker Input</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerInputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModelCheckerInput() * @generated */ int MODEL_CHECKER_INPUT = 9; /** * The feature id for the '<em><b>Specification</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_INPUT__SPECIFICATION = 0; /** * The feature id for the '<em><b>Output</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_INPUT__OUTPUT = 1; /** * The feature id for the '<em><b>Verification Unit</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_INPUT__VERIFICATION_UNIT = 2; /** * The number of structural features of the '<em>Model Checker Input</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_INPUT_FEATURE_COUNT = 3; /** * The number of operations of the '<em>Model Checker Input</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_INPUT_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerOutputImpl <em>Model Checker Output</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerOutputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModelCheckerOutput() * @generated */ int MODEL_CHECKER_OUTPUT = 10; /** * The feature id for the '<em><b>Result</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_OUTPUT__RESULT = 0; /** * The feature id for the '<em><b>Input</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_OUTPUT__INPUT = 1; /** * The number of structural features of the '<em>Model Checker Output</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_OUTPUT_FEATURE_COUNT = 2; /** * The number of operations of the '<em>Model Checker Output</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_CHECKER_OUTPUT_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVInputImpl <em>Nu SMV Input</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVInputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVInput() * @generated */ int NU_SMV_INPUT = 11; /** * The feature id for the '<em><b>Specification</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT__SPECIFICATION = MODEL_CHECKER_INPUT__SPECIFICATION; /** * The feature id for the '<em><b>Output</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT__OUTPUT = MODEL_CHECKER_INPUT__OUTPUT; /** * The feature id for the '<em><b>Verification Unit</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT__VERIFICATION_UNIT = MODEL_CHECKER_INPUT__VERIFICATION_UNIT; /** * The feature id for the '<em><b>Model File Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT__MODEL_FILE_NAME = MODEL_CHECKER_INPUT_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Session Script File Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT__SESSION_SCRIPT_FILE_NAME = MODEL_CHECKER_INPUT_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Nu SMV Input</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT_FEATURE_COUNT = MODEL_CHECKER_INPUT_FEATURE_COUNT + 2; /** * The number of operations of the '<em>Nu SMV Input</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_INPUT_OPERATION_COUNT = MODEL_CHECKER_INPUT_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVOutputImpl <em>Nu SMV Output</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVOutputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVOutput() * @generated */ int NU_SMV_OUTPUT = 12; /** * The feature id for the '<em><b>Result</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_OUTPUT__RESULT = MODEL_CHECKER_OUTPUT__RESULT; /** * The feature id for the '<em><b>Input</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_OUTPUT__INPUT = MODEL_CHECKER_OUTPUT__INPUT; /** * The feature id for the '<em><b>Output File Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_OUTPUT__OUTPUT_FILE_NAME = MODEL_CHECKER_OUTPUT_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Counter Example File Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_OUTPUT__COUNTER_EXAMPLE_FILE_NAME = MODEL_CHECKER_OUTPUT_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Nu SMV Output</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_OUTPUT_FEATURE_COUNT = MODEL_CHECKER_OUTPUT_FEATURE_COUNT + 2; /** * The number of operations of the '<em>Nu SMV Output</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_OUTPUT_OPERATION_COUNT = MODEL_CHECKER_OUTPUT_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelImpl <em>Nu SMV Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVModel() * @generated */ int NU_SMV_MODEL = 13; /** * The feature id for the '<em><b>Model</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL__MODEL = MODEL__MODEL; /** * The feature id for the '<em><b>Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL__CONTEXT = MODEL__CONTEXT; /** * The feature id for the '<em><b>Vars</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL__VARS = MODEL_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Init</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL__INIT = MODEL_FEATURE_COUNT + 1; /** * The feature id for the '<em><b>Trans</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL__TRANS = MODEL_FEATURE_COUNT + 2; /** * The number of structural features of the '<em>Nu SMV Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_FEATURE_COUNT = MODEL_FEATURE_COUNT + 3; /** * The operation id for the '<em>Text</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL___TEXT__OBJECT = MODEL___TEXT__OBJECT; /** * The number of operations of the '<em>Nu SMV Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_MODEL_OPERATION_COUNT = MODEL_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVUniversalModelImpl <em>Nu SMV Universal Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVUniversalModelImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVUniversalModel() * @generated */ int NU_SMV_UNIVERSAL_MODEL = 14; /** * The feature id for the '<em><b>Model</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL__MODEL = NU_SMV_MODEL__MODEL; /** * The feature id for the '<em><b>Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL__CONTEXT = NU_SMV_MODEL__CONTEXT; /** * The feature id for the '<em><b>Vars</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL__VARS = NU_SMV_MODEL__VARS; /** * The feature id for the '<em><b>Init</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL__INIT = NU_SMV_MODEL__INIT; /** * The feature id for the '<em><b>Trans</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL__TRANS = NU_SMV_MODEL__TRANS; /** * The number of structural features of the '<em>Nu SMV Universal Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL_FEATURE_COUNT = NU_SMV_MODEL_FEATURE_COUNT + 0; /** * The operation id for the '<em>Text</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL___TEXT__OBJECT = NU_SMV_MODEL___TEXT__OBJECT; /** * The number of operations of the '<em>Nu SMV Universal Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_UNIVERSAL_MODEL_OPERATION_COUNT = NU_SMV_MODEL_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVSpecificationImpl <em>Nu SMV Specification</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVSpecificationImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVSpecification() * @generated */ int NU_SMV_SPECIFICATION = 15; /** * The feature id for the '<em><b>Spec</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_SPECIFICATION__SPEC = SPECIFICATION__SPEC; /** * The feature id for the '<em><b>Context</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_SPECIFICATION__CONTEXT = SPECIFICATION__CONTEXT; /** * The feature id for the '<em><b>Logic</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_SPECIFICATION__LOGIC = SPECIFICATION_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Nu SMV Specification</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_SPECIFICATION_FEATURE_COUNT = SPECIFICATION_FEATURE_COUNT + 1; /** * The operation id for the '<em>Text</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_SPECIFICATION___TEXT__OBJECT = SPECIFICATION___TEXT__OBJECT; /** * The number of operations of the '<em>Nu SMV Specification</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int NU_SMV_SPECIFICATION_OPERATION_COUNT = SPECIFICATION_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.UnknownImpl <em>Unknown</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.UnknownImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getUnknown() * @generated */ int UNKNOWN = 16; /** * The feature id for the '<em><b>Reason</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNKNOWN__REASON = VERIFICATION_RESULT_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Unknown</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNKNOWN_FEATURE_COUNT = VERIFICATION_RESULT_FEATURE_COUNT + 1; /** * The number of operations of the '<em>Unknown</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int UNKNOWN_OPERATION_COUNT = VERIFICATION_RESULT_OPERATION_COUNT + 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultsCollectionImpl <em>Results Collection</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultsCollectionImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getResultsCollection() * @generated */ int RESULTS_COLLECTION = 17; /** * The feature id for the '<em><b>Entries</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULTS_COLLECTION__ENTRIES = 0; /** * The number of structural features of the '<em>Results Collection</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULTS_COLLECTION_FEATURE_COUNT = 1; /** * The operation id for the '<em>Record Result</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULTS_COLLECTION___RECORD_RESULT__VERIFICATIONUNIT_VERIFICATIONRESULT = 0; /** * The number of operations of the '<em>Results Collection</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULTS_COLLECTION_OPERATION_COUNT = 1; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentImpl <em>Component</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getComponent() * @generated */ int COMPONENT = 18; /** * The feature id for the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT__NAME = 0; /** * The feature id for the '<em><b>Object</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT__OBJECT = 1; /** * The number of structural features of the '<em>Component</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_FEATURE_COUNT = 2; /** * The number of operations of the '<em>Component</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointImpl <em>Viewpoint</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getViewpoint() * @generated */ int VIEWPOINT = 19; /** * The feature id for the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT__NAME = 0; /** * The feature id for the '<em><b>Object</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT__OBJECT = 1; /** * The number of structural features of the '<em>Viewpoint</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_FEATURE_COUNT = 2; /** * The number of operations of the '<em>Viewpoint</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerificationUnitImpl <em>Verification Unit</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerificationUnitImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getVerificationUnit() * @generated */ int VERIFICATION_UNIT = 20; /** * The feature id for the '<em><b>Model</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT__MODEL = 0; /** * The feature id for the '<em><b>Specification</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT__SPECIFICATION = 1; /** * The feature id for the '<em><b>Viewpoint</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT__VIEWPOINT = 2; /** * The feature id for the '<em><b>Component</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT__COMPONENT = 3; /** * The feature id for the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT__NAME = 4; /** * The number of structural features of the '<em>Verification Unit</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT_FEATURE_COUNT = 5; /** * The number of operations of the '<em>Verification Unit</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VERIFICATION_UNIT_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultEntryImpl <em>Result Entry</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultEntryImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getResultEntry() * @generated */ int RESULT_ENTRY = 21; /** * The feature id for the '<em><b>Verification Unit</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULT_ENTRY__VERIFICATION_UNIT = 0; /** * The feature id for the '<em><b>Result</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULT_ENTRY__RESULT = 1; /** * The number of structural features of the '<em>Result Entry</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULT_ENTRY_FEATURE_COUNT = 2; /** * The number of operations of the '<em>Result Entry</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int RESULT_ENTRY_OPERATION_COUNT = 0; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointCollectionImpl <em>Viewpoint Collection</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointCollectionImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getViewpointCollection() * @generated */ int VIEWPOINT_COLLECTION = 22; /** * The feature id for the '<em><b>Viewpoints</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION__VIEWPOINTS = 0; /** * The number of structural features of the '<em>Viewpoint Collection</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION_FEATURE_COUNT = 1; /** * The operation id for the '<em>Get Viewpoint</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION___GET_VIEWPOINT__STRING = 0; /** * The operation id for the '<em>Add Viewpoint</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION___ADD_VIEWPOINT__STRING_OBJECT = 1; /** * The operation id for the '<em>Remove Viewpoint</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION___REMOVE_VIEWPOINT__STRING = 2; /** * The operation id for the '<em>Contains Viewpoint</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION___CONTAINS_VIEWPOINT__STRING = 3; /** * The number of operations of the '<em>Viewpoint Collection</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int VIEWPOINT_COLLECTION_OPERATION_COUNT = 4; /** * The meta object id for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentCollectionImpl <em>Component Collection</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentCollectionImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getComponentCollection() * @generated */ int COMPONENT_COLLECTION = 23; /** * The feature id for the '<em><b>Components</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION__COMPONENTS = 0; /** * The number of structural features of the '<em>Component Collection</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION_FEATURE_COUNT = 1; /** * The operation id for the '<em>Get Component</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION___GET_COMPONENT__STRING = 0; /** * The operation id for the '<em>Add Component</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION___ADD_COMPONENT__STRING_OBJECT = 1; /** * The operation id for the '<em>Remove Component</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION___REMOVE_COMPONENT__STRING = 2; /** * The operation id for the '<em>Contains Component</em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION___CONTAINS_COMPONENT__STRING = 3; /** * The number of operations of the '<em>Component Collection</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMPONENT_COLLECTION_OPERATION_COUNT = 4; /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult <em>Verification Result</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Verification Result</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult * @generated */ EClass getVerificationResult(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Positive <em>Positive</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Positive</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Positive * @generated */ EClass getPositive(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Negative <em>Negative</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Negative</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Negative * @generated */ EClass getNegative(); /** * Returns the meta object for the containment reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Negative#getCounterexample <em>Counterexample</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Counterexample</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Negative#getCounterexample() * @see #getNegative() * @generated */ EReference getNegative_Counterexample(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Model <em>Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Model</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Model * @generated */ EClass getModel(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Model#getModel <em>Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Model</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Model#getModel() * @see #getModel() * @generated */ EAttribute getModel_Model(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Model#getContext <em>Context</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Context</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Model#getContext() * @see #getModel() * @generated */ EAttribute getModel_Context(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Model#text(java.lang.Object) <em>Text</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Text</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Model#text(java.lang.Object) * @generated */ EOperation getModel__Text__Object(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification <em>Specification</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Specification</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification * @generated */ EClass getSpecification(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification#getSpec <em>Spec</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Spec</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification#getSpec() * @see #getSpecification() * @generated */ EAttribute getSpecification_Spec(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification#getContext <em>Context</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Context</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification#getContext() * @see #getSpecification() * @generated */ EAttribute getSpecification_Context(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification#text(java.lang.Object) <em>Text</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Text</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification#text(java.lang.Object) * @generated */ EOperation getSpecification__Text__Object(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.CounterExample <em>Counter Example</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Counter Example</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.CounterExample * @generated */ EClass getCounterExample(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.UniversalModel <em>Universal Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Universal Model</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.UniversalModel * @generated */ EClass getUniversalModel(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker <em>Model Checker</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Model Checker</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker * @generated */ EClass getModelChecker(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getResourceContext <em>Resource Context</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Resource Context</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getResourceContext() * @see #getModelChecker() * @generated */ EAttribute getModelChecker_ResourceContext(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getResults <em>Results</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Results</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getResults() * @see #getModelChecker() * @generated */ EReference getModelChecker_Results(); /** * Returns the meta object for the reference list '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getVerificationUnits <em>Verification Units</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference list '<em>Verification Units</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getVerificationUnits() * @see #getModelChecker() * @generated */ EReference getModelChecker_VerificationUnits(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getViewpointCollection <em>Viewpoint Collection</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Viewpoint Collection</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getViewpointCollection() * @see #getModelChecker() * @generated */ EReference getModelChecker_ViewpointCollection(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getComponentCollection <em>Component Collection</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Component Collection</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getComponentCollection() * @see #getModelChecker() * @generated */ EReference getModelChecker_ComponentCollection(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#setUp(org.eclipse.emf.ecore.resource.Resource) <em>Set Up</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Set Up</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#setUp(org.eclipse.emf.ecore.resource.Resource) * @generated */ EOperation getModelChecker__SetUp__Resource(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#makeVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.Model, org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification, org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint, org.osate.xtext.aadl2.agcl.analysis.verifiers.Component) <em>Make Verification Unit</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Make Verification Unit</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#makeVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.Model, org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification, org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint, org.osate.xtext.aadl2.agcl.analysis.verifiers.Component) * @generated */ EOperation getModelChecker__MakeVerificationUnit__Model_Specification_Viewpoint_Component(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#makeVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification, org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint, org.osate.xtext.aadl2.agcl.analysis.verifiers.Component) <em>Make Verification Unit</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Make Verification Unit</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#makeVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification, org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint, org.osate.xtext.aadl2.agcl.analysis.verifiers.Component) * @generated */ EOperation getModelChecker__MakeVerificationUnit__Specification_Viewpoint_Component(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#checkVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit) <em>Check Verification Unit</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Check Verification Unit</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#checkVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit) * @generated */ EOperation getModelChecker__CheckVerificationUnit__VerificationUnit(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#prepareInput(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit) <em>Prepare Input</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Prepare Input</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#prepareInput(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit) * @generated */ EOperation getModelChecker__PrepareInput__VerificationUnit(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#processOutput(org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput) <em>Process Output</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Process Output</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#processOutput(org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput) * @generated */ EOperation getModelChecker__ProcessOutput__ModelCheckerOutput(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#callExternal(org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput) <em>Call External</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Call External</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#callExternal(org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput) * @generated */ EOperation getModelChecker__CallExternal__ModelCheckerInput(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#addVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit) <em>Add Verification Unit</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Add Verification Unit</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#addVerificationUnit(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit) * @generated */ EOperation getModelChecker__AddVerificationUnit__VerificationUnit(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#removeVerificationUnit(java.lang.String) <em>Remove Verification Unit</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Remove Verification Unit</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#removeVerificationUnit(java.lang.String) * @generated */ EOperation getModelChecker__RemoveVerificationUnit__String(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getVerificationUnit(java.lang.String) <em>Get Verification Unit</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Get Verification Unit</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#getVerificationUnit(java.lang.String) * @generated */ EOperation getModelChecker__GetVerificationUnit__String(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#checkAll() <em>Check All</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Check All</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelChecker#checkAll() * @generated */ EOperation getModelChecker__CheckAll(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModelChecker <em>Nu SMV Model Checker</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Nu SMV Model Checker</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModelChecker * @generated */ EClass getNuSMVModelChecker(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput <em>Model Checker Input</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Model Checker Input</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput * @generated */ EClass getModelCheckerInput(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput#getSpecification <em>Specification</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Specification</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput#getSpecification() * @see #getModelCheckerInput() * @generated */ EReference getModelCheckerInput_Specification(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput#getOutput <em>Output</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Output</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput#getOutput() * @see #getModelCheckerInput() * @generated */ EReference getModelCheckerInput_Output(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput#getVerificationUnit <em>Verification Unit</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Verification Unit</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerInput#getVerificationUnit() * @see #getModelCheckerInput() * @generated */ EReference getModelCheckerInput_VerificationUnit(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput <em>Model Checker Output</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Model Checker Output</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput * @generated */ EClass getModelCheckerOutput(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput#getResult <em>Result</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Result</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput#getResult() * @see #getModelCheckerOutput() * @generated */ EReference getModelCheckerOutput_Result(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput#getInput <em>Input</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Input</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ModelCheckerOutput#getInput() * @see #getModelCheckerOutput() * @generated */ EReference getModelCheckerOutput_Input(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVInput <em>Nu SMV Input</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Nu SMV Input</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVInput * @generated */ EClass getNuSMVInput(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVInput#getModelFileName <em>Model File Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Model File Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVInput#getModelFileName() * @see #getNuSMVInput() * @generated */ EAttribute getNuSMVInput_ModelFileName(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVInput#getSessionScriptFileName <em>Session Script File Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Session Script File Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVInput#getSessionScriptFileName() * @see #getNuSMVInput() * @generated */ EAttribute getNuSMVInput_SessionScriptFileName(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVOutput <em>Nu SMV Output</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Nu SMV Output</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVOutput * @generated */ EClass getNuSMVOutput(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVOutput#getOutputFileName <em>Output File Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Output File Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVOutput#getOutputFileName() * @see #getNuSMVOutput() * @generated */ EAttribute getNuSMVOutput_OutputFileName(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVOutput#getCounterExampleFileName <em>Counter Example File Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Counter Example File Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVOutput#getCounterExampleFileName() * @see #getNuSMVOutput() * @generated */ EAttribute getNuSMVOutput_CounterExampleFileName(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel <em>Nu SMV Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Nu SMV Model</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel * @generated */ EClass getNuSMVModel(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel#getVars <em>Vars</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Vars</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel#getVars() * @see #getNuSMVModel() * @generated */ EAttribute getNuSMVModel_Vars(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel#getInit <em>Init</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Init</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel#getInit() * @see #getNuSMVModel() * @generated */ EAttribute getNuSMVModel_Init(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel#getTrans <em>Trans</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Trans</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVModel#getTrans() * @see #getNuSMVModel() * @generated */ EAttribute getNuSMVModel_Trans(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVUniversalModel <em>Nu SMV Universal Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Nu SMV Universal Model</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVUniversalModel * @generated */ EClass getNuSMVUniversalModel(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVSpecification <em>Nu SMV Specification</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Nu SMV Specification</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVSpecification * @generated */ EClass getNuSMVSpecification(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVSpecification#getLogic <em>Logic</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Logic</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.NuSMVSpecification#getLogic() * @see #getNuSMVSpecification() * @generated */ EAttribute getNuSMVSpecification_Logic(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Unknown <em>Unknown</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Unknown</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Unknown * @generated */ EClass getUnknown(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Unknown#getReason <em>Reason</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Reason</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Unknown#getReason() * @see #getUnknown() * @generated */ EAttribute getUnknown_Reason(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultsCollection <em>Results Collection</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Results Collection</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultsCollection * @generated */ EClass getResultsCollection(); /** * Returns the meta object for the containment reference list '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultsCollection#getEntries <em>Entries</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Entries</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultsCollection#getEntries() * @see #getResultsCollection() * @generated */ EReference getResultsCollection_Entries(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultsCollection#recordResult(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit, org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult) <em>Record Result</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Record Result</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultsCollection#recordResult(org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit, org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult) * @generated */ EOperation getResultsCollection__RecordResult__VerificationUnit_VerificationResult(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Component <em>Component</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Component</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Component * @generated */ EClass getComponent(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Component#getName <em>Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Component#getName() * @see #getComponent() * @generated */ EAttribute getComponent_Name(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Component#getObject <em>Object</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Object</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Component#getObject() * @see #getComponent() * @generated */ EAttribute getComponent_Object(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint <em>Viewpoint</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Viewpoint</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint * @generated */ EClass getViewpoint(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint#getName <em>Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint#getName() * @see #getViewpoint() * @generated */ EAttribute getViewpoint_Name(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint#getObject <em>Object</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Object</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Viewpoint#getObject() * @see #getViewpoint() * @generated */ EAttribute getViewpoint_Object(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit <em>Verification Unit</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Verification Unit</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit * @generated */ EClass getVerificationUnit(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getModel <em>Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Model</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getModel() * @see #getVerificationUnit() * @generated */ EReference getVerificationUnit_Model(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getSpecification <em>Specification</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Specification</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getSpecification() * @see #getVerificationUnit() * @generated */ EReference getVerificationUnit_Specification(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getViewpoint <em>Viewpoint</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Viewpoint</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getViewpoint() * @see #getVerificationUnit() * @generated */ EReference getVerificationUnit_Viewpoint(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getComponent <em>Component</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Component</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getComponent() * @see #getVerificationUnit() * @generated */ EReference getVerificationUnit_Component(); /** * Returns the meta object for the attribute '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getName <em>Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Name</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationUnit#getName() * @see #getVerificationUnit() * @generated */ EAttribute getVerificationUnit_Name(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultEntry <em>Result Entry</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Result Entry</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultEntry * @generated */ EClass getResultEntry(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultEntry#getVerificationUnit <em>Verification Unit</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Verification Unit</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultEntry#getVerificationUnit() * @see #getResultEntry() * @generated */ EReference getResultEntry_VerificationUnit(); /** * Returns the meta object for the reference '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultEntry#getResult <em>Result</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the reference '<em>Result</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ResultEntry#getResult() * @see #getResultEntry() * @generated */ EReference getResultEntry_Result(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection <em>Viewpoint Collection</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Viewpoint Collection</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection * @generated */ EClass getViewpointCollection(); /** * Returns the meta object for the containment reference list '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#getViewpoints <em>Viewpoints</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Viewpoints</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#getViewpoints() * @see #getViewpointCollection() * @generated */ EReference getViewpointCollection_Viewpoints(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#getViewpoint(java.lang.String) <em>Get Viewpoint</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Get Viewpoint</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#getViewpoint(java.lang.String) * @generated */ EOperation getViewpointCollection__GetViewpoint__String(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#addViewpoint(java.lang.String, java.lang.Object) <em>Add Viewpoint</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Add Viewpoint</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#addViewpoint(java.lang.String, java.lang.Object) * @generated */ EOperation getViewpointCollection__AddViewpoint__String_Object(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#removeViewpoint(java.lang.String) <em>Remove Viewpoint</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Remove Viewpoint</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#removeViewpoint(java.lang.String) * @generated */ EOperation getViewpointCollection__RemoveViewpoint__String(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#containsViewpoint(java.lang.String) <em>Contains Viewpoint</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Contains Viewpoint</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ViewpointCollection#containsViewpoint(java.lang.String) * @generated */ EOperation getViewpointCollection__ContainsViewpoint__String(); /** * Returns the meta object for class '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection <em>Component Collection</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Component Collection</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection * @generated */ EClass getComponentCollection(); /** * Returns the meta object for the containment reference list '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#getComponents <em>Components</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Components</em>'. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#getComponents() * @see #getComponentCollection() * @generated */ EReference getComponentCollection_Components(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#getComponent(java.lang.String) <em>Get Component</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Get Component</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#getComponent(java.lang.String) * @generated */ EOperation getComponentCollection__GetComponent__String(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#addComponent(java.lang.String, java.lang.Object) <em>Add Component</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Add Component</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#addComponent(java.lang.String, java.lang.Object) * @generated */ EOperation getComponentCollection__AddComponent__String_Object(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#removeComponent(java.lang.String) <em>Remove Component</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Remove Component</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#removeComponent(java.lang.String) * @generated */ EOperation getComponentCollection__RemoveComponent__String(); /** * Returns the meta object for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#containsComponent(java.lang.String) <em>Contains Component</em>}' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the '<em>Contains Component</em>' operation. * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.ComponentCollection#containsComponent(java.lang.String) * @generated */ EOperation getComponentCollection__ContainsComponent__String(); /** * Returns the factory that creates the instances of the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the factory that creates the instances of the model. * @generated */ VerifiersFactory getVerifiersFactory(); /** * <!-- begin-user-doc --> * Defines literals for the meta objects that represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each operation of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @generated */ interface Literals { /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult <em>Verification Result</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.VerificationResult * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getVerificationResult() * @generated */ EClass VERIFICATION_RESULT = eINSTANCE.getVerificationResult(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.PositiveImpl <em>Positive</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.PositiveImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getPositive() * @generated */ EClass POSITIVE = eINSTANCE.getPositive(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NegativeImpl <em>Negative</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NegativeImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNegative() * @generated */ EClass NEGATIVE = eINSTANCE.getNegative(); /** * The meta object literal for the '<em><b>Counterexample</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference NEGATIVE__COUNTEREXAMPLE = eINSTANCE.getNegative_Counterexample(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Model <em>Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Model * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModel() * @generated */ EClass MODEL = eINSTANCE.getModel(); /** * The meta object literal for the '<em><b>Model</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute MODEL__MODEL = eINSTANCE.getModel_Model(); /** * The meta object literal for the '<em><b>Context</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute MODEL__CONTEXT = eINSTANCE.getModel_Context(); /** * The meta object literal for the '<em><b>Text</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL___TEXT__OBJECT = eINSTANCE.getModel__Text__Object(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification <em>Specification</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.Specification * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getSpecification() * @generated */ EClass SPECIFICATION = eINSTANCE.getSpecification(); /** * The meta object literal for the '<em><b>Spec</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute SPECIFICATION__SPEC = eINSTANCE.getSpecification_Spec(); /** * The meta object literal for the '<em><b>Context</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute SPECIFICATION__CONTEXT = eINSTANCE.getSpecification_Context(); /** * The meta object literal for the '<em><b>Text</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation SPECIFICATION___TEXT__OBJECT = eINSTANCE.getSpecification__Text__Object(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.CounterExampleImpl <em>Counter Example</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.CounterExampleImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getCounterExample() * @generated */ EClass COUNTER_EXAMPLE = eINSTANCE.getCounterExample(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.UniversalModel <em>Universal Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.UniversalModel * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getUniversalModel() * @generated */ EClass UNIVERSAL_MODEL = eINSTANCE.getUniversalModel(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerImpl <em>Model Checker</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModelChecker() * @generated */ EClass MODEL_CHECKER = eINSTANCE.getModelChecker(); /** * The meta object literal for the '<em><b>Resource Context</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute MODEL_CHECKER__RESOURCE_CONTEXT = eINSTANCE.getModelChecker_ResourceContext(); /** * The meta object literal for the '<em><b>Results</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER__RESULTS = eINSTANCE.getModelChecker_Results(); /** * The meta object literal for the '<em><b>Verification Units</b></em>' reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER__VERIFICATION_UNITS = eINSTANCE.getModelChecker_VerificationUnits(); /** * The meta object literal for the '<em><b>Viewpoint Collection</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER__VIEWPOINT_COLLECTION = eINSTANCE.getModelChecker_ViewpointCollection(); /** * The meta object literal for the '<em><b>Component Collection</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER__COMPONENT_COLLECTION = eINSTANCE.getModelChecker_ComponentCollection(); /** * The meta object literal for the '<em><b>Set Up</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___SET_UP__RESOURCE = eINSTANCE.getModelChecker__SetUp__Resource(); /** * The meta object literal for the '<em><b>Make Verification Unit</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___MAKE_VERIFICATION_UNIT__MODEL_SPECIFICATION_VIEWPOINT_COMPONENT = eINSTANCE.getModelChecker__MakeVerificationUnit__Model_Specification_Viewpoint_Component(); /** * The meta object literal for the '<em><b>Make Verification Unit</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___MAKE_VERIFICATION_UNIT__SPECIFICATION_VIEWPOINT_COMPONENT = eINSTANCE.getModelChecker__MakeVerificationUnit__Specification_Viewpoint_Component(); /** * The meta object literal for the '<em><b>Check Verification Unit</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___CHECK_VERIFICATION_UNIT__VERIFICATIONUNIT = eINSTANCE.getModelChecker__CheckVerificationUnit__VerificationUnit(); /** * The meta object literal for the '<em><b>Prepare Input</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___PREPARE_INPUT__VERIFICATIONUNIT = eINSTANCE.getModelChecker__PrepareInput__VerificationUnit(); /** * The meta object literal for the '<em><b>Process Output</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___PROCESS_OUTPUT__MODELCHECKEROUTPUT = eINSTANCE.getModelChecker__ProcessOutput__ModelCheckerOutput(); /** * The meta object literal for the '<em><b>Call External</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___CALL_EXTERNAL__MODELCHECKERINPUT = eINSTANCE.getModelChecker__CallExternal__ModelCheckerInput(); /** * The meta object literal for the '<em><b>Add Verification Unit</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___ADD_VERIFICATION_UNIT__VERIFICATIONUNIT = eINSTANCE.getModelChecker__AddVerificationUnit__VerificationUnit(); /** * The meta object literal for the '<em><b>Remove Verification Unit</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___REMOVE_VERIFICATION_UNIT__STRING = eINSTANCE.getModelChecker__RemoveVerificationUnit__String(); /** * The meta object literal for the '<em><b>Get Verification Unit</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___GET_VERIFICATION_UNIT__STRING = eINSTANCE.getModelChecker__GetVerificationUnit__String(); /** * The meta object literal for the '<em><b>Check All</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation MODEL_CHECKER___CHECK_ALL = eINSTANCE.getModelChecker__CheckAll(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelCheckerImpl <em>Nu SMV Model Checker</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelCheckerImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVModelChecker() * @generated */ EClass NU_SMV_MODEL_CHECKER = eINSTANCE.getNuSMVModelChecker(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerInputImpl <em>Model Checker Input</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerInputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModelCheckerInput() * @generated */ EClass MODEL_CHECKER_INPUT = eINSTANCE.getModelCheckerInput(); /** * The meta object literal for the '<em><b>Specification</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER_INPUT__SPECIFICATION = eINSTANCE.getModelCheckerInput_Specification(); /** * The meta object literal for the '<em><b>Output</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER_INPUT__OUTPUT = eINSTANCE.getModelCheckerInput_Output(); /** * The meta object literal for the '<em><b>Verification Unit</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER_INPUT__VERIFICATION_UNIT = eINSTANCE.getModelCheckerInput_VerificationUnit(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerOutputImpl <em>Model Checker Output</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ModelCheckerOutputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getModelCheckerOutput() * @generated */ EClass MODEL_CHECKER_OUTPUT = eINSTANCE.getModelCheckerOutput(); /** * The meta object literal for the '<em><b>Result</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER_OUTPUT__RESULT = eINSTANCE.getModelCheckerOutput_Result(); /** * The meta object literal for the '<em><b>Input</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL_CHECKER_OUTPUT__INPUT = eINSTANCE.getModelCheckerOutput_Input(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVInputImpl <em>Nu SMV Input</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVInputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVInput() * @generated */ EClass NU_SMV_INPUT = eINSTANCE.getNuSMVInput(); /** * The meta object literal for the '<em><b>Model File Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_INPUT__MODEL_FILE_NAME = eINSTANCE.getNuSMVInput_ModelFileName(); /** * The meta object literal for the '<em><b>Session Script File Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_INPUT__SESSION_SCRIPT_FILE_NAME = eINSTANCE.getNuSMVInput_SessionScriptFileName(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVOutputImpl <em>Nu SMV Output</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVOutputImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVOutput() * @generated */ EClass NU_SMV_OUTPUT = eINSTANCE.getNuSMVOutput(); /** * The meta object literal for the '<em><b>Output File Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_OUTPUT__OUTPUT_FILE_NAME = eINSTANCE.getNuSMVOutput_OutputFileName(); /** * The meta object literal for the '<em><b>Counter Example File Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_OUTPUT__COUNTER_EXAMPLE_FILE_NAME = eINSTANCE.getNuSMVOutput_CounterExampleFileName(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelImpl <em>Nu SMV Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVModelImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVModel() * @generated */ EClass NU_SMV_MODEL = eINSTANCE.getNuSMVModel(); /** * The meta object literal for the '<em><b>Vars</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_MODEL__VARS = eINSTANCE.getNuSMVModel_Vars(); /** * The meta object literal for the '<em><b>Init</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_MODEL__INIT = eINSTANCE.getNuSMVModel_Init(); /** * The meta object literal for the '<em><b>Trans</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_MODEL__TRANS = eINSTANCE.getNuSMVModel_Trans(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVUniversalModelImpl <em>Nu SMV Universal Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVUniversalModelImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVUniversalModel() * @generated */ EClass NU_SMV_UNIVERSAL_MODEL = eINSTANCE.getNuSMVUniversalModel(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVSpecificationImpl <em>Nu SMV Specification</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.NuSMVSpecificationImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getNuSMVSpecification() * @generated */ EClass NU_SMV_SPECIFICATION = eINSTANCE.getNuSMVSpecification(); /** * The meta object literal for the '<em><b>Logic</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute NU_SMV_SPECIFICATION__LOGIC = eINSTANCE.getNuSMVSpecification_Logic(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.UnknownImpl <em>Unknown</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.UnknownImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getUnknown() * @generated */ EClass UNKNOWN = eINSTANCE.getUnknown(); /** * The meta object literal for the '<em><b>Reason</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute UNKNOWN__REASON = eINSTANCE.getUnknown_Reason(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultsCollectionImpl <em>Results Collection</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultsCollectionImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getResultsCollection() * @generated */ EClass RESULTS_COLLECTION = eINSTANCE.getResultsCollection(); /** * The meta object literal for the '<em><b>Entries</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference RESULTS_COLLECTION__ENTRIES = eINSTANCE.getResultsCollection_Entries(); /** * The meta object literal for the '<em><b>Record Result</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation RESULTS_COLLECTION___RECORD_RESULT__VERIFICATIONUNIT_VERIFICATIONRESULT = eINSTANCE.getResultsCollection__RecordResult__VerificationUnit_VerificationResult(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentImpl <em>Component</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getComponent() * @generated */ EClass COMPONENT = eINSTANCE.getComponent(); /** * The meta object literal for the '<em><b>Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute COMPONENT__NAME = eINSTANCE.getComponent_Name(); /** * The meta object literal for the '<em><b>Object</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute COMPONENT__OBJECT = eINSTANCE.getComponent_Object(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointImpl <em>Viewpoint</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getViewpoint() * @generated */ EClass VIEWPOINT = eINSTANCE.getViewpoint(); /** * The meta object literal for the '<em><b>Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute VIEWPOINT__NAME = eINSTANCE.getViewpoint_Name(); /** * The meta object literal for the '<em><b>Object</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute VIEWPOINT__OBJECT = eINSTANCE.getViewpoint_Object(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerificationUnitImpl <em>Verification Unit</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerificationUnitImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getVerificationUnit() * @generated */ EClass VERIFICATION_UNIT = eINSTANCE.getVerificationUnit(); /** * The meta object literal for the '<em><b>Model</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference VERIFICATION_UNIT__MODEL = eINSTANCE.getVerificationUnit_Model(); /** * The meta object literal for the '<em><b>Specification</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference VERIFICATION_UNIT__SPECIFICATION = eINSTANCE.getVerificationUnit_Specification(); /** * The meta object literal for the '<em><b>Viewpoint</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference VERIFICATION_UNIT__VIEWPOINT = eINSTANCE.getVerificationUnit_Viewpoint(); /** * The meta object literal for the '<em><b>Component</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference VERIFICATION_UNIT__COMPONENT = eINSTANCE.getVerificationUnit_Component(); /** * The meta object literal for the '<em><b>Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute VERIFICATION_UNIT__NAME = eINSTANCE.getVerificationUnit_Name(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultEntryImpl <em>Result Entry</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ResultEntryImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getResultEntry() * @generated */ EClass RESULT_ENTRY = eINSTANCE.getResultEntry(); /** * The meta object literal for the '<em><b>Verification Unit</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference RESULT_ENTRY__VERIFICATION_UNIT = eINSTANCE.getResultEntry_VerificationUnit(); /** * The meta object literal for the '<em><b>Result</b></em>' reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference RESULT_ENTRY__RESULT = eINSTANCE.getResultEntry_Result(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointCollectionImpl <em>Viewpoint Collection</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ViewpointCollectionImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getViewpointCollection() * @generated */ EClass VIEWPOINT_COLLECTION = eINSTANCE.getViewpointCollection(); /** * The meta object literal for the '<em><b>Viewpoints</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference VIEWPOINT_COLLECTION__VIEWPOINTS = eINSTANCE.getViewpointCollection_Viewpoints(); /** * The meta object literal for the '<em><b>Get Viewpoint</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation VIEWPOINT_COLLECTION___GET_VIEWPOINT__STRING = eINSTANCE.getViewpointCollection__GetViewpoint__String(); /** * The meta object literal for the '<em><b>Add Viewpoint</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation VIEWPOINT_COLLECTION___ADD_VIEWPOINT__STRING_OBJECT = eINSTANCE.getViewpointCollection__AddViewpoint__String_Object(); /** * The meta object literal for the '<em><b>Remove Viewpoint</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation VIEWPOINT_COLLECTION___REMOVE_VIEWPOINT__STRING = eINSTANCE.getViewpointCollection__RemoveViewpoint__String(); /** * The meta object literal for the '<em><b>Contains Viewpoint</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation VIEWPOINT_COLLECTION___CONTAINS_VIEWPOINT__STRING = eINSTANCE.getViewpointCollection__ContainsViewpoint__String(); /** * The meta object literal for the '{@link org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentCollectionImpl <em>Component Collection</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.ComponentCollectionImpl * @see org.osate.xtext.aadl2.agcl.analysis.verifiers.impl.VerifiersPackageImpl#getComponentCollection() * @generated */ EClass COMPONENT_COLLECTION = eINSTANCE.getComponentCollection(); /** * The meta object literal for the '<em><b>Components</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference COMPONENT_COLLECTION__COMPONENTS = eINSTANCE.getComponentCollection_Components(); /** * The meta object literal for the '<em><b>Get Component</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation COMPONENT_COLLECTION___GET_COMPONENT__STRING = eINSTANCE.getComponentCollection__GetComponent__String(); /** * The meta object literal for the '<em><b>Add Component</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation COMPONENT_COLLECTION___ADD_COMPONENT__STRING_OBJECT = eINSTANCE.getComponentCollection__AddComponent__String_Object(); /** * The meta object literal for the '<em><b>Remove Component</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation COMPONENT_COLLECTION___REMOVE_COMPONENT__STRING = eINSTANCE.getComponentCollection__RemoveComponent__String(); /** * The meta object literal for the '<em><b>Contains Component</b></em>' operation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EOperation COMPONENT_COLLECTION___CONTAINS_COMPONENT__STRING = eINSTANCE.getComponentCollection__ContainsComponent__String(); } } //VerifiersPackage
apache-2.0
DataSketches/sketches-hive
src/main/java/com/yahoo/sketches/hive/kll/GetNUDF.java
972
/* * Copyright 2019, Verizon Media. * Licensed under the terms of the Apache License 2.0. See LICENSE file at the project root for terms. */ package com.yahoo.sketches.hive.kll; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.BytesWritable; import com.yahoo.memory.Memory; import com.yahoo.sketches.kll.KllFloatsSketch; @Description(name = "GetN", value = "_FUNC_(sketch)", extended = " Returns the total number of observed input values (stream length) from a given KllFloatsSketch.") public class GetNUDF extends UDF { /** * Returns N from a given sketch * @param serializedSketch serialized sketch * @return stream length */ public Long evaluate(final BytesWritable serializedSketch) { if (serializedSketch == null) { return null; } final KllFloatsSketch sketch = KllFloatsSketch.heapify(Memory.wrap(serializedSketch.getBytes())); return sketch.getN(); } }
apache-2.0
k21/buck
src/com/facebook/buck/lua/CxxLuaExtensionDescription.java
15039
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.lua; import com.facebook.buck.cxx.CxxConstructorArg; import com.facebook.buck.cxx.CxxDescriptionEnhancer; import com.facebook.buck.cxx.CxxFlags; import com.facebook.buck.cxx.CxxLinkableEnhancer; import com.facebook.buck.cxx.CxxPreprocessAndCompile; import com.facebook.buck.cxx.CxxPreprocessables; import com.facebook.buck.cxx.CxxPreprocessorInput; import com.facebook.buck.cxx.CxxSource; import com.facebook.buck.cxx.CxxSourceRuleFactory; import com.facebook.buck.cxx.toolchain.CxxBuckConfig; import com.facebook.buck.cxx.toolchain.CxxPlatform; import com.facebook.buck.cxx.toolchain.CxxPlatforms; import com.facebook.buck.cxx.toolchain.HeaderSymlinkTree; import com.facebook.buck.cxx.toolchain.HeaderVisibility; import com.facebook.buck.cxx.toolchain.LinkerMapMode; import com.facebook.buck.cxx.toolchain.linker.Linker; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkTargetMode; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.FlavorDomain; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.ImplicitDepsInferringDescription; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.SymlinkTree; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.rules.args.SourcePathArg; import com.facebook.buck.util.Optionals; import com.facebook.buck.util.RichStream; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.facebook.buck.versions.VersionPropagator; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimaps; import java.io.File; import java.nio.file.Path; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.immutables.value.Value; public class CxxLuaExtensionDescription implements Description<CxxLuaExtensionDescriptionArg>, ImplicitDepsInferringDescription< CxxLuaExtensionDescription.AbstractCxxLuaExtensionDescriptionArg>, VersionPropagator<CxxLuaExtensionDescriptionArg> { private final LuaConfig luaConfig; private final CxxBuckConfig cxxBuckConfig; private final FlavorDomain<CxxPlatform> cxxPlatforms; public CxxLuaExtensionDescription( LuaConfig luaConfig, CxxBuckConfig cxxBuckConfig, FlavorDomain<CxxPlatform> cxxPlatforms) { this.luaConfig = luaConfig; this.cxxBuckConfig = cxxBuckConfig; this.cxxPlatforms = cxxPlatforms; } private String getExtensionName(BuildTarget target, CxxPlatform cxxPlatform) { return String.format("%s.%s", target.getShortName(), cxxPlatform.getSharedLibraryExtension()); } private BuildTarget getExtensionTarget(BuildTarget target, Flavor platform) { return target.withAppendedFlavors(platform); } private Path getExtensionPath( ProjectFilesystem filesystem, BuildTarget target, CxxPlatform cxxPlatform) { return BuildTargets.getGenPath( filesystem, getExtensionTarget(target, cxxPlatform.getFlavor()), "%s") .resolve(getExtensionName(target, cxxPlatform)); } private ImmutableList<com.facebook.buck.rules.args.Arg> getExtensionArgs( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleResolver ruleResolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CellPathResolver cellRoots, CxxPlatform cxxPlatform, CxxLuaExtensionDescriptionArg args) { // Extract all C/C++ sources from the constructor arg. ImmutableMap<String, CxxSource> srcs = CxxDescriptionEnhancer.parseCxxSources( buildTarget, ruleResolver, ruleFinder, pathResolver, cxxPlatform, args); ImmutableMap<Path, SourcePath> headers = CxxDescriptionEnhancer.parseHeaders( buildTarget, ruleResolver, ruleFinder, pathResolver, Optional.of(cxxPlatform), args); // Setup the header symlink tree and combine all the preprocessor input from this rule // and all dependencies. HeaderSymlinkTree headerSymlinkTree = CxxDescriptionEnhancer.requireHeaderSymlinkTree( buildTarget, projectFilesystem, ruleResolver, cxxPlatform, headers, HeaderVisibility.PRIVATE, true); Optional<SymlinkTree> sandboxTree = Optional.empty(); if (cxxBuckConfig.sandboxSources()) { sandboxTree = CxxDescriptionEnhancer.createSandboxTree(buildTarget, ruleResolver, cxxPlatform); } ImmutableSet<BuildRule> deps = args.getCxxDeps().get(ruleResolver, cxxPlatform); ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput = ImmutableList.<CxxPreprocessorInput>builder() .add(luaConfig.getLuaCxxLibrary(ruleResolver).getCxxPreprocessorInput(cxxPlatform)) .addAll( CxxDescriptionEnhancer.collectCxxPreprocessorInput( buildTarget, cxxPlatform, deps, ImmutableListMultimap.copyOf( Multimaps.transformValues( CxxFlags.getLanguageFlagsWithMacros( args.getPreprocessorFlags(), args.getPlatformPreprocessorFlags(), args.getLangPreprocessorFlags(), cxxPlatform), f -> CxxDescriptionEnhancer.toStringWithMacrosArgs( buildTarget, cellRoots, ruleResolver, cxxPlatform, f))), ImmutableList.of(headerSymlinkTree), ImmutableSet.of(), CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform, deps), args.getIncludeDirs(), sandboxTree)) .build(); // Generate rule to build the object files. ImmutableMultimap<CxxSource.Type, Arg> compilerFlags = ImmutableListMultimap.copyOf( Multimaps.transformValues( CxxFlags.getLanguageFlagsWithMacros( args.getCompilerFlags(), args.getPlatformCompilerFlags(), args.getLangCompilerFlags(), cxxPlatform), f -> CxxDescriptionEnhancer.toStringWithMacrosArgs( buildTarget, cellRoots, ruleResolver, cxxPlatform, f))); ImmutableMap<CxxPreprocessAndCompile, SourcePath> picObjects = CxxSourceRuleFactory.of( projectFilesystem, buildTarget, ruleResolver, pathResolver, ruleFinder, cxxBuckConfig, cxxPlatform, cxxPreprocessorInput, compilerFlags, args.getPrefixHeader(), args.getPrecompiledHeader(), CxxSourceRuleFactory.PicType.PIC, sandboxTree) .requirePreprocessAndCompileRules(srcs); ImmutableList.Builder<com.facebook.buck.rules.args.Arg> argsBuilder = ImmutableList.builder(); CxxFlags.getFlagsWithMacrosWithPlatformMacroExpansion( args.getLinkerFlags(), args.getPlatformLinkerFlags(), cxxPlatform) .stream() .map( f -> CxxDescriptionEnhancer.toStringWithMacrosArgs( buildTarget, cellRoots, ruleResolver, cxxPlatform, f)) .forEach(argsBuilder::add); // Add object files into the args. argsBuilder.addAll(SourcePathArg.from(picObjects.values())); return argsBuilder.build(); } private BuildRule createExtensionBuildRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleResolver ruleResolver, CellPathResolver cellRoots, CxxPlatform cxxPlatform, CxxLuaExtensionDescriptionArg args) { if (buildTarget.getFlavors().contains(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR)) { return CxxDescriptionEnhancer.createSandboxTreeBuildRule( ruleResolver, args, cxxPlatform, buildTarget, projectFilesystem); } SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); String extensionName = getExtensionName(buildTarget, cxxPlatform); Path extensionPath = getExtensionPath(projectFilesystem, buildTarget, cxxPlatform); return CxxLinkableEnhancer.createCxxLinkableBuildRule( cxxBuckConfig, cxxPlatform, projectFilesystem, ruleResolver, pathResolver, ruleFinder, getExtensionTarget(buildTarget, cxxPlatform.getFlavor()), Linker.LinkType.SHARED, Optional.of(extensionName), extensionPath, Linker.LinkableDepType.SHARED, /* thinLto */ false, RichStream.from(args.getCxxDeps().get(ruleResolver, cxxPlatform)) .filter(NativeLinkable.class) .concat(Stream.of(luaConfig.getLuaCxxLibrary(ruleResolver))) .toImmutableList(), args.getCxxRuntimeType(), Optional.empty(), ImmutableSet.of(), ImmutableSet.of(), NativeLinkableInput.builder() .setArgs( getExtensionArgs( buildTarget.withoutFlavors(LinkerMapMode.NO_LINKER_MAP.getFlavor()), projectFilesystem, ruleResolver, pathResolver, ruleFinder, cellRoots, cxxPlatform, args)) .build(), Optional.empty()); } @Override public Class<CxxLuaExtensionDescriptionArg> getConstructorArgType() { return CxxLuaExtensionDescriptionArg.class; } @Override public BuildRule createBuildRule( TargetGraph targetGraph, BuildTarget buildTarget, final ProjectFilesystem projectFilesystem, BuildRuleParams params, final BuildRuleResolver resolver, CellPathResolver cellRoots, final CxxLuaExtensionDescriptionArg args) { // See if we're building a particular "type" of this library, and if so, extract // it as an enum. Optional<Map.Entry<Flavor, CxxPlatform>> platform = cxxPlatforms.getFlavorAndValue(buildTarget); // If a C/C++ platform is specified, then build an extension with it. if (platform.isPresent()) { return createExtensionBuildRule( buildTarget, projectFilesystem, resolver, cellRoots, platform.get().getValue(), args); } // Otherwise, we return the generic placeholder of this library, that dependents can use // get the real build rules via querying the action graph. SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); final SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); return new CxxLuaExtension(buildTarget, projectFilesystem, params) { @Override public String getModule(CxxPlatform cxxPlatform) { String baseModule = LuaUtil.getBaseModule(buildTarget, args.getBaseModule()); String name = getExtensionName(buildTarget, cxxPlatform); return baseModule.isEmpty() ? name : baseModule + File.separator + name; } @Override public SourcePath getExtension(CxxPlatform cxxPlatform) { BuildRule rule = resolver.requireRule(getBuildTarget().withAppendedFlavors(cxxPlatform.getFlavor())); return Preconditions.checkNotNull(rule.getSourcePathToOutput()); } @Override public NativeLinkTargetMode getNativeLinkTargetMode(CxxPlatform cxxPlatform) { return NativeLinkTargetMode.library(); } @Override public Iterable<? extends NativeLinkable> getNativeLinkTargetDeps(CxxPlatform cxxPlatform) { return RichStream.from(args.getCxxDeps().get(resolver, cxxPlatform)) .filter(NativeLinkable.class) .toImmutableList(); } @Override public NativeLinkableInput getNativeLinkTargetInput(CxxPlatform cxxPlatform) { return NativeLinkableInput.builder() .addAllArgs( getExtensionArgs( buildTarget, projectFilesystem, resolver, pathResolver, ruleFinder, cellRoots, cxxPlatform, args)) .addAllFrameworks(args.getFrameworks()) .build(); } @Override public Optional<Path> getNativeLinkTargetOutputPath(CxxPlatform cxxPlatform) { return Optional.empty(); } }; } @Override public void findDepsForTargetFromConstructorArgs( BuildTarget buildTarget, CellPathResolver cellRoots, AbstractCxxLuaExtensionDescriptionArg constructorArg, ImmutableCollection.Builder<BuildTarget> extraDepsBuilder, ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) { // Add deps from lua C/C++ library. Optionals.addIfPresent(luaConfig.getLuaCxxLibraryTarget(), extraDepsBuilder); // Get any parse time deps from the C/C++ platforms. extraDepsBuilder.addAll(CxxPlatforms.getParseTimeDeps(cxxPlatforms.getValues())); } @BuckStyleImmutable @Value.Immutable interface AbstractCxxLuaExtensionDescriptionArg extends CxxConstructorArg { Optional<String> getBaseModule(); } }
apache-2.0
WhiteBearSolutions/WBSAirback
packages/wbsairback-tomcat/wbsairback-tomcat-7.0.22/java/org/apache/catalina/deploy/ResourceBase.java
3649
/* * 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.catalina.deploy; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * Representation of an Context element * * @author Peter Rossbach (pero@apache.org) * @version $Id: ResourceBase.java 1027762 2010-10-26 22:19:49Z markt $ */ public class ResourceBase implements Serializable, Injectable { private static final long serialVersionUID = 1L; // ------------------------------------------------------------- Properties /** * The description of this resource. */ private String description = null; public String getDescription() { return (this.description); } public void setDescription(String description) { this.description = description; } /** * The name of this resource. */ private String name = null; @Override public String getName() { return (this.name); } public void setName(String name) { this.name = name; } /** * The name of the resource implementation class. */ private String type = null; public String getType() { return (this.type); } public void setType(String type) { this.type = type; } /** * Holder for our configured properties. */ private HashMap<String, Object> properties = new HashMap<String, Object>(); /** * Return a configured property. */ public Object getProperty(String name) { return properties.get(name); } /** * Set a configured property. */ public void setProperty(String name, Object value) { properties.put(name, value); } /** * Remove a configured property. */ public void removeProperty(String name) { properties.remove(name); } /** * List properties. */ public Iterator<String> listProperties() { return properties.keySet().iterator(); } private List<InjectionTarget> injectionTargets = new ArrayList<InjectionTarget>(); @Override public void addInjectionTarget(String injectionTargetName, String jndiName) { InjectionTarget target = new InjectionTarget(injectionTargetName, jndiName); injectionTargets.add(target); } @Override public List<InjectionTarget> getInjectionTargets() { return injectionTargets; } // -------------------------------------------------------- Package Methods /** * The NamingResources with which we are associated (if any). */ protected NamingResources resources = null; public NamingResources getNamingResources() { return (this.resources); } void setNamingResources(NamingResources resources) { this.resources = resources; } }
apache-2.0
tommyettinger/SquidLib-Demos
Benchmarks/GWT_Text/html/src/main/java/com/github/tommyettinger/bench/gwt/GWTRNG2.java
5385
package com.github.tommyettinger.bench.gwt; import com.badlogic.gdx.Gdx; import squidpony.StringKit; import squidpony.squidmath.AbstractRNG; import squidpony.squidmath.CrossHash; import squidpony.squidmath.IStatefulRNG; import java.io.Serializable; public final class GWTRNG2 extends AbstractRNG implements IStatefulRNG, Serializable { private static final long serialVersionUID = 2L; public int stateA, stateB; public GWTRNG2() { setState((int)((Math.random() * 2.0 - 1.0) * 0x80000000), (int)((Math.random() * 2.0 - 1.0) * 0x80000000)); } public GWTRNG2(final int seed) { setSeed(seed); } public GWTRNG2(final long seed) { setState(seed); } public GWTRNG2(final int stateA, final int stateB) { setState(stateA, stateB); } public GWTRNG2(final String seed) { setState(CrossHash.hash(seed), seed == null ? 1 : seed.hashCode()); } @Override public final int next(int bits) { final int s0 = stateA; final int s1 = stateB ^ s0; final int result = s0 * 31; stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); stateB = (s1 << 13 | s1 >>> 19); return (result << 28 | result >>> 4) + 0x9E3779BD >>> (32 - bits); } @Override public final int nextInt() { final int s0 = stateA; final int s1 = stateB ^ s0; final int result = s0 * 31; stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); stateB = (s1 << 13 | s1 >>> 19); return (result << 28 | result >>> 4) + 0x9E3779BD | 0; } @Override public final long nextLong() { int s0 = stateA; int s1 = stateB ^ s0; final int high = s0 * 31; s0 = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); s1 = (s1 << 13 | s1 >>> 19) ^ s0; final int low = s0 * 31; stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); stateB = (s1 << 13 | s1 >>> 19); return ((high << 28 | high >>> 4) + 0x9E3779BDL) << 32 | ((low << 28 | low >>> 4) + 0x9E3779BD & 0xFFFFFFFFL); } @Override public final boolean nextBoolean() { final int s0 = stateA; final int s1 = stateB ^ s0; stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); stateB = (s1 << 13 | s1 >>> 19); return (s0 * 31 << 28) < 0; } @Override public final double nextDouble() { int s0 = stateA; int s1 = stateB ^ s0; final int high = s0 * 31; s0 = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); s1 = (s1 << 13 | s1 >>> 19) ^ s0; final int low = s0 * 31; stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); stateB = (s1 << 13 | s1 >>> 19); return ((((high << 28 | high >>> 4) + 0x9E3779BDL) << 32 | ((low << 28 | low >>> 4) + 0x9E3779BD & 0xFFFFFFFFL)) & 0x1FFFFFFFFFFFFFL) * 0x1p-53; } @Override public final float nextFloat() { final int s0 = stateA; final int s1 = stateB ^ s0; final int result = s0 * 31; stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); stateB = (s1 << 13 | s1 >>> 19); return ((result << 28 | result >>> 4) + 0x9E3779BD & 0xFFFFFF) * 0x1p-24f; } @Override public int nextInt(int bound) { return (int) ((bound * (nextInt() & 0xFFFFFFFFL)) >>> 32) & ~(bound >> 31); } @Override public GWTRNG2 copy() { return new GWTRNG2(stateA, stateB); } @Override public Serializable toSerializable() { return this; } public void setSeed(final int seed) { int z = seed + 0xC74EAD55 | 0, a = seed ^ z; a ^= a >>> 14; z = (z ^ z >>> 10) * 0xA5CB3 | 0; a ^= a >>> 15; stateA = (z ^ z >>> 20) + (a ^= a << 13) | 0; z = seed + 0x8E9D5AAA | 0; a ^= a >>> 14; z = (z ^ z >>> 10) * 0xA5CB3 | 0; a ^= a >>> 15; stateB = (z ^ z >>> 20) + (a ^ a << 13) | 0; if((stateA | stateB) == 0) stateA = 1; } public int getStateA() { return stateA; } public void setStateA(int stateA) { this.stateA = (stateA | stateB) == 0 ? 1 : stateA; } public int getStateB() { return stateB; } public void setStateB(int stateB) { this.stateB = stateB; if((stateB | stateA) == 0) stateA = 1; } public void setState(int stateA, int stateB) { this.stateA = stateA == 0 && stateB == 0 ? 1 : stateA; this.stateB = stateB; } @Override public long getState() { return stateA & 0xFFFFFFFFL | ((long)stateB) << 32; } @Override public void setState(long state) { stateA = state == 0 ? 1 : (int)(state & 0xFFFFFFFFL); stateB = (int)(state >>> 32); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GWTRNG2 gwtrng2 = (GWTRNG2) o; if (stateA != gwtrng2.stateA) return false; return stateB == gwtrng2.stateB; } @Override public int hashCode() { return 31 * stateA + stateB | 0; } @Override public String toString() { return "GWTRNG2 with stateA 0x" + StringKit.hex(stateA) + " and stateB 0x" + StringKit.hex(stateB); } }
apache-2.0
lburgazzoli/apache-activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/OpenWireUtilTest.java
1542
/* * 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.openwire; import static org.junit.Assert.assertEquals; import org.apache.activemq.artemis.core.protocol.openwire.util.OpenWireUtil; import org.junit.Test; public class OpenWireUtilTest { @Test public void testWildcardConversion() throws Exception { String amqTarget = "TEST.ONE.>"; String coreTarget = OpenWireUtil.convertWildcard(amqTarget); assertEquals("TEST.ONE.#", coreTarget); amqTarget = "TEST.*.ONE"; coreTarget = OpenWireUtil.convertWildcard(amqTarget); assertEquals("TEST.*.ONE", coreTarget); amqTarget = "a.*.>.>"; coreTarget = OpenWireUtil.convertWildcard(amqTarget); assertEquals("a.*.#", coreTarget); } }
apache-2.0
korno/Omoidasu
src/com/coffeebaka/omoidasu/app/CategoriesExpandableListAdapter.java
3027
/* Copyright 2012 Michael Hall 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.coffeebaka.omoidasu.app; import com.coffeebaka.omoidasu.data.DataCache; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; public class CategoriesExpandableListAdapter extends BaseExpandableListAdapter{ protected Context mContext; protected LayoutInflater mInflater; public CategoriesExpandableListAdapter(Context _c){ mContext = _c; mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public Object getChild(int _groupPos, int _childPos ) { return DataCache.instance().getAllCategories().get(_groupPos).getSets().get(_childPos); } @Override public long getChildId(int _groupPos, int _childPos) { return DataCache.instance().getAllCategories().get(_groupPos).getSets().get(_childPos).getId(); } @Override public View getChildView(int _groupPosition, int _childPosition, boolean _isLastChild, View _convertView, ViewGroup _parent){ TextView t; View v; v = _convertView != null ? _convertView : mInflater.inflate(R.layout.categories_list_child, null); t = (TextView)v.findViewById(R.id.textViewSetName); t.setText(DataCache.instance().getAllCategories().get(_groupPosition).getSets().get(_childPosition).getName()); return v; } @Override public int getChildrenCount(int _groupPos) { return DataCache.instance().getAllCategories().get(_groupPos).getSets().size(); } @Override public Object getGroup(int _groupPos) { return DataCache.instance().getAllCategories().get(_groupPos); } @Override public int getGroupCount() { return DataCache.instance().getAllCategories().size(); } @Override public long getGroupId(int _groupPos) { return DataCache.instance().getAllCategories().get(_groupPos).getId(); } @Override public View getGroupView(int _groupPosition, boolean _isExpanded, View _convertView, ViewGroup _parent){ TextView t; View v = _convertView != null ? _convertView : mInflater.inflate(R.layout.categories_list_parent, null); t = (TextView)v.findViewById(R.id.textViewCategoryName); t.setText(DataCache.instance().getAllCategories().get(_groupPosition).getName()); return v; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int arg0, int arg1) { return true; } }
apache-2.0
EMResearch/EMB
jdk_8_maven/cs/graphql/spring-petclinic-graphql/src/main/java/org/springframework/samples/petclinic/repository/jpa/package-info.java
172
/** * The classes in this package represent the JPA implementation * of PetClinic's persistence layer. */ package org.springframework.samples.petclinic.repository.jpa;
apache-2.0
BlurEngine/Blur
src/main/java/com/blurengine/blur/countdown/Countdown.java
1379
/* * Copyright 2016 Ali Moghnieh * * 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.blurengine.blur.countdown; import com.blurengine.blur.framework.Component; import com.blurengine.blur.session.BlurPlayer; /** * Represents a countdown object that extends a Tickable object. Since this extends Tickable object, the implementor needs to take into account * that implementing this class may break any implementations that extend tickable. */ public interface Countdown extends Component { /** * Called when the countdown has expired. */ void onEnd(); /** * Called when this countdown ticks. This method is until the ticks are zero; when this countdown has finished. */ void onTick(); void onTick(BlurPlayer player); /** * Called when the countdown has been cancelled. */ void onCancel(); }
apache-2.0
FinishX/coolweather
gradle/gradle-2.8/src/core/org/gradle/groovy/scripts/internal/BuildScriptTransformer.java
2673
/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.groovy.scripts.internal; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.CompilationUnit; import org.gradle.api.specs.Spec; import org.gradle.groovy.scripts.ScriptSource; import org.gradle.groovy.scripts.Transformer; import org.gradle.internal.Factory; import org.gradle.model.dsl.internal.transform.ModelBlockTransformer; import java.util.Arrays; import java.util.List; public class BuildScriptTransformer implements Transformer, Factory<BuildScriptData> { private final Spec<? super Statement> filter; private final ScriptSource scriptSource; private final ImperativeStatementDetectingTransformer imperativeStatementDetectingTransformer = new ImperativeStatementDetectingTransformer(); public BuildScriptTransformer(String classpathClosureName, ScriptSource scriptSource) { final List<String> blocksToIgnore = Arrays.asList(classpathClosureName, InitialPassStatementTransformer.PLUGINS); this.filter = new Spec<Statement>() { @Override public boolean isSatisfiedBy(Statement statement) { return AstUtils.detectScriptBlock(statement, blocksToIgnore) != null; } }; this.scriptSource = scriptSource; } public void register(CompilationUnit compilationUnit) { new FilteringScriptTransformer(filter).register(compilationUnit); new TaskDefinitionScriptTransformer().register(compilationUnit); new FixMainScriptTransformer().register(compilationUnit); new StatementLabelsScriptTransformer().register(compilationUnit); new ScriptSourceTransformer(scriptSource.getDisplayName(), scriptSource.getResource().getURI()).register(compilationUnit); new ModelBlockTransformer().register(compilationUnit); imperativeStatementDetectingTransformer.register(compilationUnit); } @Override public BuildScriptData create() { return new BuildScriptData(imperativeStatementDetectingTransformer.isImperativeStatementDetected()); } }
apache-2.0
consulo/consulo
modules/base/xtest-sm-impl/src/main/java/com/intellij/execution/testframework/sm/runner/events/TreeNodeEvent.java
2586
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.testframework.sm.runner.events; import jetbrains.buildServer.messages.serviceMessages.ServiceMessage; import org.jetbrains.annotations.NonNls; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class TreeNodeEvent { @NonNls public static final String ROOT_NODE_ID = "0"; private final String myName; private final String myId; public TreeNodeEvent(@javax.annotation.Nullable String name, @Nullable String id) { myName = name; myId = id; } protected void fail(@Nonnull String message) { throw new IllegalStateException(message + ", " + toString()); } @javax.annotation.Nullable public String getName() { return myName; } /** * @return tree node id, or null if undefined */ @javax.annotation.Nullable public String getId() { return myId; } @Override public final String toString() { StringBuilder buf = new StringBuilder(getClass().getSimpleName() + "{"); append(buf, "name", myName); append(buf, "id", myId); appendToStringInfo(buf); // drop last 2 chars: ', ' buf.setLength(buf.length() - 2); buf.append("}"); return buf.toString(); } protected abstract void appendToStringInfo(@Nonnull StringBuilder buf); protected static void append(@Nonnull StringBuilder buffer, @Nonnull String key, @javax.annotation.Nullable Object value) { if (value != null) { buffer.append(key).append("="); if (value instanceof String) { buffer.append("'").append(value).append("'"); } else { buffer.append(String.valueOf(value)); } buffer.append(", "); } } @Nullable public static String getNodeId(@Nonnull ServiceMessage message) { return getNodeId(message, "nodeId"); } @javax.annotation.Nullable public static String getNodeId(@Nonnull ServiceMessage message, String key) { return message.getAttributes().get(key); } }
apache-2.0
ibmsoe/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/security/access/TestWithDisabledAuthorization.java
40036
/* * 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.hadoop.hbase.security.access; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Append; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.master.MasterCoprocessorHost; import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription; import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost; import org.apache.hadoop.hbase.regionserver.RegionScanner; import org.apache.hadoop.hbase.regionserver.RegionServerCoprocessorHost; import org.apache.hadoop.hbase.regionserver.wal.WALEdit; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.security.access.Permission.Action; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.TestTableName; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import com.google.common.collect.Lists; @Category(LargeTests.class) public class TestWithDisabledAuthorization extends SecureTestUtil { private static final Log LOG = LogFactory.getLog(TestWithDisabledAuthorization.class); static { Logger.getLogger(AccessController.class).setLevel(Level.TRACE); Logger.getLogger(AccessControlFilter.class).setLevel(Level.TRACE); Logger.getLogger(TableAuthManager.class).setLevel(Level.TRACE); } private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static final byte[] TEST_FAMILY = Bytes.toBytes("f1"); private static final byte[] TEST_FAMILY2 = Bytes.toBytes("f2"); private static final byte[] TEST_ROW = Bytes.toBytes("testrow"); private static final byte[] TEST_Q1 = Bytes.toBytes("q1"); private static final byte[] TEST_Q2 = Bytes.toBytes("q2"); private static final byte[] TEST_Q3 = Bytes.toBytes("q3"); private static final byte[] TEST_Q4 = Bytes.toBytes("q4"); private static final byte[] ZERO = Bytes.toBytes(0L); private static MasterCoprocessorEnvironment CP_ENV; private static AccessController ACCESS_CONTROLLER; private static RegionServerCoprocessorEnvironment RSCP_ENV; private RegionCoprocessorEnvironment RCP_ENV; @Rule public TestTableName TEST_TABLE = new TestTableName(); // default users // superuser private static User SUPERUSER; // user granted with all global permission private static User USER_ADMIN; // user with rw permissions on column family. private static User USER_RW; // user with read-only permissions private static User USER_RO; // user is table owner. will have all permissions on table private static User USER_OWNER; // user with create table permissions alone private static User USER_CREATE; // user with no permissions private static User USER_NONE; // user with only partial read-write perms (on family:q1 only) private static User USER_QUAL; @BeforeClass public static void setupBeforeClass() throws Exception { Configuration conf = TEST_UTIL.getConfiguration(); // Enable security enableSecurity(conf); // We expect 0.98 cell ACL semantics conf.setBoolean(AccessControlConstants.CF_ATTRIBUTE_EARLY_OUT, false); // Enable EXEC permission checking conf.setBoolean(AccessControlConstants.EXEC_PERMISSION_CHECKS_KEY, true); // Verify enableSecurity sets up what we require verifyConfiguration(conf); // Now, DISABLE only active authorization conf.setBoolean(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, false); // Start the minicluster TEST_UTIL.startMiniCluster(); MasterCoprocessorHost cpHost = TEST_UTIL.getMiniHBaseCluster().getMaster().getMasterCoprocessorHost(); cpHost.load(AccessController.class, Coprocessor.PRIORITY_HIGHEST, conf); ACCESS_CONTROLLER = (AccessController) cpHost.findCoprocessor(AccessController.class.getName()); CP_ENV = cpHost.createEnvironment(AccessController.class, ACCESS_CONTROLLER, Coprocessor.PRIORITY_HIGHEST, 1, conf); RegionServerCoprocessorHost rsHost = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0) .getRegionServerCoprocessorHost(); RSCP_ENV = rsHost.createEnvironment(AccessController.class, ACCESS_CONTROLLER, Coprocessor.PRIORITY_HIGHEST, 1, conf); // Wait for the ACL table to become available TEST_UTIL.waitUntilAllRegionsAssigned(AccessControlLists.ACL_TABLE_NAME); // create a set of test users SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" }); USER_ADMIN = User.createUserForTesting(conf, "admin2", new String[0]); USER_OWNER = User.createUserForTesting(conf, "owner", new String[0]); USER_CREATE = User.createUserForTesting(conf, "tbl_create", new String[0]); USER_RW = User.createUserForTesting(conf, "rwuser", new String[0]); USER_RO = User.createUserForTesting(conf, "rouser", new String[0]); USER_QUAL = User.createUserForTesting(conf, "rwpartial", new String[0]); USER_NONE = User.createUserForTesting(conf, "nouser", new String[0]); } @AfterClass public static void tearDownAfterClass() throws Exception { TEST_UTIL.shutdownMiniCluster(); } @Before public void setUp() throws Exception { // Create the test table (owner added to the _acl_ table) Admin admin = TEST_UTIL.getHBaseAdmin(); HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); HColumnDescriptor hcd = new HColumnDescriptor(TEST_FAMILY); hcd.setMaxVersions(100); htd.addFamily(hcd); htd.setOwner(USER_OWNER); admin.createTable(htd, new byte[][] { Bytes.toBytes("s") }); TEST_UTIL.waitUntilAllRegionsAssigned(TEST_TABLE.getTableName()); Region region = TEST_UTIL.getHBaseCluster().getRegions(TEST_TABLE.getTableName()).get(0); RegionCoprocessorHost rcpHost = region.getCoprocessorHost(); RCP_ENV = rcpHost.createEnvironment(AccessController.class, ACCESS_CONTROLLER, Coprocessor.PRIORITY_HIGHEST, 1, TEST_UTIL.getConfiguration()); // Set up initial grants grantGlobal(TEST_UTIL, USER_ADMIN.getShortName(), Permission.Action.ADMIN, Permission.Action.CREATE, Permission.Action.READ, Permission.Action.WRITE); grantOnTable(TEST_UTIL, USER_RW.getShortName(), TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ, Permission.Action.WRITE); // USER_CREATE is USER_RW plus CREATE permissions grantOnTable(TEST_UTIL, USER_CREATE.getShortName(), TEST_TABLE.getTableName(), null, null, Permission.Action.CREATE, Permission.Action.READ, Permission.Action.WRITE); grantOnTable(TEST_UTIL, USER_RO.getShortName(), TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ); grantOnTable(TEST_UTIL, USER_QUAL.getShortName(), TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1, Permission.Action.READ, Permission.Action.WRITE); assertEquals(5, AccessControlLists.getTablePermissions(TEST_UTIL.getConfiguration(), TEST_TABLE.getTableName()).size()); } @After public void tearDown() throws Exception { // Clean the _acl_ table try { deleteTable(TEST_UTIL, TEST_TABLE.getTableName()); } catch (TableNotFoundException ex) { // Test deleted the table, no problem LOG.info("Test deleted table " + TEST_TABLE.getTableName()); } // Verify all table/namespace permissions are erased assertEquals(0, AccessControlLists.getTablePermissions(TEST_UTIL.getConfiguration(), TEST_TABLE.getTableName()).size()); assertEquals(0, AccessControlLists.getNamespacePermissions(TEST_UTIL.getConfiguration(), TEST_TABLE.getTableName().getNamespaceAsString()).size()); } @Test public void testCheckPermissions() throws Exception { AccessTestAction checkGlobalAdmin = new AccessTestAction() { @Override public Void run() throws Exception { checkGlobalPerms(TEST_UTIL, Permission.Action.ADMIN); return null; } }; verifyAllowed(checkGlobalAdmin, SUPERUSER, USER_ADMIN); verifyDenied(checkGlobalAdmin, USER_OWNER, USER_CREATE, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkGlobalRead = new AccessTestAction() { @Override public Void run() throws Exception { checkGlobalPerms(TEST_UTIL, Permission.Action.READ); return null; } }; verifyAllowed(checkGlobalRead, SUPERUSER, USER_ADMIN); verifyDenied(checkGlobalRead, USER_OWNER, USER_CREATE, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkGlobalReadWrite = new AccessTestAction() { @Override public Void run() throws Exception { checkGlobalPerms(TEST_UTIL, Permission.Action.READ, Permission.Action.WRITE); return null; } }; verifyAllowed(checkGlobalReadWrite, SUPERUSER, USER_ADMIN); verifyDenied(checkGlobalReadWrite, USER_OWNER, USER_CREATE, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkTableAdmin = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), null, null, Permission.Action.ADMIN); return null; } }; verifyAllowed(checkTableAdmin, SUPERUSER, USER_ADMIN, USER_OWNER); verifyDenied(checkTableAdmin, USER_CREATE, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkTableCreate = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), null, null, Permission.Action.CREATE); return null; } }; verifyAllowed(checkTableCreate, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE); verifyDenied(checkTableCreate, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkTableRead = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), null, null, Permission.Action.READ); return null; } }; verifyAllowed(checkTableRead, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE); verifyDenied(checkTableRead, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkTableReadWrite = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), null, null, Permission.Action.READ, Permission.Action.WRITE); return null; } }; verifyAllowed(checkTableReadWrite, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE); verifyDenied(checkTableReadWrite, USER_RW, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkColumnRead = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ); return null; } }; verifyAllowed(checkColumnRead, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW, USER_RO); verifyDenied(checkColumnRead, USER_QUAL, USER_NONE); AccessTestAction checkColumnReadWrite = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ, Permission.Action.WRITE); return null; } }; verifyAllowed(checkColumnReadWrite, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW); verifyDenied(checkColumnReadWrite, USER_RO, USER_QUAL, USER_NONE); AccessTestAction checkQualifierRead = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1, Permission.Action.READ); return null; } }; verifyAllowed(checkQualifierRead, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW, USER_RO, USER_QUAL); verifyDenied(checkQualifierRead, USER_NONE); AccessTestAction checkQualifierReadWrite = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1, Permission.Action.READ, Permission.Action.WRITE); return null; } }; verifyAllowed(checkQualifierReadWrite, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW, USER_QUAL); verifyDenied(checkQualifierReadWrite, USER_RO, USER_NONE); AccessTestAction checkMultiQualifierRead = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), new Permission[] { new TablePermission(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1, Permission.Action.READ), new TablePermission(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q2, Permission.Action.READ), }); return null; } }; verifyAllowed(checkMultiQualifierRead, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW, USER_RO); verifyDenied(checkMultiQualifierRead, USER_QUAL, USER_NONE); AccessTestAction checkMultiQualifierReadWrite = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), new Permission[] { new TablePermission(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1, Permission.Action.READ, Permission.Action.WRITE), new TablePermission(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q2, Permission.Action.READ, Permission.Action.WRITE), }); return null; } }; verifyAllowed(checkMultiQualifierReadWrite, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW); verifyDenied(checkMultiQualifierReadWrite, USER_RO, USER_QUAL, USER_NONE); } /** Test grants and revocations with authorization disabled */ @Test public void testPassiveGrantRevoke() throws Exception { // Add a test user User tblUser = User.createUserForTesting(TEST_UTIL.getConfiguration(), "tbluser", new String[0]); // If we check now, the test user won't have permissions AccessTestAction checkTableRead = new AccessTestAction() { @Override public Void run() throws Exception { checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ); return null; } }; verifyDenied(tblUser, checkTableRead); // An actual read won't be denied AccessTestAction tableRead = new AccessTestAction() { @Override public Void run() throws Exception { try (Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration()); Table t = conn.getTable(TEST_TABLE.getTableName())) { t.get(new Get(TEST_ROW).addFamily(TEST_FAMILY)); } return null; } }; verifyAllowed(tblUser, tableRead); // Grant read perms to the test user grantOnTable(TEST_UTIL, tblUser.getShortName(), TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ); // Now both the permission check and actual op will succeed verifyAllowed(tblUser, checkTableRead); verifyAllowed(tblUser, tableRead); // Revoke read perms from the test user revokeFromTable(TEST_UTIL, tblUser.getShortName(), TEST_TABLE.getTableName(), TEST_FAMILY, null, Permission.Action.READ); // Now the permission check will indicate revocation but the actual op will still succeed verifyDenied(tblUser, checkTableRead); verifyAllowed(tblUser, tableRead); } /** Test master observer */ @Test public void testPassiveMasterOperations() throws Exception { // preCreateTable verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); htd.addFamily(new HColumnDescriptor(TEST_FAMILY)); ACCESS_CONTROLLER.preCreateTable(ObserverContext.createAndPrepare(CP_ENV, null), htd, null); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preModifyTable verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); htd.addFamily(new HColumnDescriptor(TEST_FAMILY)); htd.addFamily(new HColumnDescriptor(TEST_FAMILY2)); ACCESS_CONTROLLER.preModifyTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName(), htd); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preDeleteTable verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preDeleteTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName()); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preTruncateTable verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preTruncateTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName()); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preAddColumn verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HColumnDescriptor hcd = new HColumnDescriptor(TEST_FAMILY2); ACCESS_CONTROLLER.preAddColumn(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName(), hcd); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preModifyColumn verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HColumnDescriptor hcd = new HColumnDescriptor(TEST_FAMILY2); ACCESS_CONTROLLER.preModifyColumn(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName(), hcd); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preDeleteColumn verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preDeleteColumn(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName(), TEST_FAMILY2); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preEnableTable verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preEnableTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName()); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preDisableTable verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preDisableTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName()); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preMove verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HRegionInfo region = new HRegionInfo(TEST_TABLE.getTableName()); ServerName srcServer = ServerName.valueOf("1.1.1.1", 1, 0); ServerName destServer = ServerName.valueOf("2.2.2.2", 2, 0); ACCESS_CONTROLLER.preMove(ObserverContext.createAndPrepare(CP_ENV, null), region, srcServer, destServer); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preAssign verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HRegionInfo region = new HRegionInfo(TEST_TABLE.getTableName()); ACCESS_CONTROLLER.preAssign(ObserverContext.createAndPrepare(CP_ENV, null), region); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preUnassign verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HRegionInfo region = new HRegionInfo(TEST_TABLE.getTableName()); ACCESS_CONTROLLER.preUnassign(ObserverContext.createAndPrepare(CP_ENV, null), region, true); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preBalance verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preBalance(ObserverContext.createAndPrepare(CP_ENV, null)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preBalanceSwitch verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preBalanceSwitch(ObserverContext.createAndPrepare(CP_ENV, null), true); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preSnapshot verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { SnapshotDescription snapshot = SnapshotDescription.newBuilder() .setName("foo") .build(); HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); ACCESS_CONTROLLER.preSnapshot(ObserverContext.createAndPrepare(CP_ENV, null), snapshot, htd); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preCloneSnapshot verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { SnapshotDescription snapshot = SnapshotDescription.newBuilder() .setName("foo") .build(); HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); ACCESS_CONTROLLER.preCloneSnapshot(ObserverContext.createAndPrepare(CP_ENV, null), snapshot, htd); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preRestoreSnapshot verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { SnapshotDescription snapshot = SnapshotDescription.newBuilder() .setName("foo") .build(); HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); ACCESS_CONTROLLER.preRestoreSnapshot(ObserverContext.createAndPrepare(CP_ENV, null), snapshot, htd); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preDeleteSnapshot verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { SnapshotDescription snapshot = SnapshotDescription.newBuilder() .setName("foo") .build(); ACCESS_CONTROLLER.preDeleteSnapshot(ObserverContext.createAndPrepare(CP_ENV, null), snapshot); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preGetTableDescriptors verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { List<TableName> tableNamesList = Lists.newArrayList(); tableNamesList.add(TEST_TABLE.getTableName()); List<HTableDescriptor> descriptors = Lists.newArrayList(); ACCESS_CONTROLLER.preGetTableDescriptors(ObserverContext.createAndPrepare(CP_ENV, null), tableNamesList, descriptors, ".+"); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preGetTableNames verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { List<HTableDescriptor> descriptors = Lists.newArrayList(); ACCESS_CONTROLLER.preGetTableNames(ObserverContext.createAndPrepare(CP_ENV, null), descriptors, ".+"); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preCreateNamespace verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { NamespaceDescriptor ns = NamespaceDescriptor.create("test").build(); ACCESS_CONTROLLER.preCreateNamespace(ObserverContext.createAndPrepare(CP_ENV, null), ns); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preDeleteNamespace verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preDeleteNamespace(ObserverContext.createAndPrepare(CP_ENV, null), "test"); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preModifyNamespace verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { NamespaceDescriptor ns = NamespaceDescriptor.create("test").build(); ACCESS_CONTROLLER.preModifyNamespace(ObserverContext.createAndPrepare(CP_ENV, null), ns); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preGetNamespaceDescriptor verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preGetNamespaceDescriptor(ObserverContext.createAndPrepare(CP_ENV, null), "test"); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preListNamespaceDescriptors verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { List<NamespaceDescriptor> descriptors = Lists.newArrayList(); ACCESS_CONTROLLER.preListNamespaceDescriptors(ObserverContext.createAndPrepare(CP_ENV, null), descriptors); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); } /** Test region server observer */ @Test public void testPassiveRegionServerOperations() throws Exception { // preStopRegionServer verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preStopRegionServer(ObserverContext.createAndPrepare(RSCP_ENV, null)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preMerge verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName()); Region region_a = mock(Region.class); when(region_a.getTableDesc()).thenReturn(htd); Region region_b = mock(Region.class); when(region_b.getTableDesc()).thenReturn(htd); ACCESS_CONTROLLER.preMerge(ObserverContext.createAndPrepare(RSCP_ENV, null), region_a, region_b); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preRollWALWriterRequest verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preRollWALWriterRequest(ObserverContext.createAndPrepare(RSCP_ENV, null)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); } /** Test region observer */ @Test public void testPassiveRegionOperations() throws Exception { // preOpen verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preOpen(ObserverContext.createAndPrepare(RCP_ENV, null)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preFlush verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preFlush(ObserverContext.createAndPrepare(RCP_ENV, null)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preSplit verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preSplit(ObserverContext.createAndPrepare(RCP_ENV, null)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preGetClosestRowBefore verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preGetClosestRowBefore(ObserverContext.createAndPrepare(RCP_ENV, null), TEST_ROW, TEST_FAMILY, new Result()); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preGetOp verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { List<Cell> cells = Lists.newArrayList(); ACCESS_CONTROLLER.preGetOp(ObserverContext.createAndPrepare(RCP_ENV, null), new Get(TEST_ROW), cells); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preExists verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preExists(ObserverContext.createAndPrepare(RCP_ENV, null), new Get(TEST_ROW), true); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // prePut verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.prePut(ObserverContext.createAndPrepare(RCP_ENV, null), new Put(TEST_ROW), new WALEdit(), Durability.USE_DEFAULT); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preDelete verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preDelete(ObserverContext.createAndPrepare(RCP_ENV, null), new Delete(TEST_ROW), new WALEdit(), Durability.USE_DEFAULT); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preBatchMutate verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preBatchMutate(ObserverContext.createAndPrepare(RCP_ENV, null), new MiniBatchOperationInProgress<Mutation>(null, null, null, 0, 0)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preCheckAndPut verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preCheckAndPut(ObserverContext.createAndPrepare(RCP_ENV, null), TEST_ROW, TEST_FAMILY, TEST_Q1, CompareFilter.CompareOp.EQUAL, new BinaryComparator("foo".getBytes()), new Put(TEST_ROW), true); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preCheckAndDelete verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preCheckAndDelete(ObserverContext.createAndPrepare(RCP_ENV, null), TEST_ROW, TEST_FAMILY, TEST_Q1, CompareFilter.CompareOp.EQUAL, new BinaryComparator("foo".getBytes()), new Delete(TEST_ROW), true); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preAppend verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preAppend(ObserverContext.createAndPrepare(RCP_ENV, null), new Append(TEST_ROW)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preIncrement verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preIncrement(ObserverContext.createAndPrepare(RCP_ENV, null), new Increment(TEST_ROW)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preScannerOpen verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preScannerOpen(ObserverContext.createAndPrepare(RCP_ENV, null), new Scan(), mock(RegionScanner.class)); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); // preBulkLoadHFile verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { List<Pair<byte[], String>> paths = Lists.newArrayList(); ACCESS_CONTROLLER.preBulkLoadHFile(ObserverContext.createAndPrepare(RCP_ENV, null), paths); return null; } }, SUPERUSER, USER_ADMIN, USER_RW, USER_RO, USER_OWNER, USER_CREATE, USER_QUAL, USER_NONE); } @Test public void testPassiveCellPermissions() throws Exception { final Configuration conf = TEST_UTIL.getConfiguration(); // store two sets of values, one store with a cell level ACL, and one without verifyAllowed(new AccessTestAction() { @Override public Object run() throws Exception { try(Connection connection = ConnectionFactory.createConnection(conf); Table t = connection.getTable(TEST_TABLE.getTableName())) { Put p; // with ro ACL p = new Put(TEST_ROW).add(TEST_FAMILY, TEST_Q1, ZERO); p.setACL(USER_NONE.getShortName(), new Permission(Action.READ)); t.put(p); // with rw ACL p = new Put(TEST_ROW).add(TEST_FAMILY, TEST_Q2, ZERO); p.setACL(USER_NONE.getShortName(), new Permission(Action.READ, Action.WRITE)); t.put(p); // no ACL p = new Put(TEST_ROW) .add(TEST_FAMILY, TEST_Q3, ZERO) .add(TEST_FAMILY, TEST_Q4, ZERO); t.put(p); } return null; } }, USER_OWNER); // check that a scan over the test data returns the expected number of KVs final List<Cell> scanResults = Lists.newArrayList(); AccessTestAction scanAction = new AccessTestAction() { @Override public List<Cell> run() throws Exception { Scan scan = new Scan(); scan.setStartRow(TEST_ROW); scan.setStopRow(Bytes.add(TEST_ROW, new byte[]{ 0 } )); scan.addFamily(TEST_FAMILY); Connection connection = ConnectionFactory.createConnection(conf); Table t = connection.getTable(TEST_TABLE.getTableName()); try { ResultScanner scanner = t.getScanner(scan); Result result = null; do { result = scanner.next(); if (result != null) { scanResults.addAll(result.listCells()); } } while (result != null); } finally { t.close(); connection.close(); } return scanResults; } }; // owner will see all values scanResults.clear(); verifyAllowed(scanAction, USER_OWNER); assertEquals(4, scanResults.size()); // other user will also see 4 values // if cell filtering was active, we would only see 2 values scanResults.clear(); verifyAllowed(scanAction, USER_NONE); assertEquals(4, scanResults.size()); } }
apache-2.0
sghill/gocd
server/test/unit/com/thoughtworks/go/server/service/SecurityServiceTest.java
19036
/* * Copyright 2017 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.server.service; import com.thoughtworks.go.config.*; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.server.domain.Username; import org.junit.Before; import org.junit.Test; import static com.thoughtworks.go.helper.PipelineTemplateConfigMother.createTemplate; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class SecurityServiceTest { private GoConfigService goConfigService; private SecurityService securityService; @Before public void setUp() { goConfigService = mock(GoConfigService.class); when(goConfigService.security()).thenReturn(new SecurityConfig()); securityService = new SecurityService(goConfigService); } @Test public void shouldReturnTrueIfUserIsOnlyATemplateAdmin() { final Username user = new Username(new CaseInsensitiveString("user")); when(goConfigService.isGroupAdministrator(user.getUsername())).thenReturn(false); when(goConfigService.isUserAdmin(user)).thenReturn(false); SecurityService spy = spy(securityService); doReturn(true).when(spy).isAuthorizedToViewAndEditTemplates(user); assertThat(spy.canViewAdminPage(new Username(new CaseInsensitiveString("user"))), is(true)); } @Test public void shouldBeAbleToViewAdminPageIfUserCanViewTemplates() { CaseInsensitiveString username = new CaseInsensitiveString("user"); final Username user = new Username(username); CruiseConfig config = new BasicCruiseConfig(); config.addTemplate(createTemplate("s", new Authorization(new ViewConfig(new AdminUser(username))))); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isGroupAdministrator(user.getUsername())).thenReturn(false); when(goConfigService.isUserAdmin(user)).thenReturn(false); assertThat(securityService.canViewAdminPage(user), is(true)); } @Test public void shouldReturnFalseForViewingAdminPageForARegularUser() { final Username user = new Username(new CaseInsensitiveString("user")); CruiseConfig config = new BasicCruiseConfig(); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(user)).thenReturn(false); when(goConfigService.isGroupAdministrator(user.getUsername())).thenReturn(false); SecurityService spy = spy(securityService); doReturn(false).when(spy).isAuthorizedToViewAndEditTemplates(user); doReturn(false).when(spy).isAuthorizedToViewTemplates(user); assertThat(spy.canViewAdminPage(user), is(false)); } @Test public void shouldBeAbleToTellIfAUserIsAnAdmin() { Username username = new Username(new CaseInsensitiveString("user")); when(goConfigService.isUserAdmin(username)).thenReturn(Boolean.TRUE); assertThat(securityService.canViewAdminPage(username), is(true)); verify(goConfigService).isUserAdmin(username); } @Test public void shouldBeAbleToTellIfAnUserCanViewTheAdminPage() { final Username user = new Username(new CaseInsensitiveString("user")); when(goConfigService.isGroupAdministrator(user.getUsername())).thenReturn(Boolean.TRUE); assertThat(securityService.canViewAdminPage(new Username(new CaseInsensitiveString("user"))), is(true)); } @Test public void shouldBeAbleToTellIfAnUserISNotAllowedToViewTheAdminPage() { final Username user = new Username(new CaseInsensitiveString("user")); when(goConfigService.isGroupAdministrator(user.getUsername())).thenReturn(Boolean.FALSE); SecurityService spy = spy(securityService); doReturn(false).when(spy).isAuthorizedToViewAndEditTemplates(user); doReturn(false).when(spy).isAuthorizedToViewTemplates(user); assertThat(spy.canViewAdminPage(new Username(new CaseInsensitiveString("user"))), is(false)); } @Test public void shouldBeAbleToCreatePipelineIfUserIsSuperOrPipelineGroupAdmin() { final Username groupAdmin = new Username(new CaseInsensitiveString("groupAdmin")); when(goConfigService.isGroupAdministrator(groupAdmin.getUsername())).thenReturn(Boolean.TRUE); final Username admin = new Username(new CaseInsensitiveString("admin")); when(goConfigService.isGroupAdministrator(admin.getUsername())).thenReturn(Boolean.TRUE); assertThat(securityService.canCreatePipelines(new Username(new CaseInsensitiveString("groupAdmin"))), is(true)); assertThat(securityService.canCreatePipelines(new Username(new CaseInsensitiveString("admin"))), is(true)); } @Test public void shouldNotBeAbleToCreatePipelineIfUserIsTemplateAdmin() { final Username user = new Username(new CaseInsensitiveString("user")); when(goConfigService.isGroupAdministrator(user.getUsername())).thenReturn(false); when(goConfigService.isUserAdmin(user)).thenReturn(false); SecurityService spy = spy(securityService); doReturn(true).when(spy).isAuthorizedToViewAndEditTemplates(user); assertThat(spy.canCreatePipelines(new Username(new CaseInsensitiveString("user"))), is(false)); } @Test public void shouldSayThatAUserIsAuthorizedToEditTemplateWhenTheUserIsAnAdminOfThisTemplate() throws Exception { CruiseConfig config = new BasicCruiseConfig(); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); CaseInsensitiveString templateAdminName = new CaseInsensitiveString("templateAdmin"); GoConfigMother.enableSecurityWithPasswordFilePlugin(config); GoConfigMother.addUserAsSuperAdmin(config, "theSuperAdmin"); config.addTemplate(createTemplate("template", new Authorization(new AdminsConfig(new AdminUser(templateAdminName))))); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(templateAdminName))).thenReturn(false); assertThat(securityService.isAuthorizedToEditTemplate(templateName, new Username(templateAdminName)), is(true)); assertThat(securityService.isAuthorizedToEditTemplate(templateName, new Username(new CaseInsensitiveString("someOtherUserWhoIsNotAnAdmin"))), is(false)); } @Test public void shouldSayThatAUserIsAuthorizedToEditTemplateWhenTheUserIsASuperAdmin() throws Exception { CruiseConfig cruiseConfig = new BasicCruiseConfig(); String adminName = "theSuperAdmin"; CaseInsensitiveString templateName = new CaseInsensitiveString("template"); GoConfigMother.enableSecurityWithPasswordFilePlugin(cruiseConfig); GoConfigMother.addUserAsSuperAdmin(cruiseConfig, adminName).addTemplate(createTemplate("template")); when(goConfigService.cruiseConfig()).thenReturn(cruiseConfig); when(goConfigService.isUserAdmin(new Username(new CaseInsensitiveString(adminName)))).thenReturn(true); assertThat(securityService.isAuthorizedToEditTemplate(templateName, new Username(new CaseInsensitiveString(adminName))), is(true)); } @Test public void shouldSayThatAUserIsAuthorizedToViewAndEditTemplatesWhenTheUserHasPermissionsForAtLeastOneTemplate() throws Exception { CruiseConfig config = new BasicCruiseConfig(); String theSuperAdmin = "theSuperAdmin"; String templateName = "template"; String secondTemplateName = "secondTemplate"; CaseInsensitiveString templateAdminName = new CaseInsensitiveString("templateAdmin"); CaseInsensitiveString secondTemplateAdminName = new CaseInsensitiveString("secondTemplateAdmin"); GoConfigMother.enableSecurityWithPasswordFilePlugin(config); GoConfigMother.addUserAsSuperAdmin(config, theSuperAdmin); config.addTemplate(createTemplate(templateName, new Authorization(new AdminsConfig(new AdminUser(templateAdminName))))); config.addTemplate(createTemplate(secondTemplateName, new Authorization(new AdminsConfig(new AdminUser(secondTemplateAdminName))))); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(templateAdminName))).thenReturn(false); when(goConfigService.isUserAdmin(new Username(secondTemplateName))).thenReturn(false); when(goConfigService.isUserAdmin(new Username(new CaseInsensitiveString(theSuperAdmin)))).thenReturn(true); when(goConfigService.isUserAdmin(new Username(new CaseInsensitiveString("someOtherUserWhoIsNotAdminOfAnyTemplates")))).thenReturn(false); assertThat(securityService.isAuthorizedToViewAndEditTemplates(new Username(templateAdminName)), is(true)); assertThat(securityService.isAuthorizedToViewAndEditTemplates(new Username(secondTemplateAdminName)), is(true)); assertThat(securityService.isAuthorizedToViewAndEditTemplates(new Username(new CaseInsensitiveString(theSuperAdmin))), is(true)); assertThat(securityService.isAuthorizedToViewAndEditTemplates(new Username(new CaseInsensitiveString("someOtherUserWhoIsNotAdminOfAnyTemplates"))), is(false)); } @Test public void shouldReturnTrueForSuperAdminToViewTemplateConfiguration() { BasicCruiseConfig cruiseConfig = getCruiseConfigWithSecurityEnabled(); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); Username admin = new Username(new CaseInsensitiveString("admin")); GoConfigMother.addUserAsSuperAdmin(cruiseConfig, "admin").addTemplate(createTemplate("template")); when(goConfigService.cruiseConfig()).thenReturn(cruiseConfig); when(goConfigService.isUserAdmin(admin)).thenReturn(true); assertThat(securityService.isAuthorizedToViewTemplate(templateName, admin), is(true)); } @Test public void shouldReturnTrueForTemplateAdminsToViewTemplateConfiguration() { CruiseConfig config = getCruiseConfigWithSecurityEnabled(); CaseInsensitiveString templateAdmin = new CaseInsensitiveString("templateAdmin"); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); config.addTemplate(createTemplate("template", new Authorization(new AdminsConfig(new AdminUser(templateAdmin))))); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(templateAdmin))).thenReturn(false); assertThat(securityService.isAuthorizedToViewTemplate(templateName, new Username(templateAdmin)), is(true)); } @Test public void shouldReturnTrueForTemplateViewUsersToViewTemplateConfiguration() { CruiseConfig config = getCruiseConfigWithSecurityEnabled(); CaseInsensitiveString templateViewUser = new CaseInsensitiveString("templateView"); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); config.addTemplate(createTemplate("template", new Authorization(new ViewConfig(new AdminUser(templateViewUser))))); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(templateViewUser))).thenReturn(false); assertThat(securityService.isAuthorizedToViewTemplate(templateName, new Username(templateViewUser)), is(true)); } @Test public void shouldReturnTrueForGroupAdminsToViewTemplateConfigurationByDefault() { CruiseConfig config = getCruiseConfigWithSecurityEnabled(); CaseInsensitiveString groupAdmin = new CaseInsensitiveString("groupAdmin"); setUpGroupWithAuthorization(config, new Authorization(new AdminsConfig(new AdminUser(groupAdmin)))); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); config.addTemplate(createTemplate("template")); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(groupAdmin))).thenReturn(false); when(goConfigService.isGroupAdministrator(groupAdmin)).thenReturn(true); assertThat(securityService.isAuthorizedToViewTemplate(templateName, new Username(groupAdmin)), is(true)); } @Test public void shouldReturnFalseForGroupAdminsToViewTemplateConfigurationIfDisallowed() { CruiseConfig config = getCruiseConfigWithSecurityEnabled(); CaseInsensitiveString groupAdmin = new CaseInsensitiveString("groupAdmin"); setUpGroupWithAuthorization(config, new Authorization(new AdminsConfig(new AdminUser(groupAdmin)))); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); PipelineTemplateConfig template = createTemplate("template"); template.getAuthorization().setAllowGroupAdmins(false); config.addTemplate(template); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(groupAdmin))).thenReturn(false); when(goConfigService.isGroupAdministrator(groupAdmin)).thenReturn(true); assertThat(securityService.isAuthorizedToViewTemplate(templateName, new Username(groupAdmin)), is(false)); } @Test public void shouldReturnTrueForGroupAdminsWithinARoleToViewTemplate() { CaseInsensitiveString groupAdmin = new CaseInsensitiveString("groupAdmin"); BasicCruiseConfig config = new BasicCruiseConfig(); ServerConfig serverConfig = new ServerConfig(new SecurityConfig(new AdminsConfig(new AdminUser(new CaseInsensitiveString("admin")))), null); RoleConfig role = new RoleConfig(new CaseInsensitiveString("role1"), new RoleUser(groupAdmin)); serverConfig.security().addRole(role); config.setServerConfig(serverConfig); GoConfigMother.enableSecurityWithPasswordFilePlugin(config); setUpGroupWithAuthorization(config, new Authorization(new AdminsConfig(new AdminRole(role)))); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); config.addTemplate(createTemplate("template")); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(groupAdmin))).thenReturn(false); when(goConfigService.isGroupAdministrator(groupAdmin)).thenReturn(true); assertThat(securityService.isAuthorizedToViewTemplate(templateName, new Username(groupAdmin)), is(true)); } @Test public void shouldReturnFalseForGroupAdminsWithinARoleToVIewTemplateIfDisallowed() { CaseInsensitiveString groupAdmin = new CaseInsensitiveString("groupAdmin"); BasicCruiseConfig config = new BasicCruiseConfig(); ServerConfig serverConfig = new ServerConfig(new SecurityConfig(new AdminsConfig(new AdminUser(new CaseInsensitiveString("admin")))), null); RoleConfig role = new RoleConfig(new CaseInsensitiveString("role1"), new RoleUser(groupAdmin)); serverConfig.security().addRole(role); config.setServerConfig(serverConfig); GoConfigMother.enableSecurityWithPasswordFilePlugin(config); setUpGroupWithAuthorization(config, new Authorization(new AdminsConfig(new AdminRole(role)))); CaseInsensitiveString templateName = new CaseInsensitiveString("template"); PipelineTemplateConfig template = createTemplate("template"); template.getAuthorization().setAllowGroupAdmins(false); config.addTemplate(template); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(groupAdmin))).thenReturn(false); when(goConfigService.isGroupAdministrator(groupAdmin)).thenReturn(true); assertThat(securityService.isAuthorizedToViewTemplate(templateName, new Username(groupAdmin)), is(false)); } @Test public void shouldSayUserIsAuthorizedToViewTemplatesWhenTheUserHasViewPermissionsToAtLeastOneTemplate() { CruiseConfig config = new BasicCruiseConfig(); String theSuperAdmin = "theSuperAdmin"; String templateName = "template"; String secondTemplateName = "secondTemplate"; CaseInsensitiveString templateAdminName = new CaseInsensitiveString("templateAdmin"); CaseInsensitiveString templateViewUser = new CaseInsensitiveString("templateViewUser"); GoConfigMother.enableSecurityWithPasswordFilePlugin(config); GoConfigMother.addUserAsSuperAdmin(config, theSuperAdmin); config.addTemplate(createTemplate(templateName, new Authorization(new AdminsConfig(new AdminUser(templateAdminName))))); config.addTemplate(createTemplate(secondTemplateName, new Authorization(new ViewConfig(new AdminUser(templateViewUser))))); when(goConfigService.cruiseConfig()).thenReturn(config); when(goConfigService.isUserAdmin(new Username(templateAdminName))).thenReturn(false); when(goConfigService.isUserAdmin(new Username(templateViewUser))).thenReturn(false); when(goConfigService.isUserAdmin(new Username(new CaseInsensitiveString(theSuperAdmin)))).thenReturn(true); when(goConfigService.isUserAdmin(new Username(new CaseInsensitiveString("regularUser")))).thenReturn(false); assertThat(securityService.isAuthorizedToViewTemplates(new Username(templateAdminName)), is(true)); assertThat(securityService.isAuthorizedToViewTemplates(new Username(templateViewUser)), is(true)); assertThat(securityService.isAuthorizedToViewTemplates(new Username(new CaseInsensitiveString(theSuperAdmin))), is(true)); assertThat(securityService.isAuthorizedToViewTemplates(new Username(new CaseInsensitiveString("regularUser"))), is(false)); } private BasicCruiseConfig getCruiseConfigWithSecurityEnabled() { BasicCruiseConfig cruiseConfig = new BasicCruiseConfig(); ServerConfig serverConfig = new ServerConfig(new SecurityConfig(new AdminsConfig(new AdminUser(new CaseInsensitiveString("admin")))), null); cruiseConfig.setServerConfig(serverConfig); GoConfigMother.enableSecurityWithPasswordFilePlugin(cruiseConfig); return cruiseConfig; } private void setUpGroupWithAuthorization(CruiseConfig config, Authorization authorization) { new GoConfigMother().addPipelineWithGroup(config, "group", "pipeline", "stage", "job"); config.getGroups().findGroup("group").setAuthorization(authorization); } }
apache-2.0
zhangguangyong/codes
codes-platform/src/main/java/com/codes/platform/system/service/IDictionaryService.java
354
package com.codes.platform.system.service; import com.codes.platform.base.service.EntityService; import com.codes.platform.system.domain.Dictionary; /** * 字典-业务接口 * * @author zhangguangyong * * 2015年11月5日 下午5:13:28 */ public interface IDictionaryService extends EntityService<Dictionary, Integer> { }
apache-2.0
huihoo/olat
olat7.8/src/main/java/org/olat/lms/course/imports/ImportGlossaryEBL.java
6437
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <p> */ package org.olat.lms.course.imports; import java.io.File; import java.security.Principal; import org.apache.log4j.Logger; import org.olat.data.basesecurity.Identity; import org.olat.data.basesecurity.SecurityGroup; import org.olat.data.commons.fileutil.ZipUtil; import org.olat.data.commons.vfs.LocalFileImpl; import org.olat.data.commons.vfs.VFSContainer; import org.olat.data.repository.RepositoryEntry; import org.olat.data.resource.OLATResource; import org.olat.data.resource.OLATResourceManager; import org.olat.lms.commons.fileresource.GlossaryResource; import org.olat.lms.course.CourseFactory; import org.olat.lms.course.ICourse; import org.olat.lms.course.config.CourseConfig; import org.olat.lms.glossary.GlossaryManager; import org.olat.lms.reference.ReferenceService; import org.olat.lms.repository.RepositoryService; import org.olat.lms.repository.RepositoryEntryImportExport; import org.olat.lms.repository.handlers.RepositoryHandler; import org.olat.lms.repository.handlers.RepositoryHandlerFactory; import org.olat.lms.security.BaseSecurityEBL; import org.olat.system.commons.resource.OLATResourceable; import org.olat.system.logging.log4j.LoggerHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * TODO: Class Description for ImportGlossaryEBL * * <P> * Initial Date: 02.09.2011 <br> * * @author lavinia */ @Component public class ImportGlossaryEBL { private static final Logger log = LoggerHelper.getLogger(); @Autowired private RepositoryService repositoryService; @Autowired private OLATResourceManager oLATResourceManager; @Autowired private ReferenceService referenceService; @Autowired private BaseSecurityEBL baseSecurityEBL; private ImportGlossaryEBL() { } /** * Import a referenced repository entry. * * @param importExport * @param node * @param importMode * Type of import. * @param keepSoftkey * If true, no new softkey will be generated. * @param owner * @return */ public RepositoryEntry doImport(final RepositoryEntryImportExport importExport, final ICourse course, final boolean keepSoftkey, final Identity owner) { final GlossaryResource resource = createAndImportGlossaryResource(importExport); final RepositoryEntry importedRepositoryEntry = createRepositoryEntry(importExport, keepSoftkey, owner, resource); final SecurityGroup newGroup = baseSecurityEBL.createOwnerGroupWithIdentity(owner); importedRepositoryEntry.setOwnerGroup(newGroup); repositoryService.saveRepositoryEntry(importedRepositoryEntry); if (!keepSoftkey) { addReferenceAndUpdateCourseConfig(course, importedRepositoryEntry); } return importedRepositoryEntry; } /** * Creates the GlossaryResource and unzips the exported file into the glossary container. * * @param importExport * @return */ private GlossaryResource createAndImportGlossaryResource(final RepositoryEntryImportExport importExport) { final GlossaryManager gm = GlossaryManager.getInstance(); final GlossaryResource resource = gm.createGlossary(); if (resource == null) { log.error("Error adding glossary directry during repository reference import: " + importExport.getDisplayName()); return null; } // unzip contents final VFSContainer glossaryContainer = gm.getGlossaryRootFolder(resource); final File fExportedFile = importExport.getExportedFile(); if (fExportedFile.exists()) { ZipUtil.unzip(new LocalFileImpl(fExportedFile), glossaryContainer); } else { log.warn("The actual contents of the glossary were not found in the export."); } return resource; } private RepositoryEntry createRepositoryEntry(final RepositoryEntryImportExport importExport, final boolean keepSoftkey, final Principal owner, final OLATResourceable resourceable) { // create repository entry final RepositoryEntry importedRepositoryEntry = repositoryService.createRepositoryEntryInstance(owner.getName()); importedRepositoryEntry.setDisplayname(importExport.getDisplayName()); importedRepositoryEntry.setResourcename(importExport.getResourceName()); importedRepositoryEntry.setDescription(importExport.getDescription()); if (keepSoftkey) { importedRepositoryEntry.setSoftkey(importExport.getSoftkey()); } // Set the resource on the repository entry. final OLATResource ores = oLATResourceManager.findOrPersistResourceable(resourceable); importedRepositoryEntry.setOlatResource(ores); final RepositoryHandler rh = RepositoryHandlerFactory.getInstance().getRepositoryHandler(importedRepositoryEntry); importedRepositoryEntry.setCanLaunch(rh.supportsLaunch(importedRepositoryEntry)); return importedRepositoryEntry; } private void addReferenceAndUpdateCourseConfig(final ICourse course, final RepositoryEntry importedRepositoryEntry) { // set the new glossary reference final CourseConfig courseConfig = course.getCourseEnvironment().getCourseConfig(); courseConfig.setGlossarySoftKey(importedRepositoryEntry.getSoftkey()); referenceService.addReference(course, importedRepositoryEntry.getOlatResource(), GlossaryManager.GLOSSARY_REPO_REF_IDENTIFYER); CourseFactory.setCourseConfig(course.getResourceableId(), courseConfig); } }
apache-2.0
jcechace/apiman
gateway/platforms/vertx3/vertx3/src/test/java/io/apiman/gateway/platforms/vertx3/connector/HttpConnectorDrainTest.java
6768
/* * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.gateway.platforms.vertx3.connector; import io.apiman.gateway.engine.async.IAsyncHandler; import io.apiman.gateway.engine.beans.Api; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.io.IApimanBuffer; import io.apiman.gateway.engine.io.ISignalWriteStream; import io.apiman.gateway.platforms.vertx3.io.VertxApimanBuffer; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import java.net.URI; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * <p> * Test to ensure drain handler fires as expected; when the write queue has been exceeded, and * thus advertises itself as full {@link ISignalWriteStream#isFull}. This enables a simple * back-pressure mechanism which enables the corresponding ingress point to be paused (thus * backing off) until load has decreased. * </p> * <p> * The server then calls {@link HttpServerRequest#resume()}, allowing the queued data to flow * through, simulating a scenario in which the backlog has been cleared. Once the queue has * sufficiently diminished, {@link ISignalWriteStream#drainHandler(IAsyncHandler)} will be * called to indicate that the client can begin sending again. * </p> * <p> * Order of operations: * <ul> * <li>HTTP server initiated which immediately {@link HttpServerRequest#pause()}es any received * requests.</li> * <li>Invoke {@link HttpConnector#write(IApimanBuffer)} on connector until it indicates the * queue {@link HttpConnector#isFull()}.</li> * <li>{@link HttpServerRequest#resume} HTTP server to consume (and thus reduce) incoming * queue.</li> * <li>{@link ISignalWriteStream#drainHandler(IAsyncHandler)} is invoked once queue is * sufficiently small (as determined by impl which at time of writing is maxSize/2).</li> * </ul> * * <p> * The drain handler is sometimes called multiple times, I think it's okay though. * </p> * * @author Marc Savy {@literal <msavy@redhat.com>} */ @SuppressWarnings("nls") @RunWith(VertxUnitRunner.class) public class HttpConnectorDrainTest { final Api api = new Api(); { api.setApiId(""); api.setEndpoint("http://localhost:7297"); api.setOrganizationId(""); api.setParsePayload(false); api.setPublicAPI(true); api.setVersion(""); } final ApiRequest request = new ApiRequest(); { request.setApi(api); request.setApiId(""); request.setApiKey(""); request.setApiOrgId(""); request.setApiVersion(""); request.setDestination("/"); request.setType("POST"); } HttpServer server; boolean stop = false; HttpServerRequest pausedRequest = null; @Before public void setup() { } @Test public void shouldTriggerDrainHandler(TestContext context) throws Exception { Async asyncDrain = context.async(2); Async asyncServer = context.async(); server = Vertx.vertx().createHttpServer() .connectionHandler(connection -> { System.out.println("Connection"); }) .requestHandler(requestToPause -> { System.out.println("Test server: pausing inbound request!"); requestToPause.pause(); pausedRequest = requestToPause; asyncServer.complete(); requestToPause.handler(data -> {}); }).listen(7297); Vertx vertx = Vertx.vertx(); HttpConnector httpConnector = new HttpConnector(vertx, vertx.createHttpClient(), request, api, new ApimanHttpConnectorOptions() .setHasDataPolicy(true) .setUri(URI.create(api.getEndpoint())), result -> {}); // Should be fired when write queue reduces to acceptable size. httpConnector.drainHandler(drain -> { System.err.println("Drain handler has been called! Yay."); stop = true; asyncDrain.complete(); }); // Keep sending until stop is called (or reasonable upper bound.) for (int i=0; i<100000 && !httpConnector.isFull(); i++) { httpConnector.write(new VertxApimanBuffer("Anonyme\n" + "Aride\n" + "Bird Island\n" + "Cerf\n" + "Chauve Souris\n" + "Conception\n" + "Cousin\n" + "Cousine\n" + "Curieuse\n" + "Denis Island\n" + "Frégate\n" + "Félicité\n" + "Grande Soeur\n" + "Ile Cocos\n" + "La Digue\n" + "Long Island\n" + "Mahé\n" + "Moyenne\n" + "North Island\n" + "Others\n" + "Petite Soeur\n" + "Praslin\n" + "Round Island\n" + "Silhouette\n" + "St. Pierre\n" + "Ste. Anne")); } System.out.println("Connection is full? " + httpConnector.isFull()); Assert.assertTrue(httpConnector.isFull()); System.out.println("Waiting for server..."); asyncServer.await(); System.out.println("Connection is still full? " + httpConnector.isFull()); Assert.assertTrue(httpConnector.isFull()); System.out.println("Resuming #pause()d server request; waiting packets should be consumed by the server."); pausedRequest.resume(); System.out.println("Waiting for drain to be called..."); asyncDrain.await(); System.out.println("Called end on client. Should no longer be full!"); Assert.assertFalse(httpConnector.isFull()); httpConnector.end(); } }
apache-2.0
tiobe/closure-compiler
test/com/google/javascript/jscomp/Es6RewriteRestAndSpreadTest.java
20993
/* * Copyright 2014 The Closure Compiler 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.javascript.jscomp; import static com.google.common.truth.Truth.assertThat; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.CompilerTestCase.NoninjectingCompiler; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class Es6RewriteRestAndSpreadTest extends CompilerTestCase { public Es6RewriteRestAndSpreadTest() { super(MINIMAL_EXTERNS); } @Override protected CompilerPass getProcessor(Compiler compiler) { return new Es6RewriteRestAndSpread(compiler); } @Override protected int getNumRepetitions() { return 1; } @Override protected Compiler createCompiler() { return new NoninjectingCompiler(); } @Override protected NoninjectingCompiler getLastCompiler() { return (NoninjectingCompiler) super.getLastCompiler(); } @Override @Before public void setUp() throws Exception { super.setUp(); setAcceptedLanguage(LanguageMode.ECMASCRIPT_2016); setLanguageOut(LanguageMode.ECMASCRIPT3); enableTypeInfoValidation(); enableTypeCheck(); } // Spreading into array literals. @Test public void testSpreadArrayLiteralIntoArrayLiteral() { test("[...[1, 2], 3, ...[4], 5, 6, ...[], 7, 8]", "[1, 2, 3, 4, 5, 6, 7, 8]"); } @Test public void testSpreadVariableIntoArrayLiteral() { test( "var arr = [1, 2, ...mid, 4, 5];", "var arr = [1, 2].concat($jscomp.arrayFromIterable(mid), [4, 5]);"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionReturnIntoArrayLiteral() { test( "var arr = [1, 2, ...mid(), 4, 5];", "var arr = [1, 2].concat($jscomp.arrayFromIterable(mid()), [4, 5]);"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionArgumentsIntoArrayLiteral() { test( "function f() { return [...arguments, 2]; };", lines( "function f() {", " return [].concat($jscomp.arrayFromIterable(arguments), [2]);", "};")); } @Test public void testSpreadVariableAndFunctionReturnIntoArrayLiteral() { test( "var arr = [1, 2, ...mid, ...mid2(), 4, 5];", lines( "var arr = [1,2].concat(", " $jscomp.arrayFromIterable(mid), $jscomp.arrayFromIterable(mid2()), [4, 5]);")); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionReturnIntoEntireArrayLiteral() { test("var arr = [...mid()];", "var arr = [].concat($jscomp.arrayFromIterable(mid()));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionArgumentsIntoEntireArrayLiteral() { test( "function f() { return [...arguments]; };", lines("function f() {", " return [].concat($jscomp.arrayFromIterable(arguments));", "};")); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadArrayLiteralIntoArrayLiteralWithinParameterList() { test("f(1, [2, ...[3], 4], 5);", "f(1, [2, 3, 4], 5);"); } @Test public void testSpreadVariableIntoArrayLiteralWithinParameterList() { test("f(1, [2, ...mid, 4], 5);", "f(1, [2].concat($jscomp.arrayFromIterable(mid), [4]), 5);"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionReturnIntoArrayLiteralWithinParameterList() { test( "f(1, [2, ...mid(), 4], 5);", "f(1, [2].concat($jscomp.arrayFromIterable(mid()), [4]), 5);"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } // Spreading into parameter lists. @Test public void testSpreadArrayLiteralIntoEntireParameterList() { test("f(...[0, 1, 2]);", "f.apply(null, [0, 1, 2]);"); } @Test public void testSpreadArrayLiteralIntoParameterList() { test("f(...[0, 1, 2], 3);", "f.apply(null, [0, 1, 2, 3]);"); } @Test public void testSpreadVariableIntoEntireParameterList() { test("f(...arr);", "f.apply(null, $jscomp.arrayFromIterable(arr));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoParameterList() { test("f(0, ...arr, 2);", "f.apply(null, [0].concat($jscomp.arrayFromIterable(arr), [2]));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionReturnIntoEntireParameterList() { test("f(...g());", "f.apply(null, $jscomp.arrayFromIterable(g()));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadFunctionReturnIntoParameterList() { test("f(0, ...g(), 2);", "f.apply(null, [0].concat($jscomp.arrayFromIterable(g()), [2]));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoIifeParameterList() { test("(function() {})(...arr);", "(function() {}).apply(null, $jscomp.arrayFromIterable(arr))"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoAnonymousFunctionParameterList() { test("getF()(...args);", "getF().apply(null, $jscomp.arrayFromIterable(args));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoMethodParameterList() { test( externs( lines( "/**", " * @constructor", " * @struct", " */", "function TestClass() { }", "", "/** @param {...string} args */", "TestClass.prototype.testMethod = function(args) { }", "", "/** @return {!TestClass} */", "function testClassFactory() { }")), srcs(lines("var obj = new TestClass();", "obj.testMethod(...arr);")), expected( lines( "var obj = new TestClass();", "obj.testMethod.apply(obj, $jscomp.arrayFromIterable(arr));"))); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoDeepMethodParameterList() { test( externs( MINIMAL_EXTERNS + lines( "/** @param {...number} args */ function numberVarargFn(args) { }", "", "/** @type {!Iterable<number>} */ var numberIterable;")), srcs(lines("var x = {y: {z: {m: numberVarargFn}}};", "x.y.z.m(...numberIterable);")), expected( lines( "var x = {y: {z: {m: numberVarargFn}}};", "x.y.z.m.apply(x.y.z, $jscomp.arrayFromIterable(numberIterable));"))); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadMultipleArrayLiteralsIntoParameterList() { test( externs( MINIMAL_EXTERNS + "/** @param {...number} args */ function numberVarargFn(args) { }"), srcs("numberVarargFn(...[1, 2], 3, ...[4, 5], 6, ...[7, 8])"), expected("numberVarargFn.apply(null, [1, 2, 3, 4, 5, 6, 7, 8])")); } @Test public void testSpreadMultipleVariablesIntoParameterList() { test( externs( MINIMAL_EXTERNS + lines( "/** @param {...number} args */ function numberVarargFn(args) { }", "/** @type {!Iterable<number>} */ var numberIterable;")), srcs("numberVarargFn(0, ...numberIterable, 2, ...numberIterable, 4);"), expected( lines( "numberVarargFn.apply(", " null,", " [0].concat(", " $jscomp.arrayFromIterable(numberIterable),", " [2],", " $jscomp.arrayFromIterable(numberIterable),", " [4]));"))); } @Test public void testSpreadVariableIntoMethodParameterListOnAnonymousRecieverWithSideEffects() { test( externs( MINIMAL_EXTERNS + lines( "/**", " * @constructor", " * @struct", " */", "function TestClass() { }", "", "/** @param {...string} args */", "TestClass.prototype.testMethod = function(args) { }", "", "/** @return {!TestClass} */", "function testClassFactory() { }", "", "/** @type {!Iterable<string>} */ var stringIterable;")), srcs("testClassFactory().testMethod(...stringIterable);"), expected( lines( "var $jscomp$spread$args0;", "($jscomp$spread$args0 = testClassFactory()).testMethod.apply(", " $jscomp$spread$args0, $jscomp.arrayFromIterable(stringIterable));"))); } @Test public void testSpreadVariableIntoMethodParameterListOnConditionalRecieverWithSideEffects() { test( externs( MINIMAL_EXTERNS + lines( "/**", " * @constructor", " * @struct", " */", "function TestClass() { }", "", "/** @param {...string} args */", "TestClass.prototype.testMethod = function(args) { }", "", "/** @return {!TestClass} */", "function testClassFactory() { }", "", "/** @type {!Iterable<string>} */ var stringIterable;")), srcs("var x = b ? testClassFactory().testMethod(...stringIterable) : null;"), expected( lines( "var $jscomp$spread$args0;", "var x = b ? ($jscomp$spread$args0 = testClassFactory()).testMethod.apply(", " $jscomp$spread$args0, $jscomp.arrayFromIterable(stringIterable))", " : null;"))); } public void testSpreadVariableIntoMethodParameterListOnRecieversWithSideEffectsMultipleTimesInOneScope() { test( externs( MINIMAL_EXTERNS + lines( "/**", " * @constructor", " * @struct", " */", "function TestClass() { }", "", "/** @param {...string} args */", "TestClass.prototype.testMethod = function(args) { }", "", "/** @return {!TestClass} */", "function testClassFactory() { }", "", "/** @type {!Iterable<string>} */ var stringIterable;")), srcs( lines( "testClassFactory().testMethod(...stringIterable);", "testClassFactory().testMethod(...stringIterable);")), expected( lines( "var $jscomp$spread$args0;", "($jscomp$spread$args0 = testClassFactory()).testMethod.apply(", " $jscomp$spread$args0, $jscomp.arrayFromIterable(stringIterable));", "var $jscomp$spread$args1;", "($jscomp$spread$args1 = testClassFactory()).testMethod.apply(", " $jscomp$spread$args1, $jscomp.arrayFromIterable(stringIterable));"))); } @Test public void testSpreadFunctionArgumentsIntoSuperParameterList() { // TODO(b/76024335): Enable these validations and checks. // We need to test super, but super only makes sense in the context of a class, but // the type-checker doesn't understand class syntax and fails before the test even runs. disableTypeInfoValidation(); disableTypeCheck(); test( lines( "class A {", " constructor(a) {", " this.p = a;", " }", "}", "", "class B extends A {", " constructor(a) {", " super(0, ...arguments, 2);", " }", "}"), // The `super.apply` syntax below is invalid, but won't survive other transpilation passes. lines( "class A {", " constructor(a) {", " this.p = a;", " }", "}", "", "class B extends A {", " constructor(a) {", " super.apply(null, [0].concat($jscomp.arrayFromIterable(arguments), [2]));", " }", "}")); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoSuperParameterList() { // TODO(b/76024335): Enable these validations and checks. // We need to test super, but super only makes sense in the context of a class, but // the type-checker doesn't understand class syntax and fails before the test even runs. disableTypeInfoValidation(); disableTypeCheck(); test( lines( "class D {}", "", "class C extends D {", " constructor(args) {", " super(0, ...args, 2)", " }", "}"), // The `super.apply` syntax below is invalid, but won't survive other transpilation passes. lines( "class D {}", "", "class C extends D {", " constructor(args) {", " super.apply(null, [0].concat($jscomp.arrayFromIterable(args), [2]));", " }", "}")); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoParameterListWithinArrayLiteral() { test( "[1, f(2, ...mid, 4), 5];", "[1, f.apply(null, [2].concat($jscomp.arrayFromIterable(mid), [4])), 5];"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } @Test public void testSpreadVariableIntoNew() { setLanguageOut(LanguageMode.ECMASCRIPT5); test( "new F(...args);", "new (Function.prototype.bind.apply(F, [null].concat($jscomp.arrayFromIterable(args))));"); assertThat(getLastCompiler().injected).containsExactly("es6/util/arrayfromiterable"); } // Rest parameters @Test public void testUnusedRestParameterAtPositionZero() { test("function f(...zero) {}", "function f(zero) {}"); } @Test public void testUnusedRestParameterAtPositionOne() { test("function f(zero, ...one) {}", "function f(zero, one) {}"); } @Test public void testUnusedRestParameterAtPositionTwo() { test("function f(zero, one, ...two) {}", "function f(zero, one, two) {}"); } @Test public void testUsedRestParameterAtPositionZero() { test( "function f(...zero) { return zero; }", lines( "function f(zero) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 0; $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 0] = arguments[$jscomp$restIndex];", " }", " {", " let zero = $jscomp$restParams;", " return zero;", " }", "}")); } @Test public void testUsedRestParameterAtPositionTwo() { test( "function f(zero, one, ...two) { return two; }", lines( "function f(zero, one, two) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 2; $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 2] = arguments[$jscomp$restIndex];", " }", " {", " let two = $jscomp$restParams;", " return two;", " }", "}")); } @Test public void testUnusedRestParameterAtPositionZeroWithTypingOnFunction() { test( "/** @param {...number} zero */ function f(...zero) {}", "/** @param {...number} zero */ function f(zero) {}"); } @Test public void testUnusedRestParameterAtPositionZeroWithInlineTyping() { test("function f(/** ...number */ ...zero) {}", "function f(/** ...number */ zero) {}"); } @Test public void testUsedRestParameterAtPositionTwoWithTypingOnFunction() { test( "/** @param {...number} two */ function f(zero, one, ...two) { return two; }", lines( "/** @param {...number} two */", "function f(zero, one, two) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 2; $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 2] = arguments[$jscomp$restIndex];", " }", " {", " let two = $jscomp$restParams;", " return two;", " }", "}")); } @Test public void testUsedRestParameterAtPositionTwoWithTypingOnFunctionVariable() { test( "/** @param {...number} two */ var f = function(zero, one, ...two) { return two; }", lines( "/** @param {...number} two */ var f = function(zero, one, two) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 2; $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 2] = arguments[$jscomp$restIndex];", " }", " {", " let two = $jscomp$restParams;", " return two;", " }", "}")); } @Test public void testUsedRestParameterAtPositionTwoWithTypingOnFunctionProperty() { test( "/** @param {...number} two */ ns.f = function(zero, one, ...two) { return two; }", lines( "/** @param {...number} two */ ns.f = function(zero, one, two) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 2; $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 2] = arguments[$jscomp$restIndex];", " }", " {", " let two = $jscomp$restParams;", " return two;", " }", "}")); } @Test public void testWarningAboutRestParameterMissingInlineVarArgTyping() { // Warn on /** number */ testWarning( "function f(/** number */ ...zero) {}", Es6RewriteRestAndSpread.BAD_REST_PARAMETER_ANNOTATION); } @Test public void testWarningAboutRestParameterMissingVarArgTypingOnFunction() { testWarning( "/** @param {number} zero */ function f(...zero) {}", Es6RewriteRestAndSpread.BAD_REST_PARAMETER_ANNOTATION); } @Test public void testUnusedRestParameterAtPositionTwoWithUsedParameterAtPositionOne() { test( "function f(zero, one, ...two) {one = (one === undefined) ? 1 : one;}", lines( "function f(zero, one, two) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 2; $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 2] = arguments[$jscomp$restIndex];", " }", " {", " let two = $jscomp$restParams;", " one = (one === undefined) ? 1 : one;", " }", "}")); } }
apache-2.0
JyotsnaGorle/twu_biblioteca_jyotsna
src/com/twu/biblioteca/BibliotecaApp.java
4649
package com.twu.biblioteca; import com.twu.biblioteca.domainObjects.Admin; import com.twu.biblioteca.domainObjects.Book; import com.twu.biblioteca.domainObjects.Movie; import com.twu.biblioteca.inputOutputDevice.ConsoleIODevice; import com.twu.biblioteca.inputOutputDevice.InputOutputManager; import com.twu.biblioteca.menuObjects.IMenuItem; import com.twu.biblioteca.menuObjects.Menu; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Created by jyotsna on 25/02/15. */ public class BibliotecaApp { private InputOutputManager inputOutputManager; private LibraryMemberCredentials libraryMemberCredentials; private HashMap<Integer,IMenuItem> menu; public BibliotecaApp(InputOutputManager inputOutputManager, BookLibrary bookLibrary, MovieLibrary movieLibrary) { this.inputOutputManager = inputOutputManager; this.menu = Menu.createMenu(bookLibrary, movieLibrary); } public static void main(String[] args) throws IOException { BookLibrary bookLibrary = new BookLibrary(); MovieLibrary movieLibrary = new MovieLibrary(); BibliotecaApp bibliotecaApp = new BibliotecaApp( new ConsoleIODevice(),bookLibrary,movieLibrary); bibliotecaApp.startApp(bookLibrary,movieLibrary); } public void startApp(BookLibrary bookLibrary, MovieLibrary movieLibrary) throws IOException { inputOutputManager.writeOutput("-------WELCOME TO BIBLIOTECA--------"); inputOutputManager.writeOutput("Enter UserId"); String userId = inputOutputManager.getInput(); if(!userId.equals("admin")){ LibraryMember loggedInMember; do{ loggedInMember = userLogin(userId); }while (loggedInMember==null); selectOption(loggedInMember, bookLibrary, movieLibrary); } else adminLogin(userId,bookLibrary,movieLibrary); } public void selectOption(LibraryMember loggedInMember, BookLibrary bookLibrary, MovieLibrary movieLibrary) throws IOException { int choice,result=0; do { displayMenu(); inputOutputManager.writeOutput("Enter your choice"); choice = Integer.parseInt(inputOutputManager.getInput()); if(choice<=9) result = menu.get(choice).executeAction(loggedInMember, inputOutputManager); else inputOutputManager.writeOutput("invalid choice renter"); }while (result!=1 && result!=9); if(result==9){ startApp(bookLibrary,movieLibrary); } } private void adminLogin(String adminId, BookLibrary bookLibrary, MovieLibrary movieLibrary) throws IOException { Admin admin = new Admin(); inputOutputManager.writeOutput("enter pwd"); String pwd = inputOutputManager.getInput();// en-US, hi, ka, fr, de.properties, if(admin.adminLogin(adminId,pwd)){ inputOutputManager.writeOutput("admin logged in"); if(!bookLibrary.borrowedBooks.isEmpty()) { for(Map.Entry<String,Book> each : bookLibrary.borrowedBooks.entrySet()){ inputOutputManager.writeOutput(each.getValue().getTitle()+" "+each.getValue().getAuthor()+" "+each.getValue().getBookId()+" "+each.getValue().getAuthor()+" "+each.getKey()); } } if(!movieLibrary.borrowedMovies.isEmpty()){ for(Map.Entry<String,Movie> each : movieLibrary.borrowedMovies.entrySet()){ inputOutputManager.writeOutput(each.getValue().getTitle()+" "+each.getValue().getDirector()+" "+each.getValue().getMovieId()+" "+each.getKey()); } } else inputOutputManager.writeOutput("nothing borrowed yet"); return; } else inputOutputManager.writeOutput("Wrong Credentials"); } private LibraryMember userLogin(String userId) throws IOException { inputOutputManager.writeOutput("Enter password"); String pwd = inputOutputManager.getInput(); libraryMemberCredentials = new LibraryMemberCredentials(); LibraryMember loggedInUser = libraryMemberCredentials.getCustomer(userId, pwd); if(loggedInUser!=null) return loggedInUser; else { inputOutputManager.writeOutput("invalid credentials"); return null; } } public void displayMenu() throws IOException { for (Map.Entry<Integer,IMenuItem> each : menu.entrySet()){ inputOutputManager.writeOutput(String.valueOf(each.getKey())+ ". "+each.getValue().displayMenuItem()); } } }
apache-2.0
jackliu8722/cassandra-2.1.1-annotated
src/java/org/apache/cassandra/config/DatabaseDescriptor.java
54866
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.config; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Longs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.auth.AllowAllAuthenticator; import org.apache.cassandra.auth.AllowAllAuthorizer; import org.apache.cassandra.auth.AllowAllInternodeAuthenticator; import org.apache.cassandra.auth.IAuthenticator; import org.apache.cassandra.auth.IAuthorizer; import org.apache.cassandra.auth.IInternodeAuthenticator; import org.apache.cassandra.config.Config.RequestSchedulerId; import org.apache.cassandra.config.EncryptionOptions.ClientEncryptionOptions; import org.apache.cassandra.config.EncryptionOptions.ServerEncryptionOptions; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.DefsTables; import org.apache.cassandra.db.SystemKeyspace; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.FSWriteError; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.io.util.IAllocator; import org.apache.cassandra.locator.DynamicEndpointSnitch; import org.apache.cassandra.locator.EndpointSnitchInfo; import org.apache.cassandra.locator.IEndpointSnitch; import org.apache.cassandra.locator.SeedProvider; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.scheduler.IRequestScheduler; import org.apache.cassandra.scheduler.NoScheduler; import org.apache.cassandra.service.CacheService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.memory.HeapPool; import org.apache.cassandra.utils.memory.NativePool; import org.apache.cassandra.utils.memory.MemtablePool; import org.apache.cassandra.utils.memory.SlabPool; public class DatabaseDescriptor { private static final Logger logger = LoggerFactory.getLogger(DatabaseDescriptor.class); /** * Tokens are serialized in a Gossip VersionedValue String. VV are restricted to 64KB * when we send them over the wire, which works out to about 1700 tokens. */ /** * 允许的最大TOKEN数量 */ private static final int MAX_NUM_TOKENS = 1536; private static IEndpointSnitch snitch; private static InetAddress listenAddress; // leave null so we can fall through to getLocalHost private static InetAddress broadcastAddress; private static InetAddress rpcAddress; private static InetAddress broadcastRpcAddress; private static SeedProvider seedProvider; private static IInternodeAuthenticator internodeAuthenticator; /* Hashing strategy Random or OPHF */ private static IPartitioner<?> partitioner; private static String paritionerName; private static Config.DiskAccessMode indexAccessMode; private static Config conf; private static IAuthenticator authenticator = new AllowAllAuthenticator(); private static IAuthorizer authorizer = new AllowAllAuthorizer(); private static IRequestScheduler requestScheduler; private static RequestSchedulerId requestSchedulerId; private static RequestSchedulerOptions requestSchedulerOptions; private static long keyCacheSizeInMB; private static long counterCacheSizeInMB; private static IAllocator memoryAllocator; private static long indexSummaryCapacityInMB; private static String localDC; private static Comparator<InetAddress> localComparator; static { // In client mode, we use a default configuration. Note that the fields of this class will be // left unconfigured however (the partitioner or localDC will be null for instance) so this // should be used with care. try { if (Config.isClientMode()) { conf = new Config(); // at least we have to set memoryAllocator to open SSTable in client mode memoryAllocator = FBUtilities.newOffHeapAllocator(conf.memory_allocator); } else { applyConfig(loadConfig()); } } catch (ConfigurationException e) { logger.error("Fatal configuration error", e); System.err.println(e.getMessage() + "\nFatal configuration error; unable to start. See log for stacktrace."); System.exit(1); } catch (Exception e) { logger.error("Fatal error during configuration loading", e); System.err.println(e.getMessage() + "\nFatal error during configuration loading; unable to start. See log for stacktrace."); System.exit(1); } } @VisibleForTesting public static Config loadConfig() throws ConfigurationException { String loaderClass = System.getProperty("cassandra.config.loader"); ConfigurationLoader loader = loaderClass == null ? new YamlConfigurationLoader() : FBUtilities.<ConfigurationLoader>construct(loaderClass, "configuration loading"); return loader.loadConfig(); } private static void applyConfig(Config config) throws ConfigurationException { conf = config; if (conf.commitlog_sync == null) { throw new ConfigurationException("Missing required directive CommitLogSync"); } if (conf.commitlog_sync == Config.CommitLogSync.batch) { if (conf.commitlog_sync_batch_window_in_ms == null) { throw new ConfigurationException("Missing value for commitlog_sync_batch_window_in_ms: Double expected."); } else if (conf.commitlog_sync_period_in_ms != null) { throw new ConfigurationException("Batch sync specified, but commitlog_sync_period_in_ms found. Only specify commitlog_sync_batch_window_in_ms when using batch sync"); } logger.debug("Syncing log with a batch window of {}", conf.commitlog_sync_batch_window_in_ms); } else { if (conf.commitlog_sync_period_in_ms == null) { throw new ConfigurationException("Missing value for commitlog_sync_period_in_ms: Integer expected"); } else if (conf.commitlog_sync_batch_window_in_ms != null) { throw new ConfigurationException("commitlog_sync_period_in_ms specified, but commitlog_sync_batch_window_in_ms found. Only specify commitlog_sync_period_in_ms when using periodic sync."); } logger.debug("Syncing log with a period of {}", conf.commitlog_sync_period_in_ms); } if (conf.commitlog_total_space_in_mb == null) conf.commitlog_total_space_in_mb = hasLargeAddressSpace() ? 8192 : 32; /* evaluate the DiskAccessMode Config directive, which also affects indexAccessMode selection */ if (conf.disk_access_mode == Config.DiskAccessMode.auto) { conf.disk_access_mode = hasLargeAddressSpace() ? Config.DiskAccessMode.mmap : Config.DiskAccessMode.standard; indexAccessMode = conf.disk_access_mode; logger.info("DiskAccessMode 'auto' determined to be {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode); } else if (conf.disk_access_mode == Config.DiskAccessMode.mmap_index_only) { conf.disk_access_mode = Config.DiskAccessMode.standard; indexAccessMode = Config.DiskAccessMode.mmap; logger.info("DiskAccessMode is {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode); } else { indexAccessMode = conf.disk_access_mode; logger.info("DiskAccessMode is {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode); } /* Authentication and authorization backend, implementing IAuthenticator and IAuthorizer */ if (conf.authenticator != null) authenticator = FBUtilities.newAuthenticator(conf.authenticator); if (conf.authorizer != null) authorizer = FBUtilities.newAuthorizer(conf.authorizer); if (authenticator instanceof AllowAllAuthenticator && !(authorizer instanceof AllowAllAuthorizer)) throw new ConfigurationException("AllowAllAuthenticator can't be used with " + conf.authorizer); if (conf.internode_authenticator != null) internodeAuthenticator = FBUtilities.construct(conf.internode_authenticator, "internode_authenticator"); else internodeAuthenticator = new AllowAllInternodeAuthenticator(); authenticator.validateConfiguration(); authorizer.validateConfiguration(); internodeAuthenticator.validateConfiguration(); /* Hashing strategy */ if (conf.partitioner == null) { throw new ConfigurationException("Missing directive: partitioner"); } try { partitioner = FBUtilities.newPartitioner(System.getProperty("cassandra.partitioner", conf.partitioner)); } catch (Exception e) { throw new ConfigurationException("Invalid partitioner class " + conf.partitioner); } paritionerName = partitioner.getClass().getCanonicalName(); if (conf.max_hint_window_in_ms == null) { throw new ConfigurationException("max_hint_window_in_ms cannot be set to null"); } /* phi convict threshold for FailureDetector */ if (conf.phi_convict_threshold < 5 || conf.phi_convict_threshold > 16) { throw new ConfigurationException("phi_convict_threshold must be between 5 and 16"); } /* Thread per pool */ if (conf.concurrent_reads != null && conf.concurrent_reads < 2) { throw new ConfigurationException("concurrent_reads must be at least 2"); } if (conf.concurrent_writes != null && conf.concurrent_writes < 2) { throw new ConfigurationException("concurrent_writes must be at least 2"); } if (conf.concurrent_counter_writes != null && conf.concurrent_counter_writes < 2) throw new ConfigurationException("concurrent_counter_writes must be at least 2"); if (conf.concurrent_replicates != null) logger.warn("concurrent_replicates has been deprecated and should be removed from cassandra.yaml"); if (conf.file_cache_size_in_mb == null) conf.file_cache_size_in_mb = Math.min(512, (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576))); if (conf.memtable_offheap_space_in_mb == null) conf.memtable_offheap_space_in_mb = (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576)); if (conf.memtable_offheap_space_in_mb < 0) throw new ConfigurationException("memtable_offheap_space_in_mb must be positive"); // for the moment, we default to twice as much on-heap space as off-heap, as heap overhead is very large if (conf.memtable_heap_space_in_mb == null) conf.memtable_heap_space_in_mb = (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576)); if (conf.memtable_heap_space_in_mb <= 0) throw new ConfigurationException("memtable_heap_space_in_mb must be positive"); logger.info("Global memtable on-heap threshold is enabled at {}MB", conf.memtable_heap_space_in_mb); if (conf.memtable_offheap_space_in_mb == 0) logger.info("Global memtable off-heap threshold is disabled, HeapAllocator will be used instead"); else logger.info("Global memtable off-heap threshold is enabled at {}MB", conf.memtable_offheap_space_in_mb); /* Local IP, hostname or interface to bind services to */ if (conf.listen_address != null && conf.listen_interface != null) { throw new ConfigurationException("Set listen_address OR listen_interface, not both"); } else if (conf.listen_address != null) { try { listenAddress = InetAddress.getByName(conf.listen_address); } catch (UnknownHostException e) { throw new ConfigurationException("Unknown listen_address '" + conf.listen_address + "'"); } if (listenAddress.isAnyLocalAddress()) throw new ConfigurationException("listen_address cannot be a wildcard address (" + conf.listen_address + ")!"); } else if (conf.listen_interface != null) { try { Enumeration<InetAddress> addrs = NetworkInterface.getByName(conf.listen_interface).getInetAddresses(); listenAddress = addrs.nextElement(); if (addrs.hasMoreElements()) throw new ConfigurationException("Interface " + conf.listen_interface +" can't have more than one address"); } catch (SocketException e) { throw new ConfigurationException("Unknown network interface in listen_interface " + conf.listen_interface); } } /* Gossip Address to broadcast */ if (conf.broadcast_address != null) { try { broadcastAddress = InetAddress.getByName(conf.broadcast_address); } catch (UnknownHostException e) { throw new ConfigurationException("Unknown broadcast_address '" + conf.broadcast_address + "'"); } if (broadcastAddress.isAnyLocalAddress()) throw new ConfigurationException("broadcast_address cannot be a wildcard address (" + conf.broadcast_address + ")!"); } /* Local IP, hostname or interface to bind RPC server to */ if (conf.rpc_address != null && conf.rpc_interface != null) { throw new ConfigurationException("Set rpc_address OR rpc_interface, not both"); } else if (conf.rpc_address != null) { try { rpcAddress = InetAddress.getByName(conf.rpc_address); } catch (UnknownHostException e) { throw new ConfigurationException("Unknown host in rpc_address " + conf.rpc_address); } } else if (conf.rpc_interface != null) { try { Enumeration<InetAddress> addrs = NetworkInterface.getByName(conf.rpc_interface).getInetAddresses(); rpcAddress = addrs.nextElement(); if (addrs.hasMoreElements()) throw new ConfigurationException("Interface " + conf.rpc_interface +" can't have more than one address"); } catch (SocketException e) { throw new ConfigurationException("Unknown network interface in rpc_interface " + conf.rpc_interface); } } else { rpcAddress = FBUtilities.getLocalAddress(); } /* RPC address to broadcast */ if (conf.broadcast_rpc_address != null) { try { broadcastRpcAddress = InetAddress.getByName(conf.broadcast_rpc_address); } catch (UnknownHostException e) { throw new ConfigurationException("Unknown broadcast_rpc_address '" + conf.broadcast_rpc_address + "'"); } if (broadcastRpcAddress.isAnyLocalAddress()) throw new ConfigurationException("broadcast_rpc_address cannot be a wildcard address (" + conf.broadcast_rpc_address + ")!"); } else { if (rpcAddress.isAnyLocalAddress()) throw new ConfigurationException("If rpc_address is set to a wildcard address (" + conf.rpc_address + "), then " + "you must set broadcast_rpc_address to a value other than " + conf.rpc_address); broadcastRpcAddress = rpcAddress; } if (conf.thrift_framed_transport_size_in_mb <= 0) throw new ConfigurationException("thrift_framed_transport_size_in_mb must be positive"); if (conf.native_transport_max_frame_size_in_mb <= 0) throw new ConfigurationException("native_transport_max_frame_size_in_mb must be positive"); /* end point snitch */ if (conf.endpoint_snitch == null) { throw new ConfigurationException("Missing endpoint_snitch directive"); } snitch = createEndpointSnitch(conf.endpoint_snitch); EndpointSnitchInfo.create(); localDC = snitch.getDatacenter(FBUtilities.getBroadcastAddress()); localComparator = new Comparator<InetAddress>() { public int compare(InetAddress endpoint1, InetAddress endpoint2) { boolean local1 = localDC.equals(snitch.getDatacenter(endpoint1)); boolean local2 = localDC.equals(snitch.getDatacenter(endpoint2)); if (local1 && !local2) return -1; if (local2 && !local1) return 1; return 0; } }; /* Request Scheduler setup */ requestSchedulerOptions = conf.request_scheduler_options; if (conf.request_scheduler != null) { try { if (requestSchedulerOptions == null) { requestSchedulerOptions = new RequestSchedulerOptions(); } Class<?> cls = Class.forName(conf.request_scheduler); requestScheduler = (IRequestScheduler) cls.getConstructor(RequestSchedulerOptions.class).newInstance(requestSchedulerOptions); } catch (ClassNotFoundException e) { throw new ConfigurationException("Invalid Request Scheduler class " + conf.request_scheduler); } catch (Exception e) { throw new ConfigurationException("Unable to instantiate request scheduler", e); } } else { requestScheduler = new NoScheduler(); } if (conf.request_scheduler_id == RequestSchedulerId.keyspace) { requestSchedulerId = conf.request_scheduler_id; } else { // Default to Keyspace requestSchedulerId = RequestSchedulerId.keyspace; } // if data dirs, commitlog dir, or saved caches dir are set in cassandra.yaml, use that. Otherwise, // use -Dcassandra.storagedir (set in cassandra-env.sh) as the parent dir for data/, commitlog/, and saved_caches/ if (conf.commitlog_directory == null) { conf.commitlog_directory = System.getProperty("cassandra.storagedir", null); if (conf.commitlog_directory == null) throw new ConfigurationException("commitlog_directory is missing and -Dcassandra.storagedir is not set"); conf.commitlog_directory += File.separator + "commitlog"; } if (conf.saved_caches_directory == null) { conf.saved_caches_directory = System.getProperty("cassandra.storagedir", null); if (conf.saved_caches_directory == null) throw new ConfigurationException("saved_caches_directory is missing and -Dcassandra.storagedir is not set"); conf.saved_caches_directory += File.separator + "saved_caches"; } if (conf.data_file_directories == null) { String defaultDataDir = System.getProperty("cassandra.storagedir", null); if (defaultDataDir == null) throw new ConfigurationException("data_file_directories is not missing and -Dcassandra.storagedir is not set"); conf.data_file_directories = new String[]{ defaultDataDir + File.separator + "data" }; } /* data file and commit log directories. they get created later, when they're needed. */ for (String datadir : conf.data_file_directories) { if (datadir.equals(conf.commitlog_directory)) throw new ConfigurationException("commitlog_directory must not be the same as any data_file_directories"); if (datadir.equals(conf.saved_caches_directory)) throw new ConfigurationException("saved_caches_directory must not be the same as any data_file_directories"); } if (conf.commitlog_directory.equals(conf.saved_caches_directory)) throw new ConfigurationException("saved_caches_directory must not be the same as the commitlog_directory"); if (conf.memtable_flush_writers == null) conf.memtable_flush_writers = Math.min(8, Math.max(2, Math.min(FBUtilities.getAvailableProcessors(), conf.data_file_directories.length))); if (conf.memtable_flush_writers < 1) throw new ConfigurationException("memtable_flush_writers must be at least 1"); if (conf.memtable_cleanup_threshold == null) conf.memtable_cleanup_threshold = (float) (1.0 / (1 + conf.memtable_flush_writers)); if (conf.memtable_cleanup_threshold < 0.01f) throw new ConfigurationException("memtable_cleanup_threshold must be >= 0.01"); if (conf.memtable_cleanup_threshold > 0.99f) throw new ConfigurationException("memtable_cleanup_threshold must be <= 0.99"); if (conf.memtable_cleanup_threshold < 0.1f) logger.warn("memtable_cleanup_threshold is set very low, which may cause performance degradation"); if (conf.concurrent_compactors == null) conf.concurrent_compactors = Math.min(8, Math.max(2, Math.min(FBUtilities.getAvailableProcessors(), conf.data_file_directories.length))); if (conf.concurrent_compactors <= 0) throw new ConfigurationException("concurrent_compactors should be strictly greater than 0"); if (conf.initial_token != null) for (String token : tokensFromString(conf.initial_token)) partitioner.getTokenFactory().validate(token); if (conf.num_tokens == null) conf.num_tokens = 1; else if (conf.num_tokens > MAX_NUM_TOKENS) throw new ConfigurationException(String.format("A maximum number of %d tokens per node is supported", MAX_NUM_TOKENS)); try { // if key_cache_size_in_mb option was set to "auto" then size of the cache should be "min(5% of Heap (in MB), 100MB) keyCacheSizeInMB = (conf.key_cache_size_in_mb == null) ? Math.min(Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.05 / 1024 / 1024)), 100) : conf.key_cache_size_in_mb; if (keyCacheSizeInMB < 0) throw new NumberFormatException(); // to escape duplicating error message } catch (NumberFormatException e) { throw new ConfigurationException("key_cache_size_in_mb option was set incorrectly to '" + conf.key_cache_size_in_mb + "', supported values are <integer> >= 0."); } try { // if counter_cache_size_in_mb option was set to "auto" then size of the cache should be "min(2.5% of Heap (in MB), 50MB) counterCacheSizeInMB = (conf.counter_cache_size_in_mb == null) ? Math.min(Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.025 / 1024 / 1024)), 50) : conf.counter_cache_size_in_mb; if (counterCacheSizeInMB < 0) throw new NumberFormatException(); // to escape duplicating error message } catch (NumberFormatException e) { throw new ConfigurationException("counter_cache_size_in_mb option was set incorrectly to '" + conf.counter_cache_size_in_mb + "', supported values are <integer> >= 0."); } // if set to empty/"auto" then use 5% of Heap size indexSummaryCapacityInMB = (conf.index_summary_capacity_in_mb == null) ? Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.05 / 1024 / 1024)) : conf.index_summary_capacity_in_mb; if (indexSummaryCapacityInMB < 0) throw new ConfigurationException("index_summary_capacity_in_mb option was set incorrectly to '" + conf.index_summary_capacity_in_mb + "', it should be a non-negative integer."); memoryAllocator = FBUtilities.newOffHeapAllocator(conf.memory_allocator); if(conf.encryption_options != null) { logger.warn("Please rename encryption_options as server_encryption_options in the yaml"); //operate under the assumption that server_encryption_options is not set in yaml rather than both conf.server_encryption_options = conf.encryption_options; } // Hardcoded system keyspaces List<KSMetaData> systemKeyspaces = Arrays.asList(KSMetaData.systemKeyspace()); assert systemKeyspaces.size() == Schema.systemKeyspaceNames.size(); for (KSMetaData ksmd : systemKeyspaces) Schema.instance.load(ksmd); /* Load the seeds for node contact points */ if (conf.seed_provider == null) { throw new ConfigurationException("seeds configuration is missing; a minimum of one seed is required."); } try { Class<?> seedProviderClass = Class.forName(conf.seed_provider.class_name); seedProvider = (SeedProvider)seedProviderClass.getConstructor(Map.class).newInstance(conf.seed_provider.parameters); } // there are about 5 checked exceptions that could be thrown here. catch (Exception e) { logger.error("Fatal configuration error", e); System.err.println(e.getMessage() + "\nFatal configuration error; unable to start server. See log for stacktrace."); System.exit(1); } if (seedProvider.getSeeds().size() == 0) throw new ConfigurationException("The seed provider lists no seeds."); } private static IEndpointSnitch createEndpointSnitch(String snitchClassName) throws ConfigurationException { if (!snitchClassName.contains(".")) snitchClassName = "org.apache.cassandra.locator." + snitchClassName; IEndpointSnitch snitch = FBUtilities.construct(snitchClassName, "snitch"); return conf.dynamic_snitch ? new DynamicEndpointSnitch(snitch) : snitch; } /** load keyspace (keyspace) definitions, but do not initialize the keyspace instances. */ public static void loadSchemas() { ColumnFamilyStore schemaCFS = SystemKeyspace.schemaCFS(SystemKeyspace.SCHEMA_KEYSPACES_CF); // if keyspace with definitions is empty try loading the old way if (schemaCFS.estimateKeys() == 0) { logger.info("Couldn't detect any schema definitions in local storage."); // peek around the data directories to see if anything is there. if (hasExistingNoSystemTables()) logger.info("Found keyspace data in data directories. Consider using cqlsh to define your schema."); else logger.info("To create keyspaces and column families, see 'help create' in cqlsh."); } else { Schema.instance.load(DefsTables.loadFromKeyspace()); } Schema.instance.updateVersion(); } private static boolean hasExistingNoSystemTables() { for (String dataDir : getAllDataFileLocations()) { File dataPath = new File(dataDir); if (dataPath.exists() && dataPath.isDirectory()) { // see if there are other directories present. int dirCount = dataPath.listFiles(new FileFilter() { public boolean accept(File pathname) { return (pathname.isDirectory() && !Schema.systemKeyspaceNames.contains(pathname.getName())); } }).length; if (dirCount > 0) return true; } } return false; } public static IAuthenticator getAuthenticator() { return authenticator; } public static IAuthorizer getAuthorizer() { return authorizer; } public static int getPermissionsValidity() { return conf.permissions_validity_in_ms; } public static void setPermissionsValidity(int timeout) { conf.permissions_validity_in_ms = timeout; } public static int getThriftFramedTransportSize() { return conf.thrift_framed_transport_size_in_mb * 1024 * 1024; } /** * Creates all storage-related directories. */ public static void createAllDirectories() { try { if (conf.data_file_directories.length == 0) throw new ConfigurationException("At least one DataFileDirectory must be specified"); for (String dataFileDirectory : conf.data_file_directories) { FileUtils.createDirectory(dataFileDirectory); } if (conf.commitlog_directory == null) throw new ConfigurationException("commitlog_directory must be specified"); FileUtils.createDirectory(conf.commitlog_directory); if (conf.saved_caches_directory == null) throw new ConfigurationException("saved_caches_directory must be specified"); FileUtils.createDirectory(conf.saved_caches_directory); } catch (ConfigurationException e) { logger.error("Fatal error: {}", e.getMessage()); System.err.println("Bad configuration; unable to start server"); System.exit(1); } catch (FSWriteError e) { logger.error("Fatal error: {}", e.getMessage()); System.err.println(e.getCause().getMessage() + "; unable to start server"); System.exit(1); } } public static IPartitioner<?> getPartitioner() { return partitioner; } public static String getPartitionerName() { return paritionerName; } /* For tests ONLY, don't use otherwise or all hell will break loose */ public static void setPartitioner(IPartitioner<?> newPartitioner) { partitioner = newPartitioner; } public static IEndpointSnitch getEndpointSnitch() { return snitch; } public static void setEndpointSnitch(IEndpointSnitch eps) { snitch = eps; } public static IRequestScheduler getRequestScheduler() { return requestScheduler; } public static RequestSchedulerOptions getRequestSchedulerOptions() { return requestSchedulerOptions; } public static RequestSchedulerId getRequestSchedulerId() { return requestSchedulerId; } public static int getColumnIndexSize() { return conf.column_index_size_in_kb * 1024; } public static int getBatchSizeWarnThreshold() { return conf.batch_size_warn_threshold_in_kb * 1024; } public static Collection<String> getInitialTokens() { return tokensFromString(System.getProperty("cassandra.initial_token", conf.initial_token)); } public static Collection<String> tokensFromString(String tokenString) { List<String> tokens = new ArrayList<String>(); if (tokenString != null) for (String token : tokenString.split(",")) tokens.add(token.replaceAll("^\\s+", "").replaceAll("\\s+$", "")); return tokens; } public static Integer getNumTokens() { return conf.num_tokens; } public static InetAddress getReplaceAddress() { try { if (System.getProperty("cassandra.replace_address", null) != null) return InetAddress.getByName(System.getProperty("cassandra.replace_address", null)); else if (System.getProperty("cassandra.replace_address_first_boot", null) != null) return InetAddress.getByName(System.getProperty("cassandra.replace_address_first_boot", null)); return null; } catch (UnknownHostException e) { return null; } } public static Collection<String> getReplaceTokens() { return tokensFromString(System.getProperty("cassandra.replace_token", null)); } public static UUID getReplaceNode() { try { return UUID.fromString(System.getProperty("cassandra.replace_node", null)); } catch (NullPointerException e) { return null; } } public static boolean isReplacing() { if (System.getProperty("cassandra.replace_address_first_boot", null) != null && SystemKeyspace.bootstrapComplete()) { logger.info("Replace address on first boot requested; this node is already bootstrapped"); return false; } return getReplaceAddress() != null; } public static String getClusterName() { return conf.cluster_name; } public static int getMaxStreamingRetries() { return conf.max_streaming_retries; } public static int getStoragePort() { return Integer.parseInt(System.getProperty("cassandra.storage_port", conf.storage_port.toString())); } public static int getSSLStoragePort() { return Integer.parseInt(System.getProperty("cassandra.ssl_storage_port", conf.ssl_storage_port.toString())); } public static int getRpcPort() { return Integer.parseInt(System.getProperty("cassandra.rpc_port", conf.rpc_port.toString())); } public static int getRpcListenBacklog() { return conf.rpc_listen_backlog; } public static long getRpcTimeout() { return conf.request_timeout_in_ms; } public static void setRpcTimeout(Long timeOutInMillis) { conf.request_timeout_in_ms = timeOutInMillis; } public static long getReadRpcTimeout() { return conf.read_request_timeout_in_ms; } public static void setReadRpcTimeout(Long timeOutInMillis) { conf.read_request_timeout_in_ms = timeOutInMillis; } public static long getRangeRpcTimeout() { return conf.range_request_timeout_in_ms; } public static void setRangeRpcTimeout(Long timeOutInMillis) { conf.range_request_timeout_in_ms = timeOutInMillis; } public static long getWriteRpcTimeout() { return conf.write_request_timeout_in_ms; } public static void setWriteRpcTimeout(Long timeOutInMillis) { conf.write_request_timeout_in_ms = timeOutInMillis; } public static long getCounterWriteRpcTimeout() { return conf.counter_write_request_timeout_in_ms; } public static void setCounterWriteRpcTimeout(Long timeOutInMillis) { conf.counter_write_request_timeout_in_ms = timeOutInMillis; } public static long getCasContentionTimeout() { return conf.cas_contention_timeout_in_ms; } public static void setCasContentionTimeout(Long timeOutInMillis) { conf.cas_contention_timeout_in_ms = timeOutInMillis; } public static long getTruncateRpcTimeout() { return conf.truncate_request_timeout_in_ms; } public static void setTruncateRpcTimeout(Long timeOutInMillis) { conf.truncate_request_timeout_in_ms = timeOutInMillis; } public static boolean hasCrossNodeTimeout() { return conf.cross_node_timeout; } // not part of the Verb enum so we can change timeouts easily via JMX public static long getTimeout(MessagingService.Verb verb) { switch (verb) { case READ: return getReadRpcTimeout(); case RANGE_SLICE: return getRangeRpcTimeout(); case TRUNCATE: return getTruncateRpcTimeout(); case READ_REPAIR: case MUTATION: case PAXOS_COMMIT: case PAXOS_PREPARE: case PAXOS_PROPOSE: return getWriteRpcTimeout(); case COUNTER_MUTATION: return getCounterWriteRpcTimeout(); default: return getRpcTimeout(); } } /** * @return the minimum configured {read, write, range, truncate, misc} timeout */ public static long getMinRpcTimeout() { return Longs.min(getRpcTimeout(), getReadRpcTimeout(), getRangeRpcTimeout(), getWriteRpcTimeout(), getCounterWriteRpcTimeout(), getTruncateRpcTimeout()); } public static double getPhiConvictThreshold() { return conf.phi_convict_threshold; } public static void setPhiConvictThreshold(double phiConvictThreshold) { conf.phi_convict_threshold = phiConvictThreshold; } public static int getConcurrentReaders() { return conf.concurrent_reads; } public static int getConcurrentWriters() { return conf.concurrent_writes; } public static int getConcurrentCounterWriters() { return conf.concurrent_counter_writes; } public static int getFlushWriters() { return conf.memtable_flush_writers; } public static int getConcurrentCompactors() { return conf.concurrent_compactors; } public static int getCompactionThroughputMbPerSec() { return conf.compaction_throughput_mb_per_sec; } public static void setCompactionThroughputMbPerSec(int value) { conf.compaction_throughput_mb_per_sec = value; } public static boolean getDisableSTCSInL0() { return Boolean.getBoolean("cassandra.disable_stcs_in_l0"); } public static int getStreamThroughputOutboundMegabitsPerSec() { return conf.stream_throughput_outbound_megabits_per_sec; } public static void setStreamThroughputOutboundMegabitsPerSec(int value) { conf.stream_throughput_outbound_megabits_per_sec = value; } public static int getInterDCStreamThroughputOutboundMegabitsPerSec() { return conf.inter_dc_stream_throughput_outbound_megabits_per_sec; } public static void setInterDCStreamThroughputOutboundMegabitsPerSec(int value) { conf.inter_dc_stream_throughput_outbound_megabits_per_sec = value; } public static String[] getAllDataFileLocations() { return conf.data_file_directories; } public static String getCommitLogLocation() { return conf.commitlog_directory; } public static int getTombstoneWarnThreshold() { return conf.tombstone_warn_threshold; } public static void setTombstoneWarnThreshold(int threshold) { conf.tombstone_warn_threshold = threshold; } public static int getTombstoneFailureThreshold() { return conf.tombstone_failure_threshold; } public static void setTombstoneFailureThreshold(int threshold) { conf.tombstone_failure_threshold = threshold; } /** * size of commitlog segments to allocate */ public static int getCommitLogSegmentSize() { return conf.commitlog_segment_size_in_mb * 1024 * 1024; } public static String getSavedCachesLocation() { return conf.saved_caches_directory; } public static Set<InetAddress> getSeeds() { return ImmutableSet.<InetAddress>builder().addAll(seedProvider.getSeeds()).build(); } public static InetAddress getListenAddress() { return listenAddress; } public static InetAddress getBroadcastAddress() { return broadcastAddress; } public static IInternodeAuthenticator getInternodeAuthenticator() { return internodeAuthenticator; } public static void setBroadcastAddress(InetAddress broadcastAdd) { broadcastAddress = broadcastAdd; } public static boolean startRpc() { return conf.start_rpc; } public static InetAddress getRpcAddress() { return rpcAddress; } public static void setBroadcastRpcAddress(InetAddress broadcastRPCAddr) { broadcastRpcAddress = broadcastRPCAddr; } public static InetAddress getBroadcastRpcAddress() { return broadcastRpcAddress; } public static String getRpcServerType() { return conf.rpc_server_type; } public static boolean getRpcKeepAlive() { return conf.rpc_keepalive; } public static Integer getRpcMinThreads() { return conf.rpc_min_threads; } public static Integer getRpcMaxThreads() { return conf.rpc_max_threads; } public static Integer getRpcSendBufferSize() { return conf.rpc_send_buff_size_in_bytes; } public static Integer getRpcRecvBufferSize() { return conf.rpc_recv_buff_size_in_bytes; } public static Integer getInternodeSendBufferSize() { return conf.internode_send_buff_size_in_bytes; } public static Integer getInternodeRecvBufferSize() { return conf.internode_recv_buff_size_in_bytes; } public static boolean startNativeTransport() { return conf.start_native_transport; } public static int getNativeTransportPort() { return Integer.parseInt(System.getProperty("cassandra.native_transport_port", conf.native_transport_port.toString())); } public static Integer getNativeTransportMaxThreads() { return conf.native_transport_max_threads; } public static int getNativeTransportMaxFrameSize() { return conf.native_transport_max_frame_size_in_mb * 1024 * 1024; } public static double getCommitLogSyncBatchWindow() { return conf.commitlog_sync_batch_window_in_ms; } public static int getCommitLogSyncPeriod() { return conf.commitlog_sync_period_in_ms; } public static int getCommitLogPeriodicQueueSize() { return conf.commitlog_periodic_queue_size; } public static Config.CommitLogSync getCommitLogSync() { return conf.commitlog_sync; } public static Config.DiskAccessMode getDiskAccessMode() { return conf.disk_access_mode; } public static Config.DiskAccessMode getIndexAccessMode() { return indexAccessMode; } public static void setDiskFailurePolicy(Config.DiskFailurePolicy policy) { conf.disk_failure_policy = policy; } public static Config.DiskFailurePolicy getDiskFailurePolicy() { return conf.disk_failure_policy; } public static void setCommitFailurePolicy(Config.CommitFailurePolicy policy) { conf.commit_failure_policy = policy; } public static Config.CommitFailurePolicy getCommitFailurePolicy() { return conf.commit_failure_policy; } public static boolean isSnapshotBeforeCompaction() { return conf.snapshot_before_compaction; } public static boolean isAutoSnapshot() { return conf.auto_snapshot; } @VisibleForTesting public static void setAutoSnapshot(boolean autoSnapshot) { conf.auto_snapshot = autoSnapshot; } public static boolean isAutoBootstrap() { return Boolean.parseBoolean(System.getProperty("cassandra.auto_bootstrap", conf.auto_bootstrap.toString())); } public static void setHintedHandoffEnabled(boolean hintedHandoffEnabled) { conf.hinted_handoff_enabled_global = hintedHandoffEnabled; conf.hinted_handoff_enabled_by_dc.clear(); } public static void setHintedHandoffEnabled(final String dcNames) { List<String> dcNameList; try { dcNameList = Config.parseHintedHandoffEnabledDCs(dcNames); } catch (IOException e) { throw new IllegalArgumentException("Could not read csv of dcs for hinted handoff enable. " + dcNames, e); } if (dcNameList.isEmpty()) throw new IllegalArgumentException("Empty list of Dcs for hinted handoff enable"); conf.hinted_handoff_enabled_by_dc.clear(); conf.hinted_handoff_enabled_by_dc.addAll(dcNameList); } public static boolean hintedHandoffEnabled() { return conf.hinted_handoff_enabled_global; } public static Set<String> hintedHandoffEnabledByDC() { return Collections.unmodifiableSet(conf.hinted_handoff_enabled_by_dc); } public static boolean shouldHintByDC() { return !conf.hinted_handoff_enabled_by_dc.isEmpty(); } public static boolean hintedHandoffEnabled(final String dcName) { return conf.hinted_handoff_enabled_by_dc.contains(dcName); } public static void setMaxHintWindow(int ms) { conf.max_hint_window_in_ms = ms; } public static int getMaxHintWindow() { return conf.max_hint_window_in_ms; } @Deprecated public static Integer getIndexInterval() { return conf.index_interval; } public static File getSerializedCachePath(String ksName, String cfName, UUID cfId, CacheService.CacheType cacheType, String version) { StringBuilder builder = new StringBuilder(); builder.append(ksName).append('-'); builder.append(cfName).append('-'); if (cfId != null) builder.append(ByteBufferUtil.bytesToHex(ByteBufferUtil.bytes(cfId))).append('-'); builder.append(cacheType); builder.append((version == null ? "" : "-" + version + ".db")); return new File(conf.saved_caches_directory, builder.toString()); } public static int getDynamicUpdateInterval() { return conf.dynamic_snitch_update_interval_in_ms; } public static void setDynamicUpdateInterval(Integer dynamicUpdateInterval) { conf.dynamic_snitch_update_interval_in_ms = dynamicUpdateInterval; } public static int getDynamicResetInterval() { return conf.dynamic_snitch_reset_interval_in_ms; } public static void setDynamicResetInterval(Integer dynamicResetInterval) { conf.dynamic_snitch_reset_interval_in_ms = dynamicResetInterval; } public static double getDynamicBadnessThreshold() { return conf.dynamic_snitch_badness_threshold; } public static void setDynamicBadnessThreshold(Double dynamicBadnessThreshold) { conf.dynamic_snitch_badness_threshold = dynamicBadnessThreshold; } public static ServerEncryptionOptions getServerEncryptionOptions() { return conf.server_encryption_options; } public static ClientEncryptionOptions getClientEncryptionOptions() { return conf.client_encryption_options; } public static int getHintedHandoffThrottleInKB() { return conf.hinted_handoff_throttle_in_kb; } public static int getBatchlogReplayThrottleInKB() { return conf.batchlog_replay_throttle_in_kb; } public static void setHintedHandoffThrottleInKB(Integer throttleInKB) { conf.hinted_handoff_throttle_in_kb = throttleInKB; } public static int getMaxHintsThread() { return conf.max_hints_delivery_threads; } public static boolean isIncrementalBackupsEnabled() { return conf.incremental_backups; } public static void setIncrementalBackupsEnabled(boolean value) { conf.incremental_backups = value; } public static int getFileCacheSizeInMB() { return conf.file_cache_size_in_mb; } public static long getTotalCommitlogSpaceInMB() { return conf.commitlog_total_space_in_mb; } public static int getSSTablePreempiveOpenIntervalInMB() { return conf.sstable_preemptive_open_interval_in_mb; } public static boolean getTrickleFsync() { return conf.trickle_fsync; } public static int getTrickleFsyncIntervalInKb() { return conf.trickle_fsync_interval_in_kb; } public static long getKeyCacheSizeInMB() { return keyCacheSizeInMB; } public static long getIndexSummaryCapacityInMB() { return indexSummaryCapacityInMB; } public static int getKeyCacheSavePeriod() { return conf.key_cache_save_period; } public static void setKeyCacheSavePeriod(int keyCacheSavePeriod) { conf.key_cache_save_period = keyCacheSavePeriod; } public static int getKeyCacheKeysToSave() { return conf.key_cache_keys_to_save; } public static void setKeyCacheKeysToSave(int keyCacheKeysToSave) { conf.key_cache_keys_to_save = keyCacheKeysToSave; } public static long getRowCacheSizeInMB() { return conf.row_cache_size_in_mb; } public static int getRowCacheSavePeriod() { return conf.row_cache_save_period; } public static void setRowCacheSavePeriod(int rowCacheSavePeriod) { conf.row_cache_save_period = rowCacheSavePeriod; } public static int getRowCacheKeysToSave() { return conf.row_cache_keys_to_save; } public static long getCounterCacheSizeInMB() { return counterCacheSizeInMB; } public static int getCounterCacheSavePeriod() { return conf.counter_cache_save_period; } public static void setCounterCacheSavePeriod(int counterCacheSavePeriod) { conf.counter_cache_save_period = counterCacheSavePeriod; } public static int getCounterCacheKeysToSave() { return conf.counter_cache_keys_to_save; } public static void setCounterCacheKeysToSave(int counterCacheKeysToSave) { conf.counter_cache_keys_to_save = counterCacheKeysToSave; } public static IAllocator getoffHeapMemoryAllocator() { return memoryAllocator; } public static void setRowCacheKeysToSave(int rowCacheKeysToSave) { conf.row_cache_keys_to_save = rowCacheKeysToSave; } public static int getStreamingSocketTimeout() { return conf.streaming_socket_timeout_in_ms; } public static String getLocalDataCenter() { return localDC; } public static Comparator<InetAddress> getLocalComparator() { return localComparator; } public static Config.InternodeCompression internodeCompression() { return conf.internode_compression; } public static boolean getInterDCTcpNoDelay() { return conf.inter_dc_tcp_nodelay; } public static MemtablePool getMemtableAllocatorPool() { long heapLimit = ((long) conf.memtable_heap_space_in_mb) << 20; long offHeapLimit = ((long) conf.memtable_offheap_space_in_mb) << 20; switch (conf.memtable_allocation_type) { case unslabbed_heap_buffers: return new HeapPool(heapLimit, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily()); case heap_buffers: return new SlabPool(heapLimit, 0, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily()); case offheap_buffers: if (!FileUtils.isCleanerAvailable()) { logger.error("Could not free direct byte buffer: offheap_buffers is not a safe memtable_allocation_type without this ability, please adjust your config. This feature is only guaranteed to work on an Oracle JVM. Refusing to start."); System.exit(-1); } return new SlabPool(heapLimit, offHeapLimit, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily()); case offheap_objects: return new NativePool(heapLimit, offHeapLimit, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily()); default: throw new AssertionError(); } } public static int getIndexSummaryResizeIntervalInMinutes() { return conf.index_summary_resize_interval_in_minutes; } public static boolean hasLargeAddressSpace() { // currently we just check if it's a 64bit arch, but any we only really care if the address space is large String datamodel = System.getProperty("sun.arch.data.model"); if (datamodel != null) { switch (datamodel) { case "64": return true; case "32": return false; } } String arch = System.getProperty("os.arch"); return arch.contains("64") || arch.contains("sparcv9"); } }
apache-2.0
NikolasHerbst/BUNGEE
cloudstackapi/src/net/datapipe/CloudStack/authorizeSecurityGroupIngress.java
514
package net.datapipe.CloudStack; import java.util.HashMap; import org.w3c.dom.Document; public class authorizeSecurityGroupIngress { public static void main(String[] args) throws Exception { CloudStack client = CLI.factory(); HashMap<String,String> options = CLI.args_to_options(args); Document authorize_result = client.authorizeSecurityGroupIngress(options); String elements[] = {"jobid"}; CLI.printDocument(authorize_result, "/authorizesecuritygroupingressresponse", elements); } }
apache-2.0
phax/ph-oton
ph-oton-security/src/main/java/com/helger/photon/security/token/accesstoken/IAccessToken.java
3122
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]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.helger.photon.security.token.accesstoken; import java.time.LocalDateTime; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.annotation.Nonempty; import com.helger.commons.datetime.PDTFactory; import com.helger.photon.security.token.revocation.IRevocationStatus; /** * This class represents a single token. It uniquely belongs to an application * token or a user token. It consists of a random string token, a not-before * date time, an optional not-after date time and a revocation status. * * @author Philip Helger */ public interface IAccessToken { /** * The maximum string length of the token string. * * @since 8.3.7 */ int TOKEN_STRING_MAX_LENGTH = 200; /** * @return The hex-encoded string with the random data. */ @Nonnull @Nonempty String getTokenString (); /** * @return The date time before this token is not valid. */ @Nonnull LocalDateTime getNotBefore (); /** * @return The date time after which this token is not valid. May be * <code>null</code> to indicate infinity. If it is not * <code>null</code> it must be &ge; than the not-before date time. */ @Nullable LocalDateTime getNotAfter (); /** * Check if this token is valid now. This method does not consider the * revocation status! * * @return <code>true</code> if the token is valid now. This method does not * consider the revocation status! */ default boolean isValidNow () { return isValidAt (PDTFactory.getCurrentLocalDateTime ()); } /** * Check if the token is valid at the specified date and time. This method * does not consider the revocation status! * * @param aDT * The date time to check. May not be <code>null</code>. * @return <code>true</code> if the token was valid at that point in time, * <code>false</code> otherwise. */ boolean isValidAt (@Nonnull LocalDateTime aDT); /** * @return The current revocation status of this token. Never * <code>null</code>. */ @Nonnull IRevocationStatus getRevocationStatus (); /** * A short cut for <code>getRevocationStatus ().isRevoked ()</code>. * * @return <code>true</code> if this access token was revoked, * <code>false</code> otherwise. * @see #getRevocationStatus() */ default boolean isRevoked () { return getRevocationStatus ().isRevoked (); } }
apache-2.0
hortonworks/cloudbreak
redbeams/src/test/java/com/sequenceiq/redbeams/flow/redbeams/FlowSelectorTest.java
379
package com.sequenceiq.redbeams.flow.redbeams; import org.junit.jupiter.api.Test; import com.sequenceiq.flow.event.FlowSelectors; class FlowSelectorTest { @Test void testDupicateHandlerDoesNotExist() { FlowSelectors flowSelectors = new FlowSelectors(); flowSelectors.assertUniquenessInFlowEventNames("com.sequenceiq.redbeams.flow.redbeams"); } }
apache-2.0
maciej-zygmunt/unitime
JavaSource/org/unitime/timetable/solver/jgroups/AbstractSolverServer.java
8049
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.solver.jgroups; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; import org.jgroups.Address; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.interfaces.RoomAvailabilityInterface; import org.unitime.timetable.model.Class_; import org.unitime.timetable.model.DepartmentalInstructor; import org.unitime.timetable.model.ExamType; import org.unitime.timetable.model.InstructionalOffering; import org.unitime.timetable.model.Solution; import org.unitime.timetable.model.TeachingRequest; import org.unitime.timetable.model.dao._RootDAO; import org.unitime.timetable.util.Constants; import org.unitime.timetable.util.RoomAvailability; import org.unitime.timetable.util.queue.LocalQueueProcessor; import org.unitime.timetable.util.queue.QueueProcessor; /** * @author Tomas Muller */ public abstract class AbstractSolverServer implements SolverServer { protected static Log sLog = LogFactory.getLog(AbstractSolverServer.class); protected int iUsageBase = 0; protected Date iStartTime = new Date(); protected boolean iActive = false; public AbstractSolverServer() { } @Override public void start() { iActive = true; sLog.info("Solver server is up and running."); } @Override public void stop() { sLog.info("Solver server is going down..."); iActive = false; } @Override public boolean isLocal() { return true; } @Override public boolean isCoordinator() { return true; } @Override public boolean isLocalCoordinator() { return isLocal() && isCoordinator(); } @Override public Address getAddress() { return null; } @Override public Address getLocalAddress() { return getAddress(); } @Override public String getHost() { return "local"; } @Override public int getUsage() { int ret = iUsageBase; if (isLocal()) ret += 500; return ret; } @Override public void setUsageBase(int base) { iUsageBase = base; } @Override public long getAvailableMemory() { return Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory(); } @Override public int getAvailableProcessors() { return Runtime.getRuntime().availableProcessors(); } @Override public long getMemoryLimit() { return 1024l * 1024l * Long.parseLong(ApplicationProperties.getProperty(ApplicationProperty.SolverMemoryLimit)); } @Override public String getVersion() { return Constants.getVersion(); } public Date getStartTime() { return iStartTime; } @Override public boolean isActive() { return iActive; } @Override public boolean isAvailable() { if (!isActive()) return false; if (getMemoryLimit() > getAvailableMemory()) System.gc(); return getMemoryLimit() <= getAvailableMemory(); } @Override public RoomAvailabilityInterface getRoomAvailability() { return RoomAvailability.getInstance(); } @Override public void refreshCourseSolution(Long... solutionIds) { try { for (Long solutionId: solutionIds) Solution.refreshSolution(solutionId); } finally { _RootDAO.closeCurrentThreadSessions(); } } @Override public void refreshExamSolution(Long sessionId, Long examTypeId) { try { ExamType.refreshSolution(sessionId, examTypeId); } finally { _RootDAO.closeCurrentThreadSessions(); } } @Override public void refreshInstructorSolution(Collection<Long> solverGroupIds) { org.hibernate.Session hibSession = new _RootDAO().createNewSession(); try { SessionFactory hibSessionFactory = hibSession.getSessionFactory(); List<Long> classIds = (List<Long>)hibSession.createQuery( "select distinct c.uniqueId from Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long classId: classIds) { hibSessionFactory.getCache().evictEntity(Class_.class, classId); hibSessionFactory.getCache().evictCollection(Class_.class.getName()+".classInstructors", classId); } List<Long> instructorIds = (List<Long>)hibSession.createQuery( "select i.uniqueId from DepartmentalInstructor i, SolverGroup g inner join g.departments d where " + "g.uniqueId in :solverGroupId and i.department = d" ).setParameterList("solverGroupId", solverGroupIds).list(); for (Long instructorId: instructorIds) { hibSessionFactory.getCache().evictEntity(DepartmentalInstructor.class, instructorId); hibSessionFactory.getCache().evictCollection(DepartmentalInstructor.class.getName()+".classes", instructorId); } List<Long> requestIds = (List<Long>)hibSession.createQuery( "select distinct r.uniqueId from Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long requestId: requestIds) { hibSessionFactory.getCache().evictEntity(TeachingRequest.class, requestId); hibSessionFactory.getCache().evictCollection(TeachingRequest.class.getName()+".assignedInstructors", requestId); } List<Long> offeringIds = (List<Long>)hibSession.createQuery( "select distinct c.schedulingSubpart.instrOfferingConfig.instructionalOffering.uniqueId from " + "Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long offeringId: offeringIds) { hibSessionFactory.getCache().evictEntity(InstructionalOffering.class, offeringId); hibSessionFactory.getCache().evictCollection(InstructionalOffering.class.getName()+".offeringCoordinators", offeringId); } } finally { hibSession.close(); } } @Override public void setApplicationProperty(Long sessionId, String key, String value) { sLog.info("Set " + key + " to " + value + (sessionId == null ? "" : " (for session " + sessionId + ")")); Properties properties = (sessionId == null ? ApplicationProperties.getConfigProperties() : ApplicationProperties.getSessionProperties(sessionId)); if (properties == null) return; if (value == null) properties.remove(key); else properties.setProperty(key, value); } @Override public void setLoggingLevel(String name, Integer level) { sLog.info("Set logging level for " + (name == null ? "root" : name) + " to " + (level == null ? "null" : Level.toLevel(level))); Logger logger = (name == null ? Logger.getRootLogger() : Logger.getLogger(name)); if (level == null) logger.setLevel(null); else logger.setLevel(Level.toLevel(level)); } @Override public void reset() { } @Override public QueueProcessor getQueueProcessor() { return LocalQueueProcessor.getInstance(); } }
apache-2.0
xloye/tddl5
tddl-executor/src/main/java/com/taobao/tddl/executor/function/Dummy.java
1015
package com.taobao.tddl.executor.function; import com.taobao.tddl.common.exception.TddlRuntimeException; import com.taobao.tddl.common.exception.code.ErrorCode; import com.taobao.tddl.executor.common.ExecutionContext; import com.taobao.tddl.optimizer.core.datatype.DataType; import com.taobao.tddl.optimizer.core.expression.IExtraFunction; /** * 假函数,不能参与任何运算。如果需要实现bdb的运算,需要额外的写实现放到map里,这个的作用就是mysql,直接发送下去的函数 * * @author Whisper */ public class Dummy extends ScalarFunction implements IExtraFunction { @Override public DataType getReturnType() { return DataType.UndecidedType; } @Override public Object compute(Object[] args, ExecutionContext ec) { throw new TddlRuntimeException(ErrorCode.ERR_NOT_SUPPORT, "function " + this.function.getFunctionName()); } @Override public String[] getFunctionNames() { return new String[] { "dummy" }; } }
apache-2.0
LordAkkarin/BaseDefense
src/main/java/org/evilco/mc/defense/common/item/trigger/MotionDetectorItem.java
4309
/* * Copyright (C) 2014 Evil-Co <http://wwww.evil-co.org> * * 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.evilco.mc.defense.common.item.trigger; import cpw.mods.fml.common.registry.LanguageRegistry; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import org.evilco.mc.defense.common.DefenseNames; import org.evilco.mc.defense.common.block.DefenseBlock; import org.evilco.mc.defense.common.gui.creative.DefenseCreativeTab; import org.evilco.mc.defense.common.tile.trigger.MotionDetectorTileEntity; import org.evilco.mc.defense.common.util.Location; import java.util.List; /** * @auhtor Johannes Donath <johannesd@evil-co.com> * @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.org> */ public class MotionDetectorItem extends Item { /** * Constructs a new MotionDetectorItem instance. */ public MotionDetectorItem () { super (); this.setUnlocalizedName (DefenseNames.ITEM_TRIGGER_MOTION_DETECTOR); this.setCreativeTab (DefenseCreativeTab.GENERIC); } /** * {@inheritDoc} */ @Override public void addInformation (ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) { super.addInformation (par1ItemStack, par2EntityPlayer, par3List, par4); par3List.add (String.format (LanguageRegistry.instance ().getStringLocalization (DefenseNames.TRANSLATION_GENERIC_ITEM_LENS_QUALITY), par1ItemStack.getItemDamage ())); } /** * {@inheritDoc} */ @Override public void getSubItems (Item p_150895_1_, CreativeTabs p_150895_2_, List p_150895_3_) { super.getSubItems (p_150895_1_, p_150895_2_, p_150895_3_); p_150895_3_.add (new ItemStack (this, 1, 1)); for (int i = 10; i <= 50; i += 10) { p_150895_3_.add (new ItemStack (this, 1, i)); } p_150895_3_.add (new ItemStack (this, 1, 80)); p_150895_3_.add (new ItemStack (this, 1, 99)); } /** * {@inheritDoc} */ @Override public boolean onItemUse (ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10) { // skip client execution if (par3World.isRemote) return true; // check whether players may edit the block if (!par2EntityPlayer.canPlayerEdit (par4, par5, par6, par7, par1ItemStack)) return false; // place block Location blockLocation = new Location (par4, par5, par6); // get direction ForgeDirection direction = ForgeDirection.getOrientation (par7); // update location blockLocation.xCoord += direction.offsetX; blockLocation.yCoord += direction.offsetY; blockLocation.zCoord += direction.offsetZ; // check current block type if (!par3World.isAirBlock (((int) blockLocation.xCoord), ((int) blockLocation.yCoord), ((int) blockLocation.zCoord))) return false; // calculate rotation int metadata = MathHelper.floor_double (((double) (par2EntityPlayer.rotationYaw * 4.0f) / 360f + 2.5D)) & 3; // set block par3World.setBlock (((int) blockLocation.xCoord), ((int) blockLocation.yCoord), ((int) blockLocation.zCoord), DefenseBlock.TRIGGER_MOTION_DETECTOR, metadata, 2); // set lens quality TileEntity tileEntity = blockLocation.getTileEntity (par3World); ((MotionDetectorTileEntity) tileEntity).setLensQuality (par1ItemStack.getItemDamage ()); // remove item from stack if (!par2EntityPlayer.capabilities.isCreativeMode) par1ItemStack.stackSize--; // confirm item use return true; } }
apache-2.0
hqq2023623/notes
thread/src/main/java/zj/thread/guarded/AlarmInfo.java
318
package zj.thread.guarded; import zj.thread.twophase.AlarmType; /** * Created by lzj on 2017/5/2. */ public class AlarmInfo { public AlarmType type; public String id; public String extraInfo; public AlarmInfo(String id, AlarmType type) { this.type = type; this.id = id; } }
apache-2.0
google/depan
DepanViewDoc/prod/src/com/google/devtools/depan/view_doc/eclipse/ui/plugins/ElementClassTransformer.java
1195
/* * Copyright 2008 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.depan.view_doc.eclipse.ui.plugins; import com.google.devtools.depan.model.Element; import com.google.devtools.depan.model.ElementTransformer; /** * An {@link ElementTransformer} that uses the {@link Class} of the element * to give the result. * * @author Yohann Coppel * * @param <R> type for the transformation result. */ public interface ElementClassTransformer<R> { /** * Associate a R to an {@link Element} class. * @param element * @return the result of the transformation. */ R transform(Class<? extends Element> element); }
apache-2.0
theborakompanioni/thymeleaf-extras-shiro
src/test/java/at/pollux/thymeleaf/shiro/dialect/HasAllPermissionsTagTest.java
4361
package at.pollux.thymeleaf.shiro.dialect; import at.pollux.thymeleaf.shiro.test.AbstractThymeleafShiroDialectTest; import at.pollux.thymeleaf.shiro.test.mother.PermissionsMother.HasAllPermissions; import at.pollux.thymeleaf.shiro.test.user.TestUsers; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.apache.shiro.subject.Subject; import org.junit.Test; import org.junit.runner.RunWith; import org.thymeleaf.context.Context; import static at.pollux.thymeleaf.shiro.test.user.TestPermissions.PERMISSION_TYPE_1_ACTION_1_INST_1; import static at.pollux.thymeleaf.shiro.test.user.TestPermissions.PERMISSION_TYPE_1_ACTION_2_EXAMPLE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; /** * @author tbk */ @RunWith(JUnitParamsRunner.class) public class HasAllPermissionsTagTest extends AbstractThymeleafShiroDialectTest { private static final String FILE_UNDER_TEST = "shiro_hasAllPermissions.html"; private static boolean hasAllFeaturesSanityCheck(Subject subject) { return subject.isPermitted(PERMISSION_TYPE_1_ACTION_1_INST_1.label()) && subject.isPermitted(PERMISSION_TYPE_1_ACTION_2_EXAMPLE); } @Test public void itShouldNotRenderWithoutSubject() { String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ATTRIBUTE_DYNAMIC"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ELEMENT_DYNAMIC"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ATTRIBUTE_STATIC"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ELEMENT_STATIC"))); } @Test @Parameters(source = HasAllPermissions.ShouldRenderForUser.class) public void itShouldRenderOnUser(TestUsers user) { Subject subjectUnderTest = createAndLoginSubject(user); boolean hasAnyFeatures = hasAllFeaturesSanityCheck(subjectUnderTest); assertThat("User has all features", hasAnyFeatures); String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, containsString("HASALLPERMISSIONS_ATTRIBUTE_STATIC")); assertThat(result, containsString("HASALLPERMISSIONS_ELEMENT_STATIC")); subjectUnderTest.logout(); } @Test @Parameters(source = HasAllPermissions.ShouldNotRenderForUser.class) public void itShouldNotRenderForUser(TestUsers user) { Subject subjectUnderTest = createAndLoginSubject(user); boolean hasAllFeatures = hasAllFeaturesSanityCheck(subjectUnderTest); assertThat("User does not have all features", !hasAllFeatures); String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ATTRIBUTE_STATIC"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ELEMENT_STATIC"))); subjectUnderTest.logout(); } @Test @Parameters(source = HasAllPermissions.ShouldRenderExpression.class) public void itShouldRenderOnCustomContext(TestUsers user, Context context) { Subject subjectUnderTest = createAndLoginSubject(user); String result = processThymeleafFile(FILE_UNDER_TEST, context); assertThat(result, not(containsString("shiro:"))); assertThat(result, containsString("HASALLPERMISSIONS_ATTRIBUTE_DYNAMIC")); assertThat(result, containsString("HASALLPERMISSIONS_ELEMENT_DYNAMIC")); subjectUnderTest.logout(); } @Test @Parameters(source = HasAllPermissions.ShouldNotRenderExpression.class) public void itShouldNotRenderOnCustomContext(TestUsers user, Context context) { Subject subjectUnderTest = createAndLoginSubject(user); String result = processThymeleafFile(FILE_UNDER_TEST, context); assertThat(result, not(containsString("shiro:"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ATTRIBUTE_DYNAMIC"))); assertThat(result, not(containsString("HASALLPERMISSIONS_ELEMENT_DYNAMIC"))); subjectUnderTest.logout(); } }
apache-2.0
anz130/khService
Dybc/app/src/main/java/com/dyb/dybc/activity/HomeActivity.java
4546
package com.dyb.dybc.activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.dyb.dybc.R; import com.dyb.dybc.fragment.HomeFragment; import com.dyb.dybc.fragment.MineFragment; import com.dyb.dybc.fragment.MyOrderFragment; import com.dyb.dybc.fragment.ShareFragment; import com.dyb.dybc.views.TitleModule; import com.zhy.zhylib.base.BaseActivity; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by zhangyong on 2017/6/29. */ public class HomeActivity extends BaseActivity { @BindView(R.id.frameLayout) FrameLayout frameLayout; @BindView(R.id.homeLinear) LinearLayout homeLinear; @BindView(R.id.orderLinear) LinearLayout orderLinear; @BindView(R.id.shareLinear) LinearLayout shareLinear; @BindView(R.id.mineLinear) LinearLayout mineLinear; private TitleModule titleModule; private FragmentManager fragmentManager; private int selectState = 0; private List<Fragment> fragList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); init(); setListener(); } private void init() { titleModule = new TitleModule(this, "抢单"); titleModule.setLeftImageVisible(false); titleModule.setRightTextVisible(true); titleModule.setRightText("下班"); fragList = new ArrayList<>(); fragmentManager = getSupportFragmentManager(); fragList.add(new HomeFragment()); fragList.add(new MyOrderFragment()); fragList.add(new ShareFragment()); fragList.add(new MineFragment()); fragmentManager.beginTransaction().replace(R.id.frameLayout, fragList.get(0), "0").commit(); homeLinear.setSelected(true); } private void setListener(){ titleModule.setRightTextViewOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } private void initViewpager(int tag) { Fragment frag = fragmentManager.findFragmentByTag("" + tag); if (frag == null) { fragmentManager.beginTransaction().add(R.id.frameLayout, fragList.get(tag), tag + "").commit(); } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (selectState != tag) { fragmentTransaction.show(fragList.get(tag)); fragmentTransaction.hide(fragList.get(selectState)); fragmentTransaction.commit(); selectState = tag; } } private void setSelectState(int state, boolean isSelect) { if (isSelect) { setSelectState(selectState, false); } switch (state) { case 0: homeLinear.setSelected(isSelect == true ? true : false); break; case 1: orderLinear.setSelected(isSelect == true ? true : false); break; case 2: shareLinear.setSelected(isSelect == true ? true : false); break; case 3: mineLinear.setSelected(isSelect == true ? true : false); break; default: break; } } @OnClick({R.id.homeLinear, R.id.orderLinear, R.id.shareLinear, R.id.mineLinear}) public void onClick(View view) { switch (view.getId()) { case R.id.homeLinear: setSelectState(0, true); initViewpager(0); titleModule.setTitle("抢单"); break; case R.id.orderLinear: setSelectState(1, true); initViewpager(1); titleModule.setTitle("订单"); break; case R.id.shareLinear: setSelectState(2, true); initViewpager(2); titleModule.setTitle("分享赚钱"); break; case R.id.mineLinear: setSelectState(3, true); initViewpager(3); titleModule.setTitle("我的"); break; } } }
apache-2.0
detnavillus/multifield_suggester_code
suggester-builder/src/main/java/com/lucidworks/suggester/QueryCollector.java
269
package com.lucidworks.suggester; import java.util.List; import java.util.Map; public interface QueryCollector extends Runnable { public void initialize( Map<String,Object> config ); public void setSuggestionProcessor( SuggestionProcessor processor ); }
apache-2.0
liudeyu/MeLife
PMS/GzmeLife/src/com/gzmelife/app/tools/HttpDownloader.java
5232
package com.gzmelife.app.tools; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import android.util.Log; public class HttpDownloader { private URL url=null; FileUtil fileUtils=new FileUtil(); File resultFile; private HttpURLConnection curConnect=null; public interface loaderListener{ void onStart(int cursize,int allSize); void onError(int code); void OnComplete(int code); void onLoading(int cursize,int allSize); } private loaderListener mloaderListener; public File downfilePms(String urlStr,String path,String fileName) { // int flag = 2; // if(fileUtils.isFileExist(path+fileName)){ // String resultPath = path.substring(0, path.indexOf('.')) + "(" + flag++ + ")" + path.substring(path.indexOf('.')); // String filePath=fileUtils.getFileName(path+fileName); // String[] str=filePath.split("/"); // try { // InputStream input=null; // input = getInputStream(urlStr); // File resultFile=fileUtils.write2SDFromInput(path, str[1], input); // if(resultFile==null){ // return -1; // } // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return null; // // }else{ try { InputStream input=null; input = getInputStream(urlStr); resultFile=write2SDFromInput(path, fileName, input); if(resultFile==null){ return null; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // } return resultFile; } public int downfile(String urlStr,String path,String fileName) { //返回值:1:已下载 -1下载失败 int flag = 2; if(fileUtils.isFileExist(path+fileName)){ // // String resultPath = path.substring(0, path.indexOf('.')) + "(" + flag++ + ")" + path.substring(path.indexOf('.')); // String filePath=fileUtils.getFileName(path+fileName); // String[] str=filePath.split("/"); // try { // InputStream input=null; // input = getInputStream(urlStr); // File resultFile=fileUtils.write2SDFromInput(path, str[1], input); // if(resultFile==null){ // return -1; // } // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if(mloaderListener!=null) mloaderListener.onError(1); return 1; }else{ try { InputStream input=null; input = getInputStream(urlStr); // File resultFile=fileUtils.write2SDFromInput(path, fileName, input); File resultFile=write2SDFromInput(path, fileName, input); if(resultFile==null){ // if(mloaderListener!=null) // mloaderListener.onError(-1); return -1; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return 0; } //由于得到一个InputStream对象是所有文件处理前必须的操作,所以将这个操作封装成了一个方法 public InputStream getInputStream(String urlStr) throws IOException { InputStream is=null; try { url=new URL(urlStr); HttpURLConnection urlConn=(HttpURLConnection)url.openConnection(); curConnect=urlConn; is=urlConn.getInputStream(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return is; } private File write2SDFromInput(String path,String fileName,InputStream input){ File file = null; OutputStream output = null; // InputStreamReader try{ fileUtils.creatSDDir(path); byte[] fileName_gbk=fileName.getBytes("gbk"); String fileName_gbk_str=new String(fileName_gbk, "gbk"); file = fileUtils.creatSDFile(path + fileName); long newTime = (new Date()).getTime(); file.setLastModified(newTime); // Log.i("PMS", "into—--"+dateFormat(file.lastModified())); output = new FileOutputStream(file); // byte buffer [] = new byte[(int) file.length()]; int temp = 0; // byte[] data = new byte[1024]; byte[] data = new byte[512]; if(mloaderListener!=null){ if(curConnect!=null) mloaderListener.onStart(0, curConnect.getContentLength()); } int allsize= curConnect.getContentLength(); int count=0; while((temp = input.read(data)) != -1){ output.write(data, 0, temp); count+=temp; if(mloaderListener!=null){ mloaderListener.onLoading(count, allsize); } } output.flush(); } catch(Exception e){ e.printStackTrace(); if(mloaderListener!=null){ mloaderListener.onError(-1); } } finally{ try{ output.close(); if(mloaderListener!=null){ mloaderListener.OnComplete(0); } } catch(Exception e){ e.printStackTrace(); if(mloaderListener!=null){ mloaderListener.onError(-1); } } } return file; } public void setOnLoaderListener(loaderListener lister){ mloaderListener=lister; } }
apache-2.0
neovera/jdiablo
src/main/java/org/neovera/jdiablo/environment/SpringEnvironment.java
8180
/** * Copyright 2012 Neovera Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neovera.jdiablo.environment; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.neovera.jdiablo.AbstractEnvironment; import org.neovera.jdiablo.Environment; import org.neovera.jdiablo.OptionProperty; import org.neovera.jdiablo.annotation.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Bootstraps Spring and provides option values who's fields are annotated with PropertyPlaceholder (provided there is * a bean of the type PropertyPlaceholderProvider in Spring). If your context has an instance of * AutowiredAnnotationBeanPostProcessor all fields marked with the @Inject annotation are automatically set. In addition, * if the Launchable class implements the BeanFactoryAware interface, the bean factory is also set. */ public class SpringEnvironment extends AbstractEnvironment { @Option(shortOption = "scf", longOption = "springContext", description = "Spring context file", hasArgs = true, valueSeparator = ',', required = true) private String[] _springContextFiles = new String[0]; private ApplicationContext _context; private static Logger _logger = LoggerFactory.getLogger(SpringEnvironment.class); public String[] getSpringContextFiles() { return _springContextFiles; } public void setSpringContextFiles(String[] springContextFiles) { _springContextFiles = springContextFiles; } @Override public boolean start() { _context = new ClassPathXmlApplicationContext(getSpringContextFiles()); return true; } @Override public void stop() { ((AbstractApplicationContext)_context).close(); } @Override public void initialize(Environment environment, List<? extends OptionProperty> properties) { injectDependencies(environment); } @Override public void initialize(Object target, List<? extends OptionProperty> properties) { injectDependencies(target); } private void injectDependencies(Object object) { injectBeans(object); injectBeanFactory(object); injectProperties(object); } private void injectProperties(Object object) { Map<String, PropertyPlaceholderProvider> map = _context.getBeansOfType(PropertyPlaceholderProvider.class); PropertyPlaceholderProvider ppp = null; if (map.size() != 0) { ppp = map.values().iterator().next(); } // Analyze members to see if they are annotated. Map<String, String> propertyNamesByField = new HashMap<String, String>(); Class<?> clz = object.getClass(); while (!clz.equals(Object.class)) { for (Field field : clz.getDeclaredFields()) { if (field.isAnnotationPresent(PropertyPlaceholder.class)) { propertyNamesByField.put(field.getName().startsWith("_") ? field.getName().substring(1) : field.getName(), field.getAnnotation(PropertyPlaceholder.class) .value()); } } clz = clz.getSuperclass(); } PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object.getClass()); for (PropertyDescriptor pd : descriptors) { if (propertyNamesByField.keySet().contains(pd.getName())) { if (ppp == null) { _logger.error("Field {} is annotated with PropertyPlaceholder but no bean of type " + "PropertyPlaceholderProvider is defined in the Spring application context.", pd.getName()); break; } else { setValue(pd, object, ppp.getProperty(propertyNamesByField.get(pd.getName()))); } } else if (pd.getReadMethod() != null && pd.getReadMethod().isAnnotationPresent(PropertyPlaceholder.class)) { if (ppp == null) { _logger.error("Field {} is annotated with PropertyPlaceholder but no bean of type " + "PropertyPlaceholderProvider is defined in the Spring application context.", pd.getName()); break; } else { setValue(pd, object, ppp.getProperty(pd.getReadMethod().getAnnotation(PropertyPlaceholder.class).value())); } } } } private void setValue(PropertyDescriptor pd, Object target, String value) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null) { throw new RuntimeException("No write method found for property " + pd.getName()); } try { if (writeMethod.getParameterTypes()[0].equals(Boolean.class) || "boolean".equals(writeMethod.getParameterTypes()[0].getName())) { writeMethod.invoke(target, value == null ? false : "true".equals(value)); } else if (writeMethod.getParameterTypes()[0].equals(Integer.class) || "int".equals(writeMethod.getParameterTypes()[0].getName())) { writeMethod.invoke(target, value == null ? 0 : Integer.parseInt(value)); } else if (writeMethod.getParameterTypes()[0].equals(Long.class) || "long".equals(writeMethod.getParameterTypes()[0].getName())) { writeMethod.invoke(target, value == null ? 0 : Long.parseLong(value)); } else if (writeMethod.getParameterTypes()[0].equals(BigDecimal.class)) { writeMethod.invoke(target, value == null ? null : new BigDecimal(value)); } else if (writeMethod.getParameterTypes()[0].equals(String.class)) { writeMethod.invoke(target, value); } else if (writeMethod.getParameterTypes()[0].isArray() && writeMethod.getParameterTypes()[0].getName().contains(String.class.getName())) { writeMethod.invoke(target, (Object[])value.split(",")); } else { throw new RuntimeException("Could not resolve parameter type for " + writeMethod.toString()); } } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private void injectBeanFactory(Object object) { if (object instanceof BeanFactoryAware) { ((BeanFactoryAware)object).setBeanFactory(_context); } } private void injectBeans(Object object) { AutowiredAnnotationBeanPostProcessor proc = _context.getBean(AutowiredAnnotationBeanPostProcessor.class); if (proc == null) { throw new RuntimeException("Could not find an autowired annotation bean post processor of type {} " + AutowiredAnnotationBeanPostProcessor.class.getName()); } else { proc.processInjection(object); } } }
apache-2.0
clive-jevons/joynr
java/core/libjoynr/src/main/java/io/joynr/dispatching/subscription/AttributeListenerImpl.java
1286
package io.joynr.dispatching.subscription; import io.joynr.pubsub.publication.AttributeListener; /* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT 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. * #L% */ public class AttributeListenerImpl implements AttributeListener { private final String subscriptionId; private final PublicationManagerImpl publicationManagerImpl; public AttributeListenerImpl(String subscriptionId, PublicationManagerImpl publicationManagerImpl) { this.subscriptionId = subscriptionId; this.publicationManagerImpl = publicationManagerImpl; } @Override public void attributeValueChanged(Object value) { publicationManagerImpl.attributeValueChanged(subscriptionId, value); } }
apache-2.0
echatman/nextbus
src/main/java/com/echatman/nextbus/response/predictions/Predictions.java
4356
package com.echatman.nextbus.response.predictions; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * Within the <predictions> element are possibly multiple <direction> * elements and possibly multiple <message> elements. * * @author echatman */ @XmlType public class Predictions { private String agencyTitle; private List<PredictionDirection> directions = new ArrayList<>(); private String dirTitleBecauseNoPredictions; private List<PredictionMessage> messages = new ArrayList<>(); private String routeTag; private String routeTitle; private String stopTitle; private String stopTag; /** * The name of the agency to be displayed to passenger. */ @XmlAttribute public String getAgencyTitle() { return agencyTitle; } /** * Because routes can have multiple destinations the predictions are * separated by <direction> so the client can let the passenger know * whether the predicted for vehicles are actually going to their * destination. Then within the <direction> element a separate * <prediction> element is provided, one for each vehicle being * predicted. No more than 5 predictions per direction will be provided * in the feed. */ @XmlElement(name = "direction") public List<PredictionDirection> getDirections() { return directions; } /** * Title of direction. This attribute is only provided if there are no * predictions. The direction title is provided in this situation * because no <direction> elements are available since there are no * predictions. This way the User Interface can still display the title * of the direction selected even when there are no predictions. */ @XmlAttribute public String getDirTitleBecauseNoPredictions() { return dirTitleBecauseNoPredictions; } /** * The <message> elements are important to handle because they provide * important status information to passengers. These messages might be * configured for an entire agency, for a route, or for a set of stops. * If more detailed information is required then should use the messages * command. Multiple messages can be returned for a single stop. The * only attribute in the message element is called text, which contains * the text of the message. */ @XmlElement(name = "message") public List<PredictionMessage> getMessages() { return messages; } /** * Identifier for the route. */ @XmlAttribute public String getRouteTag() { return routeTag; } /** * Title of the route to be displayed to passenger. */ @XmlAttribute public String getRouteTitle() { return routeTitle; } /** * Title of the stop to be displayed to passenger. */ @XmlAttribute public String getStopTitle() { return stopTitle; } /** * Not documented, but observed in real responses. */ @XmlAttribute public String getStopTag() { return stopTag; } @SuppressWarnings("unused") private void setAgencyTitle(String agencyTitle) { this.agencyTitle = agencyTitle; } @SuppressWarnings("unused") private void setDirections(List<PredictionDirection> directions) { this.directions = directions; } @SuppressWarnings("unused") private void setDirTitleBecauseNoPredictions(String dirTitleBecauseNoPredictions) { this.dirTitleBecauseNoPredictions = dirTitleBecauseNoPredictions; } @SuppressWarnings("unused") private void setMessages(List<PredictionMessage> messages) { this.messages = messages; } @SuppressWarnings("unused") private void setRouteTag(String routeTag) { this.routeTag = routeTag; } @SuppressWarnings("unused") private void setRouteTitle(String routeTitle) { this.routeTitle = routeTitle; } @SuppressWarnings("unused") private void setStopTitle(String stopTitle) { this.stopTitle = stopTitle; } @SuppressWarnings("unused") private void setStopTag(String stopTag) { this.stopTag = stopTag; } }
apache-2.0
jrivets/saltedge-connector
src/main/java/org/jrivets/connector/saltedge/v2/ErrorResponse.java
507
package org.jrivets.connector.saltedge.v2; public class ErrorResponse { // the class of the error, one of the listed below public Error error_class; // a message describing the error public String message; public Object request; @Override public String toString() { ToStringHelper builder = new ToStringHelper(this); builder.append("error_class", error_class).append("message", message).append("request", request); return builder.toString(); } }
apache-2.0
orctom/laputa
laputa-http-client/src/main/java/com/orctom/laputa/http/client/HttpClient.java
4890
package com.orctom.laputa.http.client; import com.google.common.base.Strings; import com.orctom.laputa.http.client.core.ChannelExecutor; import com.orctom.laputa.http.client.core.HttpRequestFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.QueryStringEncoder; import io.netty.handler.codec.http.cookie.ClientCookieEncoder; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.DefaultCookie; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import static io.netty.handler.codec.http.HttpHeaderNames.COOKIE; import static io.netty.handler.codec.http.HttpMethod.POST; public class HttpClient { private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); private ChannelExecutor channelExecutor; private HttpMethod httpMethod; private URI uri; private String body; private Map<String, String> params; private Map<String, ?> headers; private Map<String, String> cookies; private HttpClient(HttpClientConfig httpClientConfig) { this.channelExecutor = ChannelExecutor.getInstance(httpClientConfig); } public static HttpClient create() { return new HttpClient(HttpClientConfig.DEFAULT); } public static HttpClient create(HttpClientConfig httpClientConfig) { return new HttpClient(httpClientConfig); } public HttpClient get(String uri) { return request(HttpMethod.GET, URI.create(uri)); } public HttpClient post(String uri) { return request(POST, URI.create(uri)); } public HttpClient delete(String uri) { return request(HttpMethod.DELETE, URI.create(uri)); } public HttpClient put(String uri) { return request(HttpMethod.PUT, URI.create(uri)); } private HttpClient request(HttpMethod httpMethod, URI uri) { this.httpMethod = httpMethod; this.uri = uri; return this; } public HttpClient withBody(String body) { this.body = body; return this; } public HttpClient withParams(Map<String, String> params) { this.params = params; return this; } public HttpClient withHeaders(Map<String, ?> headers) { this.headers = headers; return this; } public HttpClient withCookies(Map<String, String> cookies) { this.cookies = cookies; return this; } public ResponseFuture execute() { URI transformedUri = transformedUri(); DefaultFullHttpRequest request = HttpRequestFactory.create(httpMethod, transformedUri); setBody(request); setParams(request, transformedUri); setHeaders(request); setCookies(request); return channelExecutor.execute(request, uri.getHost(), uri.getPort()); } private URI transformedUri() { if (null == params || params.isEmpty()) { return uri; } QueryStringEncoder encoder = new QueryStringEncoder(uri.toString()); for (Map.Entry<String, String> entry : params.entrySet()) { encoder.addParam(entry.getKey(), entry.getValue()); } return URI.create(encoder.toString()); } private void setBody(DefaultFullHttpRequest request) { if (POST != httpMethod) { return; } if (Strings.isNullOrEmpty(body)) { return; } setRequestContent(request, body); } private void setParams(DefaultFullHttpRequest request, URI uri) { if (POST != httpMethod) { return; } String query = uri.getQuery(); if (Strings.isNullOrEmpty(query)) { return; } setRequestContent(request, query); } private void setRequestContent(DefaultFullHttpRequest request, String content) { ByteBuf byteBuf = Unpooled.copiedBuffer(content, StandardCharsets.UTF_8); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes()); request.content().clear().writeBytes(byteBuf); } private void setHeaders(HttpRequest request) { if (null == headers || headers.isEmpty()) { return; } HttpHeaders httpHeaders = request.headers(); for (Map.Entry<String, ?> entry : headers.entrySet()) { httpHeaders.set(entry.getKey(), entry.getValue()); } } private void setCookies(HttpRequest request) { if (null == cookies || cookies.isEmpty()) { return; } List<Cookie> cookieList = new ArrayList<>(cookies.size()); for (Map.Entry<String, String> entry : cookies.entrySet()) { cookieList.add(new DefaultCookie(entry.getKey(), entry.getValue())); } request.headers().set(COOKIE, ClientCookieEncoder.STRICT.encode(cookieList)); } }
apache-2.0
rborer/google-cloud-java
google-cloud-core-grpc/src/main/java/com/google/cloud/grpc/BaseGrpcServiceException.java
3009
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.grpc; import com.google.api.client.http.HttpResponseException; import com.google.api.core.InternalApi; import com.google.api.gax.grpc.ApiException; import com.google.cloud.BaseServiceException; import com.google.common.base.MoreObjects; import java.io.IOException; import java.util.Collections; /** * Base class for all exceptions from grpc-based services. */ public class BaseGrpcServiceException extends BaseServiceException { private static final long serialVersionUID = -2685197215731335549L; @InternalApi("This class should only be extended within google-cloud-java") protected BaseGrpcServiceException(String message, Throwable cause, int code, boolean retryable) { super(ExceptionData.newBuilder().setMessage(message).setCause(cause).setCode(code) .setRetryable(retryable).build()); } @InternalApi("This class should only be extended within google-cloud-java") protected BaseGrpcServiceException(IOException exception, boolean idempotent) { super(makeExceptionData(exception, idempotent)); } private static ExceptionData makeExceptionData(IOException exception, boolean idempotent) { int code = UNKNOWN_CODE; Boolean retryable = null; if (exception instanceof HttpResponseException) { // In cases where an exception is an instance of HttpResponseException, // check the status code to determine whether it's retryable code = ((HttpResponseException) exception).getStatusCode(); retryable = BaseServiceException .isRetryable(code, null, idempotent, Collections.<Error>emptySet()); } return ExceptionData.newBuilder() .setMessage(exception.getMessage()) .setCause(exception) .setRetryable(MoreObjects .firstNonNull(retryable, BaseServiceException.isRetryable(idempotent, exception))) .setCode(code) .setReason(null) .setLocation(null) .setDebugInfo(null) .build(); } public BaseGrpcServiceException(ApiException apiException) { super(ExceptionData.newBuilder() .setMessage(apiException.getMessage()) .setCause(apiException) .setRetryable(apiException.isRetryable()) .setCode(apiException.getStatusCode().value()) .setReason(apiException.getStatusCode().name()) .setLocation(null) .setDebugInfo(null) .build()); } }
apache-2.0
EBISPOT/goci
goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/service/deposition/StudiesProcessingService.java
6814
package uk.ac.ebi.spot.goci.curation.service.deposition; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.curation.service.StudyNoteOperationsService; import uk.ac.ebi.spot.goci.model.*; import uk.ac.ebi.spot.goci.model.deposition.*; import uk.ac.ebi.spot.goci.repository.NoteRepository; import uk.ac.ebi.spot.goci.repository.NoteSubjectRepository; import uk.ac.ebi.spot.goci.service.EventOperationsService; import uk.ac.ebi.spot.goci.service.PublicationService; import uk.ac.ebi.spot.goci.service.StudyService; import java.text.SimpleDateFormat; import java.util.*; @Service public class StudiesProcessingService { private Logger log = LoggerFactory.getLogger(getClass()); protected Logger getLog() { return log; } @Autowired private StudyService studyService; @Autowired private StudyNoteOperationsService noteOperationsService; @Autowired private NoteSubjectRepository noteSubjectRepository; @Autowired private NoteRepository noteRepository; @Autowired private SingleStudyProcessingService singleStudyProcessingService; @Autowired private EventOperationsService eventOperationsService; @Autowired private DepositionSampleService depositionSampleService; @Autowired private PublicationService publicationService; @Autowired private DepositionAssociationService depositionAssociationService; public boolean processStudies(DepositionSubmission depositionSubmission, SecureUser currentUser, Publication publication, Curator curator, ImportLog importLog) { for (DepositionStudyDto studyDto : depositionSubmission.getStudies()) { getLog().info("[{}] Processing study: {} | {}.", depositionSubmission.getSubmissionId(), studyDto.getStudyTag(), studyDto.getAccession()); ImportLogStep importStep = importLog.addStep(new ImportLogStep("Creating study [" + studyDto.getAccession() + "]", depositionSubmission.getSubmissionId())); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); StringBuffer studyNote = new StringBuffer(sdf.format(new Date()) + "\n"); List<DepositionAssociationDto> associations = depositionSubmission.getAssociations(); List<DepositionSampleDto> samples = depositionSubmission.getSamples(); List<DepositionNoteDto> notes = depositionSubmission.getNotes(); String studyTag = studyDto.getStudyTag(); studyNote.append("created " + studyTag + "\n"); Study study; List<EfoTrait> efoTraits; List<EfoTrait> bkgEfoTraits; try { Pair<Study, List<EfoTrait>> pair = singleStudyProcessingService.processStudy(studyDto, publication); study = pair.getLeft(); efoTraits = pair.getRight(); bkgEfoTraits = new ArrayList<>(study.getMappedBackgroundTraits()); } catch (Exception e) { getLog().error("Unable to create study [{} | {}]: {}", studyDto.getStudyTag(), studyDto.getAccession(), e.getMessage(), e); importLog.addError("Unable to create study [" + studyDto.getStudyTag() + " | " + studyDto.getAccession() + "]: " + e.getMessage(), "Creating study [" + studyDto.getAccession() + "]"); importLog.updateStatus(importStep.getId(), ImportLog.FAIL); return false; } Collection<Study> pubStudies = publication.getStudies(); if (pubStudies == null) { pubStudies = new ArrayList<>(); } pubStudies.add(study); publication.setStudies(pubStudies); studyService.save(study); publicationService.save(publication); if (associations != null) { getLog().info("Found {} associations in the submission retrieved from the Deposition App.", associations.size()); studyNote.append(depositionAssociationService.saveAssociations(currentUser, studyTag, study, associations, efoTraits, bkgEfoTraits, importLog)); } if (samples != null) { getLog().info("Found {} samples in the submission retrieved from the Deposition App.", samples.size()); studyNote.append(depositionSampleService.saveSamples(studyTag, study, samples, importLog)); } getLog().info("Creating events ..."); Event event = eventOperationsService.createEvent("STUDY_CREATION", currentUser, "Import study " + "creation"); List<Event> events = new ArrayList<>(); events.add(event); study.setEvents(events); getLog().info("Adding notes ..."); this.addStudyNote(study, studyDto.getStudyTag(), studyNote.toString(), "STUDY_CREATION", curator, "Import study creation", currentUser); if (notes != null) { //find notes in study for (DepositionNoteDto noteDto : notes) { if (noteDto.getStudyTag().equals(studyTag)) { this.addStudyNote(study, studyDto.getStudyTag(), noteDto.getNote(), noteDto.getStatus(), curator, noteDto.getNoteSubject(), currentUser); } } } studyService.save(study); importLog.updateStatus(importStep.getId(), ImportLog.SUCCESS); } getLog().info("All done ..."); return true; } private void addStudyNote(Study study, String studyTag, String noteText, String noteStatus, Curator noteCurator, String noteSubject, SecureUser currentUser) { StudyNote note = noteOperationsService.createEmptyStudyNote(study, currentUser); if (studyTag != null) { note.setTextNote(studyTag + "\n" + noteText); } else { note.setTextNote(noteText); } if (noteStatus != null) { note.setStatus(Boolean.parseBoolean(noteStatus)); } if (noteCurator != null) { note.setCurator(noteCurator); } if (noteSubject != null) { NoteSubject subject = noteSubjectRepository.findBySubjectIgnoreCase(noteSubject); if (subject == null) { subject = noteSubjectRepository.findBySubjectIgnoreCase("System note"); } note.setNoteSubject(subject); } note.setStudy(study); noteRepository.save(note); study.addNote(note); studyService.save(study); } }
apache-2.0
janezhango/BigDataMachineLearning
src/main/java/water/HeartBeatThread.java
5498
package water; import java.lang.management.ManagementFactory; import javax.management.*; import water.persist.Persist; import water.util.LinuxProcFileReader; import water.util.Log; /** * Starts a thread publishing multicast HeartBeats to the local subnet: the * Leader of this Cloud. * * @author <a href="mailto:cliffc@0xdata.com"></a> * @version 1.0 */ public class HeartBeatThread extends Thread { public HeartBeatThread() { super("Heartbeat"); setDaemon(true); } // Time between heartbeats. Strictly several iterations less than the // timeout. static final int SLEEP = 1000; // Timeout in msec before we decide to not include a Node in the next round // of Paxos Cloud Membership voting. static public final int TIMEOUT = 60000; // Timeout in msec before we decide a Node is suspect, and call for a vote // to remove him. This must be strictly greater than the TIMEOUT. static final int SUSPECT = TIMEOUT+500; // Receive queue depth count before we decide a Node is suspect, and call for a vote // to remove him. static public final int QUEUEDEPTH = 100; // My Histogram. Called from any thread calling into the MM. // Singleton, allocated now so I do not allocate during an OOM event. static private final H2O.Cleaner.Histo myHisto = new H2O.Cleaner.Histo(); // uniquely number heartbeats for better timelines static private int HB_VERSION; // The Run Method. // Started by main() on a single thread, this code publishes Cloud membership // to the Cloud once a second (across all members). If anybody disagrees // with the membership Heartbeat, they will start a round of Paxos group // discovery. public void run() { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName os; try { os = new ObjectName("java.lang:type=OperatingSystem"); } catch( MalformedObjectNameException e ) { throw Log.errRTExcept(e); } Thread.currentThread().setPriority(Thread.MAX_PRIORITY); while( true ) { // Once per second, for the entire cloud a Node will multi-cast publish // itself, so other unrelated Clouds discover each other and form up. try { Thread.sleep(SLEEP); } // Only once-sec per entire Cloud catch( InterruptedException e ) { } // Update the interesting health self-info for publication also H2O cloud = H2O.CLOUD; HeartBeat hb = H2O.SELF._heartbeat; hb._hb_version = HB_VERSION++; hb._jvm_boot_msec= TimeLine.JVM_BOOT_MSEC; final Runtime run = Runtime.getRuntime(); hb.set_free_mem (run. freeMemory()); hb.set_max_mem (run. maxMemory()); hb.set_tot_mem (run.totalMemory()); hb._keys = (H2O.STORE.size ()); hb.set_valsz (myHisto.histo(false)._cached); hb._num_cpus = (char)run.availableProcessors(); Object load = null; try { load = mbs.getAttribute(os, "SystemLoadAverage"); } catch( Exception e ) { // Ignore, data probably not available on this VM } hb._system_load_average = load instanceof Double ? ((Double) load).floatValue() : 0; int rpcs = 0; for( H2ONode h2o : cloud._memary ) rpcs += h2o.taskSize(); hb._rpcs = (char)rpcs; // Scrape F/J pool counts hb._fjthrds = new short[H2O.MAX_PRIORITY+1]; hb._fjqueue = new short[H2O.MAX_PRIORITY+1]; for( int i=0; i<hb._fjthrds.length; i++ ) { hb._fjthrds[i] = (short)H2O.getWrkThrPoolSize(i); hb._fjqueue[i] = (short)H2O.getWrkQueueSize(i); } hb._tcps_active= (char)H2ONode.TCPS.get(); // get the usable and total disk storage for the partition where the // persistent KV pairs are stored hb.set_free_disk(Persist.getIce().getUsableSpace()); hb.set_max_disk(Persist.getIce().getTotalSpace()); // get cpu utilization for the system and for this process. (linux only.) LinuxProcFileReader lpfr = new LinuxProcFileReader(); lpfr.read(); if (lpfr.valid()) { hb._system_idle_ticks = lpfr.getSystemIdleTicks(); hb._system_total_ticks = lpfr.getSystemTotalTicks(); hb._process_total_ticks = lpfr.getProcessTotalTicks(); hb._process_num_open_fds = lpfr.getProcessNumOpenFds(); } else { hb._system_idle_ticks = -1; hb._system_total_ticks = -1; hb._process_total_ticks = -1; hb._process_num_open_fds = -1; } hb._pid = lpfr.getProcessID(); // Announce what Cloud we think we are in. // Publish our health as well. UDPHeartbeat.build_and_multicast(cloud, hb); // If we have no internet connection, then the multicast goes // nowhere and we never receive a heartbeat from ourselves! // Fake it now. long now = System.currentTimeMillis(); H2O.SELF._last_heard_from = now; // Look for napping Nodes & propose removing from Cloud for( H2ONode h2o : cloud._memary ) { long delta = now - h2o._last_heard_from; if( delta > SUSPECT ) {// We suspect this Node has taken a dirt nap if( !h2o._announcedLostContact ) { Paxos.print("hart: announce suspect node",cloud._memary,h2o.toString()); h2o._announcedLostContact = true; } } else if( h2o._announcedLostContact ) { Paxos.print("hart: regained contact with node",cloud._memary,h2o.toString()); h2o._announcedLostContact = false; } } } } }
apache-2.0
erikorbons/axo
axo-core/src/main/java/axo/core/storage/StorageMethod.java
130
package axo.core.storage; public enum StorageMethod { SESSION_TEMPORARY, SESSION_TEMPORARY_IN_MEMORY, IN_MEMORY, PERMANENT }
apache-2.0
Distrotech/buck
src/com/facebook/buck/cxx/CxxPlatforms.java
12387
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.log.Logger; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.ImmutableFlavor; import com.facebook.buck.rules.HashedFileTool; import com.facebook.buck.rules.Tool; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; public class CxxPlatforms { private static final Logger LOG = Logger.get(CxxPlatforms.class); private static final ImmutableList<String> DEFAULT_ASFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_ASPPFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_CFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_CXXFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_CPPFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_CXXPPFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_LDFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_ARFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_RANLIBFLAGS = ImmutableList.of(); private static final ImmutableList<String> DEFAULT_COMPILER_ONLY_FLAGS = ImmutableList.of(); @VisibleForTesting static final DebugPathSanitizer DEFAULT_DEBUG_PATH_SANITIZER = new DebugPathSanitizer( 250, File.separatorChar, Paths.get("."), ImmutableBiMap.<Path, Path>of()); // Utility class, do not instantiate. private CxxPlatforms() { } public static CxxPlatform build( Flavor flavor, CxxBuckConfig config, Tool as, Preprocessor aspp, Compiler cc, Compiler cxx, Preprocessor cpp, Preprocessor cxxpp, Linker ld, Iterable<String> ldFlags, Tool strip, Archiver ar, Tool ranlib, ImmutableList<String> asflags, ImmutableList<String> asppflags, ImmutableList<String> cflags, ImmutableList<String> cppflags, String sharedLibraryExtension, String sharedLibraryVersionedExtensionFormat, Optional<DebugPathSanitizer> debugPathSanitizer, ImmutableMap<String, String> flagMacros) { // TODO(bhamiltoncx, andrewjcg): Generalize this so we don't need all these setters. CxxPlatform.Builder builder = CxxPlatform.builder(); builder .setFlavor(flavor) .setAs(getTool(flavor, "as", config).or(as)) .setAspp( getTool(flavor, "aspp", config).transform(getPreprocessor(aspp.getClass())).or(aspp)) // TODO(Coneko): Don't assume the compiler override specifies the same type of compiler as // the default one. .setCc(getTool(flavor, "cc", config).transform(getCompiler(cc.getClass())).or(cc)) .setCxx(getTool(flavor, "cxx", config).transform(getCompiler(cxx.getClass())).or(cxx)) .setCpp(getTool(flavor, "cpp", config).transform(getPreprocessor(cpp.getClass())).or(cpp)) .setCxxpp( getTool(flavor, "cxxpp", config).transform(getPreprocessor(cxxpp.getClass())).or(cxxpp)) .setLd(getTool(flavor, "ld", config).transform(getLinker(ld.getClass(), config)).or(ld)) .addAllLdflags(ldFlags) .setAr(getTool(flavor, "ar", config).transform(getArchiver(ar.getClass(), config)).or(ar)) .setRanlib(getTool(flavor, "ranlib", config).or(ranlib)) .setStrip(getTool(flavor, "strip", config).or(strip)) .setSharedLibraryExtension(sharedLibraryExtension) .setSharedLibraryVersionedExtensionFormat(sharedLibraryVersionedExtensionFormat) .setDebugPathSanitizer(debugPathSanitizer.or(CxxPlatforms.DEFAULT_DEBUG_PATH_SANITIZER)) .setFlagMacros(flagMacros); builder.addAllCflags(cflags); builder.addAllCxxflags(cflags); builder.addAllCppflags(cppflags); builder.addAllCxxppflags(cppflags); builder.addAllAsflags(asflags); builder.addAllAsppflags(asppflags); CxxPlatforms.addToolFlagsFromConfig(config, builder); return builder.build(); } /** * Creates a CxxPlatform with a defined flavor for a CxxBuckConfig with default values * provided from another default CxxPlatform */ public static CxxPlatform copyPlatformWithFlavorAndConfig( CxxPlatform defaultPlatform, CxxBuckConfig config, Flavor flavor ) { CxxPlatform.Builder builder = CxxPlatform.builder(); builder .setFlavor(flavor) .setAs(getTool(flavor, "as", config).or(defaultPlatform.getAs())) .setAspp( getTool(flavor, "aspp", config) .transform(getPreprocessor(defaultPlatform.getAspp().getClass())) .or(defaultPlatform.getAspp())) .setCc( getTool(flavor, "cc", config) .transform(getCompiler(defaultPlatform.getCc().getClass())) .or(defaultPlatform.getCc())) .setCxx( getTool(flavor, "cxx", config) .transform(getCompiler(defaultPlatform.getCxx().getClass())) .or(defaultPlatform.getCxx())) .setCpp( getTool(flavor, "cpp", config) .transform(getPreprocessor(defaultPlatform.getCpp().getClass())) .or(defaultPlatform.getCpp())) .setCxxpp( getTool(flavor, "cxxpp", config) .transform(getPreprocessor(defaultPlatform.getCxxpp().getClass())) .or(defaultPlatform.getCxxpp())) .setLd( getTool(flavor, "ld", config) .transform(getLinker(defaultPlatform.getLd().getClass(), config)) .or(defaultPlatform.getLd())) .setAr(getTool(flavor, "ar", config) .transform(getArchiver(defaultPlatform.getAr().getClass(), config)) .or(defaultPlatform.getAr())) .setRanlib(getTool(flavor, "ranlib", config).or(defaultPlatform.getRanlib())) .setStrip(getTool(flavor, "strip", config).or(defaultPlatform.getStrip())) .setSharedLibraryExtension(defaultPlatform.getSharedLibraryExtension()) .setSharedLibraryVersionedExtensionFormat( defaultPlatform.getSharedLibraryVersionedExtensionFormat()) .setDebugPathSanitizer(defaultPlatform.getDebugPathSanitizer()); if (config.getDefaultPlatform().isPresent()) { // Try to add the tool flags from the default platform CxxPlatforms.addToolFlagsFromCxxPlatform(builder, defaultPlatform); } CxxPlatforms.addToolFlagsFromConfig(config, builder); return builder.build(); } private static Function<Tool, Compiler> getCompiler(final Class<? extends Compiler> ccClass) { return new Function<Tool, Compiler>() { @Override public Compiler apply(Tool input) { try { return ccClass.getConstructor(Tool.class).newInstance(input); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } }; } private static Function<Tool, Preprocessor> getPreprocessor( final Class<? extends Preprocessor> cppClass) { return new Function<Tool, Preprocessor>() { @Override public Preprocessor apply(Tool input) { try { return cppClass.getConstructor(Tool.class).newInstance(input); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } }; } private static Function<Tool, Archiver> getArchiver(final Class<? extends Archiver> arClass, final CxxBuckConfig config) { return new Function<Tool, Archiver>() { @Override public Archiver apply(Tool input) { try { return config.getArchiver(input) .or(arClass.getConstructor(Tool.class).newInstance(input)); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } }; } private static Function<Tool, Linker> getLinker(final Class<? extends Linker> ldClass, final CxxBuckConfig config) { return new Function<Tool, Linker>() { @Override public Linker apply(Tool input) { try { return config.getLinker(input).or(ldClass.getConstructor(Tool.class).newInstance(input)); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } }; } public static void addToolFlagsFromConfig( CxxBuckConfig config, CxxPlatform.Builder builder) { ImmutableList<String> asflags = config.getFlags("asflags").or(DEFAULT_ASFLAGS); ImmutableList<String> cflags = config.getFlags("cflags").or(DEFAULT_CFLAGS); ImmutableList<String> cxxflags = config.getFlags("cxxflags").or(DEFAULT_CXXFLAGS); ImmutableList<String> compilerOnlyFlags = config.getFlags("compiler_only_flags") .or(DEFAULT_COMPILER_ONLY_FLAGS); builder .addAllAsflags(asflags) .addAllAsppflags(config.getFlags("asppflags").or(DEFAULT_ASPPFLAGS)) .addAllAsppflags(asflags) .addAllCflags(cflags) .addAllCflags(compilerOnlyFlags) .addAllCxxflags(cxxflags) .addAllCxxflags(compilerOnlyFlags) .addAllCppflags(config.getFlags("cppflags").or(DEFAULT_CPPFLAGS)) .addAllCppflags(cflags) .addAllCxxppflags(config.getFlags("cxxppflags").or(DEFAULT_CXXPPFLAGS)) .addAllCxxppflags(cxxflags) .addAllLdflags(config.getFlags("ldflags").or(DEFAULT_LDFLAGS)) .addAllArflags(config.getFlags("arflags").or(DEFAULT_ARFLAGS)) .addAllRanlibflags(config.getFlags("ranlibflags").or(DEFAULT_RANLIBFLAGS)); } public static void addToolFlagsFromCxxPlatform( CxxPlatform.Builder builder, CxxPlatform platform) { builder .addAllAsflags(platform.getAsflags()) .addAllAsppflags(platform.getAsppflags()) .addAllAsppflags(platform.getAsflags()) .addAllCflags(platform.getCflags()) .addAllCxxflags(platform.getCxxflags()) .addAllCppflags(platform.getCppflags()) .addAllCppflags(platform.getCflags()) .addAllCxxppflags(platform.getCxxflags()) .addAllCxxppflags(platform.getCxxppflags()) .addAllLdflags(platform.getLdflags()) .addAllArflags(platform.getArflags()) .addAllRanlibflags(platform.getRanlibflags()); } public static CxxPlatform getConfigDefaultCxxPlatform( CxxBuckConfig cxxBuckConfig, ImmutableMap<Flavor, CxxPlatform> cxxPlatformsMap, CxxPlatform systemDefaultCxxPlatform) { CxxPlatform defaultCxxPlatform; Optional<String> defaultPlatform = cxxBuckConfig.getDefaultPlatform(); if (defaultPlatform.isPresent()) { defaultCxxPlatform = cxxPlatformsMap.get( ImmutableFlavor.of(defaultPlatform.get())); if (defaultCxxPlatform == null) { LOG.warn( "Couldn't find default platform %s, falling back to system default", defaultPlatform.get()); } else { LOG.debug("Using config default C++ platform %s", defaultCxxPlatform); return defaultCxxPlatform; } } else { LOG.debug("Using system default C++ platform %s", systemDefaultCxxPlatform); } return systemDefaultCxxPlatform; } private static Optional<Tool> getTool(Flavor flavor, String name, CxxBuckConfig config) { return config .getPath(flavor.toString(), name) .transform(HashedFileTool.FROM_PATH) .transform(Functions.<Tool>identity()); } }
apache-2.0
sedmelluq/lavaplayer
main/src/main/java/com/sedmelluq/discord/lavaplayer/container/MediaContainerRegistry.java
936
package com.sedmelluq.discord.lavaplayer.container; import java.util.List; public class MediaContainerRegistry { public static final MediaContainerRegistry DEFAULT_REGISTRY = new MediaContainerRegistry(MediaContainer.asList()); private final List<MediaContainerProbe> probes; public MediaContainerRegistry(List<MediaContainerProbe> probes) { this.probes = probes; } public MediaContainerProbe find(String name) { for (MediaContainerProbe probe : probes) { if (name.equals(probe.getName())) { return probe; } } return null; } public List<MediaContainerProbe> getAll() { return probes; } public static MediaContainerRegistry extended(MediaContainerProbe... additional) { List<MediaContainerProbe> probes = MediaContainer.asList(); for (MediaContainerProbe probe : additional) { probes.add(probe); } return new MediaContainerRegistry(probes); } }
apache-2.0
summer0581/sumflow
modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/impl/cmd/GetTaskUsersByTaskIdCmd.java
2674
/** * Copyright 1996-2013 Founder International Co.,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author kenshin */ package com.founder.fix.fixflow.core.impl.cmd; import java.util.ArrayList; import java.util.List; import com.founder.fix.fixflow.core.impl.identity.Authentication; import com.founder.fix.fixflow.core.impl.identity.GroupDefinition; import com.founder.fix.fixflow.core.impl.identity.UserTo; import com.founder.fix.fixflow.core.impl.interceptor.Command; import com.founder.fix.fixflow.core.impl.interceptor.CommandContext; import com.founder.fix.fixflow.core.impl.task.TaskInstanceEntity; import com.founder.fix.fixflow.core.task.IdentityLink; import com.founder.fix.fixflow.core.task.IdentityLinkType; public class GetTaskUsersByTaskIdCmd implements Command<List<UserTo>>{ protected String taskId; public GetTaskUsersByTaskIdCmd(String taskId){ this.taskId=taskId; } public List<UserTo> execute(CommandContext commandContext) { // TODO 自动生成的方法存根 TaskInstanceEntity taskInstanceEntity=commandContext.getTaskManager().findTaskById(taskId); List<IdentityLink> identityLinks=taskInstanceEntity.getIdentityLinkQueryToList(); List<UserTo> userTos=new ArrayList<UserTo>(); if(taskInstanceEntity.getAssignee()!=null){ String userId=taskInstanceEntity.getAssignee(); UserTo userTo=Authentication.findUserInfoByUserId(userId); userTos.add(userTo); return userTos; } for (IdentityLink identityLink : identityLinks) { if(identityLink.getType()==IdentityLinkType.candidate){ if(identityLink.getUserId()!=null){ String userId=identityLink.getUserId(); UserTo userTo=Authentication.findUserInfoByUserId(userId); userTos.add(userTo); } else{ if(identityLink.getGroupId()!=null){ GroupDefinition groupDefinition=Authentication.groupDefinition(identityLink.getGroupType()); List<UserTo> userToTemp= groupDefinition.findUserChildMembersIncludeByGroupId(identityLink.getGroupId()); userTos.addAll(userToTemp); } } } } return userTos; } }
apache-2.0
SciGaP/SEAGrid-Desktop-GUI
src/main/java/org/gridchem/client/gui/jobsubmission/commands/UPDATENOTIFICATIONCommand.java
1137
/* * Created on May 30, 2008 * * Developed by: Rion Dooley - dooley [at] tacc [dot] utexas [dot] edu * TACC, Texas Advanced Computing Center * * https://www.tacc.utexas.edu/ */ package org.gridchem.client.gui.jobsubmission.commands; import java.util.ArrayList; import org.gridchem.client.Trace; import org.gridchem.client.interfaces.StatusListener; import org.gridchem.client.util.GMS3; import org.gridchem.service.beans.NotificationBean; /** * Insert Template description here. * * @author Rion Dooley < dooley [at] tacc [dot] utexas [dot] edu > * */ public class UPDATENOTIFICATIONCommand extends JobCommand { /** * @param statusListener */ public UPDATENOTIFICATIONCommand(StatusListener statusListener) { super(statusListener); this.id = UPDATENOTIFICATION; this.output = new ArrayList<NotificationBean>(); } /* (non-Javadoc) * @see org.gridchem.client.interfaces.GridCommand#execute() */ public void execute() throws Exception { Trace.entry(); GMS3.updateNotification(this); Trace.exit(); } }
apache-2.0
LuoboDcom/ZZShow
app/src/main/java/com/ys/yoosir/zzshow/mvp/base/BaseApi.java
191
package com.ys.yoosir.zzshow.mvp.base; /** @version 1.1.0 * @author yoosir * Created by Administrator on 2016/12/29 0029. */ public interface BaseApi { void onDestroy(); }
apache-2.0
ibmsoe/hbase
hbase-server/src/main/java/org/apache/hadoop/hbase/quotas/NoopQuotaLimiter.java
2276
/** * 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.hadoop.hbase.quotas; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.classification.InterfaceStability; import org.apache.hadoop.hbase.quotas.OperationQuota.OperationType; /** * Noop quota limiter returned when no limiter is associated to the user/table */ @InterfaceAudience.Private @InterfaceStability.Evolving final class NoopQuotaLimiter implements QuotaLimiter { private static QuotaLimiter instance = new NoopQuotaLimiter(); private NoopQuotaLimiter() { // no-op } @Override public void checkQuota(long estimateWriteSize, long estimateReadSize) throws ThrottlingException { // no-op } @Override public void grabQuota(long writeSize, long readSize) { // no-op } @Override public void consumeWrite(final long size) { // no-op } @Override public void consumeRead(final long size) { // no-op } @Override public boolean isBypass() { return true; } @Override public long getWriteAvailable() { throw new UnsupportedOperationException(); } @Override public long getReadAvailable() { throw new UnsupportedOperationException(); } @Override public void addOperationSize(OperationType type, long size) { } @Override public long getAvgOperationSize(OperationType type) { return -1; } @Override public String toString() { return "NoopQuotaLimiter"; } public static QuotaLimiter get() { return instance; } }
apache-2.0
Eric217/-OnSale
server/src/main/java/cn/omsfuk/discount/dao/CommentDao.java
922
package cn.omsfuk.discount.dao; import cn.omsfuk.discount.dto.CommentDto; import cn.omsfuk.discount.vo.CommentVo; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by omsfuk on 2017/7/17. */ @Repository public interface CommentDao { int insertComment(CommentDto comment); List<CommentVo> getComment(@Param("id") Integer id, @Param("userId") Integer userId, @Param("goodsId") Integer goodsId, @Param("begin") Integer begin, @Param("rows") Integer rows); int getCommentCount(@Param("id") Integer id, @Param("userId") Integer userId, @Param("goodsId") Integer goodsId); int deleteComment(@Param("id") int id); CommentVo getCommentById(@Param("id") int id); }
apache-2.0
googleinterns/step226-2020
src/main/java/com/google/vinet/servlets/MatchingServlet.java
1995
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https:www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.vinet.servlets; import com.google.vinet.data.MatchingRunner; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/admin/run-matching") public class MatchingServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ /* Construct a MatchingRunner with no initial parameters. All necessary data will be * pulled from DataStore once runner.run() is called. */ MatchingRunner runner = new MatchingRunner(); /* * Try to run the matcher. Report any failures to the caller. * In a production environment, there would be an integration here with the bug tracking system * used by the deployer, to alert the owner that the matching has failed. * At present, all errors are visible in the Google Cloud Console, and email alerts can be set * up to emulate a paging system. */ try { /* Run the matching algorithm, and delete all matches scheduled before today. Today's matches * will not be deleted. */ runner.run(true); } catch (Exception exception) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw exception; } } }
apache-2.0
actframework/act-feather
src/test/java/org/codejargon/feather/QualifiedDependencyTest.java
1928
package org.codejargon.feather; import act.di.feather.Feather; import act.di.feather.Key; import act.di.feather.Provides; import org.junit.Test; import javax.inject.Inject; import javax.inject.Qualifier; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import static org.junit.Assert.assertEquals; public class QualifiedDependencyTest { @Test public void qualifiedInstances() { Feather feather = Feather.with(new Module()); assertEquals(FooA.class, feather.instance(Key.of(Foo.class, A.class)).getClass()); assertEquals(FooB.class, feather.instance(Key.of(Foo.class, B.class)).getClass()); } @Test public void injectedQualified() { Feather feather = Feather.with(new Module()); Dummy dummy = feather.instance(Dummy.class); assertEquals(FooB.class, dummy.foo.getClass()); } @Test public void fieldInjectedQualified() { Feather feather = Feather.with(new Module()); DummyTestUnit dummy = new DummyTestUnit(); feather.injectFields(dummy); assertEquals(FooA.class, dummy.foo.getClass()); } interface Foo { } public static class FooA implements Foo { } public static class FooB implements Foo { } @Qualifier @Retention(RetentionPolicy.RUNTIME) @interface A { } @Qualifier @Retention(RetentionPolicy.RUNTIME) @interface B { } public static class Module { @Provides @A Foo a(FooA fooA) { return fooA; } @Provides @B Foo b(FooB fooB) { return fooB; } } public static class Dummy { private final Foo foo; @Inject public Dummy(@B Foo foo) { this.foo = foo; } } public static class DummyTestUnit { @Inject @A private Foo foo; } }
apache-2.0
spotify/crunch-lib
src/test/java/com/spotify/crunch/lib/DoFnsTest.java
2372
package com.spotify.crunch.lib; import com.google.common.base.Strings; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Lists; import com.spotify.crunch.test.TestAvroRecord; import org.apache.avro.util.Utf8; import org.apache.crunch.DoFn; import org.apache.crunch.MapFn; import org.apache.crunch.Pair; import org.apache.crunch.impl.mem.emit.InMemoryEmitter; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import java.util.Collection; import java.util.Iterator; import static org.junit.Assert.*; public class DoFnsTest { private static class AvroIterable implements Iterable<TestAvroRecord> { @Override public Iterator<TestAvroRecord> iterator() { final TestAvroRecord rec = new TestAvroRecord(new Utf8("something"), new Utf8(""), 1L); return new AbstractIterator<TestAvroRecord>() { private int n = 0; @Override protected TestAvroRecord computeNext() { n++; if (n > 3) return endOfData(); rec.setFieldB(new Utf8(Strings.repeat("*", n))); return rec; } }; } } private static class CollectingMapFn extends MapFn<Pair<String, Iterable<TestAvroRecord>>, Collection<TestAvroRecord>> { @Override public Collection<TestAvroRecord> map(Pair<String, Iterable<TestAvroRecord>> input) { return Lists.newArrayList(input.second()); } } @Test public void testDetach() { Collection<TestAvroRecord> expected = Lists.newArrayList( new TestAvroRecord(new Utf8("something"), new Utf8("*"), 1L), new TestAvroRecord(new Utf8("something"), new Utf8("**"), 1L), new TestAvroRecord(new Utf8("something"), new Utf8("***"), 1L) ); DoFn<Pair<String, Iterable<TestAvroRecord>>, Collection<TestAvroRecord>> doFn = DoFns.detach(new CollectingMapFn(), Avros.specifics(TestAvroRecord.class)); Pair<String, Iterable<TestAvroRecord>> input = Pair.of("key", (Iterable<TestAvroRecord>) new AvroIterable()); InMemoryEmitter<Collection<TestAvroRecord>> emitter = new InMemoryEmitter<Collection<TestAvroRecord>>(); doFn.configure(new Configuration()); doFn.initialize(); doFn.process(input, emitter); doFn.cleanup(emitter); assertEquals(expected, emitter.getOutput().get(0)); } }
apache-2.0
LuukvE/PieChecker
Android/PieChecker/src/com/piechecker/ImageAdapter.java
2064
/* * Image adapter used by the gallery fragment to correctly * scale and fit the images to the display. */ package com.piechecker; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialise some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(280, 280)); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // references to the images private Integer[] mThumbIds = { R.drawable.pie1, R.drawable.pie2, R.drawable.pie3, R.drawable.pie4, R.drawable.pie5, R.drawable.pie6, R.drawable.pie7, R.drawable.pie8, R.drawable.pie9, R.drawable.pie10, R.drawable.pie11, R.drawable.pie12, R.drawable.pie13, R.drawable.pie14, R.drawable.pie15, R.drawable.pie16, R.drawable.pie17, R.drawable.pie18, R.drawable.pie19, R.drawable.pie20, R.drawable.pie21, R.drawable.pie22, R.drawable.pie23, R.drawable.pie24, R.drawable.pie25 }; }
apache-2.0
Lotusun/Robin
src/main/java/com/charles/robin/jdbc/handlers/BeanMapHandler.java
6432
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.charles.robin.jdbc.handlers; import com.charles.robin.jdbc.RowProcessor; import java.sql.ResultSet; import java.sql.SQLException; /** * <p> * <code>ResultSetHandler</code> implementation that returns a Map of Beans. * <code>ResultSet</code> rows are converted into Beans which are then stored in * a Map under the given key. * </p> * <p> * If you had a Person table with a primary key column called ID, you could * retrieve rows from the table like this: * <p> * <pre> * ResultSetHandler&lt;Map&lt;Long, Person&gt;&gt; h = new BeanMapHandler&lt;Long, Person&gt;(Person.class, &quot;id&quot;); * Map&lt;Long, Person&gt; found = queryRunner.query(&quot;select id, name, age from person&quot;, h); * Person jane = found.get(1L); // jane's id is 1 * String janesName = jane.getName(); * Integer janesAge = jane.getAge(); * </pre> * <p> * Note that the "id" passed to BeanMapHandler can be in any case. The data type * returned for id is dependent upon how your JDBC driver converts SQL column * types from the Person table into Java types. The "name" and "age" columns are * converted according to their property descriptors by JdbcUtils. * &lt;/p&gt; * <p> * This class is thread safe. * &lt;/p&gt; * * @param <K> the type of keys maintained by the returned map * @param <V> the type of the bean * @see com.charles.robin.jdbc.ResultSetHandler * @since JdbcUtils 1.5 */ public class BeanMapHandler<K, V> extends AbstractKeyedHandler<K, V> { /** * The Class of beans produced by this handler. */ private final Class<V> type; /** * The RowProcessor implementation to use when converting rows into Objects. */ private final RowProcessor convert; /** * The column index to retrieve key values from. Defaults to 1. */ private final int columnIndex; /** * The column name to retrieve key values from. Either columnName or * columnIndex will be used but never both. */ private final String columnName; /** * Creates a new instance of BeanMapHandler. The value of the first column * of each row will be a key in the Map. * * @param type The Class that objects returned from <code>createRow()</code> * are created from. */ public BeanMapHandler(Class<V> type) { this(type, ArrayHandler.ROW_PROCESSOR, 1, null); } /** * Creates a new instance of BeanMapHandler. The value of the first column * of each row will be a key in the Map. * * @param type The Class that objects returned from <code>createRow()</code> * are created from. * @param convert The <code>RowProcessor</code> implementation to use when * converting rows into Beans */ public BeanMapHandler(Class<V> type, RowProcessor convert) { this(type, convert, 1, null); } /** * Creates a new instance of BeanMapHandler. * * @param type The Class that objects returned from <code>createRow()</code> * are created from. * @param columnIndex The values to use as keys in the Map are retrieved from the * column at this index. */ public BeanMapHandler(Class<V> type, int columnIndex) { this(type, ArrayHandler.ROW_PROCESSOR, columnIndex, null); } /** * Creates a new instance of BeanMapHandler. * * @param type The Class that objects returned from <code>createRow()</code> * are created from. * @param columnName The values to use as keys in the Map are retrieved from the * column with this name. */ public BeanMapHandler(Class<V> type, String columnName) { this(type, ArrayHandler.ROW_PROCESSOR, 1, columnName); } /** * Private Helper * * @param convert The <code>RowProcessor</code> implementation to use when * converting rows into Beans * @param columnIndex The values to use as keys in the Map are retrieved from the * column at this index. * @param columnName The values to use as keys in the Map are retrieved from the * column with this name. */ private BeanMapHandler(Class<V> type, RowProcessor convert, int columnIndex, String columnName) { super(); this.type = type; this.convert = convert; this.columnIndex = columnIndex; this.columnName = columnName; } /** * This factory method is called by <code>handle()</code> to retrieve the * key value from the current <code>ResultSet</code> row. * * @param rs ResultSet to create a key from * @return K from the configured key column name/index * @throws SQLException if a database access error occurs * @throws ClassCastException if the class datatype does not match the column type * @see com.charles.robin.jdbc.handlers.AbstractKeyedHandler#createKey(ResultSet) */ // We assume that the user has picked the correct type to match the column // so getObject will return the appropriate type and the cast will succeed. @SuppressWarnings("unchecked") @Override protected K createKey(ResultSet rs) throws SQLException { return (columnName == null) ? (K) rs.getObject(columnIndex) : (K) rs.getObject(columnName); } @Override protected V createRow(ResultSet rs) throws SQLException { return this.convert.toBean(rs, type); } }
apache-2.0
yeastrc/msdapl
MSDaPl_Web_App/src/org/uwpr/www/scheduler/EditProjectInstrumentTimeFormAction.java
12286
/** * EditProjectInstrumentTimeFormAction.java * @author Vagisha Sharma * Jan 6, 2012 */ package org.uwpr.www.scheduler; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.uwpr.instrumentlog.MsInstrument; import org.uwpr.instrumentlog.MsInstrumentUtils; import org.uwpr.instrumentlog.UsageBlockBase; import org.uwpr.scheduler.UsageBlockDeletableDecider; import org.yeastrc.project.Project; import org.yeastrc.project.ProjectFactory; import org.yeastrc.project.Researcher; import org.yeastrc.www.user.User; import org.yeastrc.www.user.UserUtils; /** * */ public class EditProjectInstrumentTimeFormAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // User making this request User user = UserUtils.getUser(request); if (user == null) { ActionErrors errors = new ActionErrors(); errors.add("username", new ActionMessage("error.login.notloggedin")); saveErrors( request, errors ); return mapping.findForward("authenticate"); } // we need a projectID int projectId = 0; try { projectId = Integer.parseInt(request.getParameter("projectId")); } catch(NumberFormatException e) { projectId = 0; } if(projectId == 0) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.scheduler.invalidid", "Invalid projectID in request.")); saveErrors( request, errors ); return mapping.findForward("standardHome"); } // Make sure the user has access to the project Project project = null; try { project = ProjectFactory.getProject(projectId); if(project == null) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.scheduler.invalidid", "Project with ID: "+projectId+" not found in the database.")); saveErrors( request, errors ); return mapping.findForward("standardHome"); } } catch(Exception e) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.load", e.getMessage())); saveErrors( request, errors ); return mapping.findForward("standardHome"); } try { if(!project.checkAccess(user.getResearcher())) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.invalidaccess", "User does not have access to edit instrument time for project "+projectId+".")); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewProject"); return new ActionForward(fwd.getPath()+"?ID="+projectId, fwd.getRedirect()); } } catch(Exception e) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.load", "Project ID: "+projectId+". ERROR: "+e.getMessage())); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewProject"); return new ActionForward(fwd.getPath()+"?ID="+projectId, fwd.getRedirect()); } // we need an instrumentID int instrumentId = 0; try { instrumentId = Integer.parseInt(request.getParameter("instrumentId")); } catch(NumberFormatException e) { instrumentId = 0; } if(instrumentId == 0) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.scheduler.invalidid", "Invalid instrumentID in request")); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewProject"); return new ActionForward(fwd.getPath()+"?ID="+projectId, fwd.getRedirect()); } MsInstrument instrument = null; try { instrument = MsInstrumentUtils.instance().getMsInstrument(instrumentId); if(instrument == null) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.scheduler.invalidid", "Instrument with ID "+instrumentId+" not found in the database.")); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewProject"); return new ActionForward(fwd.getPath()+"?ID="+projectId, fwd.getRedirect()); } } catch(Exception e) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.load", "Instrument ID: "+projectId+". ERROR: "+e.getMessage())); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewProject"); return new ActionForward(fwd.getPath()+"?ID="+projectId, fwd.getRedirect()); } // get the usageBlockIds from the request // get the usage block ID(s) List<Integer> usageBlockIds = new ArrayList<Integer>(); String usageBlockIdString = request.getParameter("usageBlockIds"); if(usageBlockIdString != null) { String[] tokens = usageBlockIdString.split(","); for(String token: tokens) { try { usageBlockIds.add(Integer.parseInt(token)); } catch(NumberFormatException e) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.invaliddata", "Invalid usage block ID found in request: "+token+".")); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewScheduler"); return new ActionForward(fwd.getPath()+"?projectId="+projectId+"&instrumentId="+instrumentId, fwd.getRedirect()); } } } if(usageBlockIds.size() == 0) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.invaliddata", "No usage block IDs found in request.")); saveErrors( request, errors ); return mapping.findForward("standardHome"); } // load the usage blocks List<UsageBlockBase> blocksToDelete = new ArrayList<UsageBlockBase>(usageBlockIds.size()); for(int usageBlockId: usageBlockIds) { UsageBlockBase usageBlock = MsInstrumentUtils.instance().getUsageBlockBase(usageBlockId); if(usageBlock == null) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.invaliddata", "No usage block found for usageBlockId: "+usageBlockId)); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewScheduler"); return new ActionForward(fwd.getPath()+"?projectId="+projectId+"&instrumentId="+instrumentId, fwd.getRedirect()); } blocksToDelete.add(usageBlock); } // get the project for the given usage blocks. They should all be for the same project. // the instrumentID form the blocks should also be the same for(UsageBlockBase block: blocksToDelete) { int blkProjId = block.getProjectID(); if(blkProjId != projectId) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.invaliddata", "Given usage block ( "+block.getID()+") is not for project "+projectId)); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewScheduler"); return new ActionForward(fwd.getPath()+"?projectId="+projectId+"&instrumentId="+instrumentId, fwd.getRedirect()); } int blkInstrId = block.getInstrumentID(); if(blkInstrId != instrumentId) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.invaliddata", "Given usage block ( "+block.getID()+") is not for instrument "+projectId)); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewScheduler"); return new ActionForward(fwd.getPath()+"?projectId="+projectId+"&instrumentId="+instrumentId, fwd.getRedirect()); } } // Make sure the old blocks can be deleted. for(UsageBlockBase block: blocksToDelete) { StringBuilder errorMessage = new StringBuilder(); if(!UsageBlockDeletableDecider.getInstance().isBlockDeletable(block, user, errorMessage)) { ActionErrors errors = new ActionErrors(); errors.add("scheduler", new ActionMessage("error.costcenter.delete", "Block ID "+block.getID()+": "+block.getStartDateFormated()+" - "+block.getEndDateFormated()+ ". "+errorMessage.toString())); saveErrors( request, errors ); ActionForward fwd = mapping.findForward("viewScheduler"); return new ActionForward(fwd.getPath()+"?projectId="+projectId+"&instrumentId="+instrumentId, fwd.getRedirect()); } } // sort the blocks by start date/time Collections.sort(blocksToDelete, new Comparator<UsageBlockBase>() { @Override public int compare(UsageBlockBase blk1, UsageBlockBase blk2) { return blk1.getStartDate().compareTo(blk2.getStartDate()); } }); // TODO Multiple creators?? Researcher creator = new Researcher(); creator.load(blocksToDelete.get(0).getResearcherID()); Researcher updater = null; if(blocksToDelete.get(0).getUpdaterResearcherID() != 0) { updater = new Researcher(); updater.load(blocksToDelete.get(0).getUpdaterResearcherID()); } EditProjectInstrumentTimeForm editForm = new EditProjectInstrumentTimeForm(); SimpleDateFormat dateFmt = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat timeFmt = new SimpleDateFormat("H"); editForm.setStartDate(dateFmt.format(blocksToDelete.get(0).getStartDate())); editForm.setEndDate(dateFmt.format(blocksToDelete.get(blocksToDelete.size() - 1).getEndDate())); editForm.setStartTime(timeFmt.format(blocksToDelete.get(0).getStartDate())); editForm.setEndTime(timeFmt.format(blocksToDelete.get(blocksToDelete.size() - 1).getEndDate())); editForm.setProjectId(projectId); editForm.setInstrumentId(instrumentId); editForm.setInstrumentName(instrument.getName()); editForm.setUsageBlockIdsToEdit(usageBlockIdString); // TODO Multiple creators?? editForm.setCreatorId(creator.getID()); dateFmt = new SimpleDateFormat("MM/dd/yyyy HH:mm a"); editForm.setCreateDate(dateFmt.format(blocksToDelete.get(0).getDateCreated())); if(updater != null) { editForm.setUpdaterId(updater.getID()); editForm.setUpdateDate(dateFmt.format(blocksToDelete.get(0).getDateChanged())); } request.setAttribute("editInstrumentTimeForm", editForm); request.getSession().setAttribute("timeOptions", TimeOption.getTimeOptions(user)); return mapping.findForward("Success"); } }
apache-2.0
Terry-L/YiBo
YiBo/src/com/shejiaomao/weibo/common/GlobalVars.java
5458
package com.shejiaomao.weibo.common; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import android.content.Context; import com.cattong.commons.ServiceProvider; import com.cattong.commons.util.ListUtil; import com.cattong.sns.Sns; import com.cattong.sns.SnsFactory; import com.cattong.weibo.Weibo; import com.cattong.weibo.WeiboFactory; import com.shejiaomao.common.ImageQuality; import com.shejiaomao.common.NetType; import com.shejiaomao.common.NetUtil.NetworkOperator; import com.shejiaomao.weibo.db.LocalAccount; import com.shejiaomao.weibo.db.LocalAccountDao; public class GlobalVars { public static boolean IS_OBEY_SINA_AGREEMENT = false; // 是否遵循新浪协议 public static boolean IS_MOBILE_NET_UPDATE_VERSION = false; //2g/3g网络下是否提示更新 //当前网络类型; public static NetworkOperator NET_OPERATOR = NetworkOperator.NONE; public static NetType NET_TYPE = NetType.NONE; //缓冲设置配置 public static boolean IS_SHOW_HEAD; public static boolean IS_SHOW_THUMBNAIL; public static int UPDATE_COUNT; public static ImageQuality IMAGE_DOWNLOAD_QUALITY; public static boolean IS_ENABLE_GESTURE; public static Locale LOCALE; public static int FONT_SIZE_HOME_BLOG; public static int FONT_SIZE_HOME_RETWEET; public static boolean IS_DETECT_IAMGE_INFO; public static boolean IS_AUTO_LOAD_COMMENTS; public static boolean IS_FULLSCREEN; //运行时环境变量 private static Map<Long, Weibo> microblogMap; private static Map<Long, Sns> snsMap; private static List<LocalAccount> accountList; static { microblogMap = new HashMap<Long, Weibo>(); accountList = new ArrayList<LocalAccount>(); snsMap = new HashMap<Long, Sns>(); } public static void addAccount(LocalAccount account) { if (account == null || accountList.contains(account)) { return; } //时间排序 int i = 0; for (i = 0; i < accountList.size(); i++) { LocalAccount temp = accountList.get(i); if (account.getCreatedAt().before(temp.getCreatedAt())) { break; } } accountList.add(i, account); if (account.isSnsAccount()) { if (snsMap.containsKey(account.getAccountId())) { return; } Sns sns = SnsFactory.getInstance(account.getAuthorization()); if (sns != null) { snsMap.put(account.getAccountId(), sns); } } else { if (!microblogMap.containsKey(account.getAccountId())) { Weibo microBlog = WeiboFactory.getInstance(account.getAuthorization()); if (microBlog != null) { microblogMap.put(account.getAccountId(), microBlog); } } } } public static void addAccounts(List<LocalAccount> list) { if (list == null || list.size() <= 0) { return; } for (LocalAccount account : list) { addAccount(account); } } public static void removeAccount(LocalAccount account) { if (!accountList.contains(account)) { return; } accountList.remove(account); microblogMap.remove(account.getAccountId()); } public static LocalAccount getAccount(long accountID) { LocalAccount account = null; if (accountID < 0) { return account; } for (int i = 0; i < accountList.size(); i++) { if (accountID == accountList.get(i).getAccountId().longValue()) { account = accountList.get(i); break; } } return account; } public static Weibo getMicroBlog(long accountID) { return microblogMap.get(accountID); } public static Sns getSns(long accountID) { return snsMap.get(accountID); } public static Sns getSns(LocalAccount account) { Sns sns = null; if (account == null) { return sns; } sns = snsMap.get(account.getAccountId()); return sns; } public static Weibo getMicroBlog(LocalAccount account) { Weibo microBlog = null; if (account == null) { return microBlog; } microBlog = microblogMap.get(account.getAccountId()); return microBlog; } public static long getAccountID(ServiceProvider sp, String userID) { long accountID = -1; for (LocalAccount account : accountList) { if (account.getServiceProvider() == sp && account.getUser().getUserId().equals(userID)) { accountID = account.getAccountId(); break; } } return accountID; } public static void clear() { microblogMap.clear(); snsMap.clear(); accountList.clear(); } /** * 获取帐号列表 * * @param context 操作相关Context * @param isReload 是否从数据库重新读取 * @return 帐号列表 */ public static List<LocalAccount> getAccountList(Context context, boolean isReload) { if (isReload || accountList.size() == 0) { reloadAccounts(context); } return accountList; } /** * 重新装载帐号 */ public static void reloadAccounts(Context context) { if (context == null) { return; } LocalAccountDao accountDao = new LocalAccountDao(context); List<LocalAccount> listAccount = accountDao.findAllValid(); GlobalVars.clear(); GlobalVars.addAccounts(listAccount); //umeng收集用户数据 gatherUser(context); } /** * umeng 收集信息 */ private static void gatherUser(Context context) { if (ListUtil.isEmpty(accountList)) { return; } for (LocalAccount account : accountList) { if (account.getServiceProvider() == ServiceProvider.Sina) { //MobclickAgent.setUserID(context, account.getUserId(), "weibo.com"); break; } } } }
apache-2.0
aparod/jonix
jonix-onix2/src/main/java/com/tectonica/jonix/onix2/PrizeName.java
2354
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * 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.tectonica.jonix.onix2; import java.io.Serializable; import com.tectonica.jonix.JPU; import com.tectonica.jonix.OnixElement; import com.tectonica.jonix.codelist.LanguageCodes; import com.tectonica.jonix.codelist.RecordSourceTypes; import com.tectonica.jonix.codelist.TextCaseFlags; import com.tectonica.jonix.codelist.TextFormats; import com.tectonica.jonix.codelist.TransliterationSchemes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ @SuppressWarnings("serial") public class PrizeName implements OnixElement, Serializable { public static final String refname = "PrizeName"; public static final String shortname = "g126"; public TextFormats textformat; public TextCaseFlags textcase; public LanguageCodes language; public TransliterationSchemes transliteration; /** * (type: DateOrDateTime) */ public String datestamp; public RecordSourceTypes sourcetype; public String sourcename; /** * (type: NonEmptyString) */ public String value; public PrizeName() {} public PrizeName(org.w3c.dom.Element element) { textformat = TextFormats.byValue(JPU.getAttribute(element, "textformat")); textcase = TextCaseFlags.byValue(JPU.getAttribute(element, "textcase")); language = LanguageCodes.byValue(JPU.getAttribute(element, "language")); transliteration = TransliterationSchemes.byValue(JPU.getAttribute(element, "transliteration")); datestamp = JPU.getAttribute(element, "datestamp"); sourcetype = RecordSourceTypes.byValue(JPU.getAttribute(element, "sourcetype")); sourcename = JPU.getAttribute(element, "sourcename"); value = JPU.getContentAsString(element); } }
apache-2.0
josesamuel/remoter
sampleservice-remoter/src/main/java/util/remoter/service/FooParcelable.java
1500
package util.remoter.service; import android.os.Parcel; import android.os.Parcelable; /** * Created by jmails on 8/20/17. */ public class FooParcelable<T> implements Parcelable { public static final Creator CREATOR = new Creator() { @Override public FooParcelable createFromParcel(Parcel in) { return new FooParcelable(in); } @Override public FooParcelable[] newArray(int size) { return new FooParcelable[size]; } }; private int intValue; private String stringValue; public FooParcelable(){ } public FooParcelable(String stringValue, int intValue) { this.stringValue = stringValue; this.intValue = intValue; } protected FooParcelable(Parcel in) { readFromParcel(in); } public int getIntValue() { return intValue; } public String getStringValue() { return stringValue; } public void setIntValue(int intValue) { this.intValue = intValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(intValue); parcel.writeString(stringValue); } public void readFromParcel(Parcel parcel){ intValue = parcel.readInt(); stringValue = parcel.readString(); } }
apache-2.0
cy19890513/Leetcode-1
src/main/java/com/fishercoder/solutions/_463.java
1731
package com.fishercoder.solutions; /** * You are given a map in form of a two-dimensional integer grid * where 1 represents land and 0 represents water. * Grid cells are connected horizontally/vertically (not diagonally). * The grid is completely surrounded by water, * and there is exactly one island (i.e., one or more connected land cells). * The island doesn't have "lakes" (water inside that isn't connected to the water around the island). * One cell is a square with side length 1. * The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Explanation: The perimeter is the 16 yellow stripes in the image below: */ public class _463 { /**Inspired by this post: https://discuss.leetcode.com/topic/68983/java-9-line-solution-add-4-for-each-land-and-remove-2-for-each-internal-edge * 1. we increment the count by 4 whenever we encounter an island * 2. also, we check in two directions: island's left and island's top, we only check these two directions, * see if this island has any island neighbors, if so, we'll deduct two from it.*/ public int islandPerimeter(int[][] grid) { int count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { count += 4; if (i > 0 && grid[i - 1][j] == 1) { count -= 2; } if (j > 0 && grid[i][j - 1] == 1) { count -= 2; } } } } return count; } }
apache-2.0
kapsitis/ddgatve-android
ddgatve-games/src/lv/ddgatve/games/game15/PickFrameDialogFragment.java
970
package lv.ddgatve.games.game15; import lv.ddgatve.games.main.R; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; public class PickFrameDialogFragment extends DialogFragment { private Game15Activity activity; public void setActivity(Game15Activity activity) { this.activity = activity; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_pick_frame) .setItems(R.array.field_types, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Game15Activity.theFrame.initialize(4, 4); activity.resetGame(which+2, which+2); } }); return builder.create(); } }
apache-2.0
nmorel/magic-counter
android/app/src/main/java/com/magiccounter/MainApplication.java
1000
package com.magiccounter; import android.app.Application; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import com.facebook.react.ReactPackage; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
apache-2.0
mdtux89/StudentAssistant
src/main/java/it/openlab/studentassistant/DatePreference.java
10273
package it.openlab.studentassistant; /*https://github.com/bostonandroid/DatePreference/blob/master/DatePreference/src/org/bostonandroid/datepreference/DatePreference.java Copyright (c) 2010, Boston Android All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: o Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. o 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. o Neither the name of Boston Android 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. */ import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.DatePicker; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DatePreference extends DialogPreference implements DatePicker.OnDateChangedListener { private String dateString; private String changedValueCanBeNull; private DatePicker datePicker; public DatePreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public DatePreference(Context context, AttributeSet attrs) { super(context, attrs); } /** * Produces a DatePicker set to the date produced by {@link #getDate()}. When * overriding be sure to call the super. * * @return a DatePicker with the date set */ @Override protected View onCreateDialogView() { this.datePicker = new DatePicker(getContext()); Calendar calendar = getDate(); datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), this); return datePicker; } /** * Produces the date used for the date picker. If the user has not selected a * date, produces the default from the XML's android:defaultValue. If the * default is not set in the XML or if the XML's default is invalid it uses * the value produced by {@link #defaultCalendar()}. * * @return the Calendar for the date picker */ public Calendar getDate() { try { Date date = formatter().parse(defaultValue()); Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } catch (java.text.ParseException e) { return defaultCalendar(); } } /** * Set the selected date to the specified string. * * @param dateString * The date, represented as a string, in the format specified by * {@link #formatter()}. */ public void setDate(String dateString) { this.dateString = dateString; } /** * Produces the date formatter used for dates in the XML. The default is yyyy.MM.dd. * Override this to change that. * * @return the SimpleDateFormat used for XML dates */ public static SimpleDateFormat formatter() { return new SimpleDateFormat("yyyy.MM.dd"); } /** * Produces the date formatter used for showing the date in the summary. The default is MMMM dd, yyyy. * Override this to change it. * * @return the SimpleDateFormat used for summary dates */ public static SimpleDateFormat summaryFormatter() { return new SimpleDateFormat("MMMM dd, yyyy"); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getString(index); } /** * Called when the date picker is shown or restored. If it's a restore it gets * the persisted value, otherwise it persists the value. */ @Override protected void onSetInitialValue(boolean restoreValue, Object def) { if (restoreValue) { this.dateString = getPersistedString(defaultValue()); setTheDate(this.dateString); } else { boolean wasNull = this.dateString == null; setDate((String) def); if (!wasNull) persistDate(this.dateString); } } /** * Called when Android pauses the activity. */ @Override protected Parcelable onSaveInstanceState() { if (isPersistent()) return super.onSaveInstanceState(); else return new SavedState(super.onSaveInstanceState()); } /** * Called when Android restores the activity. */ @Override protected void onRestoreInstanceState(Parcelable state) { if (state == null || !state.getClass().equals(SavedState.class)) { super.onRestoreInstanceState(state); setTheDate(((SavedState) state).dateValue); } else { SavedState s = (SavedState) state; super.onRestoreInstanceState(s.getSuperState()); setTheDate(s.dateValue); } } /** * Called when the user changes the date. */ public void onDateChanged(DatePicker view, int year, int month, int day) { Calendar selected = new GregorianCalendar(year, month, day); this.changedValueCanBeNull = formatter().format(selected.getTime()); } /** * Called when the dialog is closed. If the close was by pressing "OK" it * saves the value. */ @Override protected void onDialogClosed(boolean shouldSave) { if (shouldSave && this.changedValueCanBeNull != null) { setTheDate(this.changedValueCanBeNull); this.changedValueCanBeNull = null; } } private void setTheDate(String s) { setDate(s); persistDate(s); } private void persistDate(String s) { persistString(s); setSummary(summaryFormatter().format(getDate().getTime())); } /** * The default date to use when the XML does not set it or the XML has an * error. * * @return the Calendar set to the default date */ public static Calendar defaultCalendar() { return new GregorianCalendar(1970, 0, 1); } /** * The defaultCalendar() as a string using the {@link #formatter()}. * * @return a String representation of the default date */ public static String defaultCalendarString() { return formatter().format(defaultCalendar().getTime()); } private String defaultValue() { if (this.dateString == null) setDate(defaultCalendarString()); return this.dateString; } /** * Called whenever the user clicks on a button. Invokes {@link #onDateChanged(DatePicker, int, int, int)} * and {@link #onDialogClosed(boolean)}. Be sure to call the super when overriding. */ @Override public void onClick(DialogInterface dialog, int which) { super.onClick(dialog, which); datePicker.clearFocus(); onDateChanged(datePicker, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); onDialogClosed(which == DialogInterface.BUTTON1); // OK? } /** * Produces the date the user has selected for the given preference, as a * calendar. * * @param preferences * the SharedPreferences to get the date from * @param field * the name of the preference to get the date from * @return a Calendar that the user has selected */ public static Calendar getDateFor(SharedPreferences preferences, String field) { Date date = stringToDate(preferences.getString(field, defaultCalendarString())); Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } private static Date stringToDate(String dateString) { try { return formatter().parse(dateString); } catch (ParseException e) { return defaultCalendar().getTime(); } } private static class SavedState extends BaseSavedState { String dateValue; public SavedState(Parcel p) { super(p); dateValue = p.readString(); } public SavedState(Parcelable p) { super(p); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(dateValue); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
apache-2.0
asedunov/intellij-community
platform/testRunner/src/com/intellij/execution/testframework/actions/ViewAssertEqualsDiffAction.java
5503
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.testframework.actions; import com.intellij.diff.DiffDialogHints; import com.intellij.diff.impl.DiffRequestProcessor; import com.intellij.diff.impl.DiffWindowBase; import com.intellij.diff.util.DiffUserDataKeys; import com.intellij.diff.util.DiffUtil; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.TestFrameworkRunningModel; import com.intellij.execution.testframework.TestTreeView; import com.intellij.execution.testframework.TestTreeViewAction; import com.intellij.execution.testframework.stacktrace.DiffHyperlink; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ViewAssertEqualsDiffAction extends AnAction implements TestTreeViewAction { @NonNls public static final String ACTION_ID = "openAssertEqualsDiff"; public void actionPerformed(final AnActionEvent e) { if (!openDiff(e.getDataContext(), null)) { final Component component = e.getData(PlatformDataKeys.CONTEXT_COMPONENT); Messages.showInfoMessage(component, "Comparison error was not found", "No Comparison Data Found"); } } public static boolean openDiff(DataContext context, @Nullable DiffHyperlink currentHyperlink) { final AbstractTestProxy testProxy = AbstractTestProxy.DATA_KEY.getData(context); final Project project = CommonDataKeys.PROJECT.getData(context); if (testProxy != null) { DiffHyperlink diffViewerProvider = testProxy.getDiffViewerProvider(); if (diffViewerProvider != null) { final List<DiffHyperlink> providers = collectAvailableProviders(TestTreeView.MODEL_DATA_KEY.getData(context)); int index = currentHyperlink != null ? providers.indexOf(currentHyperlink) : -1; if (index == -1) index = providers.indexOf(diffViewerProvider); new MyDiffWindow(project, providers, Math.max(0, index)).show(); return true; } } if (currentHyperlink != null) { new MyDiffWindow(project, currentHyperlink).show(); return true; } return false; } private static List<DiffHyperlink> collectAvailableProviders(TestFrameworkRunningModel model) { final List<DiffHyperlink> providers = new ArrayList<>(); if (model != null) { final AbstractTestProxy root = model.getRoot(); final List<? extends AbstractTestProxy> allTests = root.getAllTests(); for (AbstractTestProxy test : allTests) { if (test.isLeaf()) { providers.addAll(test.getDiffViewerProviders()); } } } return providers; } public void update(final AnActionEvent e) { Presentation presentation = e.getPresentation(); if (e.getProject() == null) { presentation.setEnabledAndVisible(false); return; } AbstractTestProxy test = AbstractTestProxy.DATA_KEY.getData(e.getDataContext()); boolean visible = test != null && test.getDiffViewerProvider() != null; TestFrameworkRunningModel runningModel = TestTreeView.MODEL_DATA_KEY.getData(e.getDataContext()); boolean enabled = visible || (runningModel != null && runningModel.getProperties().isViewAssertEqualsDiffActionEnabled()); presentation.setEnabled(enabled); presentation.setVisible(visible); } private static class MyDiffWindow extends DiffWindowBase { @NotNull private final List<DiffHyperlink> myRequests; private final int myIndex; public MyDiffWindow(@Nullable Project project, @NotNull DiffHyperlink request) { this(project, Collections.singletonList(request), 0); } public MyDiffWindow(@Nullable Project project, @NotNull List<DiffHyperlink> requests, int index) { super(project, DiffDialogHints.DEFAULT); myRequests = requests; myIndex = index; } @NotNull @Override protected DiffRequestProcessor createProcessor() { return new MyTestDiffRequestProcessor(myProject, myRequests, myIndex); } private class MyTestDiffRequestProcessor extends TestDiffRequestProcessor { public MyTestDiffRequestProcessor(@Nullable Project project, @NotNull List<DiffHyperlink> requests, int index) { super(project, requests, index); putContextUserData(DiffUserDataKeys.DIALOG_GROUP_KEY, "#com.intellij.execution.junit2.states.ComparisonFailureState$DiffDialog"); } @Override protected void setWindowTitle(@NotNull String title) { getWrapper().setTitle(title); } @Override protected void onAfterNavigate() { DiffUtil.closeWindow(getWrapper().getWindow(), true, true); } } } }
apache-2.0
hhjuliet/zstack
sdk/src/main/java/org/zstack/sdk/CreateL3NetworkAction.java
3106
package org.zstack.sdk; import java.util.HashMap; import java.util.Map; public class CreateL3NetworkAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public CreateL3NetworkResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String name; @Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String description; @Param(required = false) public java.lang.String type = "L3BasicNetwork"; @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String l2NetworkUuid; @Param(required = false) public boolean system = false; @Param(required = false) public java.lang.String dnsDomain; @Param(required = false) public java.lang.String resourceUuid; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = true) public String sessionId; public long timeout; public long pollingInterval; public Result call() { ApiResult res = ZSClient.call(this); Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } CreateL3NetworkResult value = res.getResult(CreateL3NetworkResult.class); ret.value = value == null ? new CreateL3NetworkResult() : value; return ret; } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; completion.complete(ret); return; } CreateL3NetworkResult value = res.getResult(CreateL3NetworkResult.class); ret.value = value == null ? new CreateL3NetworkResult() : value; completion.complete(ret); } }); } Map<String, Parameter> getParameterMap() { return parameterMap; } RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "POST"; info.path = "/l3-networks"; info.needSession = true; info.needPoll = true; info.parameterName = "params"; return info; } }
apache-2.0
haikuowuya/android_system_code
src/javax/sql/StatementEvent.java
3626
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* * Created on Apr 28, 2005 */ package javax.sql; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.EventObject; /** * A <code>StatementEvent</code> is sent to all <code>StatementEventListener</code>s which were * registered with a <code>PooledConnection</code>. This occurs when the driver determines that a * <code>PreparedStatement</code> that is associated with the <code>PooledConnection</code> has been closed or the driver determines * is invalid. * <p> * @since 1.6 */ public class StatementEvent extends EventObject { private SQLException exception; private PreparedStatement statement; /** * Constructs a <code>StatementEvent</code> with the specified <code>PooledConnection</code> and * <code>PreparedStatement</code>. The <code>SQLException</code> contained in the event defaults to * null. * <p> * @param con The <code>PooledConnection</code> that the closed or invalid * <code>PreparedStatement</code>is associated with. * @param statement The <code>PreparedStatement</code> that is bieng closed or is invalid * <p> * @throws IllegalArgumentException if <code>con</code> is null. * * @since 1.6 */ public StatementEvent(PooledConnection con, PreparedStatement statement) { super(con); this.statement = statement; this.exception = null; } /** * Constructs a <code>StatementEvent</code> with the specified <code>PooledConnection</code>, * <code>PreparedStatement</code> and <code>SQLException</code> * <p> * @param con The <code>PooledConnection</code> that the closed or invalid <code>PreparedStatement</code> * is associated with. * @param statement The <code>PreparedStatement</code> that is being closed or is invalid * @param exception The <code>SQLException </code>the driver is about to throw to * the application * * @throws IllegalArgumentException if <code>con</code> is null. * <p> * @since 1.6 */ public StatementEvent(PooledConnection con, PreparedStatement statement, SQLException exception) { super(con); this.statement = statement; this.exception = exception; } /** * Returns the <code>PreparedStatement</code> that is being closed or is invalid * <p> * @return The <code>PreparedStatement</code> that is being closed or is invalid * <p> * @since 1.6 */ public PreparedStatement getStatement() { return this.statement; } /** * Returns the <code>SQLException</code> the driver is about to throw * <p> * @return The <code>SQLException</code> the driver is about to throw * <p> * @since 1.6 */ public SQLException getSQLException() { return this.exception; } }
apache-2.0
BanNT/PaaS_OpenSource
src/java/message/MessageUtil.java
732
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package message; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; /** * * @author Administrator */ public class MessageUtil { public static void errorMessage(String value){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,value,"")); } public static void successMessage(String value){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,value,"")); } }
apache-2.0
ivanceras/orm
src/test/java/com/ivanceras/db/sample/DAO_ProductAvailability.java
3509
package com.ivanceras.db.sample; /*** * This is automatically generated by DAOGenerator, based on the database table schema * * */ import com.ivanceras.db.shared.DAO; import com.ivanceras.db.api.DAO_Operator; public class DAO_ProductAvailability extends DAO{ /** * */ public DAO_ProductAvailability(){ super("ProductAvailability"); } public java.util.UUID getOrganizationId(){ return (java.util.UUID)get_Value(Column.organization_id); } public void setOrganizationId(java.util.UUID organizationId){ set_Value(Column.organization_id, organizationId); } public java.util.UUID getClientId(){ return (java.util.UUID)get_Value(Column.client_id); } public void setClientId(java.util.UUID clientId){ set_Value(Column.client_id, clientId); } public java.util.Date getCreated(){ return (java.util.Date)get_Value(Column.created); } public void setCreated(java.util.Date created){ set_Value(Column.created, created); } public java.util.UUID getCreatedby(){ return (java.util.UUID)get_Value(Column.createdby); } public void setCreatedby(java.util.UUID createdby){ set_Value(Column.createdby, createdby); } public java.util.Date getUpdated(){ return (java.util.Date)get_Value(Column.updated); } public void setUpdated(java.util.Date updated){ set_Value(Column.updated, updated); } public java.util.UUID getUpdatedby(){ return (java.util.UUID)get_Value(Column.updatedby); } public void setUpdatedby(java.util.UUID updatedby){ set_Value(Column.updatedby, updatedby); } public java.util.UUID getProductId(){ return (java.util.UUID)get_Value(Column.product_id); } public void setProductId(java.util.UUID productId){ set_Value(Column.product_id, productId); } public Boolean getAvailable(){ return (Boolean)get_Value(Column.available); } public void setAvailable(Boolean available){ set_Value(Column.available, available); } public Boolean getAlwaysAvailable(){ return (Boolean)get_Value(Column.always_available); } public void setAlwaysAvailable(Boolean alwaysAvailable){ set_Value(Column.always_available, alwaysAvailable); } public java.math.BigDecimal getStocks(){ return (java.math.BigDecimal)get_Value(Column.stocks); } public void setStocks(java.math.BigDecimal stocks){ set_Value(Column.stocks, stocks); } public java.util.Date getAvailableFrom(){ return (java.util.Date)get_Value(Column.available_from); } public void setAvailableFrom(java.util.Date availableFrom){ set_Value(Column.available_from, availableFrom); } public java.util.Date getAvailableUntil(){ return (java.util.Date)get_Value(Column.available_until); } public void setAvailableUntil(java.util.Date availableUntil){ set_Value(Column.available_until, availableUntil); } public String getAvailableDay(){ return (String)get_Value(Column.available_day); } public void setAvailableDay(String availableDay){ set_Value(Column.available_day, availableDay); } public java.util.Date getOpenTime(){ return (java.util.Date)get_Value(Column.open_time); } public void setOpenTime(java.util.Date openTime){ set_Value(Column.open_time, openTime); } public java.util.Date getCloseTime(){ return (java.util.Date)get_Value(Column.close_time); } public void setCloseTime(java.util.Date closeTime){ set_Value(Column.close_time, closeTime); } public void setProduct(DAO_Product product){ set_Value("product", product); } public DAO_Product getProduct(){ return (DAO_Product)get_Value("product"); } }
apache-2.0
medicayun/medicayundicom
dcm4jboss-all/tags/DCM4JBOSS_2_5_4/dcm4jboss-ejb/src/java/org/dcm4chex/archive/ejb/session/StudyMgtBean.java
12702
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <gunter.zeilinger@tiani.com> * Franz Willer <franz.willer@gwi-ag.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.ejb.session; import java.rmi.RemoteException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.FinderException; import javax.ejb.ObjectNotFoundException; import javax.ejb.RemoveException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.log4j.Logger; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmElement; import org.dcm4che.dict.Status; import org.dcm4che.dict.Tags; import org.dcm4che.net.DcmServiceException; import org.dcm4chex.archive.ejb.conf.AttributeFilter; import org.dcm4chex.archive.ejb.conf.ConfigurationException; import org.dcm4chex.archive.ejb.interfaces.InstanceLocal; import org.dcm4chex.archive.ejb.interfaces.InstanceLocalHome; import org.dcm4chex.archive.ejb.interfaces.PatientLocal; import org.dcm4chex.archive.ejb.interfaces.PatientLocalHome; import org.dcm4chex.archive.ejb.interfaces.SeriesLocal; import org.dcm4chex.archive.ejb.interfaces.SeriesLocalHome; import org.dcm4chex.archive.ejb.interfaces.StudyLocal; import org.dcm4chex.archive.ejb.interfaces.StudyLocalHome; /** * @author gunter.zeilinger@tiani.com * @version $Revision: 2010 $ $Date: 2005-10-07 03:55:27 +0800 (周五, 07 10月 2005) $ * @since Jun 6, 2005 * * @ejb.bean name="StudyMgt" type="Stateless" view-type="remote" * jndi-name="ejb/StudyMgt" * * @ejb.transaction-type type="Container" * @ejb.transaction type="Required" * * @ejb.ejb-ref ejb-name="Patient" view-type="local" ref-name="ejb/Patient" * @ejb.ejb-ref ejb-name="Study" view-type="local" ref-name="ejb/Study" * @ejb.ejb-ref ejb-name="Series" view-type="local" ref-name="ejb/Series" * @ejb.ejb-ref ejb-name="Instance" view-type="local" ref-name="ejb/Instance" * * @ejb.env-entry name="AttributeFilterConfigURL" type="java.lang.String" * value="resource:dcm4jboss-attribute-filter.xml" */ public abstract class StudyMgtBean implements SessionBean { private static final Logger log = Logger.getLogger(StudyMgtBean.class); private PatientLocalHome patHome; private StudyLocalHome studyHome; private SeriesLocalHome seriesHome; private InstanceLocalHome instHome; private AttributeFilter attrFilter; public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException { Context jndiCtx = null; try { jndiCtx = new InitialContext(); patHome = (PatientLocalHome) jndiCtx .lookup("java:comp/env/ejb/Patient"); studyHome = (StudyLocalHome) jndiCtx .lookup("java:comp/env/ejb/Study"); seriesHome = (SeriesLocalHome) jndiCtx .lookup("java:comp/env/ejb/Series"); instHome = (InstanceLocalHome) jndiCtx .lookup("java:comp/env/ejb/Instance"); attrFilter = new AttributeFilter((String) jndiCtx .lookup("java:comp/env/AttributeFilterConfigURL")); } catch (NamingException e) { throw new EJBException(e); } catch (ConfigurationException e) { throw new EJBException(e); } finally { if (jndiCtx != null) { try { jndiCtx.close(); } catch (NamingException ignore) { } } } } public void unsetSessionContext() { patHome = null; studyHome = null; seriesHome = null; instHome = null; } /** * @ejb.interface-method */ public void createStudy(Dataset ds) throws DcmServiceException { try { checkDuplicateStudy(ds.getString(Tags.StudyInstanceUID)); studyHome.create( ds.subSet(attrFilter.getStudyFilter()), getPatient(ds)); } catch (FinderException e) { throw new EJBException(e); } catch (CreateException e) { throw new EJBException(e); } } private PatientLocal getPatient(Dataset ds) throws DcmServiceException { String pid = ds.getString(Tags.PatientID); String issuer = ds.getString(Tags.IssuerOfPatientID); try { Collection c = issuer != null ? patHome.findByPatientIdWithIssuer(pid, issuer) : patHome.findByPatientId(pid); final int n = c.size(); switch (n) { case 0: return patHome.create(ds.subSet(attrFilter.getPatientFilter())); case 1: return (PatientLocal) c.iterator().next(); default: throw new DcmServiceException(Status.ProcessingFailure, "Found " + n + " Patients with id=" + pid + ", issuer=" + issuer); } } catch (FinderException e) { throw new EJBException(e); } catch (CreateException e) { throw new EJBException(e); } } private void checkDuplicateStudy(String suid) throws FinderException, DcmServiceException { try { studyHome.findByStudyIuid(suid); throw new DcmServiceException(Status.DuplicateSOPInstance, suid); } catch (ObjectNotFoundException e) { } } private StudyLocal getStudy(String suid) throws FinderException, DcmServiceException { try { return studyHome.findByStudyIuid(suid); } catch (ObjectNotFoundException e) { throw new DcmServiceException(Status.NoSuchSOPClass, suid); } } /** * @ejb.interface-method */ public void updateStudy(String iuid, Dataset ds) throws DcmServiceException { try { StudyLocal study = getStudy(iuid); if (ds.contains(Tags.PatientID)) { PatientLocal prevPat = study.getPatient(); PatientLocal pat = getPatient(ds); if (!pat.isIdentical(prevPat)) { log.info("Move " + study.asString() + " from " + prevPat.asString() + " to " + pat.asString()); study.setPatient(getPatient(ds)); } } Dataset attrs = study.getAttributes(false); attrs.putAll(ds.subSet(attrFilter.getStudyFilter())); study.setAttributes(attrs); DcmElement seriesSq = ds.get(Tags.RefSeriesSeq); if (seriesSq != null) { Set dirtyStudies = new HashSet(); Set dirtySeries = new HashSet(); for (int i = 0, n = seriesSq.vm(); i < n; ++i) { updateSeries(seriesSq.getItem(i), study, dirtyStudies, dirtySeries); } updateDerivedSeriesFields(dirtySeries); updateDerivedStudyFields(dirtyStudies); } } catch (FinderException e) { throw new EJBException(e); } catch (CreateException e) { throw new EJBException(e); } } private void updateDerivedStudyFields(Set dirtyStudies) throws FinderException { for (Iterator it = dirtyStudies.iterator(); it.hasNext();){ String iuid = (String) it.next(); StudyLocal study = studyHome.findByStudyIuid(iuid); study.updateDerivedFields(true, true, true, true, true, true, true); } } private void updateDerivedSeriesFields(Set dirtySeries) throws FinderException { for (Iterator it = dirtySeries.iterator(); it.hasNext();){ String iuid = (String) it.next(); SeriesLocal series = seriesHome.findBySeriesIuid(iuid); series.updateDerivedFields(true, true, true, true, true, true); } } private void updateSeries(Dataset ds, StudyLocal study, Set dirtyStudies, Set dirtySeries) throws FinderException, CreateException { Dataset newAttrs = ds.subSet(attrFilter.getSeriesFilter()); try { SeriesLocal series = seriesHome.findBySeriesIuid( ds.getString(Tags.SeriesInstanceUID)); StudyLocal prevStudy = series.getStudy(); if (!study.isIdentical(prevStudy)) { log.info("Move " + series.asString() + " from " + prevStudy.asString() + " to " + study.asString()); series.setStudy(study); dirtyStudies.add(study.getStudyIuid()); dirtyStudies.add(prevStudy.getStudyIuid()); } Dataset attrs = series.getAttributes(false); String newModality = newAttrs.getString(Tags.Modality); if (newModality != null && !newModality.equals(attrs.getString(Tags.Modality))) { dirtyStudies.add(study.getStudyIuid()); } attrs.putAll(newAttrs); series.setAttributes(attrs); DcmElement sopSq = ds.get(Tags.RefSOPSeq); if (sopSq != null) { for (int i = 0, n = sopSq.vm(); i < n; ++i) { updateInstance(sopSq.getItem(i), series, dirtyStudies, dirtySeries); } } } catch (ObjectNotFoundException e) { seriesHome.create(newAttrs, study); dirtyStudies.add(study.getStudyIuid()); } } private void updateInstance(Dataset ds, SeriesLocal series, Set dirtyStudies, Set dirtySeries) throws FinderException, CreateException { Dataset newAttrs = ds.subSet(attrFilter.getInstanceFilter()); try { InstanceLocal inst = instHome.findBySopIuid( ds.getString(Tags.RefSOPInstanceUID)); SeriesLocal prevSeries = inst.getSeries(); if (!series.isIdentical(prevSeries)) { log.info("Move " + inst.asString() + " from " + prevSeries.asString() + " to " + series.asString()); inst.setSeries(series); dirtySeries.add(series.getSeriesIuid()); dirtyStudies.add(series.getStudy().getStudyIuid()); dirtySeries.add(prevSeries.getSeriesIuid()); dirtyStudies.add(prevSeries.getStudy().getStudyIuid()); } Dataset attrs = inst.getAttributes(false); attrs.putAll(newAttrs); inst.setAttributes(attrs); } catch (ObjectNotFoundException e) { instHome.create(newAttrs, series); dirtySeries.add(series.getSeriesIuid()); dirtyStudies.add(series.getStudy().getStudyIuid()); } } /** * @ejb.interface-method */ public void deleteStudy(String iuid) throws DcmServiceException { try { getStudy(iuid).remove(); } catch (FinderException e) { throw new EJBException(e); } catch (RemoveException e) { throw new EJBException(e); } } /** * @ejb.interface-method */ public void deleteSeries(String[] iuids) { try { Set dirtyStudies = new HashSet(); for (int i = 0; i < iuids.length; i++) { SeriesLocal series = seriesHome.findBySeriesIuid(iuids[i]); dirtyStudies.add(series.getStudy().getStudyIuid()); series.remove(); } updateDerivedStudyFields(dirtyStudies); } catch (ObjectNotFoundException ignore) { } catch (FinderException e) { throw new EJBException(e); } catch (RemoveException e) { throw new EJBException(e); } } /** * @ejb.interface-method */ public void deleteInstances(String[] iuids) throws DcmServiceException { try { Set dirtySeries = new HashSet(); Set dirtyStudies = new HashSet(); for (int i = 0; i < iuids.length; i++) { InstanceLocal inst = instHome.findBySopIuid(iuids[i]); SeriesLocal series = inst.getSeries(); dirtySeries.add(series.getSeriesIuid()); dirtyStudies.add(series.getStudy().getStudyIuid()); inst.remove(); } updateDerivedSeriesFields(dirtySeries); updateDerivedStudyFields(dirtyStudies); } catch (ObjectNotFoundException ignore) { } catch (FinderException e) { throw new EJBException(e); } catch (RemoveException e) { throw new EJBException(e); } } }
apache-2.0
jbosschina/jcommerce
sandbox/web/src/main/java/com/jcommerce/gwt/client/ContentWidget.java
3374
package com.jcommerce.gwt.client; import java.util.HashMap; import java.util.Map; import com.extjs.gxt.ui.client.Style.Orientation; import com.extjs.gxt.ui.client.event.ButtonEvent; import com.extjs.gxt.ui.client.event.SelectionListener; import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.Layout; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.layout.RowLayout; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Widget; import com.jcommerce.gwt.client.IShopServiceAsync; public abstract class ContentWidget extends LayoutContainer { ContentPanel contentPanel = new ContentPanel(); private Map<String, Widget> widgets = new HashMap<String, Widget>(); FlexTable table = new FlexTable(); public ContentWidget() { super(); init(); } public ContentWidget(Layout layout) { super(layout); init(); } public boolean add(Widget panel) { contentPanel.add(panel); return true; } public boolean removeMyPanel(Widget panel) { contentPanel.remove(panel); return true; } private void init() { System.out.println("initlizing... "+this.getClass().getName()); super.add(contentPanel); contentPanel.setLayout(new RowLayout(Orientation.VERTICAL)); // Add the name // HTML nameWidget = new HTML("<b>"+getName()+"</b>"); // nameWidget.setStyleName(DEFAULT_STYLE_NAME + "-name"); contentPanel.setHeaderVisible(false); // Add the description //HTML descWidget = new HTML(getDescription()); // descWidget.setStyleName(DEFAULT_STYLE_NAME + "-description"); // contentPanel.add(descWidget); table.setCellSpacing(6); contentPanel.add(table); } /** * Get the description of this example. * * @return a description for this example */ public abstract String getDescription(); /** * Get the name of this example to use as a title. * * @return a name for this example */ public abstract String getName(); protected void refresh() { System.out.println("refresh did nothing!!!!"); } protected ContentPanel getContentPanel() { return contentPanel; } protected IShopServiceAsync getService() { return Utils.getService(); } public PageState curState; protected PageState getCurState() { return null; } protected void setCurState(PageState curState) { this.curState = curState; } public String getButtonText() { return null; } protected void buttonClicked() { } public SelectionListener<ButtonEvent> getButtonListener() { return new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { buttonClicked(); } }; } public void log(String s) { StringBuffer buf = new StringBuffer(); buf.append("[").append(this.getClass().getName()).append("]:").append(s); Logger.getClientLogger().log(buf.toString()); System.out.println(buf.toString()); } }
apache-2.0
vam-google/google-cloud-java
google-cloud-clients/google-cloud-trace/src/main/java/com/google/cloud/trace/v2/package-info.java
1518
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A client to Stackdriver Trace API. * * <p>The interfaces provided are listed below, along with usage samples. * * <p>================== TraceServiceClient ================== * * <p>Service Description: This file describes an API for collecting and viewing traces and spans * within a trace. A Trace is a collection of spans corresponding to a single operation or set of * operations for an application. A span is an individual timed event which forms a node of the * trace tree. A single trace may contain span(s) from multiple services. * * <p>Sample for TraceServiceClient: * * <pre> * <code> * try (TraceServiceClient traceServiceClient = TraceServiceClient.create()) { * ProjectName name = ProjectName.of("[PROJECT]"); * List&lt;Span&gt; spans = new ArrayList&lt;&gt;(); * traceServiceClient.batchWriteSpans(name, spans); * } * </code> * </pre> */ package com.google.cloud.trace.v2;
apache-2.0
gsvic/Cosine-Similarity-with-MapReduce
src/main/java/com/gsvic/csmr/CSMRBase.java
3356
/* * Copyright 2014 Giannakouris - Salalidis Victor * * 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.gsvic.csmr; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; public class CSMRBase { private static String path; public static void generatePairs(String in, String out) throws IOException,InterruptedException,ClassNotFoundException{ Configuration conf = new Configuration(); path = out; Job job; Path input, output; input = new Path(in); output = new Path(path+"/CSMRPairs"); job = new Job(conf); job.setJobName("CSMR Pairs Job"); job.setJarByClass(CSMRBase.class); FileInputFormat.addInputPath(job, input); FileOutputFormat.setOutputPath(job, output); job.setMapperClass(CSMRMapper.class); job.setReducerClass(CSMRReducer.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(DocumentWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(VectorArrayWritable.class); job.waitForCompletion(true); } public static void StartCSMR() throws IOException,InterruptedException, ClassNotFoundException{ Configuration conf = new Configuration(); Job job; job = new Job(conf); job.setJobName("CSMR Cosine Similarity Job"); job.setJarByClass(CSMRBase.class); FileInputFormat.addInputPath(job, new Path(path+"/CSMRPairs/part-r-00000")); FileOutputFormat.setOutputPath(job, new Path(path+"/Results")); job.setMapperClass(Mapper.class); job.setReducerClass(CosineSimilarityReducer.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(VectorArrayWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(DoubleWritable.class); System.exit( job.waitForCompletion(true) ? 1 : 0 ); } }
apache-2.0
johnjianfang/jxse
src/test/java/net/jxta/impl/cm/SrdiTest.java
14260
package net.jxta.impl.cm; import java.io.IOException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import net.jxta.id.IDFactory; import net.jxta.impl.cm.SrdiManager.SrdiPushEntriesInterface; import net.jxta.peer.PeerID; import net.jxta.peergroup.PeerGroup; import net.jxta.peergroup.PeerGroupID; import net.jxta.rendezvous.RendezVousService; import net.jxta.rendezvous.RendezVousStatus; import net.jxta.rendezvous.RendezvousEvent; import org.jmock.Expectations; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @Ignore("Needs Updating to junit4 and tests revisited") public class SrdiTest { private PeerGroup groupMock; private SrdiPushEntriesInterface srdiInterfaceMock; private SrdiAPI srdiIndex; private RendezVousService rendezvousServiceMock; private ScheduledExecutorService executorServiceMock; private ScheduledFuture<?> srdiPeriodicPushTaskHandle; private static final long PUSH_INTERVAL = 10000L; private SrdiManager srdiManager; private JUnit4Mockery mockery; @Before protected void setUp() throws Exception { mockery = new JUnit4Mockery(); groupMock = mockery.mock(PeerGroup.class); srdiInterfaceMock = mockery.mock(SrdiPushEntriesInterface.class); srdiIndex = mockery.mock(SrdiAPI.class); rendezvousServiceMock = mockery.mock(RendezVousService.class); executorServiceMock = mockery.mock(ScheduledExecutorService.class); srdiPeriodicPushTaskHandle = mockery.mock(ScheduledFuture.class); mockery.checking(new Expectations() {{ ignoring(groupMock).getResolverService(); atLeast(1).of(groupMock).getRendezVousService(); will(returnValue(rendezvousServiceMock)); one(rendezvousServiceMock).addListener(with(any(SrdiManager.class))); }}); srdiManager = new SrdiManager(groupMock, "testHandler", srdiInterfaceMock, srdiIndex); } @Test public void testStartPush() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); } @Test public void testStartPushIgnoredIfPeerIsRdvInGroup() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(true)); never(executorServiceMock); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); } @Test public void testStartPushIgnoredIfRdvConnectionNotEstablished() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(false)); never(executorServiceMock); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); } public void testStartPushIgnoredIfRdvServiceIsInAdHocMode() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.ADHOC)); never(executorServiceMock); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); } public void testStartPushSchedulesSrdiPeriodicPushTask() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); } @Ignore("Needs updating") public void testRendezvousConnectEventRestartsPush() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(false)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.RDVCONNECT, null)); } @Ignore("Needs updating") public void testRendezvousConnectEventIgnoredIfModeIsAdHoc() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(false)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.ADHOC)); never(executorServiceMock); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.RDVCONNECT, null)); } @Ignore("Needs updating") public void testRendezvousConnectIgnoredIfPushNotStarted() { mockery.checking(new Expectations() {{ never(executorServiceMock); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.RDVCONNECT, null)); } @Ignore("Needs updating") public void testRendezvousDisconnectEventStopsPush() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); will(returnValue(srdiPeriodicPushTaskHandle)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(srdiPeriodicPushTaskHandle).cancel(false); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.RDVDISCONNECT, null)); } @Ignore("Needs updating") public void testBecameRendezvousEventStopsPush() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); will(returnValue(srdiPeriodicPushTaskHandle)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(srdiPeriodicPushTaskHandle).cancel(false); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.BECAMERDV, null)); } @Ignore("Needs updating") public void testBecameRendezvousEventIgnoredIfNoPushNotStarted() { mockery.checking(new Expectations() {{ never(executorServiceMock); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.BECAMERDV, null)); } @Ignore("Needs updating") public void testBecameEdgeEventStartsPush() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(true)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.BECAMEEDGE, null)); } @Ignore("Needs updating") public void testBecameEdgeEventIgnoredIfNotConnectedToRendezvous() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(true)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(false)); never(executorServiceMock); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.BECAMEEDGE, null)); } @Ignore("Needs updating") public void testBecameEdgeEventIgnoredIfRendezvousIsInAdHocMode() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(true)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.ADHOC)); never(executorServiceMock); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.BECAMEEDGE, null)); } @Ignore("Needs updating") public void testBecameEdgeEventIgnoredIfPushNotStarted() { mockery.checking(new Expectations() {{ never(executorServiceMock); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.BECAMEEDGE, null)); } @Ignore("Needs updating") public void testRdvFailedEventStopsPush() { mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); one(rendezvousServiceMock).isConnectedToRendezVous(); will(returnValue(true)); one(rendezvousServiceMock).getRendezVousStatus(); will(returnValue(RendezVousStatus.EDGE)); one(executorServiceMock).scheduleWithFixedDelay(with(any(SrdiManagerPeriodicPushTask.class)), with(equal(0L)), with(equal(PUSH_INTERVAL)), with(equal(TimeUnit.MILLISECONDS))); will(returnValue(srdiPeriodicPushTaskHandle)); }}); srdiManager.startPush(executorServiceMock, PUSH_INTERVAL); mockery.checking(new Expectations() {{ one(srdiPeriodicPushTaskHandle).cancel(false); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.RDVFAILED, null)); } @Ignore("Needs updating") public void testClientFailedEventRemovesPeerFromSrdiIndexIfCurrentlyARendezvous() throws IOException { final PeerID peerId = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(true)); one(srdiIndex).remove(peerId); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.CLIENTFAILED, peerId)); } @Ignore("Needs updating") public void testClientFailedEventIgnoredIfNotARendezvous() throws IOException { final PeerID peerId = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID); mockery.checking(new Expectations() {{ one(groupMock).isRendezvous(); will(returnValue(false)); never(srdiIndex).remove(peerId); }}); srdiManager.rendezvousEvent(new RendezvousEvent(new Object(), RendezvousEvent.CLIENTFAILED, peerId)); } }
apache-2.0