gt
stringclasses
1 value
context
stringlengths
2.05k
161k
package org.jetbrains.idea.svn.commandLine; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.api.ProgressTracker; import org.jetbrains.idea.svn.properties.PropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * @author Konstantin Kolosovsky. */ // TODO: Probably make command immutable and use CommandBuilder for updates. public class Command { @NotNull private final List<String> myParameters = ContainerUtil.newArrayList(); @NotNull private final List<String> myOriginalParameters = ContainerUtil.newArrayList(); @NotNull private final SvnCommandName myName; private File workingDirectory; @Nullable private File myConfigDir; @Nullable private LineCommandListener myResultBuilder; @Nullable private volatile SVNURL myRepositoryUrl; @NotNull private SvnTarget myTarget; @Nullable private Collection<File> myTargets; @Nullable private PropertyValue myPropertyValue; @Nullable private ProgressTracker myCanceller; public Command(@NotNull SvnCommandName name) { myName = name; } public void put(@Nullable Depth depth) { CommandUtil.put(myParameters, depth, false); } public void put(@NotNull SvnTarget target) { CommandUtil.put(myParameters, target); } public void put(@Nullable SVNRevision revision) { CommandUtil.put(myParameters, revision); } public void put(@NotNull String parameter, boolean condition) { CommandUtil.put(myParameters, condition, parameter); } public void put(@NonNls @NotNull String... parameters) { put(Arrays.asList(parameters)); } public void put(@NotNull List<String> parameters) { myParameters.addAll(parameters); } public void putIfNotPresent(@NotNull String parameter) { if (!myParameters.contains(parameter)) { myParameters.add(parameter); } } @Nullable public ProgressTracker getCanceller() { return myCanceller; } public void setCanceller(@Nullable ProgressTracker canceller) { myCanceller = canceller; } @Nullable public File getConfigDir() { return myConfigDir; } public File getWorkingDirectory() { return workingDirectory; } @Nullable public LineCommandListener getResultBuilder() { return myResultBuilder; } @Nullable public SVNURL getRepositoryUrl() { return myRepositoryUrl; } @NotNull public SVNURL requireRepositoryUrl() { SVNURL result = getRepositoryUrl(); assert result != null; return result; } @NotNull public SvnTarget getTarget() { return myTarget; } @Nullable public List<String> getTargetsPaths() { return ContainerUtil.isEmpty(myTargets) ? null : ContainerUtil.map(myTargets, file -> CommandUtil.format(file.getAbsolutePath(), null)); } @Nullable public PropertyValue getPropertyValue() { return myPropertyValue; } @NotNull public SvnCommandName getName() { return myName; } public void setWorkingDirectory(File workingDirectory) { this.workingDirectory = workingDirectory; } public void setConfigDir(@Nullable File configDir) { this.myConfigDir = configDir; } public void setResultBuilder(@Nullable LineCommandListener resultBuilder) { myResultBuilder = resultBuilder; } public void setRepositoryUrl(@Nullable SVNURL repositoryUrl) { myRepositoryUrl = repositoryUrl; } public void setTarget(@NotNull SvnTarget target) { myTarget = target; } public void setTargets(@Nullable Collection<File> targets) { myTargets = targets; } public void setPropertyValue(@Nullable PropertyValue propertyValue) { myPropertyValue = propertyValue; } // TODO: used only to ensure authentication info is not logged to file. Remove when command execution model is refactored // TODO: - so we could determine if parameter should be logged by the parameter itself. public void saveOriginalParameters() { myOriginalParameters.clear(); myOriginalParameters.addAll(myParameters); } @NotNull public List<String> getParameters() { return ContainerUtil.newArrayList(myParameters); } public String getText() { List<String> data = new ArrayList<>(); if (myConfigDir != null) { data.add("--config-dir"); data.add(myConfigDir.getPath()); } data.add(myName.getName()); data.addAll(myOriginalParameters); List<String> targetsPaths = getTargetsPaths(); if (!ContainerUtil.isEmpty(targetsPaths)) { data.addAll(targetsPaths); } return StringUtil.join(data, " "); } public boolean isLocalInfo() { return is(SvnCommandName.info) && hasLocalTarget() && !myParameters.contains("--revision"); } public boolean isLocalStatus() { return is(SvnCommandName.st) && hasLocalTarget() && !myParameters.contains("-u"); } public boolean isLocalProperty() { boolean isPropertyCommand = is(SvnCommandName.proplist) || is(SvnCommandName.propget) || is(SvnCommandName.propset) || is(SvnCommandName.propdel); return isPropertyCommand && hasLocalTarget() && isLocal(getRevision()); } public boolean isLocalCat() { return is(SvnCommandName.cat) && hasLocalTarget() && isLocal(getRevision()); } @Nullable private SVNRevision getRevision() { int index = myParameters.indexOf("--revision"); return index >= 0 && index + 1 < myParameters.size() ? SVNRevision.parse(myParameters.get(index + 1)) : null; } public boolean is(@NotNull SvnCommandName name) { return name.equals(myName); } private boolean hasLocalTarget() { return myTarget.isFile() && isLocal(myTarget.getPegRevision()); } private static boolean isLocal(@Nullable SVNRevision revision) { return revision == null || SVNRevision.UNDEFINED.equals(revision) || SVNRevision.BASE.equals(revision) || SVNRevision.WORKING.equals(revision); } }
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.services.jbpm; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Function; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceUnitInfo; import org.apache.commons.io.IOUtils; import org.appformer.maven.support.DependencyFilter; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.compiler.kie.builder.impl.KieServicesImpl; import org.drools.core.impl.InternalKieContainer; import org.jbpm.kie.services.impl.DeployedUnitImpl; import org.jbpm.services.api.DeploymentService; import org.jbpm.services.api.RuntimeDataService; import org.jbpm.services.api.model.DeployedUnit; import org.jbpm.services.api.model.DeploymentUnit; import org.jbpm.services.api.model.ProcessInstanceDesc; import org.jbpm.services.api.query.QueryService; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieModule; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.scanner.KieMavenRepository; import org.kie.scanner.KieModuleMetaData; import org.kie.server.api.KieServerConstants; import org.kie.server.api.KieServerEnvironment; import org.kie.server.api.model.KieContainerStatus; import org.kie.server.api.model.KieServerInfo; import org.kie.server.api.model.KieServerMode; import org.kie.server.api.model.KieServiceResponse; import org.kie.server.api.model.Message; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.ServiceResponse; import org.kie.server.services.api.KieServerRegistry; import org.kie.server.services.impl.KieContainerInstanceImpl; import org.kie.server.services.impl.KieServerImpl; import org.kie.server.services.impl.KieServerRegistryImpl; import org.kie.server.services.impl.storage.file.KieServerStateFileRepository; import org.kie.server.services.jbpm.jpa.PersistenceUnitExtensionsLoaderMock; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class JbpmKieServerExtensionTest { private static final String RESOURCES = "src/main/resources/"; private static final String CONTAINER_ID = "my-container"; private static final String GROUP_ID = "org.kie.server.test"; private static final String ARTIFACT_ID = "my-test-artifact"; private static final String VERSION = "1.0.0.Final"; private static final String VERSION_SNAPSHOT = "1.0.0-SNAPSHOT"; private boolean deployed = false; @Captor private ArgumentCaptor<Function<DeploymentUnit, Boolean>> beforeUndeployCaptor; @Mock private DeploymentService deploymentService; @Mock private RuntimeDataService runtimeDataService; @Mock private QueryService queryService; @Mock private KieServerImpl kieServer; @Mock private KieServerInfo kieServerInfo; @Captor private ArgumentCaptor<PersistenceUnitInfo> persistenceUnitInfoCaptor; private KieServerMode mode; private List<ProcessInstanceDesc> activeProcessInstances = new ArrayList<>(); private KieServicesImpl kieServices; private KieServerRegistry context; private JbpmKieServerExtension extension; private InternalKieContainer kieContainer; private DeploymentUnit deploymentUnit; private DeployedUnitImpl deployedUnit; private RuntimeManager runimeManager; private RuntimeEngine engine; private KieSession session; @Before public void init() { KieServerEnvironment.setServerId(UUID.randomUUID().toString()); context = new KieServerRegistryImpl(); context.registerStateRepository(new KieServerStateFileRepository(new File("target"))); kieServices = (KieServicesImpl) KieServices.Factory.get(); when(kieServerInfo.getMode()).thenAnswer(invocationOnMock -> mode); when(kieServer.getInfo()).thenReturn(new ServiceResponse<KieServerInfo>(KieServiceResponse.ResponseType.SUCCESS, "", kieServerInfo)); extension = spy(new JbpmKieServerExtension() { { this.deploymentService = JbpmKieServerExtensionTest.this.deploymentService; this.runtimeDataService = JbpmKieServerExtensionTest.this.runtimeDataService; this.kieServer = JbpmKieServerExtensionTest.this.kieServer; } }); when(deploymentService.isDeployed(anyString())).thenAnswer((Answer<Boolean>) invocation -> deployed); doAnswer(invocation -> { deployed = false; return null; }).when(deploymentService).undeploy(any(), any()); doAnswer(invocation -> { deployed = false; return null; }).when(deploymentService).undeploy(any()); doAnswer((Answer<Void>) invocation -> { deploymentUnit = (DeploymentUnit) invocation.getArguments()[0]; deployed = true; return null; }).when(deploymentService).deploy(any()); when(deploymentService.getDeployedUnit(anyString())).thenAnswer((Answer<DeployedUnit>) invocation -> { deployedUnit = new DeployedUnitImpl(deploymentUnit); runimeManager = mock(RuntimeManager.class); engine = mock(RuntimeEngine.class); when(runimeManager.getRuntimeEngine(any())).thenReturn(engine); session = mock(KieSession.class); when(engine.getKieSession()).thenReturn(session); deployedUnit.setRuntimeManager(runimeManager); return deployedUnit; }); extension.setQueryService(queryService); extension.setContext(context); when(runtimeDataService.getProcessInstancesByDeploymentId(anyString(), anyList(), any())).thenReturn(activeProcessInstances); } @After public void clear() { kieServices.nullAllContainerIds(); } @Test public void testCreateContainer() throws IOException { testDeployContainer(VERSION); } @Test public void testCreateSNAPSHOTContainer() throws IOException { testDeployContainer(VERSION_SNAPSHOT); } @Test public void testDisposePRODUCTIONContainer() throws IOException { testDispose(KieServerMode.PRODUCTION); } @Test public void testDisposeSNAPSHOTContainer() throws IOException { testDispose(KieServerMode.DEVELOPMENT); } private void testDispose(KieServerMode mode) throws IOException { this.mode = mode; String version; if(mode.equals(KieServerMode.DEVELOPMENT)) { version = VERSION_SNAPSHOT; } else { version = VERSION; } testDeployContainer(version); KieModuleMetaData metaData = KieModuleMetaData.Factory.newKieModuleMetaData(new ReleaseId(GROUP_ID, ARTIFACT_ID, version), DependencyFilter.COMPILE_FILTER); List<Message> messages = new ArrayList<>(); Map<String, Object> params = new HashMap<>(); params.put(KieServerConstants.KIE_SERVER_PARAM_MODULE_METADATA, metaData); params.put(KieServerConstants.KIE_SERVER_PARAM_MESSAGES, messages); params.put(KieServerConstants.KIE_SERVER_PARAM_RESET_BEFORE_UPDATE, Boolean.FALSE); extension.disposeContainer(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), params); if(mode.equals(KieServerMode.DEVELOPMENT)) { verify(deploymentService).undeploy(any(), beforeUndeployCaptor.capture()); Function<DeploymentUnit, Boolean> function = beforeUndeployCaptor.getValue(); function.apply(deploymentUnit); verify(runtimeDataService).getProcessInstancesByDeploymentId(eq(CONTAINER_ID), anyList(), any()); verify(runimeManager, times(activeProcessInstances.size())).getRuntimeEngine(any()); verify(engine, times(activeProcessInstances.size())).getKieSession(); verify(session, times(activeProcessInstances.size())).abortProcessInstance(eq(new Long(1))); verify(runimeManager, times(activeProcessInstances.size())).disposeRuntimeEngine(any()); } else { verify(deploymentService).undeploy(any()); } } @Test public void testIsUpdateAllowedDevModeSNAPSHOT() throws IOException { testDeployContainer(VERSION_SNAPSHOT); mode = KieServerMode.DEVELOPMENT; assertTrue(extension.isUpdateContainerAllowed(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), new HashMap<>())); } @Test public void testIsUpdateAllowedDevModeNonSNAPSHOT() throws IOException { testDeployContainer(VERSION); mode = KieServerMode.DEVELOPMENT; assertTrue(extension.isUpdateContainerAllowed(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), new HashMap<>())); } @Test public void testIsUpdateAllowedProductionModeWithoutProcessInstances() throws IOException { testIsUpdateAllowed(false); } @Test public void testIsUpdateAllowedProductionModeWithProcessInstances() throws IOException { testIsUpdateAllowed(true); } @Test public void testLoadDefaultQueryDefinitions() { extension.registerDefaultQueryDefinitions(); verify(queryService, times(10)).replaceQuery(any()); } @Test public void testUpdateContainerProductionMode() throws IOException { testUpdateContainer(KieServerMode.PRODUCTION, VERSION, false); } @Test public void testUpdateContainerProductionModeWithForcedCleanup() throws IOException { testUpdateContainer(KieServerMode.PRODUCTION, VERSION, true); } @Test public void testUpdateDevModeSNAPSHOTContainer() throws IOException { testUpdateContainer(KieServerMode.DEVELOPMENT, VERSION_SNAPSHOT, false); } @Test public void testUpdateDevModeSNAPSHOTContainerWithForcedCeanup() throws IOException { activeProcessInstances.add(mockProcessInstance()); activeProcessInstances.add(mockProcessInstance()); activeProcessInstances.add(mockProcessInstance()); testUpdateContainer(KieServerMode.DEVELOPMENT, VERSION_SNAPSHOT, true); } @Test public void testUpdateDevModeNonSNAPSHOTContainer() throws IOException { testUpdateContainer(KieServerMode.DEVELOPMENT, VERSION, false); } @Test public void testUpdateDevModeNonSNAPSHOTContainerWithForcedCeanup() throws IOException { activeProcessInstances.add(mockProcessInstance()); activeProcessInstances.add(mockProcessInstance()); activeProcessInstances.add(mockProcessInstance()); testUpdateContainer(KieServerMode.DEVELOPMENT, VERSION, true); } @Test public void testPrepareContainerUpdateDevModeSNAPSHOTWithForcedCleanup() throws IOException { testPrepareContainerUpdate(KieServerMode.DEVELOPMENT, VERSION_SNAPSHOT, true); } @Test public void testPrepareContainerUpdateDevModeSNAPSHOT() throws IOException { testPrepareContainerUpdate(KieServerMode.DEVELOPMENT, VERSION_SNAPSHOT, false); } @Test public void testPrepareContainerUpdateDevModeNonSNAPSHOTWithForcedCleanup() throws IOException { testPrepareContainerUpdate(KieServerMode.DEVELOPMENT, VERSION, true); } @Test public void testPrepareContainerUpdateDevModeNonSNAPSHOT() throws IOException { testPrepareContainerUpdate(KieServerMode.DEVELOPMENT, VERSION, false); } @Test public void testBuildEntityManagerFactoryWithPersistenceUnitExtensionsLoaderEnabled() { testBuildEntityManagerFactoryWithPersistenceUnitExtensionsLoader(true); } @Test public void testBuildEntityManagerFactoryWithPersistenceUnitExtensionsLoaderDisabled() { testBuildEntityManagerFactoryWithPersistenceUnitExtensionsLoader(false); } private void testBuildEntityManagerFactoryWithPersistenceUnitExtensionsLoader(boolean enabled) { Map<String, String> properties = new HashMap<>(); System.setProperty(PersistenceUnitExtensionsLoaderMock.ENABLED_PROPERTY, Boolean.toString(enabled)); EntityManagerFactory emf = mock(EntityManagerFactory.class); doReturn(emf).when(extension).createEntityManagerFactory(any(), any(), any()); extension.build(properties); verify(extension).createEntityManagerFactory(any(), persistenceUnitInfoCaptor.capture(), any()); if (enabled) { assertTrue(persistenceUnitInfoCaptor.getValue().getManagedClassNames().contains(PersistenceUnitExtensionsLoaderMock.ENTITY_MOCK)); } else { assertFalse(persistenceUnitInfoCaptor.getValue().getManagedClassNames().contains(PersistenceUnitExtensionsLoaderMock.ENTITY_MOCK)); } } @After public void cleanUp() { System.clearProperty(PersistenceUnitExtensionsLoaderMock.ENABLED_PROPERTY); } private void testPrepareContainerUpdate(KieServerMode mode, String version, boolean cleanup) throws IOException { this.mode = mode; activeProcessInstances.add(mockProcessInstance()); activeProcessInstances.add(mockProcessInstance()); activeProcessInstances.add(mockProcessInstance()); testDeployContainer(version); KieModuleMetaData metaData = KieModuleMetaData.Factory.newKieModuleMetaData(new ReleaseId(GROUP_ID, ARTIFACT_ID, version), DependencyFilter.COMPILE_FILTER); List<Message> messages = new ArrayList<>(); Map<String, Object> params = new HashMap<>(); params.put(KieServerConstants.KIE_SERVER_PARAM_MODULE_METADATA, metaData); params.put(KieServerConstants.KIE_SERVER_PARAM_MESSAGES, messages); params.put(KieServerConstants.KIE_SERVER_PARAM_RESET_BEFORE_UPDATE, cleanup); extension.prepareContainerUpdate(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), params); if(mode.equals(KieServerMode.PRODUCTION) || !cleanup) { verify(runtimeDataService, never()).getProcessInstancesByDeploymentId(eq(CONTAINER_ID), anyList(), any()); verify(runimeManager, never()).getRuntimeEngine(any()); verify(engine, never()).getKieSession(); verify(session, never()).abortProcessInstance(eq(new Long(1))); verify(runimeManager, never()).disposeRuntimeEngine(any()); } else { verify(runtimeDataService).getProcessInstancesByDeploymentId(eq(CONTAINER_ID), anyList(), any()); verify(runimeManager, times(activeProcessInstances.size())).getRuntimeEngine(any()); verify(engine, times(activeProcessInstances.size())).getKieSession(); verify(session, times(activeProcessInstances.size())).abortProcessInstance(eq(new Long(1))); verify(runimeManager, times(activeProcessInstances.size())).disposeRuntimeEngine(any()); } } private ProcessInstanceDesc mockProcessInstance() { ProcessInstanceDesc instance = mock(ProcessInstanceDesc.class); when(instance.getId()).thenReturn(new Long(1)); return instance; } private void testUpdateContainer(KieServerMode mode, String version, boolean cleanup) throws IOException { this.mode = mode; testDeployContainer(version); KieModuleMetaData metaData = KieModuleMetaData.Factory.newKieModuleMetaData(new ReleaseId(GROUP_ID, ARTIFACT_ID, version), DependencyFilter.COMPILE_FILTER); List<Message> messages = new ArrayList<>(); Map<String, Object> params = new HashMap<>(); params.put(KieServerConstants.KIE_SERVER_PARAM_MODULE_METADATA, metaData); params.put(KieServerConstants.KIE_SERVER_PARAM_MESSAGES, messages); params.put(KieServerConstants.KIE_SERVER_PARAM_RESET_BEFORE_UPDATE, cleanup); extension.updateContainer(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), params); if (mode.equals(KieServerMode.PRODUCTION)) { verify(deploymentService).undeploy(any()); } else { verify(deploymentService).undeploy(any(), beforeUndeployCaptor.capture()); Function<DeploymentUnit, Boolean> function = beforeUndeployCaptor.getValue(); assertNotNull(function); assertTrue(function.apply(deploymentUnit)); verify(runtimeDataService, never()).getProcessInstancesByDeploymentId(eq(CONTAINER_ID), anyList(), any()); verify(runimeManager, never()).getRuntimeEngine(any()); verify(engine, never()).getKieSession(); verify(session, never()).abortProcessInstance(eq(new Long(1))); verify(runimeManager, never()).disposeRuntimeEngine(any()); } verify(deploymentService, times(2)).deploy(any()); } private void testDeployContainer(String version) throws IOException { createEmptyKjar(GROUP_ID, ARTIFACT_ID, version); ReleaseId releaseId = new ReleaseId(GROUP_ID, ARTIFACT_ID, version); kieContainer = (InternalKieContainer) kieServices.newKieContainer(CONTAINER_ID, releaseId); KieContainerInstanceImpl containerInstance = new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer); KieModuleMetaData metaData = KieModuleMetaData.Factory.newKieModuleMetaData(releaseId, DependencyFilter.COMPILE_FILTER); List<Message> messages = new ArrayList<>(); Map<String, Object> params = new HashMap<>(); params.put(KieServerConstants.KIE_SERVER_PARAM_MODULE_METADATA, metaData); params.put(KieServerConstants.KIE_SERVER_PARAM_MESSAGES, messages); extension.createContainer(CONTAINER_ID, containerInstance, params); verify(deploymentService).deploy(any()); } private void testIsUpdateAllowed(boolean existingInstances) throws IOException { mode = KieServerMode.PRODUCTION; List<ProcessInstanceDesc> activeProcesses = new ArrayList<>(); if (existingInstances) { activeProcesses.add(mock(ProcessInstanceDesc.class)); activeProcesses.add(mock(ProcessInstanceDesc.class)); } when(runtimeDataService.getProcessInstancesByDeploymentId(anyString(), anyList(), any())).thenReturn(activeProcesses); testDeployContainer(VERSION); if (existingInstances) { assertFalse(extension.isUpdateContainerAllowed(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), new HashMap<>())); } else { assertTrue(extension.isUpdateContainerAllowed(CONTAINER_ID, new KieContainerInstanceImpl(CONTAINER_ID, KieContainerStatus.STARTED, kieContainer), new HashMap<>())); } } private void createEmptyKjar(String groupId, String artifactId, String version) throws IOException { // create empty kjar; content does not matter KieServices kieServices = KieServices.Factory.get(); KieFileSystem kfs = kieServices.newKieFileSystem(); org.kie.api.builder.ReleaseId releaseId = kieServices.newReleaseId(groupId, artifactId, version); kfs.generateAndWritePomXML(releaseId); String processContent = IOUtils.toString(this.getClass().getResourceAsStream("/processes/hiring.bpmn2"), Charset.defaultCharset()); kfs.write(RESOURCES + "hiring.bpmn2", processContent); KieModule kieModule = kieServices.newKieBuilder(kfs).buildAll().getKieModule(); byte[] pom = kfs.read("pom.xml"); byte[] jar = ((InternalKieModule) kieModule).getBytes(); KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, jar, pom); } }
/* * 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.messy.tests; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.util.CollectionUtils; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService.ScriptType; import org.elasticsearch.script.groovy.GroovyPlugin; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.global.Global; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Order; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.AbstractNumericTestCase; import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile; import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles; import org.elasticsearch.search.aggregations.metrics.percentiles.PercentilesMethod; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.global; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.percentiles; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.filter; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.Matchers.*; /** * */ public class HDRPercentilesTests extends AbstractNumericTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return pluginList(GroovyPlugin.class); } private static double[] randomPercentiles() { final int length = randomIntBetween(1, 20); final double[] percentiles = new double[length]; for (int i = 0; i < percentiles.length; ++i) { switch (randomInt(20)) { case 0: percentiles[i] = 0; break; case 1: percentiles[i] = 100; break; default: percentiles[i] = randomDouble() * 100; break; } } Arrays.sort(percentiles); Loggers.getLogger(HDRPercentilesTests.class).info("Using percentiles={}", Arrays.toString(percentiles)); return percentiles; } private static int randomSignificantDigits() { return randomIntBetween(0, 5); } private void assertConsistent(double[] pcts, Percentiles percentiles, long minValue, long maxValue, int numberSigDigits) { final List<Percentile> percentileList = CollectionUtils.iterableAsArrayList(percentiles); assertEquals(pcts.length, percentileList.size()); for (int i = 0; i < pcts.length; ++i) { final Percentile percentile = percentileList.get(i); assertThat(percentile.getPercent(), equalTo(pcts[i])); double value = percentile.getValue(); double allowedError = value / Math.pow(10, numberSigDigits); assertThat(value, greaterThanOrEqualTo(minValue - allowedError)); assertThat(value, lessThanOrEqualTo(maxValue + allowedError)); if (percentile.getPercent() == 0) { assertThat(value, closeTo(minValue, allowedError)); } if (percentile.getPercent() == 100) { assertThat(value, closeTo(maxValue, allowedError)); } } for (int i = 1; i < percentileList.size(); ++i) { assertThat(percentileList.get(i).getValue(), greaterThanOrEqualTo(percentileList.get(i - 1).getValue())); } } @Override @Test public void testEmptyAggregation() throws Exception { int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation( histogram("histo") .field("value") .interval(1l) .minDocCount(0) .subAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR) .percentiles(10, 15))).execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); Histogram histo = searchResponse.getAggregations().get("histo"); assertThat(histo, notNullValue()); Histogram.Bucket bucket = histo.getBuckets().get(1); assertThat(bucket, notNullValue()); Percentiles percentiles = bucket.getAggregations().get("percentiles"); assertThat(percentiles, notNullValue()); assertThat(percentiles.getName(), equalTo("percentiles")); assertThat(percentiles.percentile(10), equalTo(Double.NaN)); assertThat(percentiles.percentile(15), equalTo(Double.NaN)); } @Override @Test public void testUnmapped() throws Exception { int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx_unmapped") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("value") .percentiles(0, 10, 15, 100)).execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(0l)); Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertThat(percentiles, notNullValue()); assertThat(percentiles.getName(), equalTo("percentiles")); assertThat(percentiles.percentile(0), equalTo(Double.NaN)); assertThat(percentiles.percentile(10), equalTo(Double.NaN)); assertThat(percentiles.percentile(15), equalTo(Double.NaN)); assertThat(percentiles.percentile(100), equalTo(Double.NaN)); } @Override @Test public void testSingleValuedField() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomIntBetween(1, 5); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("value") .percentiles(pcts)) .execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValue, maxValue, sigDigits); } @Override @Test public void testSingleValuedField_getProperty() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( global("global").subAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR) .field("value") .percentiles(pcts))).execute().actionGet(); assertHitCount(searchResponse, 10); Global global = searchResponse.getAggregations().get("global"); assertThat(global, notNullValue()); assertThat(global.getName(), equalTo("global")); assertThat(global.getDocCount(), equalTo(10l)); assertThat(global.getAggregations(), notNullValue()); assertThat(global.getAggregations().asMap().size(), equalTo(1)); Percentiles percentiles = global.getAggregations().get("percentiles"); assertThat(percentiles, notNullValue()); assertThat(percentiles.getName(), equalTo("percentiles")); assertThat((Percentiles) global.getProperty("percentiles"), sameInstance(percentiles)); } @Override @Test public void testSingleValuedField_PartiallyUnmapped() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx", "idx_unmapped") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("value") .percentiles(pcts)) .execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValue, maxValue, sigDigits); } @Override @Test public void testSingleValuedField_WithValueScript() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("value") .script(new Script("_value - 1")).percentiles(pcts)).execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValue - 1, maxValue - 1, sigDigits); } @Override @Test public void testSingleValuedField_WithValueScript_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("value") .script(new Script("_value - dec", ScriptType.INLINE, null, params)).percentiles(pcts)).execute() .actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValue - 1, maxValue - 1, sigDigits); } @Override @Test public void testMultiValuedField() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("values") .percentiles(pcts)) .execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValues, maxValues, sigDigits); } @Override @Test public void testMultiValuedField_WithValueScript() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("values") .script(new Script("_value - 1")).percentiles(pcts)).execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValues - 1, maxValues - 1, sigDigits); } @Test public void testMultiValuedField_WithValueScript_Reverse() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("values") .script(new Script("20 - _value")).percentiles(pcts)).execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, 20 - maxValues, 20 - minValues, sigDigits); } @Override @Test public void testMultiValuedField_WithValueScript_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR).field("values") .script(new Script("_value - dec", ScriptType.INLINE, null, params)).percentiles(pcts)).execute() .actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValues - 1, maxValues - 1, sigDigits); } @Override @Test public void testScript_SingleValued() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR) .script(new Script("doc['value'].value")).percentiles(pcts)).execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValue, maxValue, sigDigits); } @Override @Test public void testScript_SingleValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR) .script(new Script("doc['value'].value - dec", ScriptType.INLINE, null, params)).percentiles(pcts)) .execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValue - 1, maxValue - 1, sigDigits); } @Override public void testScriptMultiValued() throws Exception { final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles").numberOfSignificantValueDigits(sigDigits).method(PercentilesMethod.HDR) .script(new Script("doc['values'].values")).percentiles(pcts)).execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValues, maxValues, sigDigits); } @Override public void testScriptMultiValuedWithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); final double[] pcts = randomPercentiles(); int sigDigits = randomSignificantDigits(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( percentiles("percentiles") .numberOfSignificantValueDigits(sigDigits) .method(PercentilesMethod.HDR) .script(new Script( "List values = doc['values'].values; double[] res = new double[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = values.get(i) - dec; }; return res;", ScriptType.INLINE, null, params)).percentiles(pcts)).execute().actionGet(); assertHitCount(searchResponse, 10); final Percentiles percentiles = searchResponse.getAggregations().get("percentiles"); assertConsistent(pcts, percentiles, minValues - 1, maxValues - 1, sigDigits); } @Test public void testOrderBySubAggregation() { int sigDigits = randomSignificantDigits(); boolean asc = randomBoolean(); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( histogram("histo").field("value").interval(2l) .subAggregation( percentiles("percentiles").method(PercentilesMethod.HDR).numberOfSignificantValueDigits(sigDigits) .percentiles(99)) .order(Order.aggregation("percentiles", "99", asc))).execute().actionGet(); assertHitCount(searchResponse, 10); Histogram histo = searchResponse.getAggregations().get("histo"); double previous = asc ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; for (Histogram.Bucket bucket : histo.getBuckets()) { Percentiles percentiles = bucket.getAggregations().get("percentiles"); double p99 = percentiles.percentile(99); if (asc) { assertThat(p99, greaterThanOrEqualTo(previous)); } else { assertThat(p99, lessThanOrEqualTo(previous)); } previous = p99; } } @Override public void testOrderByEmptyAggregation() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( terms("terms").field("value").order(Terms.Order.compound(Terms.Order.aggregation("filter>percentiles.99", true))) .subAggregation(filter("filter").filter(termQuery("value", 100)) .subAggregation(percentiles("percentiles").method(PercentilesMethod.HDR).field("value")))) .get(); assertHitCount(searchResponse, 10); Terms terms = searchResponse.getAggregations().get("terms"); assertThat(terms, notNullValue()); List<Terms.Bucket> buckets = terms.getBuckets(); assertThat(buckets, notNullValue()); assertThat(buckets.size(), equalTo(10)); for (int i = 0; i < 10; i++) { Terms.Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKeyAsNumber(), equalTo((Number) Long.valueOf(i + 1))); assertThat(bucket.getDocCount(), equalTo(1L)); Filter filter = bucket.getAggregations().get("filter"); assertThat(filter, notNullValue()); assertThat(filter.getDocCount(), equalTo(0L)); Percentiles percentiles = filter.getAggregations().get("percentiles"); assertThat(percentiles, notNullValue()); assertThat(percentiles.percentile(99), equalTo(Double.NaN)); } } }
/* * Copyright 2013-2019 Real Logic 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. */ package uk.co.real_logic.sbe.xml; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import uk.co.real_logic.sbe.PrimitiveType; import uk.co.real_logic.sbe.PrimitiveValue; import uk.co.real_logic.sbe.TestUtil; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static uk.co.real_logic.sbe.xml.XmlSchemaParser.parse; public class SetTypeTest { @Test public void shouldHandleBinarySetType() throws Exception { final String testXmlString = "<types>" + "<set name=\"biOp\" encodingType=\"uint8\">" + " <choice name=\"Bit0\" description=\"Bit 0\">0</choice>" + " <choice name=\"Bit1\" description=\"Bit 1\">1</choice>" + "</set>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/set", testXmlString); final SetType e = (SetType)map.get("biOp"); assertThat(e.name(), is("biOp")); assertThat(e.encodingType(), is(PrimitiveType.UINT8)); assertThat(e.choices().size(), is(2)); assertThat(e.getChoice("Bit1").primitiveValue(), is(PrimitiveValue.parse("1", PrimitiveType.UINT8))); assertThat(e.getChoice("Bit0").primitiveValue(), is(PrimitiveValue.parse("0", PrimitiveType.UINT8))); } @Test public void shouldHandleSetTypeList() throws Exception { final String testXmlString = "<types>" + "<set name=\"listed\" encodingType=\"uint8\">" + " <choice name=\"Bit0\">0</choice>" + " <choice name=\"Bit1\">1</choice>" + " <choice name=\"Bit2\">2</choice>" + " <choice name=\"Bit3\">3</choice>" + "</set>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/set", testXmlString); final SetType e = (SetType)map.get("listed"); assertThat(e.encodingType(), is(PrimitiveType.UINT8)); int foundBit0 = 0, foundBit1 = 0, foundBit2 = 0, foundBit3 = 0, count = 0; for (final SetType.Choice choice : e.choices()) { switch (choice.name()) { case "Bit0": foundBit0++; break; case "Bit1": foundBit1++; break; case "Bit2": foundBit2++; break; case "Bit3": foundBit3++; break; } count++; } assertThat(count, is(4)); assertThat(foundBit0, is(1)); assertThat(foundBit1, is(1)); assertThat(foundBit2, is(1)); assertThat(foundBit3, is(1)); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenIllegalEncodingTypeSpecified() throws Exception { final String testXmlString = "<types>" + "<set name=\"biOp\" encodingType=\"char\">" + " <choice name=\"Bit0\">0</choice>" + " <choice name=\"Bit1\">1</choice>" + "</set>" + "</types>"; parseTestXmlWithMap("/types/set", testXmlString); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenDuplicateValueSpecified() throws Exception { final String testXmlString = "<types>" + "<set name=\"biOp\" encodingType=\"uint8\">" + " <choice name=\"Bit0\">0</choice>" + " <choice name=\"AnotherBit0\">0</choice>" + "</set>" + "</types>"; parseTestXmlWithMap("/types/set", testXmlString); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenDuplicateNameSpecified() throws Exception { final String testXmlString = "<types>" + "<set name=\"biOp\" encodingType=\"uint8\">" + " <choice name=\"Bit0\">0</choice>" + " <choice name=\"Bit0\">1</choice>" + "</set>" + "</types>"; parseTestXmlWithMap("/types/set", testXmlString); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenValueOutOfBoundsSpecified() throws Exception { final String testXmlString = "<types>" + "<set name=\"biOp\" encodingType=\"uint8\">" + " <choice name=\"Bit0\">0</choice>" + " <choice name=\"Bit100\">100</choice>" + "</set>" + "</types>"; parseTestXmlWithMap("/types/set", testXmlString); } @Test public void shouldHandleEncodingTypesWithNamedTypes() throws Exception { final MessageSchema schema = parse(TestUtil.getLocalResource( "encoding-types-schema.xml"), ParserOptions.DEFAULT); final List<Field> fields = schema.getMessage(1).fields(); assertNotNull(fields); SetType type = (SetType)fields.get(3).type(); assertThat(type.encodingType(), is(PrimitiveType.UINT8)); type = (SetType)fields.get(4).type(); assertThat(type.encodingType(), is(PrimitiveType.UINT16)); type = (SetType)fields.get(5).type(); assertThat(type.encodingType(), is(PrimitiveType.UINT32)); type = (SetType)fields.get(6).type(); assertThat(type.encodingType(), is(PrimitiveType.UINT64)); } private static Map<String, Type> parseTestXmlWithMap(final String xPathExpr, final String xml) throws ParserConfigurationException, XPathExpressionException, IOException, SAXException { final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream(xml.getBytes())); final XPath xPath = XPathFactory.newInstance().newXPath(); final NodeList list = (NodeList)xPath.compile(xPathExpr).evaluate(document, XPathConstants.NODESET); final Map<String, Type> map = new HashMap<>(); final ParserOptions options = ParserOptions.builder() .stopOnError(true) .suppressOutput(true) .warningsFatal(true) .build(); document.setUserData(XmlSchemaParser.ERROR_HANDLER_KEY, new ErrorHandler(options), null); for (int i = 0, size = list.getLength(); i < size; i++) { final Type t = new SetType(list.item(i)); map.put(t.name(), t); } return map; } }
/* * UnivKansasElementIISetupUPb * * Copyright 2006-2015 James F. Bowring and www.Earth-Time.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.earthtime.Tripoli.massSpecSetups.singleCollector.ThermoFinnigan; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.earthtime.Tripoli.dataModels.DataModelInterface; import org.earthtime.Tripoli.dataModels.RawIntensityDataModel; import org.earthtime.Tripoli.dataModels.RawRatioDataModel; import org.earthtime.Tripoli.dataModels.VirtualCollectorModel; import org.earthtime.Tripoli.dataModels.aquisitionTypeDataModels.IsotopeMappingModel; import org.earthtime.Tripoli.dataModels.collectorModels.AbstractCollectorModel; import org.earthtime.Tripoli.dataModels.collectorModels.IonCounterCollectorModel; import org.earthtime.Tripoli.fractions.TripoliFraction; import org.earthtime.Tripoli.massSpecSetups.AbstractMassSpecSetup; import org.earthtime.UPb_Redux.ReduxConstants; import org.earthtime.UPb_Redux.valueModels.ValueModel; import org.earthtime.dataDictionaries.IsotopeNames; import org.earthtime.dataDictionaries.MassSpecTypeEnum; import org.earthtime.dataDictionaries.RawRatioNames; import org.earthtime.isotopes.IsotopesEnum; /** * * @author James F. Bowring */ public final class UnivKansasElementIISetupUPb extends AbstractMassSpecSetup implements // Comparable<AbstractMassSpecSetup>, Serializable { private static UnivKansasElementIISetupUPb instance = null; private UnivKansasElementIISetupUPb() { super(); NAME = "University of Kansas Element II Setup"; massSpecType = MassSpecTypeEnum.SINGLE; VIRTUAL_COLLECTOR_COUNT = 10; COLLECTOR_DATA_FREQUENCY_MILLISECS = 214; //0.214410714 sec countOfAcquisitions = 0; isotopeMappingModel = new IsotopeMappingModel(); collectorNameToModelMap = new TreeMap<>(); useConstantBackgroundFitFunction = false; this.commonLeadCorrectionHighestLevel = "NONE"; AbstractCollectorModel singleCollector = // new IonCounterCollectorModel(// "Single", // new ValueModel("DeadTime", // new BigDecimal(12.0e-9, // ReduxConstants.mathContext10), // "ABS", // new BigDecimal(1.0e-9, ReduxConstants.mathContext10), // BigDecimal.ZERO), // IonCounterCollectorModel.CollectedDataStyle.COUNTS); // from Noah June 2015 //isotope int. time (s) //206 0.032 //207 0.080 //208 0.016 //232 0.020 //238 0.020 isotopeMappingModel.getIsotopeToCollectorMap().put(// IsotopesEnum.U238, singleCollector); isotopeMappingModel.getIsotopeToIntegrationTimeMap().put( // IsotopesEnum.U238, 0.020); isotopeMappingModel.getIsotopeToCollectorMap().put(// IsotopesEnum.Th232, singleCollector); isotopeMappingModel.getIsotopeToIntegrationTimeMap().put( // IsotopesEnum.Th232, 0.020); isotopeMappingModel.getIsotopeToCollectorMap().put(// IsotopesEnum.Pb208, singleCollector); isotopeMappingModel.getIsotopeToIntegrationTimeMap().put( // IsotopesEnum.Pb208, 0.016); isotopeMappingModel.getIsotopeToCollectorMap().put(// IsotopesEnum.Pb207, singleCollector); isotopeMappingModel.getIsotopeToIntegrationTimeMap().put( // IsotopesEnum.Pb207, 0.080); isotopeMappingModel.getIsotopeToCollectorMap().put(// IsotopesEnum.Pb206, singleCollector); isotopeMappingModel.getIsotopeToIntegrationTimeMap().put( // IsotopesEnum.Pb206, 0.032); collectorNameToModelMap.put("Single", singleCollector); } /** * * @return */ public static UnivKansasElementIISetupUPb getInstance() { if (instance == null) { instance = new UnivKansasElementIISetupUPb(); } return instance; } /** * * * @param intensitiesScan * @param isStandard the value of isStandard * @param fractionID the value of fractionID * @param usingFullPropagation the value of usingFullPropagation * @param tripoliFraction the value of tripoliFraction * @return the * java.util.SortedSet<org.earthtime.Tripoli.dataModels.DataModelInterface> */ @Override public SortedSet<DataModelInterface> rawRatiosFactory(String[][] intensitiesScan, boolean isStandard, String fractionID, boolean usingFullPropagation, TripoliFraction tripoliFraction) { countOfAcquisitions = intensitiesScan.length; return rawRatiosFactoryRevised(); } /** * yRevised(); } * * /** * * * @param intensitiesScan * @param isStandard the value of isStandard * @param fractionID the value of fractionID * @param usingFullPropagation the value of usingFullPropagation * @param tripoliFraction the value of tripoliFraction * @return the * java.util.SortedSet<org.earthtime.Tripoli.dataModels.DataModelInterface> */ public SortedSet<DataModelInterface> rawRatiosFactoryRevised() { virtualCollectors = new ArrayList<>(VIRTUAL_COLLECTOR_COUNT); for (int i = 0; i < VIRTUAL_COLLECTOR_COUNT; i++) { virtualCollectors.add(new VirtualCollectorModel(i + 1)); } // background virtualCollectors.get(5 - 1).updateCollector(true); virtualCollectors.get(4 - 1).updateCollector(true); virtualCollectors.get(3 - 1).updateCollector(true); virtualCollectors.get(2 - 1).updateCollector(true); virtualCollectors.get(1 - 1).updateCollector(true); // on peak virtualCollectors.get(10 - 1).updateCollector(false); virtualCollectors.get(9 - 1).updateCollector(false); virtualCollectors.get(8 - 1).updateCollector(false); virtualCollectors.get(7 - 1).updateCollector(false); virtualCollectors.get(6 - 1).updateCollector(false); // isotope models genericIsotopeModels = new TreeSet<>(); U238 = new RawIntensityDataModel( // IsotopeNames.U238, virtualCollectors.get(5 - 1), virtualCollectors.get(10 - 1), COLLECTOR_DATA_FREQUENCY_MILLISECS,// isotopeMappingModel.getIsotopeToCollectorMap().get(IsotopesEnum.U238)); genericIsotopeModels.add(U238); isotopeToRawIntensitiesMap.put(IsotopesEnum.U238, U238); Th232 = new RawIntensityDataModel( // IsotopeNames.Th232, virtualCollectors.get(4 - 1), virtualCollectors.get(9 - 1), COLLECTOR_DATA_FREQUENCY_MILLISECS,// isotopeMappingModel.getIsotopeToCollectorMap().get(IsotopesEnum.Th232)); genericIsotopeModels.add(Th232); isotopeToRawIntensitiesMap.put(IsotopesEnum.Th232, Th232); Pb208 = new RawIntensityDataModel( // IsotopeNames.Pb208, virtualCollectors.get(3 - 1), virtualCollectors.get(8 - 1), COLLECTOR_DATA_FREQUENCY_MILLISECS,// isotopeMappingModel.getIsotopeToCollectorMap().get(IsotopesEnum.Pb208)); genericIsotopeModels.add(Pb208); isotopeToRawIntensitiesMap.put(IsotopesEnum.Pb208, Pb208); Pb207 = new RawIntensityDataModel( // IsotopeNames.Pb207, virtualCollectors.get(2 - 1), virtualCollectors.get(7 - 1), COLLECTOR_DATA_FREQUENCY_MILLISECS,// isotopeMappingModel.getIsotopeToCollectorMap().get(IsotopesEnum.Pb207)); genericIsotopeModels.add(Pb207); isotopeToRawIntensitiesMap.put(IsotopesEnum.Pb207, Pb207); Pb206 = new RawIntensityDataModel( // IsotopeNames.Pb206, virtualCollectors.get(1 - 1), virtualCollectors.get(6 - 1), COLLECTOR_DATA_FREQUENCY_MILLISECS,// isotopeMappingModel.getIsotopeToCollectorMap().get(IsotopesEnum.Pb206)); genericIsotopeModels.add(Pb206); isotopeToRawIntensitiesMap.put(IsotopesEnum.Pb206, Pb206); isotopeMappingModel.setIsotopeToRawIntensitiesMap(isotopeToRawIntensitiesMap); // raw ratios rawRatios = new TreeSet<>(); DataModelInterface r206_238w = new RawRatioDataModel(RawRatioNames.r206_238w, Pb206, U238, true, false, COLLECTOR_DATA_FREQUENCY_MILLISECS); rawRatios.add(r206_238w); DataModelInterface r206_207w = new RawRatioDataModel(RawRatioNames.r206_207w, Pb206, Pb207, true, false, COLLECTOR_DATA_FREQUENCY_MILLISECS); rawRatios.add(r206_207w); DataModelInterface r208_232w = new RawRatioDataModel(RawRatioNames.r208_232w, Pb208, Th232, true, false, COLLECTOR_DATA_FREQUENCY_MILLISECS); rawRatios.add(r208_232w); return rawRatios; } /** * * @param integrationTime */ @Override public void assignIntegrationTime(double integrationTime) { throw new UnsupportedOperationException("Not legal."); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.geosparql.assembler; import static org.apache.jena.geosparql.assembler.VocabGeoSPARQL.*; import static org.apache.jena.sparql.util.graph.GraphUtils.getBooleanValue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.jena.assembler.Assembler; import org.apache.jena.atlas.io.IO; import org.apache.jena.geosparql.configuration.GeoSPARQLConfig; import org.apache.jena.geosparql.configuration.GeoSPARQLOperations; import org.apache.jena.geosparql.configuration.SrsException; import org.apache.jena.geosparql.spatial.SpatialIndexException; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.query.Dataset; import org.apache.jena.query.DatasetFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.apache.jena.shared.JenaException; import org.apache.jena.sparql.core.DatasetGraph; import org.apache.jena.sparql.core.assembler.DatasetAssembler; import org.apache.jena.sparql.util.graph.GraphUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GeoAssembler extends DatasetAssembler { private static Logger LOG = LoggerFactory.getLogger(GeoAssembler.class); @Override public DatasetGraph createDataset(Assembler a, Resource root) { // Base dataset. DatasetGraph base = super.createBaseDataset(root, pDataset); Graph graph = root.getModel().getGraph(); Node subj = root.asNode(); // GeoSPARQL RDFS inference. CLI: names = {"--inference", "-i"} boolean inference = true; if (root.hasProperty(pInference) ) inference = getBooleanValue(root, pInference); // Apply default geometry to single Feature-Geometry. CLI: names = {"--default_geometry", "-dg"} boolean applyDefaultGeometry = false; if (root.hasProperty(pApplyDefaultGeometry) ) applyDefaultGeometry = getBooleanValue(root, pApplyDefaultGeometry); // These can be deleted when it is confirmed by users that features are not used. // Note: jena-fuseki-geosparql seems not to have them. // // Validate geometry literals in the data. CLI: names = {"--validate", "-v"} // boolean validategeometryliteral = false; // if (root.hasProperty(pValidateGeometryLiteral) ) // validateGeometryLiteral = getBooleanValue(root, pValidateGeometryLiteral); // Modifies dataset // // Convert Geo predicates in the data to Geometry with WKT WGS84 Point GeometryLiteral. CLI: names = {"--convert_geo", "-c"} // boolean convertGeoPredicates = false; // if (root.hasProperty(pConvertGeoPredicates) ) // convertGeoPredicates = getBooleanValue(root, pConvertGeoPredicates); // Code returns modified dataset which is ignored so this is a no-op. // //Remove Geo predicates in the data after combining to Geometry. CLI: names = {"--remove_geo", "-rg"} // boolean removeGeoPredicates = false; // if (root.hasProperty(pRemoveGeoPredicates) ) // removeGeoPredicates = getBooleanValue(root, pRemoveGeoPredicates); // Query Rewrite enabled. CLI: names = {"--rewrite", "-r"} boolean queryRewrite = true; if (root.hasProperty(pQueryRewrite) ) queryRewrite = getBooleanValue(root, pQueryRewrite); // Indexing enabled. CLI: names = {"--index", "-x"} boolean indexEnabled = true; if (root.hasProperty(pIndexEnabled) ) indexEnabled = getBooleanValue(root, pIndexEnabled); // Index sizes. names = {"--index_sizes", "-xs"} List<Integer> indexSizes = Arrays.asList(-1, -1, -1); // "List of Index item sizes: [Geometry Literal, Geometry Transform, Query Rewrite]. Unlimited: -1, Off: 0" if (root.hasProperty(pIndexSizes) ) indexSizes = getListInteger(root, pIndexSizes, 3); //Index expiry. names = {"--index_expiry", "-xe"} List<Integer> indexExpiries = Arrays.asList(5000, 5000, 5000); // "List of Index item expiry in milliseconds: [Geometry Literal, Geometry Transform, Query Rewrite]. Off: 0, Minimum: 1001" if (root.hasProperty(pIndexExpiries) ) indexExpiries = getListInteger(root, pIndexSizes, 3); // Spatial Index file. CLI: names = {"--spatial_index", "-si"} String spatialIndexFilename = null; // "File to load or store the spatial index. Default to " + SPATIAL_INDEX_FILE + " in TDB folder if using TDB and not set. Otherwise spatial index is not stored. if (root.hasProperty(pSpatialIndexFile) ) spatialIndexFilename = GraphUtils.getStringValue(root, pSpatialIndexFile); // ---- Build Dataset dataset = DatasetFactory.wrap(base); // Conversion of data. Startup-only. // needed for w3c:geo/wgs84_pos#lat/log. // (names = {"--convert_geo", "-c"} // "Convert Geo predicates in the data to Geometry with WKT WGS84 Point Geometry Literal." // GeoSPARQLOperations.convertGeoPredicates returns the different (in-memory) dataset but which is ignored. // //Convert Geo predicates to Geometry Literals. // if ( convertGeoPredicates ) //Apply validation of Geometry Literal. // GeoSPARQLOperations.convertGeoPredicates(dataset, removeGeoPredicates); //Apply hasDefaultGeometry relations to single Feature hasGeometry Geometry. if (applyDefaultGeometry) GeoSPARQLOperations.applyDefaultGeometry(dataset); //Apply GeoSPARQL schema and RDFS inferencing to the dataset. if (inference) GeoSPARQLOperations.applyInferencing(dataset); //Setup GeoSPARQL if (indexEnabled) { GeoSPARQLConfig.setupMemoryIndex(indexSizes.get(0), indexSizes.get(1), indexSizes.get(2), (long)indexExpiries.get(0), (long)indexExpiries.get(1), (long)indexExpiries.get(2), queryRewrite); } else { GeoSPARQLConfig.setupNoIndex(queryRewrite); } prepareSpatialExtension(dataset, spatialIndexFilename); return base; } private static List<Integer> getListInteger(Resource r, Property p, int len) { String integers = GraphUtils.getStringValue(r, p); String[] values = integers.split(","); List<Integer> integerList = new ArrayList<>(); for (String val : values) { val = val.trim(); integerList.add(Integer.parseInt(val)); } if ( len >= 0 && integerList.size() != len) throw new JenaException("Expected list of exactly "+len+" integers"); return integerList; } private static void prepareSpatialExtension(Dataset dataset, String spatialIndex){ boolean isEmpty = dataset.calculate(()->dataset.isEmpty()); if ( isEmpty && spatialIndex != null ) { LOG.warn("Dataset empty. Spatial Index not constructed. Server will require restarting after adding data and any updates to build Spatial Index."); return; } if ( isEmpty ) // Nothing to do. return; try { if ( spatialIndex == null ) { GeoSPARQLConfig.setupSpatialIndex(dataset); return; } Path spatialIndexPath = Path.of(spatialIndex); if ( ! Files.exists(spatialIndexPath) || Files.size(spatialIndexPath) == 0 ) GeoSPARQLConfig.setupSpatialIndex(dataset, spatialIndexPath.toFile()); } catch (SrsException ex) { // Data but no spatial data. if ( ! ex.getMessage().startsWith("No SRS found") ) throw ex; LOG.warn(ex.getMessage()); } catch (IOException ex) { IO.exception(ex); return; } catch (SpatialIndexException ex) { String msg = "Failed to create spatial index: "+ex.getMessage(); LOG.error(msg); throw new JenaException(msg, ex); } } }
/* * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.remoting.httpinvoker; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.remoting.support.RemoteInvocationResult; import org.springframework.util.StringUtils; /** * {@link HttpInvokerRequestExecutor} implementation that uses * <a href="http://jakarta.apache.org/commons/httpclient">Jakarta Commons HttpClient</a> * to execute POST requests. Requires Commons HttpClient 3.0 or higher. * * <p>Allows to use a pre-configured {@link org.apache.commons.httpclient.HttpClient} * instance, potentially with authentication, HTTP connection pooling, etc. * Also designed for easy subclassing, providing specific template methods. * * @author Juergen Hoeller * @author Mark Fisher * @since 1.1 * @see SimpleHttpInvokerRequestExecutor */ public class CommonsHttpInvokerRequestExecutor extends AbstractHttpInvokerRequestExecutor { /** * Default timeout value if no HttpClient is explicitly provided. */ private static final int DEFAULT_READ_TIMEOUT_MILLISECONDS = (60 * 1000); private HttpClient httpClient; /** * Create a new CommonsHttpInvokerRequestExecutor with a default * HttpClient that uses a default MultiThreadedHttpConnectionManager. * Sets the socket read timeout to {@link #DEFAULT_READ_TIMEOUT_MILLISECONDS}. * @see org.apache.commons.httpclient.HttpClient * @see org.apache.commons.httpclient.MultiThreadedHttpConnectionManager */ public CommonsHttpInvokerRequestExecutor() { this.httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); this.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); } /** * Create a new CommonsHttpInvokerRequestExecutor with the given * HttpClient instance. The socket read timeout of the provided * HttpClient will not be changed. * @param httpClient the HttpClient instance to use for this request executor */ public CommonsHttpInvokerRequestExecutor(HttpClient httpClient) { this.httpClient = httpClient; } /** * Set the HttpClient instance to use for this request executor. */ public void setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; } /** * Return the HttpClient instance that this request executor uses. */ public HttpClient getHttpClient() { return this.httpClient; } /** * Set the socket read timeout for the underlying HttpClient. A value * of 0 means <emphasis>never</emphasis> timeout. * @param timeout the timeout value in milliseconds * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setSoTimeout(int) * @see #DEFAULT_READ_TIMEOUT_MILLISECONDS */ public void setReadTimeout(int timeout) { if (timeout < 0) { throw new IllegalArgumentException("timeout must be a non-negative value"); } this.httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout); } /** * Execute the given request through Commons HttpClient. * <p>This method implements the basic processing workflow: * The actual work happens in this class's template methods. * @see #createPostMethod * @see #setRequestBody * @see #executePostMethod * @see #validateResponse * @see #getResponseBody */ protected RemoteInvocationResult doExecuteRequest( HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { PostMethod postMethod = createPostMethod(config); try { setRequestBody(config, postMethod, baos); executePostMethod(config, getHttpClient(), postMethod); validateResponse(config, postMethod); InputStream responseBody = getResponseBody(config, postMethod); return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); } finally { // Need to explicitly release because it might be pooled. postMethod.releaseConnection(); } } /** * Create a PostMethod for the given configuration. * <p>The default implementation creates a standard PostMethod with * "application/x-java-serialized-object" as "Content-Type" header. * @param config the HTTP invoker configuration that specifies the * target service * @return the PostMethod instance * @throws IOException if thrown by I/O methods */ protected PostMethod createPostMethod(HttpInvokerClientConfiguration config) throws IOException { PostMethod postMethod = new PostMethod(config.getServiceUrl()); LocaleContext locale = LocaleContextHolder.getLocaleContext(); if (locale != null) { postMethod.addRequestHeader(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale.getLocale())); } if (isAcceptGzipEncoding()) { postMethod.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } return postMethod; } /** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation * as the PostMethod's request body. This can be overridden, for example, * to write a specific encoding and potentially set appropriate HTTP * request headers. * @param config the HTTP invoker configuration that specifies the target service * @param postMethod the PostMethod to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws IOException if thrown by I/O methods * @see org.apache.commons.httpclient.methods.PostMethod#setRequestBody(java.io.InputStream) * @see org.apache.commons.httpclient.methods.PostMethod#setRequestEntity * @see org.apache.commons.httpclient.methods.InputStreamRequestEntity */ protected void setRequestBody( HttpInvokerClientConfiguration config, PostMethod postMethod, ByteArrayOutputStream baos) throws IOException { postMethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray(), getContentType())); } /** * Execute the given PostMethod instance. * @param config the HTTP invoker configuration that specifies the target service * @param httpClient the HttpClient to execute on * @param postMethod the PostMethod to execute * @throws IOException if thrown by I/O methods * @see org.apache.commons.httpclient.HttpClient#executeMethod(org.apache.commons.httpclient.HttpMethod) */ protected void executePostMethod( HttpInvokerClientConfiguration config, HttpClient httpClient, PostMethod postMethod) throws IOException { httpClient.executeMethod(postMethod); } /** * Validate the given response as contained in the PostMethod object, * throwing an exception if it does not correspond to a successful HTTP response. * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid * parsing the response body and trying to deserialize from a corrupted stream. * @param config the HTTP invoker configuration that specifies the target service * @param postMethod the executed PostMethod to validate * @throws IOException if validation failed * @see org.apache.commons.httpclient.methods.PostMethod#getStatusCode() * @see org.apache.commons.httpclient.HttpException */ protected void validateResponse(HttpInvokerClientConfiguration config, PostMethod postMethod) throws IOException { if (postMethod.getStatusCode() >= 300) { throw new HttpException( "Did not receive successful HTTP response: status code = " + postMethod.getStatusCode() + ", status message = [" + postMethod.getStatusText() + "]"); } } /** * Extract the response body from the given executed remote invocation * request. * <p>The default implementation simply fetches the PostMethod's response * body stream. If the response is recognized as GZIP response, the * InputStream will get wrapped in a GZIPInputStream. * @param config the HTTP invoker configuration that specifies the target service * @param postMethod the PostMethod to read the response body from * @return an InputStream for the response body * @throws IOException if thrown by I/O methods * @see #isGzipResponse * @see java.util.zip.GZIPInputStream * @see org.apache.commons.httpclient.methods.PostMethod#getResponseBodyAsStream() * @see org.apache.commons.httpclient.methods.PostMethod#getResponseHeader(String) */ protected InputStream getResponseBody(HttpInvokerClientConfiguration config, PostMethod postMethod) throws IOException { if (isGzipResponse(postMethod)) { return new GZIPInputStream(postMethod.getResponseBodyAsStream()); } else { return postMethod.getResponseBodyAsStream(); } } /** * Determine whether the given response indicates a GZIP response. * <p>Default implementation checks whether the HTTP "Content-Encoding" * header contains "gzip" (in any casing). * @param postMethod the PostMethod to check * @return whether the given response indicates a GZIP response */ protected boolean isGzipResponse(PostMethod postMethod) { Header encodingHeader = postMethod.getResponseHeader(HTTP_HEADER_CONTENT_ENCODING); return (encodingHeader != null && encodingHeader.getValue() != null && encodingHeader.getValue().toLowerCase().indexOf(ENCODING_GZIP) != -1); } }
/* Copyright 2006 Jerry Huxtable 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.osgeo.proj4j.proj; import org.osgeo.proj4j.*; import org.osgeo.proj4j.datum.Ellipsoid; import org.osgeo.proj4j.units.AngleFormat; import org.osgeo.proj4j.units.Unit; import org.osgeo.proj4j.units.Units; import org.osgeo.proj4j.util.ProjectionMath; /** * A map projection is a mathematical algorithm * for representing a spheroidal surface * on a plane. * A single projection * defines a (usually infinite) family of * {@link CoordinateReferenceSystem}s, * distinguished by different values for the * projection parameters. */ public abstract class Projection implements Cloneable { /** * The minimum latitude of the bounds of this projection */ protected double minLatitude = -Math.PI/2; /** * The minimum longitude of the bounds of this projection. This is relative to the projection centre. */ protected double minLongitude = -Math.PI; /** * The maximum latitude of the bounds of this projection */ protected double maxLatitude = Math.PI/2; /** * The maximum longitude of the bounds of this projection. This is relative to the projection centre. */ protected double maxLongitude = Math.PI; /** * The latitude of the centre of projection */ protected double projectionLatitude = 0.0; /** * The longitude of the centre of projection, in radians */ protected double projectionLongitude = 0.0; /** * Standard parallel 1 (for projections which use it) */ protected double projectionLatitude1 = 0.0; /** * Standard parallel 2 (for projections which use it) */ protected double projectionLatitude2 = 0.0; /** * The projection alpha value */ protected double alpha = Double.NaN; /** * The projection lonc value */ protected double lonc = Double.NaN; /** * The projection scale factor */ protected double scaleFactor = 1.0; /** * The false Easting of this projection */ protected double falseEasting = 0; /** * The false Northing of this projection */ protected double falseNorthing = 0; /** * Indicates whether a Southern Hemisphere UTM zone */ protected boolean isSouth = false; /** * The latitude of true scale. Only used by specific projections. */ protected double trueScaleLatitude = 0.0; /** * The equator radius */ protected double a = 0; /** * The eccentricity */ protected double e = 0; /** * The eccentricity squared */ protected double es = 0; /** * 1-(eccentricity squared) */ protected double one_es = 0; /** * 1/(1-(eccentricity squared)) */ protected double rone_es = 0; /** * The ellipsoid used by this projection */ protected Ellipsoid ellipsoid; /** * True if this projection is using a sphere (es == 0) */ protected boolean spherical; /** * True if this projection is geocentric */ protected boolean geocentric; /** * The name of this projection */ protected String name = null; /** * Conversion factor from metres to whatever units the projection uses. */ protected double fromMetres = 1; /** * The total scale factor = Earth radius * units */ protected double totalScale = 0; /** * falseEasting, adjusted to the appropriate units using fromMetres */ private double totalFalseEasting = 0; /** * falseNorthing, adjusted to the appropriate units using fromMetres */ private double totalFalseNorthing = 0; /** * units of this projection. Default is metres, but may be degrees */ protected Unit unit = null; // Some useful constants protected final static double EPS10 = 1e-10; protected final static double RTD = 180.0/Math.PI; protected final static double DTR = Math.PI/180.0; protected Projection() { setEllipsoid( Ellipsoid.SPHERE ); } public Object clone() { try { Projection e = (Projection)super.clone(); return e; } catch ( CloneNotSupportedException e ) { throw new InternalError(); } } /** * Projects a geographic point (in degrees), producing a projected result * (in the units of the target coordinate system). * * @param src the input geographic coordinate (in degrees) * @param dst the projected coordinate (in coordinate system units) * @return the target coordinate */ public ProjCoordinate project( ProjCoordinate src, ProjCoordinate dst ) { double x = src.x*DTR; if ( projectionLongitude != 0 ) x = ProjectionMath.normalizeLongitude( x-projectionLongitude ); return projectRadians(x, src.y*DTR, dst); } /** * Projects a geographic point (in radians), producing a projected result * (in the units of the target coordinate system). * * @param src the input geographic coordinate (in radians) * @param dst the projected coordinate (in coordinate system units) * @return the target coordinate * */ public ProjCoordinate projectRadians( ProjCoordinate src, ProjCoordinate dst ) { double x = src.x; if ( projectionLongitude != 0 ) x = ProjectionMath.normalizeLongitude( x-projectionLongitude ); return projectRadians(x, src.y, dst); } /** * Transform a geographic point (in radians), * producing a projected result (in the units of the target coordinate system). * * @param x the geographic x ordinate (in radians) * @param y the geographic y ordinate (in radians) * @param dst the projected coordinate (in coordinate system units) * @return the target coordinate */ private ProjCoordinate projectRadians(double x, double y, ProjCoordinate dst ) { project(x, y, dst); if (unit == Units.DEGREES) { // convert radians to DD dst.x *= RTD; dst.y *= RTD; } else { // assume result is in metres dst.x = totalScale * dst.x + totalFalseEasting; dst.y = totalScale * dst.y + totalFalseNorthing; } return dst; } /** * Computes the projection of a given point * (i.e. from geographics to projection space). * This should be overridden for all projections. * * @param x the geographic x ordinate (in radians) * @param y the geographic y ordinatee (in radians) * @param dst the projected coordinate (in coordinate system units) * @return the target coordinate */ protected ProjCoordinate project(double x, double y, ProjCoordinate dst) { dst.x = x; dst.y = y; return dst; } /** * Inverse-projects a point (in the units defined by the coordinate system), * producing a geographic result (in degrees) * * @param src the input projected coordinate (in coordinate system units) * @param dst the inverse-projected geographic coordinate (in degrees) * @return the target coordinate */ public ProjCoordinate inverseProject(ProjCoordinate src, ProjCoordinate dst) { inverseProjectRadians(src, dst); dst.x *= RTD; dst.y *= RTD; return dst; } /** * Inverse-transforms a point (in the units defined by the coordinate system), * producing a geographic result (in radians) * * @param src the input projected coordinate (in coordinate system units) * @param dst the inverse-projected geographic coordinate (in radians) * @return the target coordinate * */ public ProjCoordinate inverseProjectRadians(ProjCoordinate src, ProjCoordinate dst) { double x; double y; if (unit == Units.DEGREES) { // convert DD to radians x = src.x * DTR; y = src.y * DTR; } else { x = (src.x - totalFalseEasting) / totalScale; y = (src.y - totalFalseNorthing) / totalScale; } projectInverse(x, y, dst); if (dst.x < -Math.PI) dst.x = -Math.PI; else if (dst.x > Math.PI) dst.x = Math.PI; if (projectionLongitude != 0) dst.x = ProjectionMath.normalizeLongitude(dst.x+projectionLongitude); return dst; } /** * Computes the inverse projection of a given point * (i.e. from projection space to geographics). * This should be overridden for all projections. * * @param x the projected x ordinate (in coordinate system units) * @param y the projected y ordinate (in coordinate system units) * @param dst the inverse-projected geographic coordinate (in radians) * @return the target coordinate */ protected ProjCoordinate projectInverse(double x, double y, ProjCoordinate dst) { dst.x = x; dst.y = y; return dst; } /** * Tests whether this projection is conformal. * A conformal projection preserves local angles. * * @return true if this projection is conformal */ public boolean isConformal() { return false; } /** * Tests whether this projection is equal-area * An equal-area projection preserves relative sizes * of projected areas. * * @return true if this projection is equal-area */ public boolean isEqualArea() { return false; } /** * Tests whether this projection has an inverse. * If this method returns <tt>true</tt> * then the {@link #inverseProject(ProjCoordinate, ProjCoordinate)} * and {@link #inverseProjectRadians(ProjCoordinate, ProjCoordinate)} * methods will return meaningful results. * * @return true if this projection has an inverse */ public boolean hasInverse() { return false; } /** * Tests whether under this projection lines of * latitude and longitude form a rectangular grid */ public boolean isRectilinear() { return false; } /** * Returns true if latitude lines are parallel for this projection */ public boolean parallelsAreParallel() { return isRectilinear(); } /** * Returns true if the given lat/long point is visible in this projection */ public boolean inside(double x, double y) { x = normalizeLongitude( (float)(x*DTR-projectionLongitude) ); return minLongitude <= x && x <= maxLongitude && minLatitude <= y && y <= maxLatitude; } /** * Set the name of this projection. */ public void setName( String name ) { this.name = name; } public String getName() { if ( name != null ) return name; return toString(); } /** * Get a string which describes this projection in PROJ.4 format. * <p> * WARNING: currently this does not output all required parameters in some cases. * E.g. for Albers the standard latitudes are missing. */ public String getPROJ4Description() { AngleFormat format = new AngleFormat( AngleFormat.ddmmssPattern, false ); StringBuffer sb = new StringBuffer(); sb.append( "+proj="+getName()+ " +a="+a ); if ( es != 0 ) sb.append( " +es="+es ); sb.append( " +lon_0=" ); format.format( projectionLongitude, sb, null ); sb.append( " +lat_0=" ); format.format( projectionLatitude, sb, null ); if ( falseEasting != 1 ) sb.append( " +x_0="+falseEasting ); if ( falseNorthing != 1 ) sb.append( " +y_0="+falseNorthing ); if ( scaleFactor != 1 ) sb.append( " +k="+scaleFactor ); if ( fromMetres != 1 ) sb.append( " +fr_meters="+fromMetres ); return sb.toString(); } public String toString() { return "None"; } /** * Set the minimum latitude. This is only used for Shape clipping and doesn't affect projection. */ public void setMinLatitude( double minLatitude ) { this.minLatitude = minLatitude; } public double getMinLatitude() { return minLatitude; } /** * Set the maximum latitude. This is only used for Shape clipping and doesn't affect projection. */ public void setMaxLatitude( double maxLatitude ) { this.maxLatitude = maxLatitude; } public double getMaxLatitude() { return maxLatitude; } public double getMaxLatitudeDegrees() { return maxLatitude*RTD; } public double getMinLatitudeDegrees() { return minLatitude*RTD; } public void setMinLongitude( double minLongitude ) { this.minLongitude = minLongitude; } public double getMinLongitude() { return minLongitude; } public void setMinLongitudeDegrees( double minLongitude ) { this.minLongitude = DTR*minLongitude; } public double getMinLongitudeDegrees() { return minLongitude*RTD; } public void setMaxLongitude( double maxLongitude ) { this.maxLongitude = maxLongitude; } public double getMaxLongitude() { return maxLongitude; } public void setMaxLongitudeDegrees( double maxLongitude ) { this.maxLongitude = DTR*maxLongitude; } public double getMaxLongitudeDegrees() { return maxLongitude*RTD; } /** * Set the projection latitude in radians. */ public void setProjectionLatitude( double projectionLatitude ) { this.projectionLatitude = projectionLatitude; } public double getProjectionLatitude() { return projectionLatitude; } /** * Set the projection latitude in degrees. */ public void setProjectionLatitudeDegrees( double projectionLatitude ) { this.projectionLatitude = DTR*projectionLatitude; } public double getProjectionLatitudeDegrees() { return projectionLatitude*RTD; } /** * Set the projection longitude in radians. */ public void setProjectionLongitude( double projectionLongitude ) { this.projectionLongitude = normalizeLongitudeRadians( projectionLongitude ); } public double getProjectionLongitude() { return projectionLongitude; } /** * Set the projection longitude in degrees. */ public void setProjectionLongitudeDegrees( double projectionLongitude ) { this.projectionLongitude = DTR*projectionLongitude; } public double getProjectionLongitudeDegrees() { return projectionLongitude*RTD; } /** * Set the latitude of true scale in radians. This is only used by certain projections. */ public void setTrueScaleLatitude( double trueScaleLatitude ) { this.trueScaleLatitude = trueScaleLatitude; } public double getTrueScaleLatitude() { return trueScaleLatitude; } /** * Set the latitude of true scale in degrees. This is only used by certain projections. */ public void setTrueScaleLatitudeDegrees( double trueScaleLatitude ) { this.trueScaleLatitude = DTR*trueScaleLatitude; } public double getTrueScaleLatitudeDegrees() { return trueScaleLatitude*RTD; } /** * Set the projection latitude in radians. */ public void setProjectionLatitude1( double projectionLatitude1 ) { this.projectionLatitude1 = projectionLatitude1; } public double getProjectionLatitude1() { return projectionLatitude1; } /** * Set the projection latitude in degrees. */ public void setProjectionLatitude1Degrees( double projectionLatitude1 ) { this.projectionLatitude1 = DTR*projectionLatitude1; } public double getProjectionLatitude1Degrees() { return projectionLatitude1*RTD; } /** * Set the projection latitude in radians. */ public void setProjectionLatitude2( double projectionLatitude2 ) { this.projectionLatitude2 = projectionLatitude2; } public double getProjectionLatitude2() { return projectionLatitude2; } /** * Set the projection latitude in degrees. */ public void setProjectionLatitude2Degrees( double projectionLatitude2 ) { this.projectionLatitude2 = DTR*projectionLatitude2; } public double getProjectionLatitude2Degrees() { return projectionLatitude2*RTD; } /** * Sets the alpha value. */ public void setAlphaDegrees( double alpha ) { this.alpha = DTR * alpha; } /** * Gets the alpha value, in radians. * * @return the alpha value */ public double getAlpha() { return alpha; } /** * Sets the lonc value. */ public void setLonCDegrees( double lonc ) { this.lonc = DTR * lonc; } /** * Gets the lonc value, in radians. * * @return the lonc value */ public double getLonC() { return lonc; } /** * Set the false Northing in projected units. */ public void setFalseNorthing( double falseNorthing ) { this.falseNorthing = falseNorthing; } public double getFalseNorthing() { return falseNorthing; } /** * Set the false Easting in projected units. */ public void setFalseEasting( double falseEasting ) { this.falseEasting = falseEasting; } public double getFalseEasting() { return falseEasting; } public void setSouthernHemisphere(boolean isSouth) { this.isSouth = isSouth; } public boolean getSouthernHemisphere() { return isSouth; } /** * Set the projection scale factor. This is set to 1 by default. * This value is called "k0" in PROJ.4. */ public void setScaleFactor( double scaleFactor ) { this.scaleFactor = scaleFactor; } /** * Gets the projection scale factor. * This value is called "k0" in PROJ.4. * * @return */ public double getScaleFactor() { return scaleFactor; } public double getEquatorRadius() { return a; } /** * Set the conversion factor from metres to projected units. This is set to 1 by default. */ public void setFromMetres( double fromMetres ) { this.fromMetres = fromMetres; } public double getFromMetres() { return fromMetres; } public void setEllipsoid( Ellipsoid ellipsoid ) { this.ellipsoid = ellipsoid; a = ellipsoid.equatorRadius; e = ellipsoid.eccentricity; es = ellipsoid.eccentricity2; } public Ellipsoid getEllipsoid() { return ellipsoid; } /** * Returns the ESPG code for this projection, or 0 if unknown. */ public int getEPSGCode() { return 0; } public void setUnits(Unit unit) { this.unit = unit; } /** * Initialize the projection. This should be called after setting parameters and before using the projection. * This is for performance reasons as initialization may be expensive. */ public void initialize() { spherical = (e == 0.0); one_es = 1-es; rone_es = 1.0/one_es; totalScale = a * fromMetres; totalFalseEasting = falseEasting * fromMetres; totalFalseNorthing = falseNorthing * fromMetres; } public static float normalizeLongitude(float angle) { if ( Double.isInfinite(angle) || Double.isNaN(angle) ) throw new InvalidValueException("Infinite or NaN longitude"); while (angle > 180) angle -= 360; while (angle < -180) angle += 360; return angle; } public static double normalizeLongitudeRadians( double angle ) { if ( Double.isInfinite(angle) || Double.isNaN(angle) ) throw new InvalidValueException("Infinite or NaN longitude"); while (angle > Math.PI) angle -= ProjectionMath.TWOPI; while (angle < -Math.PI) angle += ProjectionMath.TWOPI; return angle; } }
package interdroid.swan.contextexpressions; import android.os.Parcel; import android.os.Parcelable; import interdroid.swan.SwanException; import interdroid.swan.ContextManager; import interdroid.swan.contextservice.SensorConfigurationException; import interdroid.swan.contextservice.SensorManager; import interdroid.swan.contextservice.SensorSetupFailedException; /** * An expression which combines two sub-expressions with an operator. * * @author nick &lt;palmer@cs.vu.nl&gt; * */ public class LogicExpression extends Expression { /** * */ private static final long serialVersionUID = 6206620564361837288L; /** * The left expression. */ private final Expression mLeftExpression; /** * The right expression. */ private final Expression mRightExpression; /** * The comparator being used to combine left and right. */ private final LogicOperator mOperator; /** * Constructs am operator expression. * * @param left * the left expression. * @param operator * the joining operator. * @param right * the right expression. */ public LogicExpression(final Expression left, final LogicOperator operator, final Expression right) { // TODO: Verify operator matches arguments properly this.mLeftExpression = left; this.mRightExpression = right; this.mOperator = operator; } /** * Constructs an operator expression with no right expression. * * @param operator * the operator. Must be LogicOperator.NOT. * @param expression * the left expression. */ public LogicExpression(final LogicOperator operator, final Expression expression) { this(expression, operator, null); if (operator != LogicOperator.NOT) { throw new IllegalArgumentException(); } } /** * Construct from a parcel. * * @param in * the parcel to read values from. */ protected LogicExpression(final Parcel in) { super(in); mLeftExpression = in.readParcelable(getClass().getClassLoader()); mOperator = LogicOperator.convert(in.readInt()); mRightExpression = in.readParcelable(getClass().getClassLoader()); } /** * The CREATOR used to construct from a parcel. */ public static final Parcelable.Creator<LogicExpression> CREATOR = new Parcelable.Creator<LogicExpression>() { @Override public LogicExpression createFromParcel(final Parcel in) { return new LogicExpression(in); } @Override public LogicExpression[] newArray(final int size) { return new LogicExpression[size]; } }; @Override public final void initialize(final String id, final SensorManager sensorManager) throws SensorConfigurationException, SensorSetupFailedException { setId(id); mLeftExpression.initialize(id + ".L", sensorManager); if (mRightExpression != null) { mRightExpression.initialize(id + ".R", sensorManager); } } @Override public final void destroy(final String id, final SensorManager sensorManager) throws SwanException { mLeftExpression.destroy(id + ".L", sensorManager); if (mRightExpression != null) { mRightExpression.destroy(id + ".R", sensorManager); } } private boolean leftFirst() { // if we can defer one of the expressions for a longer time than we need // to keep history for the other, we might be able to turn off a sensor // for a while (e.g. one.deferUntil - other.history) iff we're able to // short circuit the expression. That depends one the operator and the // value of the first expression long leftDeferUntil = mLeftExpression.getDeferUntil(); long leftHistory = mLeftExpression.getHistoryLength(); long rightDeferUntil = mRightExpression.getDeferUntil(); long rightHistory = mRightExpression.getHistoryLength(); return (leftDeferUntil - rightHistory > rightDeferUntil - leftHistory); } @Override protected final void evaluateImpl(final long now) throws SwanException { boolean leftFirst = leftFirst(); Expression firstExpression = leftFirst ? mLeftExpression : mRightExpression; Expression lastExpression = leftFirst ? mRightExpression : mLeftExpression; firstExpression.evaluate(now); int firstResult = firstExpression.getResult(); // Can we short circuit and don't evaluate the last expression? // FALSE && ?? -> FALSE // TRUE || ?? -> TRUE if (firstResult == ContextManager.FALSE && mOperator.equals(LogicOperator.AND)) { setResult(ContextManager.FALSE, now); // we can now turn off the last expression for a while lastExpression.sleepAndBeReadyAt(firstExpression.getDeferUntil()); return; } else if ((firstResult == ContextManager.TRUE) && mOperator.equals(LogicOperator.OR)) { setResult(ContextManager.TRUE, now); // we can now turn off the last expression for a while lastExpression.sleepAndBeReadyAt(firstExpression.getDeferUntil()); return; } // We might evaluate the right side. Test for null in case we deal with // a unary logic expresson int lastResult = ContextManager.UNDEFINED; if (lastExpression != null) { lastExpression.evaluate(now); lastResult = lastExpression.getResult(); } switch (mOperator) { case NOT: if (firstResult == ContextManager.UNDEFINED) { setResult(ContextManager.UNDEFINED, now); } else if (firstResult == ContextManager.TRUE) { setResult(ContextManager.FALSE, now); } else if (firstResult == ContextManager.FALSE) { setResult(ContextManager.TRUE, now); } break; case AND: if (firstResult == ContextManager.UNDEFINED || lastResult == ContextManager.UNDEFINED) { setResult(ContextManager.UNDEFINED, now); } else if (firstResult == ContextManager.TRUE && lastResult == ContextManager.TRUE) { setResult(ContextManager.TRUE, now); } else { setResult(ContextManager.FALSE, now); } break; case OR: if (firstResult == ContextManager.UNDEFINED && lastResult == ContextManager.UNDEFINED) { setResult(ContextManager.UNDEFINED, now); } else if (firstResult == ContextManager.TRUE || lastResult == ContextManager.TRUE) { setResult(ContextManager.TRUE, now); } else { setResult(ContextManager.FALSE, now); } break; default: throw new IllegalArgumentException("Unknown Logical Operator: " + mOperator); } } @Override protected final long getDeferUntilImpl() { long mDeferUntil; if (mRightExpression != null) { // Smart energy optimization // A | B | && | || // ------------------- // T | T | min | max // T | F | min | A // F | T | min | B // F | F | max | min // TODO: ContextManager.FALSE should be in a custom enum if (mOperator.equals(LogicOperator.AND) && mLeftExpression.getResult() == ContextManager.FALSE && mRightExpression.getResult() == ContextManager.FALSE) { mDeferUntil = Math.max(mLeftExpression.getDeferUntil(), mRightExpression.getDeferUntil()); } else if (mOperator.equals(LogicOperator.OR) && mLeftExpression.getResult() == ContextManager.TRUE && mRightExpression.getResult() == ContextManager.TRUE) { mDeferUntil = Math.max(mLeftExpression.getDeferUntil(), mRightExpression.getDeferUntil()); } else if (mOperator.equals(LogicOperator.OR) && mLeftExpression.getResult() == ContextManager.TRUE) { mDeferUntil = mLeftExpression.getDeferUntil(); } else if (mOperator.equals(LogicOperator.OR) && mRightExpression.getResult() == ContextManager.TRUE) { mDeferUntil = mRightExpression.getDeferUntil(); } else { mDeferUntil = Math.min(mLeftExpression.getDeferUntil(), mRightExpression.getDeferUntil()); } } else { mDeferUntil = mLeftExpression.getDeferUntil(); } return mDeferUntil; } @Override protected final String toStringImpl() { if (mRightExpression == null) { return mOperator + "(" + mLeftExpression + ")"; } else { return "(" + mLeftExpression + " " + mOperator + " " + mRightExpression + ")"; } } @Override protected final void writeToParcelImpl(final Parcel dest, final int flags) { dest.writeParcelable(mLeftExpression, flags); dest.writeInt(mOperator.convert()); dest.writeParcelable(mRightExpression, flags); } @Override protected final int getSubtypeId() { return LOGIC_EXPRESSION_TYPE; } @Override protected final String toParseStringImpl() { if (mRightExpression == null) { return mOperator.toString() + " " + mLeftExpression.toParseString(); } else { return "(" + mLeftExpression.toParseString() + " " + mOperator + " " + mRightExpression.toParseString() + ")"; } } @Override public void sleepAndBeReadyAt(long readyTime) { mLeftExpression.sleepAndBeReadyAt(readyTime); mRightExpression.sleepAndBeReadyAt(readyTime); } @Override public long getHistoryLength() { return Math.max(mLeftExpression.getHistoryLength(), mRightExpression.getHistoryLength()); } protected boolean hasCurrentTime() { return false; } @Override public TimestampedValue[] getValues(String string, long now) { return new TimestampedValue[] { new TimestampedValue(getResult(), getLastEvaluationTime()) }; } /** * @return the left side of this expression. */ public Expression getLeftExpression() { return mLeftExpression; } /** * @return the right side of this expression. */ public Expression getRightExpression() { return mRightExpression; } /** * @return the operator for this expression. */ public LogicOperator getOperator() { return mOperator; } @Override public HistoryReductionMode getHistoryReductionMode() { return HistoryReductionMode.DEFAULT_MODE; } @Override public boolean isConstant() { // TODO Auto-generated method stub return false; } }
/* * 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.calcite.prepare; import org.apache.calcite.config.CalciteConnectionConfig; import org.apache.calcite.jdbc.CalciteSchema; import org.apache.calcite.jdbc.JavaTypeFactoryImpl; import org.apache.calcite.model.ModelHandler; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rel.type.RelDataTypeFactoryImpl; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rel.type.RelDataTypeSystem; import org.apache.calcite.schema.AggregateFunction; import org.apache.calcite.schema.Function; import org.apache.calcite.schema.FunctionParameter; import org.apache.calcite.schema.ScalarFunction; import org.apache.calcite.schema.Table; import org.apache.calcite.schema.TableFunction; import org.apache.calcite.schema.TableMacro; import org.apache.calcite.schema.Wrapper; import org.apache.calcite.schema.impl.ScalarFunctionImpl; import org.apache.calcite.sql.SqlFunctionCategory; import org.apache.calcite.sql.SqlIdentifier; import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.SqlOperatorTable; import org.apache.calcite.sql.SqlSyntax; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.FamilyOperandTypeChecker; import org.apache.calcite.sql.type.InferTypes; import org.apache.calcite.sql.type.OperandTypes; import org.apache.calcite.sql.type.ReturnTypes; import org.apache.calcite.sql.type.SqlReturnTypeInference; import org.apache.calcite.sql.type.SqlTypeFactoryImpl; import org.apache.calcite.sql.type.SqlTypeFamily; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.sql.util.ListSqlOperatorTable; import org.apache.calcite.sql.validate.SqlMoniker; import org.apache.calcite.sql.validate.SqlMonikerImpl; import org.apache.calcite.sql.validate.SqlMonikerType; import org.apache.calcite.sql.validate.SqlNameMatcher; import org.apache.calcite.sql.validate.SqlNameMatchers; import org.apache.calcite.sql.validate.SqlUserDefinedAggFunction; import org.apache.calcite.sql.validate.SqlUserDefinedFunction; import org.apache.calcite.sql.validate.SqlUserDefinedTableFunction; import org.apache.calcite.sql.validate.SqlUserDefinedTableMacro; import org.apache.calcite.sql.validate.SqlValidatorUtil; import org.apache.calcite.util.Util; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Objects; import java.util.function.Predicate; /** * Implementation of {@link org.apache.calcite.prepare.Prepare.CatalogReader} * and also {@link org.apache.calcite.sql.SqlOperatorTable} based on tables and * functions defined schemas. */ public class CalciteCatalogReader implements Prepare.CatalogReader { protected final CalciteSchema rootSchema; protected final RelDataTypeFactory typeFactory; private final List<List<String>> schemaPaths; protected final SqlNameMatcher nameMatcher; protected final CalciteConnectionConfig config; public CalciteCatalogReader(CalciteSchema rootSchema, List<String> defaultSchema, RelDataTypeFactory typeFactory, CalciteConnectionConfig config) { this(rootSchema, SqlNameMatchers.withCaseSensitive(config != null && config.caseSensitive()), ImmutableList.of(Objects.requireNonNull(defaultSchema), ImmutableList.of()), typeFactory, config); } protected CalciteCatalogReader(CalciteSchema rootSchema, SqlNameMatcher nameMatcher, List<List<String>> schemaPaths, RelDataTypeFactory typeFactory, CalciteConnectionConfig config) { this.rootSchema = Objects.requireNonNull(rootSchema); this.nameMatcher = nameMatcher; this.schemaPaths = Util.immutableCopy(Util.isDistinct(schemaPaths) ? schemaPaths : new LinkedHashSet<>(schemaPaths)); this.typeFactory = typeFactory; this.config = config; } public CalciteCatalogReader withSchemaPath(List<String> schemaPath) { return new CalciteCatalogReader(rootSchema, nameMatcher, ImmutableList.of(schemaPath, ImmutableList.of()), typeFactory, config); } public Prepare.PreparingTable getTable(final List<String> names) { // First look in the default schema, if any. // If not found, look in the root schema. CalciteSchema.TableEntry entry = SqlValidatorUtil.getTableEntry(this, names); if (entry != null) { final Table table = entry.getTable(); if (table instanceof Wrapper) { final Prepare.PreparingTable relOptTable = ((Wrapper) table).unwrap(Prepare.PreparingTable.class); if (relOptTable != null) { return relOptTable; } } return RelOptTableImpl.create(this, table.getRowType(typeFactory), entry, null); } return null; } @Override public CalciteConnectionConfig getConfig() { return config; } private Collection<Function> getFunctionsFrom(List<String> names) { final List<Function> functions2 = new ArrayList<>(); final List<List<String>> schemaNameList = new ArrayList<>(); if (names.size() > 1) { // Name qualified: ignore path. But we do look in "/catalog" and "/", // the last 2 items in the path. if (schemaPaths.size() > 1) { schemaNameList.addAll(Util.skip(schemaPaths)); } else { schemaNameList.addAll(schemaPaths); } } else { for (List<String> schemaPath : schemaPaths) { CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, schemaPath, nameMatcher); if (schema != null) { schemaNameList.addAll(schema.getPath()); } } } for (List<String> schemaNames : schemaNameList) { CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, Iterables.concat(schemaNames, Util.skipLast(names)), nameMatcher); if (schema != null) { final String name = Util.last(names); functions2.addAll(schema.getFunctions(name, true)); } } return functions2; } public RelDataType getNamedType(SqlIdentifier typeName) { CalciteSchema.TypeEntry typeEntry = SqlValidatorUtil.getTypeEntry(getRootSchema(), typeName); if (typeEntry != null) { return typeEntry.getType().apply(typeFactory); } else { return null; } } public List<SqlMoniker> getAllSchemaObjectNames(List<String> names) { final CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, names, nameMatcher); if (schema == null) { return ImmutableList.of(); } final List<SqlMoniker> result = new ArrayList<>(); // Add root schema if not anonymous if (!schema.name.equals("")) { result.add(moniker(schema, null, SqlMonikerType.SCHEMA)); } final Map<String, CalciteSchema> schemaMap = schema.getSubSchemaMap(); for (String subSchema : schemaMap.keySet()) { result.add(moniker(schema, subSchema, SqlMonikerType.SCHEMA)); } for (String table : schema.getTableNames()) { result.add(moniker(schema, table, SqlMonikerType.TABLE)); } final NavigableSet<String> functions = schema.getFunctionNames(); for (String function : functions) { // views are here as well result.add(moniker(schema, function, SqlMonikerType.FUNCTION)); } return result; } private SqlMonikerImpl moniker(CalciteSchema schema, String name, SqlMonikerType type) { final List<String> path = schema.path(name); if (path.size() == 1 && !schema.root().name.equals("") && type == SqlMonikerType.SCHEMA) { type = SqlMonikerType.CATALOG; } return new SqlMonikerImpl(path, type); } public List<List<String>> getSchemaPaths() { return schemaPaths; } public Prepare.PreparingTable getTableForMember(List<String> names) { return getTable(names); } @SuppressWarnings("deprecation") public RelDataTypeField field(RelDataType rowType, String alias) { return nameMatcher.field(rowType, alias); } @SuppressWarnings("deprecation") public boolean matches(String string, String name) { return nameMatcher.matches(string, name); } public RelDataType createTypeFromProjection(final RelDataType type, final List<String> columnNameList) { return SqlValidatorUtil.createTypeFromProjection(type, columnNameList, typeFactory, nameMatcher.isCaseSensitive()); } public void lookupOperatorOverloads(final SqlIdentifier opName, SqlFunctionCategory category, SqlSyntax syntax, List<SqlOperator> operatorList) { if (syntax != SqlSyntax.FUNCTION) { return; } final Predicate<Function> predicate; if (category == null) { predicate = function -> true; } else if (category.isTableFunction()) { predicate = function -> function instanceof TableMacro || function instanceof TableFunction; } else { predicate = function -> !(function instanceof TableMacro || function instanceof TableFunction); } getFunctionsFrom(opName.names) .stream() .filter(predicate) .map(function -> toOp(opName, function)) .forEachOrdered(operatorList::add); } /** Creates an operator table that contains functions in the given class. * * @see ModelHandler#addFunctions */ public static SqlOperatorTable operatorTable(String className) { // Dummy schema to collect the functions final CalciteSchema schema = CalciteSchema.createRootSchema(false, false); ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(), className, "*", true); // The following is technical debt; see [CALCITE-2082] Remove // RelDataTypeFactory argument from SqlUserDefinedAggFunction constructor final SqlTypeFactoryImpl typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT); final ListSqlOperatorTable table = new ListSqlOperatorTable(); for (String name : schema.getFunctionNames()) { for (Function function : schema.getFunctions(name, true)) { final SqlIdentifier id = new SqlIdentifier(name, SqlParserPos.ZERO); table.add( toOp(typeFactory, id, function)); } } return table; } private SqlOperator toOp(SqlIdentifier name, final Function function) { return toOp(typeFactory, name, function); } /** Converts a function to a {@link org.apache.calcite.sql.SqlOperator}. * * <p>The {@code typeFactory} argument is technical debt; see [CALCITE-2082] * Remove RelDataTypeFactory argument from SqlUserDefinedAggFunction * constructor. */ private static SqlOperator toOp(RelDataTypeFactory typeFactory, SqlIdentifier name, final Function function) { List<RelDataType> argTypes = new ArrayList<>(); List<SqlTypeFamily> typeFamilies = new ArrayList<>(); for (FunctionParameter o : function.getParameters()) { final RelDataType type = o.getType(typeFactory); argTypes.add(type); typeFamilies.add( Util.first(type.getSqlTypeName().getFamily(), SqlTypeFamily.ANY)); } final FamilyOperandTypeChecker typeChecker = OperandTypes.family(typeFamilies, i -> function.getParameters().get(i).isOptional()); final List<RelDataType> paramTypes = toSql(typeFactory, argTypes); if (function instanceof ScalarFunction) { return new SqlUserDefinedFunction(name, infer((ScalarFunction) function), InferTypes.explicit(argTypes), typeChecker, paramTypes, function); } else if (function instanceof AggregateFunction) { return new SqlUserDefinedAggFunction(name, infer((AggregateFunction) function), InferTypes.explicit(argTypes), typeChecker, (AggregateFunction) function, false, false, typeFactory); } else if (function instanceof TableMacro) { return new SqlUserDefinedTableMacro(name, ReturnTypes.CURSOR, InferTypes.explicit(argTypes), typeChecker, paramTypes, (TableMacro) function); } else if (function instanceof TableFunction) { return new SqlUserDefinedTableFunction(name, ReturnTypes.CURSOR, InferTypes.explicit(argTypes), typeChecker, paramTypes, (TableFunction) function); } else { throw new AssertionError("unknown function type " + function); } } private static SqlReturnTypeInference infer(final ScalarFunction function) { return opBinding -> { final RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); final RelDataType type; if (function instanceof ScalarFunctionImpl) { type = ((ScalarFunctionImpl) function).getReturnType(typeFactory, opBinding); } else { type = function.getReturnType(typeFactory); } return toSql(typeFactory, type); }; } private static SqlReturnTypeInference infer( final AggregateFunction function) { return opBinding -> { final RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); final RelDataType type = function.getReturnType(typeFactory); return toSql(typeFactory, type); }; } private static List<RelDataType> toSql( final RelDataTypeFactory typeFactory, List<RelDataType> types) { return Lists.transform(types, type -> toSql(typeFactory, type)); } private static RelDataType toSql(RelDataTypeFactory typeFactory, RelDataType type) { if (type instanceof RelDataTypeFactoryImpl.JavaType && ((RelDataTypeFactoryImpl.JavaType) type).getJavaClass() == Object.class) { return typeFactory.createTypeWithNullability( typeFactory.createSqlType(SqlTypeName.ANY), true); } return JavaTypeFactoryImpl.toSql(typeFactory, type); } public List<SqlOperator> getOperatorList() { return null; } public CalciteSchema getRootSchema() { return rootSchema; } public RelDataTypeFactory getTypeFactory() { return typeFactory; } public void registerRules(RelOptPlanner planner) throws Exception { } @SuppressWarnings("deprecation") @Override public boolean isCaseSensitive() { return nameMatcher.isCaseSensitive(); } public SqlNameMatcher nameMatcher() { return nameMatcher; } @Override public <C> C unwrap(Class<C> aClass) { if (aClass.isInstance(this)) { return aClass.cast(this); } return null; } } // End CalciteCatalogReader.java
/* * Copyright (c) 2013-2014, ickStream GmbH * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ickStream 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. */ package com.ickstream.common.jsonrpc; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; /** * Message sender implementation that sends JSON-RPC message to the specified HTTP endpoint using HTTP POST messages */ public class HttpMessageSender implements MessageSender { private String endpoint; private String accessToken; private JsonRpcResponseHandler responseHandler; private JsonHelper jsonHelper = new JsonHelper(); private HttpClient httpClient; private MessageLogger messageLogger; private Boolean asynchronous = false; /** * Creates a new message sender instance * The created instance will ignore responses unless {@link #setResponseHandler(JsonRpcResponseHandler)} is called to * specify a response handler. * * @param httpClient The {@link HttpClient} instance to use * @param endpoint The HTTP endpoint url to send the message to */ public HttpMessageSender(HttpClient httpClient, String endpoint) { this(httpClient, endpoint, false); } /** * Creates a new message sender instance * * @param httpClient The {@link HttpClient} instance to use * @param endpoint The HTTP endpoint url to send the message to * @param accessToken The OAuth access token to use for authorization * @param responseHandler The response handler to use for handling responses */ public HttpMessageSender(HttpClient httpClient, String endpoint, String accessToken, JsonRpcResponseHandler responseHandler) { this(httpClient, endpoint, false, accessToken, responseHandler); } /** * Creates a new message sender instance * The created instance will ignore responses unless {@link #setResponseHandler(JsonRpcResponseHandler)} is called to * specify a response handler. * * @param httpClient The {@link HttpClient} instance to use * @param endpoint The HTTP endpoint url to send the message to * @param asynchronous If true, the message will be sent in a new thread, this is typically useful if this message sender is used with {@link AsyncJsonRpcClient} */ public HttpMessageSender(HttpClient httpClient, String endpoint, Boolean asynchronous) { this(httpClient, endpoint, asynchronous, null, null); } /** * Creates a new message sender instance * * @param httpClient The {@link HttpClient} instance to use * @param endpoint The HTTP endpoint url to send the message to * @param asynchronous If true, the message will be sent in a new thread, this is typically useful if this message sender is used with {@link AsyncJsonRpcClient} * @param accessToken The OAuth access token to use for authorization * @param responseHandler The response handler to use for handling responses */ public HttpMessageSender(HttpClient httpClient, String endpoint, Boolean asynchronous, String accessToken, JsonRpcResponseHandler responseHandler) { this.httpClient = httpClient; this.endpoint = endpoint; this.accessToken = accessToken; this.responseHandler = responseHandler; this.asynchronous = asynchronous; } /** * Set the OAuth access token to use for authorization * * @param accessToken An OAuth access token */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * Set the response handler to use when processing responses on message sent by this message sender * * @param responseHandler A response handler */ public void setResponseHandler(JsonRpcResponseHandler responseHandler) { this.responseHandler = responseHandler; } /** * Set the message logger implementation that should be used to log message sent and responses received using this * message sender * * @param messageLogger A message logger implementation */ public void setMessageLogger(MessageLogger messageLogger) { this.messageLogger = messageLogger; } private void reportInvalidJson(String message) { if (responseHandler != null) { JsonRpcResponse response = new JsonRpcResponse("2.0", null); response.setError(new JsonRpcResponse.Error(JsonRpcError.INVALID_JSON, "Invalid JSON", message)); String errorString = jsonHelper.objectToString(response); if (messageLogger != null) { messageLogger.onIncomingMessage(endpoint, errorString); } responseHandler.onResponse(response); } } /** * Send the specified message using HTTP POST * * @param message The message to send */ @Override public void sendMessage(String message) { final JsonRpcRequest request = jsonHelper.stringToObject(message, JsonRpcRequest.class); if (request == null) { reportInvalidJson(message); return; } final HttpClient httpClient = this.httpClient; final HttpPost httpRequest = new HttpPost(endpoint); try { Class.forName("org.apache.http.entity.ContentType"); StringEntity stringEntity = new StringEntity(message, ContentType.create("application/json", Charset.forName("utf-8"))); httpRequest.setEntity(stringEntity); } catch (ClassNotFoundException e) { try { StringEntity stringEntity = new StringEntity(message, "utf-8"); httpRequest.setEntity(stringEntity); } catch (UnsupportedEncodingException e1) { reportInvalidJson(message); return; } } httpRequest.setHeader("Authorization", "Bearer " + accessToken); if (messageLogger != null) { messageLogger.onOutgoingMessage(endpoint, message); } if (asynchronous) { new Thread(new Runnable() { @Override public void run() { processMessage(httpClient, httpRequest, request); } }).start(); } else { processMessage(httpClient, httpRequest, request); } } private void processMessage(final HttpClient httpClient, final HttpPost httpRequest, final JsonRpcRequest request) { try { final HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() < 400) { String responseString = EntityUtils.toString(httpResponse.getEntity()); if (responseString != null && responseString.length() > 0 && responseHandler != null) { if (messageLogger != null) { messageLogger.onIncomingMessage(endpoint, responseString); } JsonRpcResponse response = jsonHelper.stringToObject(responseString, JsonRpcResponse.class); if (response != null) { responseHandler.onResponse(response); } } } else if (httpResponse.getStatusLine().getStatusCode() == 401) { if (responseHandler != null) { JsonRpcResponse response = new JsonRpcResponse(request.getJsonrpc(), request.getId()); response.setError(new JsonRpcResponse.Error(JsonRpcError.UNAUTHORIZED, "Unauthorized access", null)); String errorString = jsonHelper.objectToString(response); if (messageLogger != null) { messageLogger.onIncomingMessage(endpoint, errorString); } responseHandler.onResponse(response); } } else { if (responseHandler != null) { JsonRpcResponse response = new JsonRpcResponse(request.getJsonrpc(), request.getId()); response.setError(new JsonRpcResponse.Error(JsonRpcError.SERVICE_ERROR, httpResponse.getStatusLine().getReasonPhrase(), null)); String errorString = jsonHelper.objectToString(response); if (messageLogger != null) { messageLogger.onIncomingMessage(endpoint, errorString); } responseHandler.onResponse(response); } } } catch (IOException e) { if (responseHandler != null) { JsonRpcResponse response = new JsonRpcResponse(request.getJsonrpc(), request.getId()); response.setError(new JsonRpcResponse.Error(JsonRpcError.SERVICE_ERROR, e.getMessage(), null)); String errorString = jsonHelper.objectToString(response); if (messageLogger != null) { messageLogger.onIncomingMessage(endpoint, errorString); } responseHandler.onResponse(response); } } } }
/* * Copyright 2018-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.support.bgtasks; import com.facebook.buck.core.model.BuildId; import com.facebook.buck.core.util.log.Logger; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Asynchronous-enabled implementation of {@link BackgroundTaskManager}. Tasks run in a pool. Takes * a blocking flag in constructor; when {@code blocking=true}, manager waits for tasks to complete * before returning control to client. When {@code blocking=false}, manager schedules on a separate * thread and does not wait for task completion. Scheduler thread is paused whenever a new command * begins. * * <p>NOTE: only a manager on buckd should be set/instantiated to nonblocking mode, otherwise * unexpected behavior might occur */ public class AsyncBackgroundTaskManager extends BackgroundTaskManager { private static final Logger LOG = Logger.get(AsyncBackgroundTaskManager.class); private static final int DEFAULT_THREADS = 3; private final Queue<ManagedBackgroundTask> scheduledTasks = new LinkedList<>(); private final Map<Class<?>, ManagedBackgroundTask> cancellableTasks = new ConcurrentHashMap<>(); private final boolean blocking; private final AtomicBoolean schedulerRunning; private final AtomicInteger commandsRunning; private final AtomicBoolean schedulingOpen; private final Semaphore availableThreads; private final Optional<ExecutorService> scheduler; private final ExecutorService taskPool; private final ScheduledExecutorService timeoutPool; /** * Constructs an {@link AsyncBackgroundTaskManager}. If in nonblocking mode, sets up a scheduler * thread and pool for tasks. * * @param blocking bool indicating if this manager should block when running tasks or not * @param nThreads (optional) number of threads in pool. defaults to {@code DEFAULT_THREADS} if * not provided */ public AsyncBackgroundTaskManager(boolean blocking, int nThreads) { this.blocking = blocking; this.schedulerRunning = new AtomicBoolean(false); this.taskPool = Executors.newFixedThreadPool(nThreads); this.timeoutPool = Executors.newScheduledThreadPool(1); this.scheduler = blocking ? Optional.empty() : Optional.of(Executors.newFixedThreadPool(1)); this.commandsRunning = new AtomicInteger(0); this.availableThreads = new Semaphore(nThreads); this.schedulingOpen = new AtomicBoolean(true); } public AsyncBackgroundTaskManager(boolean blocking) { this(blocking, DEFAULT_THREADS); } @Override public TaskManagerScope getNewScope(BuildId buildId) { return new TaskManagerScope(this, buildId); } private void startSchedulingIfNeeded() { Preconditions.checkState(scheduler.isPresent()); if (schedulerRunning.getAndSet(true)) { return; } scheduler.get().submit(this::scheduleLoop); } private void shutDownScheduling() { schedulingOpen.set(false); try { if (!blocking) { scheduler.get().shutdownNow(); scheduler.get().awaitTermination(1, TimeUnit.SECONDS); } } catch (InterruptedException e) { scheduler.get().shutdownNow(); } } /** Shut down scheduler and pool threads. */ @Override public void shutdownNow() { shutDownScheduling(); timeoutPool.shutdownNow(); // we lose timeouts on shutdown taskPool.shutdownNow(); } @Override public void shutdown(long timeout, TimeUnit units) throws InterruptedException { shutDownScheduling(); timeoutPool.shutdownNow(); // we lose timeouts on shutdown taskPool.shutdown(); taskPool.awaitTermination(timeout, units); } @Override public void schedule(ManagedBackgroundTask task) { if (!schedulingOpen.get()) { LOG.warn("Manager is not accepting new tasks; newly scheduled tasks will not be run."); return; } Class<?> actionClass = task.getTask().getAction().getClass(); synchronized (cancellableTasks) { if (cancellableTasks.containsKey(actionClass)) { cancellableTasks.get(actionClass).markToCancel(); } if (task.getTask().getShouldCancelOnRepeat()) { cancellableTasks.put(actionClass, task); } } synchronized (scheduledTasks) { scheduledTasks.add(task); scheduledTasks.notify(); } } /** * Runs a task. Exceptions are caught and logged. * * @param managedTask Task to run */ void runTask(ManagedBackgroundTask managedTask) { try { BackgroundTask<?> task = managedTask.getTask(); task.run(); } catch (InterruptedException e) { LOG.warn(e, "Task %s interrupted.", managedTask.getId()); } catch (Throwable e) { LOG.warn(e, "%s while running task %s", e.getClass().getName(), managedTask.getId()); } } private void addTimeoutIfNeeded(Future<?> taskHandler, ManagedBackgroundTask task) { Optional<Timeout> timeout = task.getTask().getTimeout(); if (timeout.isPresent()) { timeoutPool.schedule( () -> { if (taskHandler.cancel(true)) { LOG.warn(String.format("Task %s timed out", task.getId())); } }, timeout.get().timeout(), timeout.get().unit()); } } @Override protected void notify(Notification code) { if (blocking) { notifySync(code); } else { notifyAsync(code); } } private Future<?> submitTask(ManagedBackgroundTask task) { Future<?> handler = taskPool.submit( () -> { runTask(task); availableThreads.release(); }); addTimeoutIfNeeded(handler, task); return handler; } private boolean taskCancelled(ManagedBackgroundTask task) { cancellableTasks.remove(task.getTask().getAction().getClass(), task); return task.getToCancel(); } private void notifySync(Notification code) { switch (code) { case COMMAND_START: commandsRunning.incrementAndGet(); break; case COMMAND_END: if (commandsRunning.decrementAndGet() > 0) { return; } try { ArrayList<Future<?>> futures; synchronized (scheduledTasks) { futures = new ArrayList<>(scheduledTasks.size()); while (!scheduledTasks.isEmpty()) { if (!schedulingOpen.get()) { break; } availableThreads.acquire(); ManagedBackgroundTask task = scheduledTasks.remove(); if (taskCancelled(task)) { availableThreads.release(); continue; } futures.add(submitTask(task)); } } for (Future<?> future : futures) { try { future.get(); } catch (ExecutionException e) { // task exceptions should normally be caught in runTask LOG.error(e, "Task threw exception"); } catch (CancellationException e) { LOG.info(e, "Task was cancelled"); } } } catch (InterruptedException e) { LOG.warn("Blocking manager interrupted"); } } } private void notifyAsync(Notification code) { startSchedulingIfNeeded(); switch (code) { case COMMAND_START: commandsRunning.incrementAndGet(); break; case COMMAND_END: synchronized (commandsRunning) { commandsRunning.decrementAndGet(); commandsRunning.notify(); } break; } } private void scheduleLoop() { try { while (!Thread.interrupted()) { synchronized (scheduledTasks) { while (scheduledTasks.isEmpty()) { scheduledTasks.wait(); } } synchronized (commandsRunning) { while (commandsRunning.get() > 0) { commandsRunning.wait(); } } availableThreads.acquire(); ManagedBackgroundTask task = scheduledTasks.remove(); if (taskCancelled(task)) { availableThreads.release(); continue; } submitTask(task); } } catch (InterruptedException e) { // do nothing. got interrupted. } LOG.info("Scheduler thread interrupted; shutting down manager"); if (schedulingOpen.get()) { schedulingOpen.set(false); taskPool.shutdownNow(); } } /** * Return list of currently scheduled (not yet submitted) tasks. For debugging/testing. * * @return list of currently scheduled tasks */ @VisibleForTesting protected Queue<ManagedBackgroundTask> getScheduledTasks() { return scheduledTasks; } /** * Return map of tasks that might be cancelled (i.e. not run) if a task with the same action is * subsequently scheduled. Tasks in this map are currently scheduled, not yet run. For * debugging/testing. * * @return map of cancellable tasks */ @VisibleForTesting protected Map<Class<?>, ManagedBackgroundTask> getCancellableTasks() { return cancellableTasks; } /** * Check if the manager is shut down. "Shut down" means that all executors are terminated and * manager is no longer accepting new task submissions. For debugging/testing. * * @return true if manager is shut down, false otherwise */ @VisibleForTesting protected boolean isShutDown() { boolean schedulerDone = true; if (scheduler.isPresent()) { schedulerDone = scheduler.get().isTerminated(); } return taskPool.isTerminated() && timeoutPool.isTerminated() && schedulerDone && !schedulingOpen.get(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package tests.unit.com.microsoft.azure.iothub.auth; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertTrue; import com.microsoft.azure.iothub.DeviceClient; import com.microsoft.azure.iothub.DeviceClientConfig; import com.microsoft.azure.iothub.auth.IotHubSasToken; import com.microsoft.azure.iothub.auth.Signature; import mockit.Mocked; import mockit.NonStrictExpectations; import org.junit.Test; import java.net.URISyntaxException; /** Unit tests for IotHubSasToken. */ public class IotHubSasTokenTest { @Mocked Signature mockSig; // Tests_SRS_IOTHUBSASTOKEN_11_001: [The SAS token shall have the format "SharedAccessSignature sig=<signature>&se=<expiryTime>&sr=<resourceURI>". The params can be in any order.] @Test public void sasTokenHasCorrectFormat() throws URISyntaxException { final String resourceUri = "sample-resource-uri"; final String iotHubHostname = "sample-iothub-hostname.net"; final String deviceKey = "sample-device-key"; final String deviceId = "sample-device-ID"; final long expiryTime = 100; final String signature = "sample-sig"; new NonStrictExpectations() { { mockSig.toString(); result = signature; } }; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, deviceKey, null), expiryTime); String tokenStr = token.toString(); // assert that sig, se and sr exist in the token in any order. assertThat(tokenStr.indexOf("SharedAccessSignature "), is(not(-1))); assertThat(tokenStr.indexOf("sig="), is(not(-1))); assertThat(tokenStr.indexOf("se="), is(not(-1))); assertThat(tokenStr.indexOf("sr="), is(not(-1))); } // Tests_SRS_IOTHUBSASTOKEN_11_002: [The expiry time shall be the given expiry time, where it is a UNIX timestamp and indicates the time after which the token becomes invalid.] @Test public void expiryTimeSetCorrectly() throws URISyntaxException { final String resourceUri = "sample-resource-uri"; final String iotHubHostname = "sample-iothub-hostname.net"; final String deviceKey = "sample-device-key"; final String deviceId = "sample-device-ID"; final long expiryTime = 100; final String signature = "sample-sig"; new NonStrictExpectations() { { mockSig.toString(); result = signature; } }; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, deviceKey, null), expiryTime); String tokenStr = token.toString(); // extract the value assigned to se. int expiryTimeKeyIdx = tokenStr.indexOf("se="); int expiryTimeStartIdx = expiryTimeKeyIdx + 3; int expiryTimeEndIdx = tokenStr.indexOf("&", expiryTimeStartIdx); if (expiryTimeEndIdx == -1) { expiryTimeEndIdx = tokenStr.length(); } String testExpiryTimeStr = tokenStr.substring(expiryTimeStartIdx, expiryTimeEndIdx); String expectedExpiryTimeStr = Long.toString(expiryTime); assertThat(testExpiryTimeStr, is(expectedExpiryTimeStr)); } // Tests_SRS_IOTHUBSASTOKEN_11_005: [The signature shall be correctly computed and set.] // Tests_SRS_IOTHUBSASTOKEN_11_006: [The function shall return the string representation of the SAS token.] @Test public void signatureSetCorrectly() throws URISyntaxException { final String resourceUri = "sample-resource-uri"; final String deviceId = "sample-device-ID"; final String iotHubHostname = "sample-iothub-hostname.net"; final String deviceKey = "sample-device-key"; final long expiryTime = 100; final String signature = "sample-sig"; new NonStrictExpectations() { { mockSig.toString(); result = signature; } }; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, deviceKey, null), expiryTime); String tokenStr = token.toString(); // extract the value assigned to sig. int signatureKeyIdx = tokenStr.indexOf("sig="); int signatureStartIdx = signatureKeyIdx + 4; int signatureEndIdx = tokenStr.indexOf("&", signatureStartIdx); if (signatureEndIdx == -1) { signatureEndIdx = tokenStr.length(); } String testSignature = tokenStr.substring(signatureStartIdx, signatureEndIdx); final String expectedSignature = signature; assertThat(testSignature, is(expectedSignature)); } // Tests_SRS_IOTHUBSASTOKEN_11_013: [**The token generated from DeviceClientConfig shall use correct expiry time (seconds rather than milliseconds)] @Test public void constructorSetsExpiryTimeCorrectly() throws URISyntaxException { String iotHubHostname = "sample-iothub-hostname.net"; String deviceKey = "sample-device-key"; String deviceId = "sample-device-ID"; long token_valid_secs = 100; long expiryTimeTestErrorRange = 1; long expiryTimeBaseInSecs = System.currentTimeMillis() / 1000l + token_valid_secs + 1l; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, deviceKey, null), expiryTimeBaseInSecs); String tokenStr = token.toString(); // extract the value assigned to se. int expiryTimeKeyIdx = tokenStr.indexOf("se="); int expiryTimeStartIdx = expiryTimeKeyIdx + 3; int expiryTimeEndIdx = tokenStr.indexOf("&", expiryTimeStartIdx); if (expiryTimeEndIdx == -1) { expiryTimeEndIdx = tokenStr.length(); } String testExpiryTimeStr = tokenStr.substring(expiryTimeStartIdx, expiryTimeEndIdx); long expiryTimeInSecs = Long.valueOf(testExpiryTimeStr); assertTrue(expiryTimeBaseInSecs <= expiryTimeInSecs && expiryTimeInSecs <= (expiryTimeBaseInSecs + expiryTimeTestErrorRange)); } // Tests_SRS_IOTHUBSASTOKEN_25_007: [**If device key is not provided in config then the SASToken from config shall be used.**]** @Test public void setValidSASTokenCorrectly() throws URISyntaxException { String iotHubHostname = "sample-iothub-hostname.net"; String deviceId = "sample-device-ID"; String sastoken = "SharedAccessSignature sr=sample-iothub-hostname.net%2fdevices%2fsample-device-ID&sig=S3%2flPidfBF48B7%2fOFAxMOYH8rpOneq68nu61D%2fBP6fo%3d&se=1469813873"; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, null,sastoken), 0); String tokenStr = token.toString(); assertTrue(tokenStr == sastoken); } // Tests_SRS_IOTHUBSASTOKEN_25_008: [**The required format for the SAS Token shall be verified and IllegalArgumentException is thrown if unmatched.**]** //Tests_SRS_IOTHUBSASTOKEN_11_001: [**The SAS token shall have the format `SharedAccessSignature sig=<signature >&se=<expiryTime>&sr=<resourceURI>`. The params can be in any order.**]** @Test(expected = IllegalArgumentException.class) public void doesNotSetInvalidSASToken() throws URISyntaxException { String iotHubHostname = "sample-iothub-hostname.net"; String deviceId = "sample-device-ID"; String sastoken = "SharedAccessSignature sr =sample-iothub-hostname.net%2fdevices%2fsample-device-ID&sig =S3%2flPidfBF48B7%2fOFAxMOYH8rpOneq68nu61D%2fBP6fo%3d&se =1469813873"; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, null, sastoken), 0); String tokenStr = token.toString(); assertTrue(tokenStr != sastoken); } // Tests_SRS_IOTHUBSASTOKEN_25_008: [**The required format for the SAS Token shall be verified and IllegalArgumentException is thrown if unmatched.**]** //Tests_SRS_IOTHUBSASTOKEN_11_001: [**The SAS token shall have the format `SharedAccessSignature sig=<signature >&se=<expiryTime>&sr=<resourceURI>`. The params can be in any order.**]** @Test(expected = IllegalArgumentException.class) public void doesNotSetSASTokenWithoutSe() throws URISyntaxException { String iotHubHostname = "sample-iothub-hostname.net"; String deviceId = "sample-device-ID"; String sastoken = "SharedAccessSignature sr=sample-iothub-hostname.net%2fdevices%2fsample-device-ID&sig=S3%2flPidfBF48B7%2fOFAxMOYH8rpOneq68nu61D%2fBP6fo%3d"; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, null, sastoken), 0); String tokenStr = token.toString(); assertTrue(tokenStr != sastoken); } // Tests_SRS_IOTHUBSASTOKEN_25_008: [**The required format for the SAS Token shall be verified and IllegalArgumentException is thrown if unmatched.**]** //Tests_SRS_IOTHUBSASTOKEN_11_001: [**The SAS token shall have the format `SharedAccessSignature sig=<signature >&se=<expiryTime>&sr=<resourceURI>`. The params can be in any order.**]** @Test(expected = IllegalArgumentException.class) public void doesNotSetSASTokenWithoutSr() throws URISyntaxException { String iotHubHostname = "sample-iothub-hostname.net"; String deviceId = "sample-device-ID"; String sastoken = "SharedAccessSignature sig=S3%2flPidfBF48B7%2fOFAxMOYH8rpOneq68nu61D%2fBP6fo%3d&se=1469813873";; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, null, sastoken), 0); String tokenStr = token.toString(); assertTrue(tokenStr != sastoken); } // Tests_SRS_IOTHUBSASTOKEN_25_008: [**The required format for the SAS Token shall be verified and IllegalArgumentException is thrown if unmatched.**]** //Tests_SRS_IOTHUBSASTOKEN_11_001: [**The SAS token shall have the format `SharedAccessSignature sig=<signature >&se=<expiryTime>&sr=<resourceURI>`. The params can be in any order.**]** @Test(expected = IllegalArgumentException.class) public void doesNotSetSASTokenWithoutSig() throws URISyntaxException { String iotHubHostname = "sample-iothub-hostname.net"; String deviceId = "sample-device-ID"; String sastoken = "SharedAccessSignature sr=sample-iothub-hostname.net%2fdevices%2fsample-device-ID&se=1469813873"; IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubHostname, deviceId, null,sastoken), 0); String tokenStr = token.toString(); assertTrue(tokenStr == sastoken); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/spanner/admin/database/v1/spanner_database_admin.proto package com.google.spanner.admin.database.v1; /** * <pre> * Enqueues the given DDL statements to be applied, in order but not * necessarily all at once, to the database schema at some point (or * points) in the future. The server checks that the statements * are executable (syntactically valid, name tables that exist, etc.) * before enqueueing them, but they may still fail upon * later execution (e.g., if a statement from another batch of * statements is applied first and it conflicts in some way, or if * there is some data-related problem like a `NULL` value in a column to * which `NOT NULL` would be added). If a statement fails, all * subsequent statements in the batch are automatically cancelled. * Each batch of statements is assigned a name which can be used with * the [Operations][google.longrunning.Operations] API to monitor * progress. See the * [operation_id][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.operation_id] field for more * details. * </pre> * * Protobuf type {@code google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} */ public final class UpdateDatabaseDdlRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) UpdateDatabaseDdlRequestOrBuilder { // Use UpdateDatabaseDdlRequest.newBuilder() to construct. private UpdateDatabaseDdlRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateDatabaseDdlRequest() { database_ = ""; statements_ = com.google.protobuf.LazyStringArrayList.EMPTY; operationId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private UpdateDatabaseDdlRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); database_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { statements_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } statements_.add(s); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); operationId_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { statements_ = statements_.getUnmodifiableView(); } makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.spanner.admin.database.v1.SpannerDatabaseAdminProto.internal_static_google_spanner_admin_database_v1_UpdateDatabaseDdlRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.spanner.admin.database.v1.SpannerDatabaseAdminProto.internal_static_google_spanner_admin_database_v1_UpdateDatabaseDdlRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.class, com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.Builder.class); } private int bitField0_; public static final int DATABASE_FIELD_NUMBER = 1; private volatile java.lang.Object database_; /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public java.lang.String getDatabase() { java.lang.Object ref = database_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); database_ = s; return s; } } /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public com.google.protobuf.ByteString getDatabaseBytes() { java.lang.Object ref = database_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); database_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATEMENTS_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList statements_; /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public com.google.protobuf.ProtocolStringList getStatementsList() { return statements_; } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public int getStatementsCount() { return statements_.size(); } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public java.lang.String getStatements(int index) { return statements_.get(index); } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public com.google.protobuf.ByteString getStatementsBytes(int index) { return statements_.getByteString(index); } public static final int OPERATION_ID_FIELD_NUMBER = 3; private volatile java.lang.Object operationId_; /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public java.lang.String getOperationId() { java.lang.Object ref = operationId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); operationId_ = s; return s; } } /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public com.google.protobuf.ByteString getOperationIdBytes() { java.lang.Object ref = operationId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); operationId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getDatabaseBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, database_); } for (int i = 0; i < statements_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, statements_.getRaw(i)); } if (!getOperationIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, operationId_); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getDatabaseBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, database_); } { int dataSize = 0; for (int i = 0; i < statements_.size(); i++) { dataSize += computeStringSizeNoTag(statements_.getRaw(i)); } size += dataSize; size += 1 * getStatementsList().size(); } if (!getOperationIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, operationId_); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest)) { return super.equals(obj); } com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest other = (com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) obj; boolean result = true; result = result && getDatabase() .equals(other.getDatabase()); result = result && getStatementsList() .equals(other.getStatementsList()); result = result && getOperationId() .equals(other.getOperationId()); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); hash = (37 * hash) + DATABASE_FIELD_NUMBER; hash = (53 * hash) + getDatabase().hashCode(); if (getStatementsCount() > 0) { hash = (37 * hash) + STATEMENTS_FIELD_NUMBER; hash = (53 * hash) + getStatementsList().hashCode(); } hash = (37 * hash) + OPERATION_ID_FIELD_NUMBER; hash = (53 * hash) + getOperationId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Enqueues the given DDL statements to be applied, in order but not * necessarily all at once, to the database schema at some point (or * points) in the future. The server checks that the statements * are executable (syntactically valid, name tables that exist, etc.) * before enqueueing them, but they may still fail upon * later execution (e.g., if a statement from another batch of * statements is applied first and it conflicts in some way, or if * there is some data-related problem like a `NULL` value in a column to * which `NOT NULL` would be added). If a statement fails, all * subsequent statements in the batch are automatically cancelled. * Each batch of statements is assigned a name which can be used with * the [Operations][google.longrunning.Operations] API to monitor * progress. See the * [operation_id][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.operation_id] field for more * details. * </pre> * * Protobuf type {@code google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.spanner.admin.database.v1.SpannerDatabaseAdminProto.internal_static_google_spanner_admin_database_v1_UpdateDatabaseDdlRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.spanner.admin.database.v1.SpannerDatabaseAdminProto.internal_static_google_spanner_admin_database_v1_UpdateDatabaseDdlRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.class, com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.Builder.class); } // Construct using com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); database_ = ""; statements_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); operationId_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.spanner.admin.database.v1.SpannerDatabaseAdminProto.internal_static_google_spanner_admin_database_v1_UpdateDatabaseDdlRequest_descriptor; } public com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest getDefaultInstanceForType() { return com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.getDefaultInstance(); } public com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest build() { com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest buildPartial() { com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest result = new com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.database_ = database_; if (((bitField0_ & 0x00000002) == 0x00000002)) { statements_ = statements_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.statements_ = statements_; result.operationId_ = operationId_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) { return mergeFrom((com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest other) { if (other == com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.getDefaultInstance()) return this; if (!other.getDatabase().isEmpty()) { database_ = other.database_; onChanged(); } if (!other.statements_.isEmpty()) { if (statements_.isEmpty()) { statements_ = other.statements_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureStatementsIsMutable(); statements_.addAll(other.statements_); } onChanged(); } if (!other.getOperationId().isEmpty()) { operationId_ = other.operationId_; onChanged(); } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object database_ = ""; /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public java.lang.String getDatabase() { java.lang.Object ref = database_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); database_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public com.google.protobuf.ByteString getDatabaseBytes() { java.lang.Object ref = database_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); database_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public Builder setDatabase( java.lang.String value) { if (value == null) { throw new NullPointerException(); } database_ = value; onChanged(); return this; } /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public Builder clearDatabase() { database_ = getDefaultInstance().getDatabase(); onChanged(); return this; } /** * <pre> * Required. The database to update. * </pre> * * <code>optional string database = 1;</code> */ public Builder setDatabaseBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); database_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList statements_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureStatementsIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { statements_ = new com.google.protobuf.LazyStringArrayList(statements_); bitField0_ |= 0x00000002; } } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public com.google.protobuf.ProtocolStringList getStatementsList() { return statements_.getUnmodifiableView(); } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public int getStatementsCount() { return statements_.size(); } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public java.lang.String getStatements(int index) { return statements_.get(index); } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public com.google.protobuf.ByteString getStatementsBytes(int index) { return statements_.getByteString(index); } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public Builder setStatements( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureStatementsIsMutable(); statements_.set(index, value); onChanged(); return this; } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public Builder addStatements( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureStatementsIsMutable(); statements_.add(value); onChanged(); return this; } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public Builder addAllStatements( java.lang.Iterable<java.lang.String> values) { ensureStatementsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, statements_); onChanged(); return this; } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public Builder clearStatements() { statements_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * DDL statements to be applied to the database. * </pre> * * <code>repeated string statements = 2;</code> */ public Builder addStatementsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureStatementsIsMutable(); statements_.add(value); onChanged(); return this; } private java.lang.Object operationId_ = ""; /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public java.lang.String getOperationId() { java.lang.Object ref = operationId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); operationId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public com.google.protobuf.ByteString getOperationIdBytes() { java.lang.Object ref = operationId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); operationId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public Builder setOperationId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } operationId_ = value; onChanged(); return this; } /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public Builder clearOperationId() { operationId_ = getDefaultInstance().getOperationId(); onChanged(); return this; } /** * <pre> * If empty, the new update request is assigned an * automatically-generated operation ID. Otherwise, `operation_id` * is used to construct the name of the resulting * [Operation][google.longrunning.Operation]. * Specifying an explicit operation ID simplifies determining * whether the statements were executed in the event that the * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] call is replayed, * or the return value is otherwise lost: the [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] and * `operation_id` fields can be combined to form the * [name][google.longrunning.Operation.name] of the resulting * [longrunning.Operation][google.longrunning.Operation]: `&lt;database&gt;/operations/&lt;operation_id&gt;`. * `operation_id` should be unique within the database, and must be * a valid identifier: `[a-z][a-z0-9_]*`. Note that * automatically-generated operation IDs always begin with an * underscore. If the named operation already exists, * [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] returns * `ALREADY_EXISTS`. * </pre> * * <code>optional string operation_id = 3;</code> */ public Builder setOperationIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); operationId_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder setDatabaseWithDatabaseName(com.google.spanner.admin.database.v1.DatabaseName value) { if (value == null) { return setDatabase(""); } return setDatabase(value.toString()); } public final com.google.spanner.admin.database.v1.DatabaseName getDatabaseAsDatabaseName() { java.lang.String str = getDatabase(); if (str.isEmpty()) { return null; } return com.google.spanner.admin.database.v1.DatabaseName.parse(str); } // @@protoc_insertion_point(builder_scope:google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) } public final com.google.spanner.admin.database.v1.DatabaseName getDatabaseAsDatabaseName() { java.lang.String str = getDatabase(); if (str.isEmpty()) { return null; } return com.google.spanner.admin.database.v1.DatabaseName.parse(str); } // @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) private static final com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(); } public static com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateDatabaseDdlRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateDatabaseDdlRequest>() { public UpdateDatabaseDdlRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UpdateDatabaseDdlRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UpdateDatabaseDdlRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateDatabaseDdlRequest> getParserForType() { return PARSER; } public com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package edu.ur.ir.oai.metadata.provider.service; import java.util.Date; import org.marc4j.marc.Record; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import edu.ur.ir.export.MarcExportService; import edu.ur.ir.institution.DeletedInstitutionalItemVersion; import edu.ur.ir.institution.InstitutionalCollection; import edu.ur.ir.institution.InstitutionalItemVersion; import edu.ur.ir.oai.OaiUtil; import edu.ur.ir.oai.metadata.provider.ListSetsService; import edu.ur.ir.oai.metadata.provider.OaiMetadataProvider; import edu.ur.ir.person.BasicPersonNameFormatter; public class DefaultMarcOaiMetadataProvider implements OaiMetadataProvider{ /** eclipse generated id */ private static final long serialVersionUID = -8227691687049064056L; /** Prefix handled by this provider */ public static String METADATA_PREFIX = "marc21"; public static String METADATA_NAMESPACE = "http://urresearch.rochester.edu/OAI/2.0/marc21/"; public static String SCHEMA = "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"; MarcXmlElementAppender marcXmlAppender = new MarcXmlElementAppender(); /** Person name formatter */ private BasicPersonNameFormatter nameFormatter; /** namespace for the oai url */ private String namespaceIdentifier; /** service to deal with listing set information */ private ListSetsService listSetsService; // the marc export service private MarcExportService marcExportService; /** * Get the xml output for the item * * @see edu.ur.ir.oai.metadata.provider.OaiMetadataProvider#getMetadata(edu.ur.ir.institution.InstitutionalItemVersion) */ public void addXml(Element record, InstitutionalItemVersion institutionalItemVersion) { Document doc = record.getOwnerDocument(); // create the header createHeader(doc, record, institutionalItemVersion); boolean showAllFields = false; if( institutionalItemVersion.getItem().isPubliclyViewable() && !institutionalItemVersion.getItem().isEmbargoed() && !institutionalItemVersion.isWithdrawn() ) { showAllFields = true; } Element metadataTag = doc.createElement("metadata"); record.appendChild(metadataTag); Record marcRecord = marcExportService.export(institutionalItemVersion, showAllFields, false); marcXmlAppender.addToDocument(marcRecord, doc, metadataTag); } /** * * @see edu.ur.ir.oai.metadata.provider.OaiMetadataProvider#getMetadataPrefixSupport() */ public String getMetadataPrefix() { return METADATA_PREFIX; } /** * @see edu.ur.ir.oai.metadata.provider.OaiMetadataProvider#supportsPrefix(java.lang.String) */ public boolean supports(String metadataPrefix) { return METADATA_PREFIX.equalsIgnoreCase(metadataPrefix); } /** * Create the header for the item. * * @param doc * @param institutionalItemVersion */ private void createHeader(Document doc, Element record, InstitutionalItemVersion institutionalItemVersion) { // create the header element of the record Element header = doc.createElement("header"); record.appendChild(header); // identifier element Element identifier = doc.createElement("identifier"); Text data = doc.createTextNode("oai:" + namespaceIdentifier + ":" + institutionalItemVersion.getId().toString()); identifier.appendChild(data); header.appendChild(identifier); // datestamp element Element datestamp = doc.createElement("datestamp"); Date d = institutionalItemVersion.getDateLastModified(); if( d == null ) { d = institutionalItemVersion.getDateOfDeposit(); } String zuluDateTime = OaiUtil.getZuluTime(d); data = doc.createTextNode(zuluDateTime); datestamp.appendChild(data); header.appendChild(datestamp); InstitutionalCollection collection = institutionalItemVersion.getVersionedInstitutionalItem().getInstitutionalItem().getInstitutionalCollection(); Element setSpec = doc.createElement("setSpec"); data = doc.createTextNode(listSetsService.getSetSpec(collection)); setSpec.appendChild(data); header.appendChild(setSpec); } public BasicPersonNameFormatter getNameFormatter() { return nameFormatter; } public void setNameFormatter(BasicPersonNameFormatter nameFormatter) { this.nameFormatter = nameFormatter; } public String getNamespaceIdentifier() { return namespaceIdentifier; } public void setNamespaceIdentifier(String namespaceIdentifier) { this.namespaceIdentifier = namespaceIdentifier; } public ListSetsService getListSetsService() { return listSetsService; } public void setListSetsService(ListSetsService listSetsService) { this.listSetsService = listSetsService; } /** * Get the namespace for the provider * * @see edu.ur.ir.oai.metadata.provider.OaiMetadataProvider#getNamespace() */ public String getMetadataNamespace() { return METADATA_NAMESPACE; } /* (non-Javadoc) * @see edu.ur.ir.oai.metadata.provider.OaiMetadataProvider#getSchema() */ public String getSchema() { return SCHEMA; } public void addXml(Element record, DeletedInstitutionalItemVersion institutionalItemVersion) { Document doc = record.getOwnerDocument(); // create the header createHeader(doc, record, institutionalItemVersion); } /** * Create the header for the deleted item. * * @param doc * @param deletedInstitutionalItemVersion */ private void createHeader(Document doc, Element record, DeletedInstitutionalItemVersion institutionalItemVersion) { // create the header element of the record Element header = doc.createElement("header"); record.appendChild(header); // identifier element Element identifier = doc.createElement("identifier"); header.setAttribute("status", "deleted"); Text data = doc.createTextNode("oai:" + namespaceIdentifier + ":" + institutionalItemVersion.getInstitutionalItemVersionId().toString()); identifier.appendChild(data); header.appendChild(identifier); // datestamp element Element datestamp = doc.createElement("datestamp"); Date d = institutionalItemVersion.getDeletedInstitutionalItem().getDeletedDate(); String zuluDateTime = OaiUtil.getZuluTime(d); data = doc.createTextNode(zuluDateTime); datestamp.appendChild(data); header.appendChild(datestamp); Long collectionId = institutionalItemVersion.getDeletedInstitutionalItem().getInstitutionalCollectionId(); if( collectionId != null ) { String setSpecStr = listSetsService.getSetSpec(collectionId); if( setSpecStr != null ) { Element setSpec = doc.createElement("setSpec"); data = doc.createTextNode(setSpecStr); setSpec.appendChild(data); header.appendChild(setSpec); } } } /** * Set the marc export service. * * @param marcExportService */ public void setMarcExportService(MarcExportService marcExportService) { this.marcExportService = marcExportService; } }
package org.sakaiproject.event.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sakaiproject.event.api.EventQueryService; import org.sakaiproject.util.Xml; import org.w3c.dom.Document; import org.w3c.dom.Node; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.sakaiproject.db.api.SqlService; /** * Implementation of EventQueryService * It returns xml event lists for a given user eid. */ public class EventQueryServiceImpl implements EventQueryService { private static Logger log = LoggerFactory.getLogger(EventQueryServiceImpl.class); private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * Returns a list of events of a user between 2 dates. * @param eid is the user that we want to query * @param startDate limit the query ti these dates * @param endDate limit the query ti these dates * @return String as the result of the Query in xml */ public String getUserActivity(String eid, Date startDate, Date endDate) { String query = "select se.EVENT_ID, se.EVENT_DATE, se.EVENT, se.REF, se.CONTEXT, se.EVENT_CODE, um.USER_ID, um.EID from " + "SAKAI_EVENT se, SAKAI_SESSION ss, SAKAI_USER_ID_MAP um " + "where se.SESSION_ID = ss.SESSION_ID and um.EID = ? and "; if (sqlService.getVendor().equals("oracle")) { query += "EVENT_DATE BETWEEN to_date(?, 'YYYY-MM-DD HH24:MI') AND to_date(?, 'YYYY-MM-DD HH24:MI') "; } else { query += "EVENT_DATE BETWEEN ? AND ?"; } query += " and um.USER_ID = ss.SESSION_USER order by se.EVENT_DATE desc"; return queryEventTableWithEid(query, new Object[]{eid, startDate, endDate}); } /** * Returns a list of events of a user between 2 dates. * @param eid is the user that we want to query * @param startDateString limit the query ti these dates. In this case as String if we call it as a rest * @param endDateString limit the query ti these dates. In this case as String if we call it as a rest * @return String as the result of the Query in xml */ public String getUserActivityRestVersion(String eid, String startDateString, String endDateString) { Date startDate; Date endDate; try { startDate = getDateFromString(startDateString); endDate = getDateFromString(endDateString); } catch (ParseException e) { return "Activity Webservices exception : " + e.getMessage(); } String query = "select se.EVENT_ID, se.EVENT_DATE, se.EVENT, se.REF, se.CONTEXT, se.EVENT_CODE, um.USER_ID, um.EID from " + "SAKAI_EVENT se, SAKAI_SESSION ss, SAKAI_USER_ID_MAP um " + "where se.SESSION_ID = ss.SESSION_ID and um.EID = ? and "; if (sqlService.getVendor().equals("oracle")) { query += "EVENT_DATE BETWEEN to_date(?, 'YYYY-MM-DD HH24:MI') AND to_date(?, 'YYYY-MM-DD HH24:MI') "; } else { query += "EVENT_DATE BETWEEN ? AND ?"; } query += " and um.USER_ID = ss.SESSION_USER order by se.EVENT_DATE desc"; return queryEventTableWithEid(query, new Object[]{eid, startDate, endDate}); } /** * Returns the User's logon activity. * @param eid is the user that we want to query * @return String as the result of the Query in xml */ public String getUserLogonActivity(String eid) { String query = ("select se.EVENT_ID, se.EVENT_DATE, se.EVENT, se.REF, se.CONTEXT, se.EVENT_CODE, um.USER_ID, um.EID from " + "SAKAI_EVENT se, SAKAI_SESSION ss, SAKAI_USER_ID_MAP um " + "where se.SESSION_ID = ss.SESSION_ID and um.EID = ? and " + "um.USER_ID = ss.SESSION_USER and se.EVENT = 'user.login' order by se.EVENT_DATE desc"); return queryEventTableWithEid(query, new Object[]{eid}); } /** * Returns the User's activity filtered by one event type. * @param eid is the user that we want to query * @param eventType the event type to filter * @return String as the result of the Query in xml */ public String getUserActivityByType(String eid, String eventType) { String query = ("select se.EVENT_ID, se.EVENT_DATE, se.EVENT, se.REF, se.CONTEXT, se.EVENT_CODE, um.USER_ID, um.EID from " + "SAKAI_EVENT se, SAKAI_SESSION ss, SAKAI_USER_ID_MAP um " + "where se.SESSION_ID = ss.SESSION_ID and um.EID = ? and " + "um.USER_ID = ss.SESSION_USER and se.EVENT = ? order by se.EVENT_DATE desc"); return queryEventTableWithEid(query, new Object[]{eid, eventType}); } /** * Parses the string to create a date object */ private Date getDateFromString(String dateString) throws ParseException { try { Date date = df.parse(dateString); return date; } catch (ParseException e) { log.warn("Date format should be yyyy-MM-dd HH:mm:ss"); throw new ParseException("Date format should be yyyy-MM-dd HH:mm:ss",e.getErrorOffset()); } } /** * Executes the query */ private String queryEventTableWithEid(String query, Object[] args) { Document doc = Xml.createDocument(); Node results = doc.createElement("events"); doc.appendChild(results); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; boolean returnErrorMessage = false; String errorMessage = ""; try { conn = sqlService.borrowConnection(); ps = conn.prepareStatement(query); for (int i = 0; i < args.length; i++) { if (args[i] instanceof String) { ps.setString(i + 1, (String) args[i]); } else if (args[i] instanceof Date) { ps.setString(i + 1, df.format(args[i])); long date = ((Date) args[i]).getTime(); } } rs = ps.executeQuery(); buildXmlFromResultSet(results, rs); } catch (Exception e) { log.error(e.getMessage(), e); returnErrorMessage = true; errorMessage= "Activity Webservices exception :" + e.getMessage(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (ps != null) { try { ps.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } if (returnErrorMessage) return errorMessage; } return Xml.writeDocumentToString(doc); } /** * Creates the xml result based in the SQL query */ private Document buildXmlFromResultSet(Node results, ResultSet rs) throws SQLException { Document doc = results.getOwnerDocument(); while (rs.next()) { Node eventNode = doc.createElement("event"); results.appendChild(eventNode); Node id = doc.createElement("event_id"); id.appendChild(doc.createTextNode(rs.getString("EVENT_ID"))); eventNode.appendChild(id); Node event_date = doc.createElement("event_date"); event_date.appendChild(doc.createTextNode(df.format(rs.getTimestamp("EVENT_DATE")))); eventNode.appendChild(event_date); Node event = doc.createElement("event_type"); event.appendChild(doc.createTextNode(rs.getString("EVENT"))); eventNode.appendChild(event); Node ref = doc.createElement("ref"); ref.appendChild(doc.createTextNode(rs.getString("REF"))); eventNode.appendChild(ref); Node context = doc.createElement("context"); context.appendChild(doc.createTextNode(rs.getString("CONTEXT"))); eventNode.appendChild(context); Node event_code = doc.createElement("event_code"); event_code.appendChild(doc.createTextNode(rs.getString("EVENT_CODE"))); eventNode.appendChild(event_code); Node user_id = doc.createElement("user_id"); user_id.appendChild(doc.createTextNode(rs.getString("USER_ID"))); eventNode.appendChild(user_id); Node eidNode = doc.createElement("eid"); eidNode.appendChild(doc.createTextNode(rs.getString("EID"))); eventNode.appendChild(eidNode); } return doc; } /************************************************************************************************************************************************* * Dependencies ************************************************************************************************************************************************/ /** Dependency: SqlService. */ protected SqlService sqlService; public void setSqlService(SqlService sqlService) { this.sqlService = sqlService; } /********************************************************************************************************************************************************************************************************************************************************** * Init and Destroy *********************************************************************************************************************************************************************************************************************************************************/ /** * Init method. */ public void init() { log.info(this + ".init()"); } /** * Final cleanup. */ public void destroy() { log.info(this + ".destroy()"); } }
/* * 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.presto.execution; import com.google.common.base.Ticker; import io.airlift.units.Duration; import org.joda.time.DateTime; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import static io.airlift.units.Duration.succinctNanos; import static java.lang.Math.max; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; // Query time workflow chart. Left side shows query workflow. Right side shows // associated time durations with a query. // // Create ----------- // | | waitingForPrerequisitesTime // V V // Queued ----------- // | | queuedTime // V V // Wait for Resources ----------- // | | waitingForResourcesTime // V V // Dispatching ----------- // | | dispatchingTime // V V // Planning ---------------------------------- // | | executionTime | planningTime // | Analysis Start | | ----------- // | | | | | analysisTime // | V | | V // | Analysis End | | ----------- // V | V // Starting | ----------- // | | // V | // Running | // | | // V | // Finishing | ----------- // | | | finishingTime // V V V // End ---------------------------------- public class QueryStateTimer { private final Ticker ticker; private final DateTime createTime = DateTime.now(); private final long createNanos; private final AtomicReference<Long> beginQueuedNanos = new AtomicReference<>(); private final AtomicReference<Long> beginResourceWaitingNanos = new AtomicReference<>(); private final AtomicReference<Long> beginDispatchingNanos = new AtomicReference<>(); private final AtomicReference<Long> beginPlanningNanos = new AtomicReference<>(); private final AtomicReference<Long> beginFinishingNanos = new AtomicReference<>(); private final AtomicReference<Long> endNanos = new AtomicReference<>(); private final AtomicReference<Duration> waitingForPrerequisitesTime = new AtomicReference<>(); private final AtomicReference<Duration> queuedTime = new AtomicReference<>(); private final AtomicReference<Duration> resourceWaitingTime = new AtomicReference<>(); private final AtomicReference<Duration> dispatchingTime = new AtomicReference<>(); private final AtomicReference<Duration> executionTime = new AtomicReference<>(); private final AtomicReference<Duration> planningTime = new AtomicReference<>(); private final AtomicReference<Duration> finishingTime = new AtomicReference<>(); private final AtomicReference<Long> beginAnalysisNanos = new AtomicReference<>(); private final AtomicReference<Duration> analysisTime = new AtomicReference<>(); private final AtomicReference<Long> lastHeartbeatNanos; public QueryStateTimer(Ticker ticker) { this.ticker = requireNonNull(ticker, "ticker is null"); this.createNanos = tickerNanos(); this.lastHeartbeatNanos = new AtomicReference<>(createNanos); } // // State transitions // public void beginQueued() { beginQueued(tickerNanos()); } private void beginQueued(long now) { waitingForPrerequisitesTime.compareAndSet(null, nanosSince(createNanos, now)); beginQueuedNanos.compareAndSet(null, now); } public void beginWaitingForResources() { beginWaitingForResources(tickerNanos()); } private void beginWaitingForResources(long now) { beginQueued(now); queuedTime.compareAndSet(null, nanosSince(beginQueuedNanos, now)); beginResourceWaitingNanos.compareAndSet(null, now); } public void beginDispatching() { beginDispatching(tickerNanos()); } private void beginDispatching(long now) { beginWaitingForResources(now); resourceWaitingTime.compareAndSet(null, nanosSince(beginResourceWaitingNanos, now)); beginDispatchingNanos.compareAndSet(null, now); } public void beginPlanning() { beginPlanning(tickerNanos()); } private void beginPlanning(long now) { beginDispatching(now); dispatchingTime.compareAndSet(null, nanosSince(beginDispatchingNanos, now)); beginPlanningNanos.compareAndSet(null, now); } public void beginStarting() { beginStarting(tickerNanos()); } private void beginStarting(long now) { beginPlanning(now); planningTime.compareAndSet(null, nanosSince(beginPlanningNanos, now)); } public void beginRunning() { beginRunning(tickerNanos()); } private void beginRunning(long now) { beginStarting(now); } public void beginFinishing() { beginFinishing(tickerNanos()); } private void beginFinishing(long now) { beginRunning(now); beginFinishingNanos.compareAndSet(null, now); } public void endQuery() { endQuery(tickerNanos()); } private void endQuery(long now) { beginFinishing(now); finishingTime.compareAndSet(null, nanosSince(beginFinishingNanos, now)); executionTime.compareAndSet(null, nanosSince(beginPlanningNanos, now)); endNanos.compareAndSet(null, now); } // // Additional timings // public void beginAnalyzing() { beginAnalysisNanos.compareAndSet(null, tickerNanos()); } public void endAnalysis() { analysisTime.compareAndSet(null, nanosSince(beginAnalysisNanos, tickerNanos())); } public void recordHeartbeat() { lastHeartbeatNanos.set(tickerNanos()); } // // Stats // public DateTime getCreateTime() { return createTime; } public Optional<DateTime> getExecutionStartTime() { return toDateTime(beginPlanningNanos); } public Duration getElapsedTime() { if (endNanos.get() != null) { return succinctNanos(endNanos.get() - createNanos); } return nanosSince(createNanos, tickerNanos()); } public Duration getWaitingForPrerequisitesTime() { Duration waitingForPrerequisitesTime = this.waitingForPrerequisitesTime.get(); if (waitingForPrerequisitesTime != null) { return waitingForPrerequisitesTime; } // if prerequisite wait time is not set, the query is still waiting for prerequisites to finish return getElapsedTime(); } public Duration getQueuedTime() { return getDuration(queuedTime, beginQueuedNanos); } public Duration getResourceWaitingTime() { return getDuration(resourceWaitingTime, beginResourceWaitingNanos); } public Duration getDispatchingTime() { return getDuration(dispatchingTime, beginDispatchingNanos); } public Duration getPlanningTime() { return getDuration(planningTime, beginPlanningNanos); } public Duration getFinishingTime() { return getDuration(finishingTime, beginFinishingNanos); } public Duration getExecutionTime() { return getDuration(executionTime, beginPlanningNanos); } public Optional<DateTime> getEndTime() { return toDateTime(endNanos); } public Duration getAnalysisTime() { return getDuration(analysisTime, beginAnalysisNanos); } public DateTime getLastHeartbeat() { return toDateTime(lastHeartbeatNanos.get()); } // // Helper methods // private long tickerNanos() { return ticker.read(); } private static Duration nanosSince(AtomicReference<Long> start, long end) { Long startNanos = start.get(); if (startNanos == null) { throw new IllegalStateException("Start time not set"); } return nanosSince(startNanos, end); } private static Duration nanosSince(long start, long now) { return succinctNanos(max(0, now - start)); } private Duration getDuration(AtomicReference<Duration> finalDuration, AtomicReference<Long> start) { Duration duration = finalDuration.get(); if (duration != null) { return duration; } Long startNanos = start.get(); if (startNanos != null) { return nanosSince(startNanos, tickerNanos()); } return new Duration(0, MILLISECONDS); } private Optional<DateTime> toDateTime(AtomicReference<Long> instantNanos) { Long nanos = instantNanos.get(); if (nanos == null) { return Optional.empty(); } return Optional.of(toDateTime(nanos)); } private DateTime toDateTime(long instantNanos) { long millisSinceCreate = NANOSECONDS.toMillis(instantNanos - createNanos); return new DateTime(createTime.getMillis() + millisSinceCreate); } }
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.css.compiler.passes; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.css.JobDescription.SourceMapDetailLevel; import com.google.common.css.compiler.ast.CssNode; import com.google.debugging.sourcemap.FilePosition; import com.google.debugging.sourcemap.SourceMapFormat; import com.google.debugging.sourcemap.SourceMapGenerator; import com.google.debugging.sourcemap.SourceMapGeneratorFactory; import com.google.debugging.sourcemap.SourceMapGeneratorV3; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; /** * Class to collect and generate source map(v3) for Gss compiler. It is intended to be used by * {@link com.google.common.css.compiler.passes.CodePrinter}. * * <p>Source Map Revision 3 Proposal: * https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?usp=sharing * * @see com.google.debugging.sourcemap.SourceMapGeneratorV3 * * @author steveyang@google.com (Chenyun Yang) */ public final class DefaultGssSourceMapGenerator implements GssSourceMapGenerator { /** The underlying source map generator to use. */ private SourceMapGenerator generator; /** * Maintains a mapping from a given node's source code position to its generated output. * This position is relative to the current run of the CodePrinter and will be normalized * later on by the SourceMap. */ static class Mapping { CssNode node; FilePosition start; FilePosition end; } /** * Map used internally to get {@code Predicate<CssNode>}s from {@code DetailLevel}. * * <ul> * <li>{@code ALL} provides the most details by generating source map for every nodes containing * source locations. * <li>{@code DEFAULT} generates source map for selected nodes and results in a smaller output * suitable to use in production. * </ul> */ private static final ImmutableMap<SourceMapDetailLevel, Predicate<CssNode>> DETAIL_LEVEL_PREDICATES = Maps.immutableEnumMap( ImmutableMap.of( SourceMapDetailLevel.ALL, Predicates.<CssNode>alwaysTrue(), SourceMapDetailLevel.DEFAULT, Predicates.<CssNode>alwaysTrue())); /** Deque to hold current mappings on stack while visiting the subtree. **/ private final Deque<Mapping> mappings; /** List of all the mappings generated for code visit **/ private final List<Mapping> allMappings; private SourceMapDetailLevel sourceMapDetailLevel; /** Predicate to determine whether to include current node under visit into {@code mappings}. **/ private Predicate<CssNode> detailLevelPredicate; /** * Constructor to get source map class to use. * * @param sourceMapDetailLevel used to control the output details of source map */ public DefaultGssSourceMapGenerator(SourceMapDetailLevel sourceMapDetailLevel) { Preconditions.checkState(sourceMapDetailLevel != null); this.mappings = new ArrayDeque<>(); this.generator = SourceMapGeneratorFactory.getInstance(SourceMapFormat.V3); this.allMappings = new ArrayList<>(); this.sourceMapDetailLevel = sourceMapDetailLevel; this.detailLevelPredicate = DETAIL_LEVEL_PREDICATES.get(this.sourceMapDetailLevel); } /** * Appends the generated source map to {@code out}. * * @param out an {@link Appendable} object to append the output on * @param name filename to be written inside the source map (not the filename where writes to) * * @see SourceMapGeneratorV3#appendTo */ @Override public void appendOutputTo(Appendable out, String name) throws IOException { generateSourceMap(); generator.appendTo(out, name); } /** * Starts the source mapping for the given node at the current position. * This is intended to be called before the node is written to the buffer. * * @param node the {@link CssNode} to be processed * @param startLine the first character's line number once it starts writing output * @param startCharIndex the first character's character index once it starts writing output */ @Override public void startSourceMapping(CssNode node, int startLine, int startCharIndex) { Preconditions.checkState(node != null); Preconditions.checkState(startLine >= 0); Preconditions.checkState(startCharIndex >= 0); if (node.getSourceCodeLocation() != null && detailLevelPredicate.apply(node)) { Mapping mapping = new Mapping(); mapping.node = node; mapping.start = new FilePosition(startLine, startCharIndex); mappings.push(mapping); allMappings.add(mapping); } } /** * Finishes the source mapping for the given node at the current position. * This is intended to be called immediately after the whole node is written to the buffer. * * @param node the {@link CssNode} to be processed * @param endLine the last character's line number when it ends writing output * @param endCharIndex the last character's character index when it ends writing output */ @Override public void endSourceMapping(CssNode node, int endLine, int endCharIndex) { Preconditions.checkState(node != null); Preconditions.checkState(endLine >= 0); // -1 when a node contributes no content at the start of the buffer, // as when a CssImportBlockNode is encountered, and there is no // copyright comment. Preconditions.checkState(endCharIndex >= -1); endCharIndex++; // if (!mappings.isEmpty() && mappings.peek().node == node) { Mapping mapping = mappings.pop(); mapping.end = new FilePosition(endLine, endCharIndex); } } /** * Sets the prefix to be added to the beginning of each source path passed to * {@link #addMapping} as debuggers expect (prefix + sourceName) to be a URL * for loading the source code. * * @param path The URL prefix to save in the sourcemap file */ @Override public void setSourceRoot(String path){ ((SourceMapGeneratorV3) generator).setSourceRoot(path); } /** * Generates the source map by passing all mappings to {@link #generator}. */ private void generateSourceMap() { List<CompleteMapping> completeMappings = new ArrayList<>(allMappings.size()); for (Mapping mapping : allMappings) { // If the node does not have an associated source file or source location // is unknown, then the node does not have sufficient info for source map. if (mapping.node.getSourceCodeLocation().isUnknown()) { continue; } CompleteMapping completeMapping = new CompleteMapping(mapping); if (completeMapping.sourceFile == null) { continue; } completeMappings.add(completeMapping); } Collections.sort(completeMappings); for (CompleteMapping completeMapping : completeMappings) { // TODO: could pass in an optional symbol name generator.addMapping( completeMapping.sourceFile, null, completeMapping.inputStart, completeMapping.outputStart, completeMapping.outputEnd); } } private static final class CompleteMapping implements Comparable<CompleteMapping> { final String sourceFile; final FilePosition inputStart; final FilePosition outputStart; final FilePosition outputEnd; CompleteMapping(Mapping mapping) { CssNode node = mapping.node; this.sourceFile = getSourceFileName(node); this.inputStart = new FilePosition( getStartLineno(node), getStartCharIndex(node)); this.outputStart = mapping.start; this.outputEnd = mapping.end; } @Override public int compareTo(CompleteMapping m) { int delta = outputStart.getLine() - m.outputStart.getLine(); if (delta == 0) { delta = outputStart.getColumn() - m.outputStart.getColumn(); } return delta; } /** * Gets the source file file for current node. */ private static String getSourceFileName(CssNode node) { return node.getSourceCodeLocation().getSourceCode().getFileName(); } /** * Gets the start line index in the source code of {@code node} adjusted to 0-based indices. * * <p> * Note: Gss compiler uses a 1-based line number and source map V3 uses a 0-based line number. */ private static int getStartLineno(CssNode node) { return node.getSourceCodeLocation().getLineNumber() - 1; } /** * Gets the start character index in the output buffer for current {@code node}. */ private static int getStartCharIndex(CssNode node) { return node.getSourceCodeLocation().getCharacterIndex(); } } }
/* * 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.zeppelin.server; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import javax.net.ssl.SSLContext; import javax.servlet.DispatcherType; import javax.servlet.Servlet; import javax.ws.rs.core.Application; import org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet; import org.apache.zeppelin.conf.ZeppelinConfiguration; import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars; import org.apache.zeppelin.interpreter.InterpreterFactory; import org.apache.zeppelin.notebook.Notebook; import org.apache.zeppelin.notebook.repo.NotebookRepo; import org.apache.zeppelin.notebook.repo.NotebookRepoSync; import org.apache.zeppelin.rest.InterpreterRestApi; import org.apache.zeppelin.rest.NotebookRestApi; import org.apache.zeppelin.rest.ZeppelinRestApi; import org.apache.zeppelin.scheduler.SchedulerFactory; import org.apache.zeppelin.socket.NotebookServer; import org.eclipse.jetty.server.AbstractConnector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Main class of Zeppelin. * * @author Leemoonsoo * */ public class ZeppelinServer extends Application { private static final Logger LOG = LoggerFactory.getLogger(ZeppelinServer.class); private SchedulerFactory schedulerFactory; public static Notebook notebook; public static NotebookServer notebookServer; public static Server jettyServer; private InterpreterFactory replFactory; private NotebookRepo notebookRepo; public static void main(String[] args) throws Exception { ZeppelinConfiguration conf = ZeppelinConfiguration.create(); conf.setProperty("args", args); jettyServer = setupJettyServer(conf); // REST api final ServletContextHandler restApi = setupRestApiContextHandler(conf); // Notebook server final ServletContextHandler notebook = setupNotebookServer(conf); // Web UI final WebAppContext webApp = setupWebAppContext(conf); // add all handlers ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[]{restApi, notebook, webApp}); jettyServer.setHandler(contexts); LOG.info("Start zeppelin server"); try { jettyServer.start(); } catch (Exception e) { LOG.error("Error while running jettyServer", e); System.exit(-1); } LOG.info("Started zeppelin server"); Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { LOG.info("Shutting down Zeppelin Server ... "); try { jettyServer.stop(); ZeppelinServer.notebook.getInterpreterFactory().close(); } catch (Exception e) { LOG.error("Error while stopping servlet container", e); } LOG.info("Bye"); } }); // when zeppelin is started inside of ide (especially for eclipse) // for graceful shutdown, input any key in console window if (System.getenv("ZEPPELIN_IDENT_STRING") == null) { try { System.in.read(); } catch (IOException e) { } System.exit(0); } jettyServer.join(); ZeppelinServer.notebook.getInterpreterFactory().close(); } private static Server setupJettyServer(ZeppelinConfiguration conf) throws Exception { AbstractConnector connector; if (conf.useSsl()) { connector = new SslSelectChannelConnector(getSslContextFactory(conf)); } else { connector = new SelectChannelConnector(); } // Set some timeout options to make debugging easier. int timeout = 1000 * 30; connector.setMaxIdleTime(timeout); connector.setSoLingerTime(-1); connector.setHost(conf.getServerAddress()); connector.setPort(conf.getServerPort()); final Server server = new Server(); server.addConnector(connector); return server; } private static ServletContextHandler setupNotebookServer(ZeppelinConfiguration conf) throws Exception { notebookServer = new NotebookServer(); final ServletHolder servletHolder = new ServletHolder(notebookServer); servletHolder.setInitParameter("maxTextMessageSize", "1024000"); final ServletContextHandler cxfContext = new ServletContextHandler( ServletContextHandler.SESSIONS); cxfContext.setSessionHandler(new SessionHandler()); cxfContext.setContextPath(conf.getServerContextPath()); cxfContext.addServlet(servletHolder, "/ws/*"); cxfContext.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class)); return cxfContext; } private static SslContextFactory getSslContextFactory(ZeppelinConfiguration conf) throws Exception { // Note that the API for the SslContextFactory is different for // Jetty version 9 SslContextFactory sslContextFactory = new SslContextFactory(); // Set keystore sslContextFactory.setKeyStore(conf.getKeyStorePath()); sslContextFactory.setKeyStoreType(conf.getKeyStoreType()); sslContextFactory.setKeyStorePassword(conf.getKeyStorePassword()); sslContextFactory.setKeyManagerPassword(conf.getKeyManagerPassword()); // Set truststore sslContextFactory.setTrustStore(conf.getTrustStorePath()); sslContextFactory.setTrustStoreType(conf.getTrustStoreType()); sslContextFactory.setTrustStorePassword(conf.getTrustStorePassword()); sslContextFactory.setNeedClientAuth(conf.useClientAuth()); return sslContextFactory; } private static SSLContext getSslContext(ZeppelinConfiguration conf) throws Exception { SslContextFactory scf = getSslContextFactory(conf); if (!scf.isStarted()) { scf.start(); } return scf.getSslContext(); } private static ServletContextHandler setupRestApiContextHandler(ZeppelinConfiguration conf) { final ServletHolder cxfServletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet()); cxfServletHolder.setInitParameter("javax.ws.rs.Application", ZeppelinServer.class.getName()); cxfServletHolder.setName("rest"); cxfServletHolder.setForcedPath("rest"); final ServletContextHandler cxfContext = new ServletContextHandler(); cxfContext.setSessionHandler(new SessionHandler()); cxfContext.setContextPath(conf.getServerContextPath()); cxfContext.addServlet(cxfServletHolder, "/api/*"); cxfContext.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class)); return cxfContext; } private static WebAppContext setupWebAppContext( ZeppelinConfiguration conf) { WebAppContext webApp = new WebAppContext(); webApp.setContextPath(conf.getServerContextPath()); File warPath = new File(conf.getString(ConfVars.ZEPPELIN_WAR)); if (warPath.isDirectory()) { // Development mode, read from FS // webApp.setDescriptor(warPath+"/WEB-INF/web.xml"); webApp.setResourceBase(warPath.getPath()); webApp.setParentLoaderPriority(true); } else { // use packaged WAR webApp.setWar(warPath.getAbsolutePath()); } // Explicit bind to root webApp.addServlet( new ServletHolder(new DefaultServlet()), "/*" ); return webApp; } public ZeppelinServer() throws Exception { ZeppelinConfiguration conf = ZeppelinConfiguration.create(); this.schedulerFactory = new SchedulerFactory(); this.replFactory = new InterpreterFactory(conf, notebookServer); this.notebookRepo = new NotebookRepoSync(conf); notebook = new Notebook(conf, notebookRepo, schedulerFactory, replFactory, notebookServer); } @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); return classes; } @Override public java.util.Set<java.lang.Object> getSingletons() { Set<Object> singletons = new HashSet<Object>(); /** Rest-api root endpoint */ ZeppelinRestApi root = new ZeppelinRestApi(); singletons.add(root); NotebookRestApi notebookApi = new NotebookRestApi(notebook, notebookServer); singletons.add(notebookApi); InterpreterRestApi interpreterApi = new InterpreterRestApi(replFactory); singletons.add(interpreterApi); return singletons; } }
/* * 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.zeppelin.livy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import org.apache.commons.lang3.StringUtils; import org.apache.zeppelin.interpreter.InterpreterContext; import org.apache.zeppelin.interpreter.InterpreterResult; import org.apache.zeppelin.interpreter.InterpreterResult.Code; import org.apache.zeppelin.interpreter.InterpreterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.security.kerberos.client.KerberosRestTemplate; import org.springframework.web.client.RestTemplate; import java.nio.charset.Charset; import java.util.*; import java.util.Map.Entry; /*** * Livy helper class */ public class LivyHelper { Logger LOGGER = LoggerFactory.getLogger(LivyHelper.class); Gson gson = new GsonBuilder().setPrettyPrinting().create(); HashMap<String, Object> paragraphHttpMap = new HashMap<>(); Properties property; Integer MAX_NOS_RETRY = 60; LivyHelper(Properties property) { this.property = property; } public Integer createSession(InterpreterContext context, String kind) throws Exception { try { Map<String, String> conf = new HashMap<String, String>(); Iterator<Entry<Object, Object>> it = property.entrySet().iterator(); while (it.hasNext()) { Entry<Object, Object> pair = it.next(); if (pair.getKey().toString().startsWith("livy.spark.") && !pair.getValue().toString().isEmpty()) conf.put(pair.getKey().toString().substring(5), pair.getValue().toString()); } String confData = gson.toJson(conf); String user = context.getAuthenticationInfo().getUser(); String json = executeHTTP(property.getProperty("zeppelin.livy.url") + "/sessions", "POST", "{" + "\"kind\": \"" + kind + "\", " + "\"conf\": " + confData + ", " + "\"proxyUser\": " + (StringUtils.isEmpty(user) ? null : "\"" + user + "\"") + "}", context.getParagraphId() ); Map jsonMap = (Map<Object, Object>) gson.fromJson(json, new TypeToken<Map<Object, Object>>() { }.getType()); Integer sessionId = ((Double) jsonMap.get("id")).intValue(); if (!jsonMap.get("state").equals("idle")) { Integer nosRetry = MAX_NOS_RETRY; while (nosRetry >= 0) { LOGGER.error(String.format("sessionId:%s state is %s", jsonMap.get("id"), jsonMap.get("state"))); Thread.sleep(1000); json = executeHTTP(property.getProperty("zeppelin.livy.url") + "/sessions/" + sessionId, "GET", null, context.getParagraphId()); jsonMap = (Map<Object, Object>) gson.fromJson(json, new TypeToken<Map<Object, Object>>() { }.getType()); if (jsonMap.get("state").equals("idle")) { break; } else if (jsonMap.get("state").equals("error")) { json = executeHTTP(property.getProperty("zeppelin.livy.url") + "/sessions/" + sessionId + "/log", "GET", null, context.getParagraphId()); jsonMap = (Map<Object, Object>) gson.fromJson(json, new TypeToken<Map<Object, Object>>() { }.getType()); String logs = StringUtils.join((ArrayList<String>) jsonMap.get("log"), '\n'); LOGGER.error(String.format("Cannot start %s.\n%s", kind, logs)); throw new Exception(String.format("Cannot start %s.\n%s", kind, logs)); } nosRetry--; } if (nosRetry <= 0) { LOGGER.error("Error getting session for user within 60Sec."); throw new Exception(String.format("Cannot start %s.", kind)); } } return sessionId; } catch (Exception e) { LOGGER.error("Error getting session for user", e); throw e; } } protected void initializeSpark(final InterpreterContext context, final Map<String, Integer> userSessionMap) throws Exception { interpret("val sqlContext= new org.apache.spark.sql.SQLContext(sc)\n" + "import sqlContext.implicits._", context, userSessionMap); } public InterpreterResult interpretInput(String stringLines, final InterpreterContext context, final Map<String, Integer> userSessionMap, LivyOutputStream out) { try { String[] lines = stringLines.split("\n"); String[] linesToRun = new String[lines.length + 1]; for (int i = 0; i < lines.length; i++) { linesToRun[i] = lines[i]; } linesToRun[lines.length] = "print(\"\")"; out.setInterpreterOutput(context.out); context.out.clear(); Code r = null; String incomplete = ""; boolean inComment = false; for (int l = 0; l < linesToRun.length; l++) { String s = linesToRun[l]; // check if next line starts with "." (but not ".." or "./") it is treated as an invocation //for spark if (l + 1 < linesToRun.length) { String nextLine = linesToRun[l + 1].trim(); boolean continuation = false; if (nextLine.isEmpty() || nextLine.startsWith("//") // skip empty line or comment || nextLine.startsWith("}") || nextLine.startsWith("object")) { // include "} object" for Scala companion object continuation = true; } else if (!inComment && nextLine.startsWith("/*")) { inComment = true; continuation = true; } else if (inComment && nextLine.lastIndexOf("*/") >= 0) { inComment = false; continuation = true; } else if (nextLine.length() > 1 && nextLine.charAt(0) == '.' && nextLine.charAt(1) != '.' // ".." && nextLine.charAt(1) != '/') { // "./" continuation = true; } else if (inComment) { continuation = true; } if (continuation) { incomplete += s + "\n"; continue; } } InterpreterResult res; try { res = interpret(incomplete + s, context, userSessionMap); } catch (Exception e) { LOGGER.error("Interpreter exception", e); return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e)); } r = res.code(); if (r == Code.ERROR) { out.setInterpreterOutput(null); return res; } else if (r == Code.INCOMPLETE) { incomplete += s + "\n"; } else { out.write((res.message() + "\n").getBytes(Charset.forName("UTF-8"))); incomplete = ""; } } if (r == Code.INCOMPLETE) { out.setInterpreterOutput(null); return new InterpreterResult(r, "Incomplete expression"); } else { out.setInterpreterOutput(null); return new InterpreterResult(Code.SUCCESS); } } catch (Exception e) { LOGGER.error("error in interpretInput", e); return new InterpreterResult(Code.ERROR, e.getMessage()); } } public InterpreterResult interpret(String stringLines, final InterpreterContext context, final Map<String, Integer> userSessionMap) throws Exception { stringLines = stringLines //for "\n" present in string .replaceAll("\\\\n", "\\\\\\\\n") //for new line present in string .replaceAll("\\n", "\\\\n") // for \" present in string .replaceAll("\\\\\"", "\\\\\\\\\"") // for " present in string .replaceAll("\"", "\\\\\""); if (stringLines.trim().equals("")) { return new InterpreterResult(Code.SUCCESS, ""); } Map jsonMap = executeCommand(stringLines, context, userSessionMap); Integer id = ((Double) jsonMap.get("id")).intValue(); InterpreterResult res = getResultFromMap(jsonMap); if (res != null) { return res; } while (true) { Thread.sleep(1000); if (paragraphHttpMap.get(context.getParagraphId()) == null) { return new InterpreterResult(Code.INCOMPLETE, ""); } jsonMap = getStatusById(context, userSessionMap, id); InterpreterResult interpreterResult = getResultFromMap(jsonMap); if (interpreterResult != null) { return interpreterResult; } } } private InterpreterResult getResultFromMap(Map jsonMap) { if (jsonMap.get("state").equals("available")) { if (((Map) jsonMap.get("output")).get("status").equals("error")) { StringBuilder errorMessage = new StringBuilder((String) ((Map) jsonMap .get("output")).get("evalue")); if (errorMessage.toString().equals("incomplete statement") || errorMessage.toString().contains("EOF")) { return new InterpreterResult(Code.INCOMPLETE, ""); } String traceback = gson.toJson(((Map) jsonMap.get("output")).get("traceback")); if (!traceback.equals("[]")) { errorMessage .append("\n") .append("traceback: \n") .append(traceback); } return new InterpreterResult(Code.ERROR, errorMessage.toString()); } if (((Map) jsonMap.get("output")).get("status").equals("ok")) { String result = (String) ((Map) ((Map) jsonMap.get("output")) .get("data")).get("text/plain"); if (result != null) { result = result.trim(); if (result.startsWith("<link") || result.startsWith("<script") || result.startsWith("<style") || result.startsWith("<div")) { result = "%html " + result; } } return new InterpreterResult(Code.SUCCESS, result); } } return null; } private Map executeCommand(String lines, InterpreterContext context, Map<String, Integer> userSessionMap) throws Exception { String json = executeHTTP(property.get("zeppelin.livy.url") + "/sessions/" + userSessionMap.get(context.getAuthenticationInfo().getUser()) + "/statements", "POST", "{\"code\": \"" + lines + "\" }", context.getParagraphId()); if (json.matches("^(\")?Session (\'[0-9]\' )?not found(.?\"?)$")) { throw new Exception("Exception: Session not found, Livy server would have restarted, " + "or lost session."); } try { Map jsonMap = gson.fromJson(json, new TypeToken<Map>() { }.getType()); return jsonMap; } catch (Exception e) { LOGGER.error("Error executeCommand", e); throw e; } } private Map getStatusById(InterpreterContext context, Map<String, Integer> userSessionMap, Integer id) throws Exception { String json = executeHTTP(property.getProperty("zeppelin.livy.url") + "/sessions/" + userSessionMap.get(context.getAuthenticationInfo().getUser()) + "/statements/" + id, "GET", null, context.getParagraphId()); try { Map jsonMap = gson.fromJson(json, new TypeToken<Map>() { }.getType()); return jsonMap; } catch (Exception e) { LOGGER.error("Error getStatusById", e); throw e; } } private RestTemplate getRestTemplate() { String keytabLocation = property.getProperty("zeppelin.livy.keytab"); String principal = property.getProperty("zeppelin.livy.principal"); if (StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal)) { return new KerberosRestTemplate(keytabLocation, principal); } return new RestTemplate(); } protected String executeHTTP(String targetURL, String method, String jsonData, String paragraphId) throws Exception { RestTemplate restTemplate = getRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); ResponseEntity<String> response = null; if (method.equals("POST")) { HttpEntity<String> entity = new HttpEntity<String>(jsonData, headers); response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class); paragraphHttpMap.put(paragraphId, response); } else if (method.equals("GET")) { HttpEntity<String> entity = new HttpEntity<String>(headers); response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class); paragraphHttpMap.put(paragraphId, response); } else if (method.equals("DELETE")) { HttpEntity<String> entity = new HttpEntity<String>(headers); response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class); } if (response == null) { return null; } if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201 || response.getStatusCode().value() == 404) { return response.getBody(); } else { String responseString = response.getBody(); if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) { return responseString; } LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); throw new Exception(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); } } public void cancelHTTP(String paragraphId) { paragraphHttpMap.put(paragraphId, null); } public void closeSession(Map<String, Integer> userSessionMap) { for (Map.Entry<String, Integer> entry : userSessionMap.entrySet()) { try { executeHTTP(property.getProperty("zeppelin.livy.url") + "/sessions/" + entry.getValue(), "DELETE", null, null); } catch (Exception e) { LOGGER.error(String.format("Error closing session for user with session ID: %s", entry.getValue()), e); } } } }
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.protocols.channels; import org.bitcoinj.core.*; import org.bitcoinj.utils.Threading; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.HashMultimap; import com.google.common.util.concurrent.SettableFuture; import com.google.protobuf.ByteString; import net.jcip.annotations.GuardedBy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.Date; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.ReentrantLock; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * This class maintains a set of {@link StoredClientChannel}s, automatically (re)broadcasting the contract transaction * and broadcasting the refund transaction over the given {@link TransactionBroadcaster}. */ public class StoredPaymentChannelClientStates implements WalletExtension { private static final Logger log = LoggerFactory.getLogger(StoredPaymentChannelClientStates.class); static final String EXTENSION_ID = StoredPaymentChannelClientStates.class.getName(); static final int MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET = 10; @GuardedBy("lock") @VisibleForTesting final HashMultimap<Sha256Hash, StoredClientChannel> mapChannels = HashMultimap.create(); @VisibleForTesting final Timer channelTimeoutHandler = new Timer(true); private Wallet containingWallet; private final SettableFuture<TransactionBroadcaster> announcePeerGroupFuture = SettableFuture.create(); protected final ReentrantLock lock = Threading.lock("StoredPaymentChannelClientStates"); /** * Creates a new StoredPaymentChannelClientStates and associates it with the given {@link Wallet} and * {@link TransactionBroadcaster} which are used to complete and announce contract and refund * transactions. */ public StoredPaymentChannelClientStates(@Nullable Wallet containingWallet, TransactionBroadcaster announcePeerGroup) { setTransactionBroadcaster(announcePeerGroup); this.containingWallet = containingWallet; } /** * Creates a new StoredPaymentChannelClientStates and associates it with the given {@link Wallet} * * Use this constructor if you use WalletAppKit, it will provide the broadcaster for you (no need to call the setter) */ public StoredPaymentChannelClientStates(@Nullable Wallet containingWallet) { this.containingWallet = containingWallet; } /** * Use this setter if the broadcaster is not available during instantiation and you're not using WalletAppKit. * This setter will let you delay the setting of the broadcaster until the Bitcoin network is ready. * * @param transactionBroadcaster which is used to complete and announce contract and refund transactions. */ public void setTransactionBroadcaster(TransactionBroadcaster transactionBroadcaster) { this.announcePeerGroupFuture.set(checkNotNull(transactionBroadcaster)); } /** Returns this extension from the given wallet, or null if no such extension was added. */ @Nullable public static StoredPaymentChannelClientStates getFromWallet(Wallet wallet) { return (StoredPaymentChannelClientStates) wallet.getExtensions().get(EXTENSION_ID); } /** Returns the outstanding amount of money sent back to us for all channels to this server added together. */ public Coin getBalanceForServer(Sha256Hash id) { Coin balance = Coin.ZERO; lock.lock(); try { Set<StoredClientChannel> setChannels = mapChannels.get(id); for (StoredClientChannel channel : setChannels) { synchronized (channel) { if (channel.close != null) continue; balance = balance.add(channel.valueToMe); } } return balance; } finally { lock.unlock(); } } /** * Returns the number of seconds from now until this servers next channel will expire, or zero if no unexpired * channels found. */ public long getSecondsUntilExpiry(Sha256Hash id) { lock.lock(); try { final Set<StoredClientChannel> setChannels = mapChannels.get(id); final long nowSeconds = Utils.currentTimeSeconds(); int earliestTime = Integer.MAX_VALUE; for (StoredClientChannel channel : setChannels) { synchronized (channel) { if (channel.expiryTimeSeconds() > nowSeconds) earliestTime = Math.min(earliestTime, (int) channel.expiryTimeSeconds()); } } return earliestTime == Integer.MAX_VALUE ? 0 : earliestTime - nowSeconds; } finally { lock.unlock(); } } /** * Finds an inactive channel with the given id and returns it, or returns null. */ @Nullable StoredClientChannel getUsableChannelForServerID(Sha256Hash id) { lock.lock(); try { Set<StoredClientChannel> setChannels = mapChannels.get(id); for (StoredClientChannel channel : setChannels) { synchronized (channel) { // Check if the channel is usable (has money, inactive) and if so, activate it. log.info("Considering channel {} contract {}", channel.hashCode(), channel.contract.getHash()); if (channel.close != null || channel.valueToMe.equals(Coin.ZERO)) { log.info(" ... but is closed or empty"); continue; } if (!channel.active) { log.info(" ... activating"); channel.active = true; return channel; } log.info(" ... but is already active"); } } } finally { lock.unlock(); } return null; } /** * Finds a channel with the given id and contract hash and returns it, or returns null. */ @Nullable StoredClientChannel getChannel(Sha256Hash id, Sha256Hash contractHash) { lock.lock(); try { Set<StoredClientChannel> setChannels = mapChannels.get(id); for (StoredClientChannel channel : setChannels) { if (channel.contract.getHash().equals(contractHash)) return channel; } return null; } finally { lock.unlock(); } } /** * Adds the given channel to this set of stored states, broadcasting the contract and refund transactions when the * channel expires and notifies the wallet of an update to this wallet extension */ void putChannel(final StoredClientChannel channel) { putChannel(channel, true); } // Adds this channel and optionally notifies the wallet of an update to this extension (used during deserialize) private void putChannel(final StoredClientChannel channel, boolean updateWallet) { lock.lock(); try { mapChannels.put(channel.id, channel); channelTimeoutHandler.schedule(new TimerTask() { @Override public void run() { TransactionBroadcaster announcePeerGroup = getAnnouncePeerGroup(); removeChannel(channel); announcePeerGroup.broadcastTransaction(channel.contract); announcePeerGroup.broadcastTransaction(channel.refund); } // Add the difference between real time and Utils.now() so that test-cases can use a mock clock. }, new Date(channel.expiryTimeSeconds() * 1000 + (System.currentTimeMillis() - Utils.currentTimeMillis()))); } finally { lock.unlock(); } if (updateWallet) containingWallet.addOrUpdateExtension(this); } /** * If the peer group has not been set for MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET seconds, then * the programmer probably forgot to set it and we should throw exception. */ private TransactionBroadcaster getAnnouncePeerGroup() { try { return announcePeerGroupFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException e) { String err = "Transaction broadcaster not set"; log.error(err); throw new RuntimeException(err, e); } } /** * <p>Removes the channel with the given id from this set of stored states and notifies the wallet of an update to * this wallet extension.</p> * * <p>Note that the channel will still have its contract and refund transactions broadcast via the connected * {@link TransactionBroadcaster} as long as this {@link StoredPaymentChannelClientStates} continues to * exist in memory.</p> */ void removeChannel(StoredClientChannel channel) { lock.lock(); try { mapChannels.remove(channel.id, channel); } finally { lock.unlock(); } containingWallet.addOrUpdateExtension(this); } @Override public String getWalletExtensionID() { return EXTENSION_ID; } @Override public boolean isWalletExtensionMandatory() { return false; } @Override public byte[] serializeWalletExtension() { lock.lock(); try { ClientState.StoredClientPaymentChannels.Builder builder = ClientState.StoredClientPaymentChannels.newBuilder(); for (StoredClientChannel channel : mapChannels.values()) { // First a few asserts to make sure things won't break checkState(channel.valueToMe.signum() >= 0 && channel.valueToMe.compareTo(NetworkParameters.MAX_MONEY) < 0); checkState(channel.refundFees.signum() >= 0 && channel.refundFees.compareTo(NetworkParameters.MAX_MONEY) < 0); checkNotNull(channel.myKey.getPrivKeyBytes()); checkState(channel.refund.getConfidence().getSource() == TransactionConfidence.Source.SELF); final ClientState.StoredClientPaymentChannel.Builder value = ClientState.StoredClientPaymentChannel.newBuilder() .setId(ByteString.copyFrom(channel.id.getBytes())) .setContractTransaction(ByteString.copyFrom(channel.contract.bitcoinSerialize())) .setRefundTransaction(ByteString.copyFrom(channel.refund.bitcoinSerialize())) .setMyKey(ByteString.copyFrom(channel.myKey.getPrivKeyBytes())) .setValueToMe(channel.valueToMe.value) .setRefundFees(channel.refundFees.value); if (channel.close != null) value.setCloseTransactionHash(ByteString.copyFrom(channel.close.getHash().getBytes())); builder.addChannels(value); } return builder.build().toByteArray(); } finally { lock.unlock(); } } @Override public void deserializeWalletExtension(Wallet containingWallet, byte[] data) throws Exception { lock.lock(); try { checkState(this.containingWallet == null || this.containingWallet == containingWallet); this.containingWallet = containingWallet; NetworkParameters params = containingWallet.getParams(); ClientState.StoredClientPaymentChannels states = ClientState.StoredClientPaymentChannels.parseFrom(data); for (ClientState.StoredClientPaymentChannel storedState : states.getChannelsList()) { Transaction refundTransaction = new Transaction(params, storedState.getRefundTransaction().toByteArray()); refundTransaction.getConfidence().setSource(TransactionConfidence.Source.SELF); StoredClientChannel channel = new StoredClientChannel(new Sha256Hash(storedState.getId().toByteArray()), new Transaction(params, storedState.getContractTransaction().toByteArray()), refundTransaction, ECKey.fromPrivate(storedState.getMyKey().toByteArray()), Coin.valueOf(storedState.getValueToMe()), Coin.valueOf(storedState.getRefundFees()), false); if (storedState.hasCloseTransactionHash()) { Sha256Hash closeTxHash = new Sha256Hash(storedState.getCloseTransactionHash().toByteArray()); channel.close = containingWallet.getTransaction(closeTxHash); } putChannel(channel, false); } } finally { lock.unlock(); } } @Override public String toString() { lock.lock(); try { StringBuilder buf = new StringBuilder("Client payment channel states:\n"); for (StoredClientChannel channel : mapChannels.values()) buf.append(" ").append(channel).append("\n"); return buf.toString(); } finally { lock.unlock(); } } } /** * Represents the state of a channel once it has been opened in such a way that it can be stored and used to resume a * channel which was interrupted (eg on connection failure) or keep track of refund transactions which need broadcast * when they expire. */ class StoredClientChannel { Sha256Hash id; Transaction contract, refund; // The transaction that closed the channel (generated by the server) Transaction close; ECKey myKey; Coin valueToMe, refundFees; // In-memory flag to indicate intent to resume this channel (or that the channel is already in use) boolean active = false; StoredClientChannel(Sha256Hash id, Transaction contract, Transaction refund, ECKey myKey, Coin valueToMe, Coin refundFees, boolean active) { this.id = id; this.contract = contract; this.refund = refund; this.myKey = myKey; this.valueToMe = valueToMe; this.refundFees = refundFees; this.active = active; } long expiryTimeSeconds() { return refund.getLockTime() + 60 * 5; } @Override public String toString() { final String newline = String.format("%n"); final String closeStr = close == null ? "still open" : close.toString().replaceAll(newline, newline + " "); return String.format("Stored client channel for server ID %s (%s)%n" + " Key: %s%n" + " Value left: %s%n" + " Refund fees: %s%n" + " Contract: %s" + "Refund: %s" + "Close: %s", id, active ? "active" : "inactive", myKey, valueToMe, refundFees, contract.toString().replaceAll(newline, newline + " "), refund.toString().replaceAll(newline, newline + " "), closeStr); } }
/* * Copyright 2013 gitblit.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.gitblit.git; import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_SIDE_BAND_64K; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.BatchRefUpdate; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.ReceiveCommand; import org.eclipse.jgit.transport.ReceiveCommand.Result; import org.eclipse.jgit.transport.ReceiveCommand.Type; import org.eclipse.jgit.transport.ReceivePack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.gitblit.Constants; import com.gitblit.Keys; import com.gitblit.manager.IGitblit; import com.gitblit.models.RepositoryModel; import com.gitblit.models.TicketModel; import com.gitblit.models.TicketModel.Change; import com.gitblit.models.TicketModel.Field; import com.gitblit.models.TicketModel.Patchset; import com.gitblit.models.TicketModel.PatchsetType; import com.gitblit.models.TicketModel.Status; import com.gitblit.models.UserModel; import com.gitblit.tickets.BranchTicketService; import com.gitblit.tickets.ITicketService; import com.gitblit.tickets.TicketMilestone; import com.gitblit.tickets.TicketNotifier; import com.gitblit.utils.ArrayUtils; import com.gitblit.utils.DiffUtils; import com.gitblit.utils.DiffUtils.DiffStat; import com.gitblit.utils.JGitUtils; import com.gitblit.utils.JGitUtils.MergeResult; import com.gitblit.utils.JGitUtils.MergeStatus; import com.gitblit.utils.RefLogUtils; import com.gitblit.utils.StringUtils; /** * PatchsetReceivePack processes receive commands and allows for creating, updating, * and closing Gitblit tickets. It also executes Groovy pre- and post- receive * hooks. * * The patchset mechanism defined in this class is based on the ReceiveCommits class * from the Gerrit code review server. * * The general execution flow is: * <ol> * <li>onPreReceive()</li> * <li>executeCommands()</li> * <li>onPostReceive()</li> * </ol> * * @author Android Open Source Project * @author James Moger * */ public class PatchsetReceivePack extends GitblitReceivePack { protected static final List<String> MAGIC_REFS = Arrays.asList(Constants.R_FOR, Constants.R_TICKET); protected static final Pattern NEW_PATCHSET = Pattern.compile("^refs/tickets/(?:[0-9a-zA-Z][0-9a-zA-Z]/)?([1-9][0-9]*)(?:/new)?$"); private static final Logger LOGGER = LoggerFactory.getLogger(PatchsetReceivePack.class); protected final ITicketService ticketService; protected final TicketNotifier ticketNotifier; private boolean requireMergeablePatchset; public PatchsetReceivePack(IGitblit gitblit, Repository db, RepositoryModel repository, UserModel user) { super(gitblit, db, repository, user); this.ticketService = gitblit.getTicketService(); this.ticketNotifier = ticketService.createNotifier(); } /** Returns the patchset ref root from the ref */ private String getPatchsetRef(String refName) { for (String patchRef : MAGIC_REFS) { if (refName.startsWith(patchRef)) { return patchRef; } } return null; } /** Checks if the supplied ref name is a patchset ref */ private boolean isPatchsetRef(String refName) { return !StringUtils.isEmpty(getPatchsetRef(refName)); } /** Checks if the supplied ref name is a change ref */ private boolean isTicketRef(String refName) { return refName.startsWith(Constants.R_TICKETS_PATCHSETS); } /** Extracts the integration branch from the ref name */ private String getIntegrationBranch(String refName) { String patchsetRef = getPatchsetRef(refName); String branch = refName.substring(patchsetRef.length()); if (branch.indexOf('%') > -1) { branch = branch.substring(0, branch.indexOf('%')); } String defaultBranch = "master"; try { defaultBranch = getRepository().getBranch(); } catch (Exception e) { LOGGER.error("failed to determine default branch for " + repository.name, e); } long ticketId = 0L; try { ticketId = Long.parseLong(branch); } catch (Exception e) { // not a number } if (ticketId > 0 || branch.equalsIgnoreCase("default") || branch.equalsIgnoreCase("new")) { return defaultBranch; } return branch; } /** Extracts the ticket id from the ref name */ private long getTicketId(String refName) { if (refName.startsWith(Constants.R_FOR)) { String ref = refName.substring(Constants.R_FOR.length()); if (ref.indexOf('%') > -1) { ref = ref.substring(0, ref.indexOf('%')); } try { return Long.parseLong(ref); } catch (Exception e) { // not a number } } else if (refName.startsWith(Constants.R_TICKET) || refName.startsWith(Constants.R_TICKETS_PATCHSETS)) { return PatchsetCommand.getTicketNumber(refName); } return 0L; } /** Returns true if the ref namespace exists */ private boolean hasRefNamespace(String ref) { Map<String, Ref> blockingFors; try { blockingFors = getRepository().getRefDatabase().getRefs(ref); } catch (IOException err) { sendError("Cannot scan refs in {0}", repository.name); LOGGER.error("Error!", err); return true; } if (!blockingFors.isEmpty()) { sendError("{0} needs the following refs removed to receive patchsets: {1}", repository.name, blockingFors.keySet()); return true; } return false; } /** Removes change ref receive commands */ private List<ReceiveCommand> excludeTicketCommands(Collection<ReceiveCommand> commands) { List<ReceiveCommand> filtered = new ArrayList<ReceiveCommand>(); for (ReceiveCommand cmd : commands) { if (!isTicketRef(cmd.getRefName())) { // this is not a ticket ref update filtered.add(cmd); } } return filtered; } /** Removes patchset receive commands for pre- and post- hook integrations */ private List<ReceiveCommand> excludePatchsetCommands(Collection<ReceiveCommand> commands) { List<ReceiveCommand> filtered = new ArrayList<ReceiveCommand>(); for (ReceiveCommand cmd : commands) { if (!isPatchsetRef(cmd.getRefName())) { // this is a non-patchset ref update filtered.add(cmd); } } return filtered; } /** Process receive commands EXCEPT for Patchset commands. */ @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { Collection<ReceiveCommand> filtered = excludePatchsetCommands(commands); super.onPreReceive(rp, filtered); } /** Process receive commands EXCEPT for Patchset commands. */ @Override public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { Collection<ReceiveCommand> filtered = excludePatchsetCommands(commands); super.onPostReceive(rp, filtered); // send all queued ticket notifications after processing all patchsets ticketNotifier.sendAll(); } @Override protected void validateCommands() { // workaround for JGit's awful scoping choices // // set the patchset refs to OK to bypass checks in the super implementation for (final ReceiveCommand cmd : filterCommands(Result.NOT_ATTEMPTED)) { if (isPatchsetRef(cmd.getRefName())) { if (cmd.getType() == ReceiveCommand.Type.CREATE) { cmd.setResult(Result.OK); } } } super.validateCommands(); } /** Execute commands to update references. */ @Override protected void executeCommands() { // we process patchsets unless the user is pushing something special boolean processPatchsets = true; for (ReceiveCommand cmd : filterCommands(Result.NOT_ATTEMPTED)) { if (ticketService instanceof BranchTicketService && BranchTicketService.BRANCH.equals(cmd.getRefName())) { // the user is pushing an update to the BranchTicketService data processPatchsets = false; } } // workaround for JGit's awful scoping choices // // reset the patchset refs to NOT_ATTEMPTED (see validateCommands) for (ReceiveCommand cmd : filterCommands(Result.OK)) { if (isPatchsetRef(cmd.getRefName())) { cmd.setResult(Result.NOT_ATTEMPTED); } else if (ticketService instanceof BranchTicketService && BranchTicketService.BRANCH.equals(cmd.getRefName())) { // the user is pushing an update to the BranchTicketService data processPatchsets = false; } } List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED); if (toApply.isEmpty()) { return; } ProgressMonitor updating = NullProgressMonitor.INSTANCE; boolean sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K); if (sideBand) { SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut); pm.setDelayStart(250, TimeUnit.MILLISECONDS); updating = pm; } BatchRefUpdate batch = getRepository().getRefDatabase().newBatchUpdate(); batch.setAllowNonFastForwards(isAllowNonFastForwards()); batch.setRefLogIdent(getRefLogIdent()); batch.setRefLogMessage("push", true); ReceiveCommand patchsetRefCmd = null; PatchsetCommand patchsetCmd = null; for (ReceiveCommand cmd : toApply) { if (Result.NOT_ATTEMPTED != cmd.getResult()) { // Already rejected by the core receive process. continue; } if (isPatchsetRef(cmd.getRefName()) && processPatchsets) { if (ticketService == null) { sendRejection(cmd, "Sorry, the ticket service is unavailable and can not accept patchsets at this time."); continue; } if (!ticketService.isReady()) { sendRejection(cmd, "Sorry, the ticket service can not accept patchsets at this time."); continue; } if (UserModel.ANONYMOUS.equals(user)) { // server allows anonymous pushes, but anonymous patchset // contributions are prohibited by design sendRejection(cmd, "Sorry, anonymous patchset contributions are prohibited."); continue; } final Matcher m = NEW_PATCHSET.matcher(cmd.getRefName()); if (m.matches()) { // prohibit pushing directly to a patchset ref long id = getTicketId(cmd.getRefName()); sendError("You may not directly push directly to a patchset ref!"); sendError("Instead, please push to one the following:"); sendError(" - {0}{1,number,0}", Constants.R_FOR, id); sendError(" - {0}{1,number,0}", Constants.R_TICKET, id); sendRejection(cmd, "protected ref"); continue; } if (hasRefNamespace(Constants.R_FOR)) { // the refs/for/ namespace exists and it must not LOGGER.error("{} already has refs in the {} namespace", repository.name, Constants.R_FOR); sendRejection(cmd, "Sorry, a repository administrator will have to remove the {} namespace", Constants.R_FOR); continue; } if (patchsetRefCmd != null) { sendRejection(cmd, "You may only push one patchset at a time."); continue; } // responsible verification String responsible = PatchsetCommand.getSingleOption(cmd, PatchsetCommand.RESPONSIBLE); if (!StringUtils.isEmpty(responsible)) { UserModel assignee = gitblit.getUserModel(responsible); if (assignee == null) { // no account by this name sendRejection(cmd, "{0} can not be assigned any tickets because there is no user account by that name", responsible); continue; } else if (!assignee.canPush(repository)) { // account does not have RW permissions sendRejection(cmd, "{0} ({1}) can not be assigned any tickets because the user does not have RW permissions for {2}", assignee.getDisplayName(), assignee.username, repository.name); continue; } } // milestone verification String milestone = PatchsetCommand.getSingleOption(cmd, PatchsetCommand.MILESTONE); if (!StringUtils.isEmpty(milestone)) { TicketMilestone milestoneModel = ticketService.getMilestone(repository, milestone); if (milestoneModel == null) { // milestone does not exist sendRejection(cmd, "Sorry, \"{0}\" is not a valid milestone!", milestone); continue; } } // watcher verification List<String> watchers = PatchsetCommand.getOptions(cmd, PatchsetCommand.WATCH); if (!ArrayUtils.isEmpty(watchers)) { for (String watcher : watchers) { UserModel user = gitblit.getUserModel(watcher); if (user == null) { // watcher does not exist sendRejection(cmd, "Sorry, \"{0}\" is not a valid username for the watch list!", watcher); continue; } } } patchsetRefCmd = cmd; patchsetCmd = preparePatchset(cmd); if (patchsetCmd != null) { batch.addCommand(patchsetCmd); } continue; } batch.addCommand(cmd); } if (!batch.getCommands().isEmpty()) { try { batch.execute(getRevWalk(), updating); } catch (IOException err) { for (ReceiveCommand cmd : toApply) { if (cmd.getResult() == Result.NOT_ATTEMPTED) { sendRejection(cmd, "lock error: {0}", err.getMessage()); LOGGER.error(MessageFormat.format("failed to lock {0}:{1}", repository.name, cmd.getRefName()), err); } } } } // // set the results into the patchset ref receive command // if (patchsetRefCmd != null && patchsetCmd != null) { if (!patchsetCmd.getResult().equals(Result.OK)) { // patchset command failed! LOGGER.error(patchsetCmd.getType() + " " + patchsetCmd.getRefName() + " " + patchsetCmd.getResult()); patchsetRefCmd.setResult(patchsetCmd.getResult(), patchsetCmd.getMessage()); } else { // all patchset commands were applied patchsetRefCmd.setResult(Result.OK); // update the ticket branch ref RefUpdate ru = updateRef(patchsetCmd.getTicketBranch(), patchsetCmd.getNewId()); updateReflog(ru); TicketModel ticket = processPatchset(patchsetCmd); if (ticket != null) { ticketNotifier.queueMailing(ticket); } } } // // if there are standard ref update receive commands that were // successfully processed, process referenced tickets, if any // List<ReceiveCommand> allUpdates = ReceiveCommand.filter(batch.getCommands(), Result.OK); List<ReceiveCommand> refUpdates = excludePatchsetCommands(allUpdates); List<ReceiveCommand> stdUpdates = excludeTicketCommands(refUpdates); if (!stdUpdates.isEmpty()) { int ticketsProcessed = 0; for (ReceiveCommand cmd : stdUpdates) { switch (cmd.getType()) { case CREATE: case UPDATE: case UPDATE_NONFASTFORWARD: if (cmd.getRefName().startsWith(Constants.R_HEADS)) { Collection<TicketModel> tickets = processMergedTickets(cmd); ticketsProcessed += tickets.size(); for (TicketModel ticket : tickets) { ticketNotifier.queueMailing(ticket); } } break; default: break; } } if (ticketsProcessed == 1) { sendInfo("1 ticket updated"); } else if (ticketsProcessed > 1) { sendInfo("{0} tickets updated", ticketsProcessed); } } // reset the ticket caches for the repository ticketService.resetCaches(repository); } /** * Prepares a patchset command. * * @param cmd * @return the patchset command */ private PatchsetCommand preparePatchset(ReceiveCommand cmd) { String branch = getIntegrationBranch(cmd.getRefName()); long number = getTicketId(cmd.getRefName()); TicketModel ticket = null; if (number > 0 && ticketService.hasTicket(repository, number)) { ticket = ticketService.getTicket(repository, number); } if (ticket == null) { if (number > 0) { // requested ticket does not exist sendError("Sorry, {0} does not have ticket {1,number,0}!", repository.name, number); sendRejection(cmd, "Invalid ticket number"); return null; } } else { if (ticket.isMerged()) { // ticket already merged & resolved Change mergeChange = null; for (Change change : ticket.changes) { if (change.isMerge()) { mergeChange = change; break; } } sendError("Sorry, {0} already merged {1} from ticket {2,number,0} to {3}!", mergeChange.author, mergeChange.patchset, number, ticket.mergeTo); sendRejection(cmd, "Ticket {0,number,0} already resolved", number); return null; } else if (!StringUtils.isEmpty(ticket.mergeTo)) { // ticket specifies integration branch branch = ticket.mergeTo; } } final int shortCommitIdLen = settings.getInteger(Keys.web.shortCommitIdLength, 6); final String shortTipId = cmd.getNewId().getName().substring(0, shortCommitIdLen); final RevCommit tipCommit = JGitUtils.getCommit(getRepository(), cmd.getNewId().getName()); final String forBranch = branch; RevCommit mergeBase = null; Ref forBranchRef = getAdvertisedRefs().get(Constants.R_HEADS + forBranch); if (forBranchRef == null || forBranchRef.getObjectId() == null) { // unknown integration branch sendError("Sorry, there is no integration branch named ''{0}''.", forBranch); sendRejection(cmd, "Invalid integration branch specified"); return null; } else { // determine the merge base for the patchset on the integration branch String base = JGitUtils.getMergeBase(getRepository(), forBranchRef.getObjectId(), tipCommit.getId()); if (StringUtils.isEmpty(base)) { sendError(""); sendError("There is no common ancestry between {0} and {1}.", forBranch, shortTipId); sendError("Please reconsider your proposed integration branch, {0}.", forBranch); sendError(""); sendRejection(cmd, "no merge base for patchset and {0}", forBranch); return null; } mergeBase = JGitUtils.getCommit(getRepository(), base); } // ensure that the patchset can be cleanly merged right now MergeStatus status = JGitUtils.canMerge(getRepository(), tipCommit.getName(), forBranch); switch (status) { case ALREADY_MERGED: sendError(""); sendError("You have already merged this patchset.", forBranch); sendError(""); sendRejection(cmd, "everything up-to-date"); return null; case MERGEABLE: break; default: if (ticket == null || requireMergeablePatchset) { sendError(""); sendError("Your patchset can not be cleanly merged into {0}.", forBranch); sendError("Please rebase your patchset and push again."); sendError("NOTE:", number); sendError("You should push your rebase to refs/for/{0,number,0}", number); sendError(""); sendError(" git push origin HEAD:refs/for/{0,number,0}", number); sendError(""); sendRejection(cmd, "patchset not mergeable"); return null; } } // check to see if this commit is already linked to a ticket long id = identifyTicket(tipCommit, false); if (id > 0) { sendError("{0} has already been pushed to ticket {1,number,0}.", shortTipId, id); sendRejection(cmd, "everything up-to-date"); return null; } PatchsetCommand psCmd; if (ticket == null) { /* * NEW TICKET */ Patchset patchset = newPatchset(null, mergeBase.getName(), tipCommit.getName()); int minLength = 10; int maxLength = 100; String minTitle = MessageFormat.format(" minimum length of a title is {0} characters.", minLength); String maxTitle = MessageFormat.format(" maximum length of a title is {0} characters.", maxLength); if (patchset.commits > 1) { sendError(""); sendError("To create a proposal ticket, please squash your commits and"); sendError("provide a meaningful commit message with a short title &"); sendError("an optional description/body."); sendError(""); sendError(minTitle); sendError(maxTitle); sendError(""); sendRejection(cmd, "please squash to one commit"); return null; } // require a reasonable title/subject String title = tipCommit.getFullMessage().trim().split("\n")[0]; if (title.length() < minLength) { // reject, title too short sendError(""); sendError("Please supply a longer title in your commit message!"); sendError(""); sendError(minTitle); sendError(maxTitle); sendError(""); sendRejection(cmd, "ticket title is too short [{0}/{1}]", title.length(), maxLength); return null; } if (title.length() > maxLength) { // reject, title too long sendError(""); sendError("Please supply a more concise title in your commit message!"); sendError(""); sendError(minTitle); sendError(maxTitle); sendError(""); sendRejection(cmd, "ticket title is too long [{0}/{1}]", title.length(), maxLength); return null; } // assign new id long ticketId = ticketService.assignNewId(repository); // create the patchset command psCmd = new PatchsetCommand(user.username, patchset); psCmd.newTicket(tipCommit, forBranch, ticketId, cmd.getRefName()); } else { /* * EXISTING TICKET */ Patchset patchset = newPatchset(ticket, mergeBase.getName(), tipCommit.getName()); psCmd = new PatchsetCommand(user.username, patchset); psCmd.updateTicket(tipCommit, forBranch, ticket, cmd.getRefName()); } // confirm user can push the patchset boolean pushPermitted = ticket == null || !ticket.hasPatchsets() || ticket.isAuthor(user.username) || ticket.isPatchsetAuthor(user.username) || ticket.isResponsible(user.username) || user.canPush(repository); switch (psCmd.getPatchsetType()) { case Proposal: // proposals (first patchset) are always acceptable break; case FastForward: // patchset updates must be permitted if (!pushPermitted) { // reject sendError(""); sendError("To push a patchset to this ticket one of the following must be true:"); sendError(" 1. you created the ticket"); sendError(" 2. you created the first patchset"); sendError(" 3. you are specified as responsible for the ticket"); sendError(" 4. you have push (RW) permissions to {0}", repository.name); sendError(""); sendRejection(cmd, "not permitted to push to ticket {0,number,0}", ticket.number); return null; } break; default: // non-fast-forward push if (!pushPermitted) { // reject sendRejection(cmd, "non-fast-forward ({0})", psCmd.getPatchsetType()); return null; } break; } return psCmd; } /** * Creates or updates an ticket with the specified patchset. * * @param cmd * @return a ticket if the creation or update was successful */ private TicketModel processPatchset(PatchsetCommand cmd) { Change change = cmd.getChange(); if (cmd.isNewTicket()) { // create the ticket object TicketModel ticket = ticketService.createTicket(repository, cmd.getTicketId(), change); if (ticket != null) { sendInfo(""); sendHeader("#{0,number,0}: {1}", ticket.number, StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG)); sendInfo("created proposal ticket from patchset"); sendInfo(ticketService.getTicketUrl(ticket)); sendInfo(""); // log the new patch ref RefLogUtils.updateRefLog(user, getRepository(), Arrays.asList(new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), cmd.getRefName()))); return ticket; } else { sendError("FAILED to create ticket"); } } else { // update an existing ticket TicketModel ticket = ticketService.updateTicket(repository, cmd.getTicketId(), change); if (ticket != null) { sendInfo(""); sendHeader("#{0,number,0}: {1}", ticket.number, StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG)); if (change.patchset.rev == 1) { // new patchset sendInfo("uploaded patchset {0} ({1})", change.patchset.number, change.patchset.type.toString()); } else { // updated patchset sendInfo("added {0} {1} to patchset {2}", change.patchset.added, change.patchset.added == 1 ? "commit" : "commits", change.patchset.number); } sendInfo(ticketService.getTicketUrl(ticket)); sendInfo(""); // log the new patchset ref RefLogUtils.updateRefLog(user, getRepository(), Arrays.asList(new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), cmd.getRefName()))); // return the updated ticket return ticket; } else { sendError("FAILED to upload {0} for ticket {1,number,0}", change.patchset, cmd.getTicketId()); } } return null; } /** * Automatically closes open tickets that have been merged to their integration * branch by a client. * * @param cmd */ private Collection<TicketModel> processMergedTickets(ReceiveCommand cmd) { Map<Long, TicketModel> mergedTickets = new LinkedHashMap<Long, TicketModel>(); final RevWalk rw = getRevWalk(); try { rw.reset(); rw.markStart(rw.parseCommit(cmd.getNewId())); if (!ObjectId.zeroId().equals(cmd.getOldId())) { rw.markUninteresting(rw.parseCommit(cmd.getOldId())); } RevCommit c; while ((c = rw.next()) != null) { rw.parseBody(c); long ticketNumber = identifyTicket(c, true); if (ticketNumber == 0L || mergedTickets.containsKey(ticketNumber)) { continue; } TicketModel ticket = ticketService.getTicket(repository, ticketNumber); String integrationBranch; if (StringUtils.isEmpty(ticket.mergeTo)) { // unspecified integration branch integrationBranch = null; } else { // specified integration branch integrationBranch = Constants.R_HEADS + ticket.mergeTo; } // ticket must be open and, if specified, the ref must match the integration branch if (ticket.isClosed() || (integrationBranch != null && !integrationBranch.equals(cmd.getRefName()))) { continue; } String baseRef = PatchsetCommand.getBasePatchsetBranch(ticket.number); boolean knownPatchset = false; Set<Ref> refs = getRepository().getAllRefsByPeeledObjectId().get(c.getId()); if (refs != null) { for (Ref ref : refs) { if (ref.getName().startsWith(baseRef)) { knownPatchset = true; break; } } } String mergeSha = c.getName(); String mergeTo = Repository.shortenRefName(cmd.getRefName()); Change change; Patchset patchset; if (knownPatchset) { // identify merged patchset by the patchset tip patchset = null; for (Patchset ps : ticket.getPatchsets()) { if (ps.tip.equals(mergeSha)) { patchset = ps; break; } } if (patchset == null) { // should not happen - unless ticket has been hacked sendError("Failed to find the patchset for {0} in ticket {1,number,0}?!", mergeSha, ticket.number); continue; } // create a new change change = new Change(user.username); } else { // new patchset pushed by user String base = cmd.getOldId().getName(); patchset = newPatchset(ticket, base, mergeSha); PatchsetCommand psCmd = new PatchsetCommand(user.username, patchset); psCmd.updateTicket(c, mergeTo, ticket, null); // create a ticket patchset ref updateRef(psCmd.getPatchsetBranch(), c.getId()); RefUpdate ru = updateRef(psCmd.getTicketBranch(), c.getId()); updateReflog(ru); // create a change from the patchset command change = psCmd.getChange(); } // set the common change data about the merge change.setField(Field.status, Status.Merged); change.setField(Field.mergeSha, mergeSha); change.setField(Field.mergeTo, mergeTo); if (StringUtils.isEmpty(ticket.responsible)) { // unassigned tickets are assigned to the closer change.setField(Field.responsible, user.username); } ticket = ticketService.updateTicket(repository, ticket.number, change); if (ticket != null) { sendInfo(""); sendHeader("#{0,number,0}: {1}", ticket.number, StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG)); sendInfo("closed by push of {0} to {1}", patchset, mergeTo); sendInfo(ticketService.getTicketUrl(ticket)); sendInfo(""); mergedTickets.put(ticket.number, ticket); } else { String shortid = mergeSha.substring(0, settings.getInteger(Keys.web.shortCommitIdLength, 6)); sendError("FAILED to close ticket {0,number,0} by push of {1}", ticketNumber, shortid); } } } catch (IOException e) { LOGGER.error("Can't scan for changes to close", e); } finally { rw.reset(); } return mergedTickets.values(); } /** * Try to identify a ticket id from the commit. * * @param commit * @param parseMessage * @return a ticket id or 0 */ private long identifyTicket(RevCommit commit, boolean parseMessage) { // try lookup by change ref Map<AnyObjectId, Set<Ref>> map = getRepository().getAllRefsByPeeledObjectId(); Set<Ref> refs = map.get(commit.getId()); if (!ArrayUtils.isEmpty(refs)) { for (Ref ref : refs) { long number = PatchsetCommand.getTicketNumber(ref.getName()); if (number > 0) { return number; } } } if (parseMessage) { // parse commit message looking for fixes/closes #n Pattern p = Pattern.compile("(?:fixes|closes)[\\s-]+#?(\\d+)", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(commit.getFullMessage()); while (m.find()) { String val = m.group(); return Long.parseLong(val); } } return 0L; } private int countCommits(String baseId, String tipId) { int count = 0; RevWalk walk = getRevWalk(); walk.reset(); walk.sort(RevSort.TOPO); walk.sort(RevSort.REVERSE, true); try { RevCommit tip = walk.parseCommit(getRepository().resolve(tipId)); RevCommit base = walk.parseCommit(getRepository().resolve(baseId)); walk.markStart(tip); walk.markUninteresting(base); for (;;) { RevCommit c = walk.next(); if (c == null) { break; } count++; } } catch (IOException e) { // Should never happen, the core receive process would have // identified the missing object earlier before we got control. LOGGER.error("failed to get commit count", e); return 0; } finally { walk.release(); } return count; } /** * Creates a new patchset with metadata. * * @param ticket * @param mergeBase * @param tip */ private Patchset newPatchset(TicketModel ticket, String mergeBase, String tip) { int totalCommits = countCommits(mergeBase, tip); Patchset newPatchset = new Patchset(); newPatchset.tip = tip; newPatchset.base = mergeBase; newPatchset.commits = totalCommits; Patchset currPatchset = ticket == null ? null : ticket.getCurrentPatchset(); if (currPatchset == null) { /* * PROPOSAL PATCHSET * patchset 1, rev 1 */ newPatchset.number = 1; newPatchset.rev = 1; newPatchset.type = PatchsetType.Proposal; // diffstat from merge base DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), mergeBase, tip); newPatchset.insertions = diffStat.getInsertions(); newPatchset.deletions = diffStat.getDeletions(); } else { /* * PATCHSET UPDATE */ int added = totalCommits - currPatchset.commits; boolean ff = JGitUtils.isMergedInto(getRepository(), currPatchset.tip, tip); boolean squash = added < 0; boolean rebase = !currPatchset.base.equals(mergeBase); // determine type, number and rev of the patchset if (ff) { /* * FAST-FORWARD * patchset number preserved, rev incremented */ boolean merged = JGitUtils.isMergedInto(getRepository(), currPatchset.tip, ticket.mergeTo); if (merged) { // current patchset was already merged // new patchset, mark as rebase newPatchset.type = PatchsetType.Rebase; newPatchset.number = currPatchset.number + 1; newPatchset.rev = 1; // diffstat from parent DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), mergeBase, tip); newPatchset.insertions = diffStat.getInsertions(); newPatchset.deletions = diffStat.getDeletions(); } else { // FF update to patchset newPatchset.type = PatchsetType.FastForward; newPatchset.number = currPatchset.number; newPatchset.rev = currPatchset.rev + 1; newPatchset.parent = currPatchset.tip; // diffstat from parent DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), currPatchset.tip, tip); newPatchset.insertions = diffStat.getInsertions(); newPatchset.deletions = diffStat.getDeletions(); } } else { /* * NON-FAST-FORWARD * new patchset, rev 1 */ if (rebase && squash) { newPatchset.type = PatchsetType.Rebase_Squash; newPatchset.number = currPatchset.number + 1; newPatchset.rev = 1; } else if (squash) { newPatchset.type = PatchsetType.Squash; newPatchset.number = currPatchset.number + 1; newPatchset.rev = 1; } else if (rebase) { newPatchset.type = PatchsetType.Rebase; newPatchset.number = currPatchset.number + 1; newPatchset.rev = 1; } else { newPatchset.type = PatchsetType.Amend; newPatchset.number = currPatchset.number + 1; newPatchset.rev = 1; } // diffstat from merge base DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), mergeBase, tip); newPatchset.insertions = diffStat.getInsertions(); newPatchset.deletions = diffStat.getDeletions(); } if (added > 0) { // ignore squash (negative add) newPatchset.added = added; } } return newPatchset; } private RefUpdate updateRef(String ref, ObjectId newId) { ObjectId ticketRefId = ObjectId.zeroId(); try { ticketRefId = getRepository().resolve(ref); } catch (Exception e) { // ignore } try { RefUpdate ru = getRepository().updateRef(ref, false); ru.setRefLogIdent(getRefLogIdent()); ru.setForceUpdate(true); ru.setExpectedOldObjectId(ticketRefId); ru.setNewObjectId(newId); RefUpdate.Result result = ru.update(getRevWalk()); if (result == RefUpdate.Result.LOCK_FAILURE) { sendError("Failed to obtain lock when updating {0}:{1}", repository.name, ref); sendError("Perhaps an administrator should remove {0}/{1}.lock?", getRepository().getDirectory(), ref); return null; } return ru; } catch (IOException e) { LOGGER.error("failed to update ref " + ref, e); sendError("There was an error updating ref {0}:{1}", repository.name, ref); } return null; } private void updateReflog(RefUpdate ru) { if (ru == null) { return; } ReceiveCommand.Type type = null; switch (ru.getResult()) { case NEW: type = Type.CREATE; break; case FAST_FORWARD: type = Type.UPDATE; break; case FORCED: type = Type.UPDATE_NONFASTFORWARD; break; default: LOGGER.error(MessageFormat.format("unexpected ref update type {0} for {1}", ru.getResult(), ru.getName())); return; } ReceiveCommand cmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(), ru.getName(), type); RefLogUtils.updateRefLog(user, getRepository(), Arrays.asList(cmd)); } /** * Merge the specified patchset to the integration branch. * * @param ticket * @param patchset * @return true, if successful */ public MergeStatus merge(TicketModel ticket) { PersonIdent committer = new PersonIdent(user.getDisplayName(), StringUtils.isEmpty(user.emailAddress) ? (user.username + "@gitblit") : user.emailAddress); Patchset patchset = ticket.getCurrentPatchset(); String message = MessageFormat.format("Merged #{0,number,0} \"{1}\"", ticket.number, ticket.title); Ref oldRef = null; try { oldRef = getRepository().getRef(ticket.mergeTo); } catch (IOException e) { LOGGER.error("failed to get ref for " + ticket.mergeTo, e); } MergeResult mergeResult = JGitUtils.merge( getRepository(), patchset.tip, ticket.mergeTo, committer, message); if (StringUtils.isEmpty(mergeResult.sha)) { LOGGER.error("FAILED to merge {} to {} ({})", new Object [] { patchset, ticket.mergeTo, mergeResult.status.name() }); return mergeResult.status; } Change change = new Change(user.username); change.setField(Field.status, Status.Merged); change.setField(Field.mergeSha, mergeResult.sha); change.setField(Field.mergeTo, ticket.mergeTo); if (StringUtils.isEmpty(ticket.responsible)) { // unassigned tickets are assigned to the closer change.setField(Field.responsible, user.username); } long ticketId = ticket.number; ticket = ticketService.updateTicket(repository, ticket.number, change); if (ticket != null) { ticketNotifier.queueMailing(ticket); // update the reflog with the merge if (oldRef != null) { ReceiveCommand cmd = new ReceiveCommand(oldRef.getObjectId(), ObjectId.fromString(mergeResult.sha), oldRef.getName()); RefLogUtils.updateRefLog(user, getRepository(), Arrays.asList(cmd)); } return mergeResult.status; } else { LOGGER.error("FAILED to resolve ticket {} by merge from web ui", ticketId); } return mergeResult.status; } public void sendAll() { ticketNotifier.sendAll(); } }
package info.tomaszminiach.superspinner; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; @SuppressWarnings("unused") public class SuperSpinner extends FrameLayout { //only package private fields boolean isFilterable = false; ListAdapter mAdapter; String emptyText = "no data"; FilterListener filterListener; CallbackFilterListener callbackFilterListener; View hintView; AdapterView.OnItemSelectedListener onItemSelectedListener; Object selectedItem; OnClickListener externalOnClickListener; PopupViewHolder popupViewHolder; OnClickListener internalOnClickListener = new OnClickListener() { @Override public void onClick(View view) { showPopup(); if (externalOnClickListener != null) { externalOnClickListener.onClick(view); } } }; void showPopup(){ LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.view_superspinner_popup, SuperSpinner.this, false); popupViewHolder = new PopupViewHolder(); popupViewHolder.searchIcon = layout.findViewById(R.id.searchImage); popupViewHolder.searchProgressBar = layout.findViewById(R.id.progressBar); final AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(layout); final AlertDialog dialog = builder.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { popupViewHolder=null; } }); dialog.show(); popupViewHolder.emptyView = (TextView) layout.findViewById(R.id.emptyView); popupViewHolder.emptyView.setGravity(Gravity.CENTER); popupViewHolder.emptyView.setText(emptyText); popupViewHolder.list = (ListView) layout.findViewById(R.id.listView); popupViewHolder.list.setEmptyView(popupViewHolder.emptyView); popupViewHolder.list.setAdapter(mAdapter); final EditText filterEditText = (EditText) layout.findViewById(R.id.editText); View searchLayout = layout.findViewById(R.id.searchLayout); popupViewHolder.list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { selectItem(i); dialog.dismiss(); if (onItemSelectedListener != null) onItemSelectedListener.onItemSelected(adapterView, view, i, l); } }); if (filterListener != null || callbackFilterListener != null) { searchLayout.setVisibility(VISIBLE); filter(null);//initial request filterEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { filter(filterEditText.getText().toString()); } }); } else { searchLayout.setVisibility(GONE); } } public OnClickListener getExternalOnClickListener() { return externalOnClickListener; } @Override public void setOnClickListener(OnClickListener externalOnClickListener) { this.externalOnClickListener = externalOnClickListener; } void showState(boolean isSearching) { if (popupViewHolder==null) return; if (isSearching) { popupViewHolder.emptyView.setVisibility(INVISIBLE); popupViewHolder.searchProgressBar.setVisibility(VISIBLE); popupViewHolder.searchIcon.setVisibility(GONE); } else { popupViewHolder.emptyView.setVisibility(VISIBLE); popupViewHolder.searchProgressBar.setVisibility(GONE); popupViewHolder.searchIcon.setVisibility(VISIBLE); } } void filter(String text) { if(popupViewHolder==null) return; if (filterListener != null) { mAdapter = filterListener.onFilter(text); popupViewHolder.list.setAdapter(mAdapter); } if (callbackFilterListener != null) { showState(true); ListAdapter result = callbackFilterListener.onFilter(text, registerCallback()); } } Callback registerCallback() { return new Callback() { @Override public void provideAdapter(ListAdapter adapter) { if(popupViewHolder==null) return; showState(false); mAdapter = adapter; popupViewHolder.list.setAdapter(mAdapter); } }; } /** * be careful when using this method - make sure that the requested position is valid for * adapter which is currently assigned (every filtering can replace adapter) * * @param i position of item in adapter */ public void selectItem(int i) { removeAllViews(); addView(mAdapter.getView(i, null, SuperSpinner.this)); selectedItem = mAdapter.getItem(i); } /** * This spinner do not require any adapter assigned - it can request for it only when it is needed. * You can set the selected item by passing just this item and corresponding view. * * @param selectedItem object * @param view view */ public void selectItem(Object selectedItem, View view) { removeAllViews(); addView(view); this.selectedItem = selectedItem; } public int getCount() { return mAdapter.getCount(); } public SuperSpinner(Context context) { super(context); init(context); } public SuperSpinner(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public SuperSpinner(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public SuperSpinner(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } void init(final Context context) { hintView = new TextView(context); ((TextView) hintView).setText(R.string.select); hintView.setPadding(5, 5, 5, 5); removeAllViews(); addView(hintView); super.setOnClickListener(internalOnClickListener); } public boolean isFilterable() { return isFilterable; } /** * set if filter is visible * * @deprecated The spinner is filterable when one of listeners is not null, and not filterable * when both are null. To set them use {@link #setFilterListener(FilterListener)} or * {@link #setCallbackFilterListener(CallbackFilterListener)} */ @Deprecated public void setFilterable(boolean IS_FILTERABLE) { this.isFilterable = IS_FILTERABLE; } /** * Set the adapter for the spinner. The adapter is then passed to internal instance of * {@link ListView}. * If {@link #setFilterListener(FilterListener)} or * {@link #setCallbackFilterListener(CallbackFilterListener)} are used then there might be no * need to use this methid. * * @param adapter adapter to set */ public void setAdapter(ListAdapter adapter) { this.mAdapter = adapter; } public void swapAdapter(ListAdapter adapter) { setAdapter(adapter); } public FilterListener getFilterListener() { return filterListener; } public void setFilterListener(FilterListener filterListener) { this.filterListener = filterListener; } public CallbackFilterListener getCallbackFilterListener() { return callbackFilterListener; } public void setCallbackFilterListener(CallbackFilterListener callbackFilterListener) { this.callbackFilterListener = callbackFilterListener; } /** * Text that is shown when there are no items in the list * * @param emptyText the shown text */ public void setEmptyText(String emptyText) { this.emptyText = emptyText; if (popupViewHolder != null) popupViewHolder.emptyView.setText(emptyText); } /** * Set the view for not initial spinner state when nothing is selected. * By default its a simple "select" text with small padding * * @param v hint view */ public void setHintView(View v) { removeAllViews(); hintView = v; addView(hintView); } /** * Set the view for not initial spinner state when nothing is selected. * By default its a simple "select" text with small padding * * @param resourceId resource id of hint view */ public void setHintView(int resourceId) { removeAllViews(); LayoutInflater layoutInflater = LayoutInflater.from(getContext()); hintView = layoutInflater.inflate(resourceId, this); } /** * Set the view for not initial spinner state when nothing is selected. * By default its a simple "select" text with small padding * * @param resourceId resource id of hint view */ public void setHintView(int resourceId, int textViewResourceId, String text) { setHintView(resourceId); ((TextView)hintView.findViewById(textViewResourceId)).setText(text); } /** * Set the view for not initial spinner state when nothing is selected. * By default its a simple "select" text with small padding * * @param resourceId resource id of hint view */ public void setHintView(int resourceId, int textViewResourceId, int textResourceId) { setHintView(resourceId,textViewResourceId,getResources().getString(textResourceId)); } public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener onItemSelectedListener) { this.onItemSelectedListener = onItemSelectedListener; } public Object getSelectedItem() { return selectedItem; } //views on the popup class PopupViewHolder { ListView list; View searchIcon, searchProgressBar; TextView emptyView; } public interface FilterListener { ListAdapter onFilter(String text); } public interface CallbackFilterListener { ListAdapter onFilter(String text, Callback callback); } public interface Callback { void provideAdapter(ListAdapter adapter); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.metrics; import java.util.Objects; import org.apache.beam.sdk.metrics.MetricUpdates.MetricUpdate; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Matchers for metrics. */ public class MetricMatchers { /** * Matches a {@link MetricUpdate} with the given name and contents. * * <p>Visible since it may be used in runner-specific tests. */ public static <T> Matcher<MetricUpdate<T>> metricUpdate(final String name, final T update) { return new TypeSafeMatcher<MetricUpdate<T>>() { @Override protected boolean matchesSafely(MetricUpdate<T> item) { return Objects.equals(name, item.getKey().metricName().name()) && Objects.equals(update, item.getUpdate()); } @Override public void describeTo(Description description) { description .appendText("MetricUpdate{name=").appendValue(name) .appendText(", update=").appendValue(update) .appendText("}"); } }; } /** * Matches a {@link MetricUpdate} with the given namespace, name, step and contents. * * <p>Visible since it may be used in runner-specific tests. */ public static <T> Matcher<MetricUpdate<T>> metricUpdate( final String namespace, final String name, final String step, final T update) { return new TypeSafeMatcher<MetricUpdate<T>>() { @Override protected boolean matchesSafely(MetricUpdate<T> item) { return Objects.equals(namespace, item.getKey().metricName().namespace()) && Objects.equals(name, item.getKey().metricName().name()) && Objects.equals(step, item.getKey().stepName()) && Objects.equals(update, item.getUpdate()); } @Override public void describeTo(Description description) { description .appendText("MetricUpdate{inNamespace=").appendValue(namespace) .appendText(", name=").appendValue(name) .appendText(", step=").appendValue(step) .appendText(", update=").appendValue(update) .appendText("}"); } }; } /** * Matches a {@link MetricResult} with the given namespace, name and step, and whose attempted * value equals the given value. */ public static <T> Matcher<MetricResult<T>> attemptedMetricsResult( final String namespace, final String name, final String step, final T attempted) { return new TypeSafeMatcher<MetricResult<T>>() { @Override protected boolean matchesSafely(MetricResult<T> item) { return Objects.equals(namespace, item.name().namespace()) && Objects.equals(name, item.name().name()) && item.step().contains(step) && Objects.equals(attempted, item.attempted()); } @Override public void describeTo(Description description) { description .appendText("MetricResult{inNamespace=").appendValue(namespace) .appendText(", name=").appendValue(name) .appendText(", step=").appendValue(step) .appendText(", attempted=").appendValue(attempted) .appendText("}"); } @Override protected void describeMismatchSafely(MetricResult<T> item, Description mismatchDescription) { mismatchDescription.appendText("MetricResult{"); describeMetricsResultMembersMismatch(item, mismatchDescription, namespace, name, step); if (!Objects.equals(attempted, item.attempted())) { mismatchDescription .appendText("attempted: ").appendValue(attempted) .appendText(" != ").appendValue(item.attempted()); } mismatchDescription.appendText("}"); } }; } /** * Matches a {@link MetricResult} with the given namespace, name and step, and whose committed * value equals the given value. */ public static <T> Matcher<MetricResult<T>> committedMetricsResult( final String namespace, final String name, final String step, final T committed) { return new TypeSafeMatcher<MetricResult<T>>() { @Override protected boolean matchesSafely(MetricResult<T> item) { return Objects.equals(namespace, item.name().namespace()) && Objects.equals(name, item.name().name()) && item.step().contains(step) && Objects.equals(committed, item.committed()); } @Override public void describeTo(Description description) { description .appendText("MetricResult{inNamespace=").appendValue(namespace) .appendText(", name=").appendValue(name) .appendText(", step=").appendValue(step) .appendText(", committed=").appendValue(committed) .appendText("}"); } @Override protected void describeMismatchSafely(MetricResult<T> item, Description mismatchDescription) { mismatchDescription.appendText("MetricResult{"); describeMetricsResultMembersMismatch(item, mismatchDescription, namespace, name, step); if (!Objects.equals(committed, item.committed())) { mismatchDescription .appendText("committed: ").appendValue(committed) .appendText(" != ").appendValue(item.committed()); } mismatchDescription.appendText("}"); } }; } static Matcher<MetricResult<DistributionResult>> distributionAttemptedMinMax( final String namespace, final String name, final String step, final Long attemptedMin, final Long attemptedMax) { return new TypeSafeMatcher<MetricResult<DistributionResult>>() { @Override protected boolean matchesSafely(MetricResult<DistributionResult> item) { return Objects.equals(namespace, item.name().namespace()) && Objects.equals(name, item.name().name()) && item.step().contains(step) && Objects.equals(attemptedMin, item.attempted().min()) && Objects.equals(attemptedMax, item.attempted().max()); } @Override public void describeTo(Description description) { description .appendText("MetricResult{inNamespace=").appendValue(namespace) .appendText(", name=").appendValue(name) .appendText(", step=").appendValue(step) .appendText(", attemptedMin=").appendValue(attemptedMin) .appendText(", attemptedMax=").appendValue(attemptedMax) .appendText("}"); } @Override protected void describeMismatchSafely(MetricResult<DistributionResult> item, Description mismatchDescription) { mismatchDescription.appendText("MetricResult{"); describeMetricsResultMembersMismatch(item, mismatchDescription, namespace, name, step); if (!Objects.equals(attemptedMin, item.attempted())) { mismatchDescription .appendText("attemptedMin: ").appendValue(attemptedMin) .appendText(" != ").appendValue(item.attempted()); } if (!Objects.equals(attemptedMax, item.attempted())) { mismatchDescription .appendText("attemptedMax: ").appendValue(attemptedMax) .appendText(" != ").appendValue(item.attempted()); } mismatchDescription.appendText("}"); } }; } static Matcher<MetricResult<DistributionResult>> distributionCommittedMinMax( final String namespace, final String name, final String step, final Long committedMin, final Long committedMax) { return new TypeSafeMatcher<MetricResult<DistributionResult>>() { @Override protected boolean matchesSafely(MetricResult<DistributionResult> item) { return Objects.equals(namespace, item.name().namespace()) && Objects.equals(name, item.name().name()) && item.step().contains(step) && Objects.equals(committedMin, item.committed().min()) && Objects.equals(committedMax, item.committed().max()); } @Override public void describeTo(Description description) { description .appendText("MetricResult{inNamespace=").appendValue(namespace) .appendText(", name=").appendValue(name) .appendText(", step=").appendValue(step) .appendText(", committedMin=").appendValue(committedMin) .appendText(", committedMax=").appendValue(committedMax) .appendText("}"); } @Override protected void describeMismatchSafely(MetricResult<DistributionResult> item, Description mismatchDescription) { mismatchDescription.appendText("MetricResult{"); describeMetricsResultMembersMismatch(item, mismatchDescription, namespace, name, step); if (!Objects.equals(committedMin, item.committed())) { mismatchDescription .appendText("committedMin: ").appendValue(committedMin) .appendText(" != ").appendValue(item.committed()); } if (!Objects.equals(committedMax, item.committed())) { mismatchDescription .appendText("committedMax: ").appendValue(committedMax) .appendText(" != ").appendValue(item.committed()); } mismatchDescription.appendText("}"); } }; } private static <T> void describeMetricsResultMembersMismatch( MetricResult<T> item, Description mismatchDescription, String namespace, String name, String step) { if (!Objects.equals(namespace, item.name().namespace())) { mismatchDescription .appendText("inNamespace: ").appendValue(namespace) .appendText(" != ").appendValue(item.name().namespace()); } if (!Objects.equals(name, item.name().name())) { mismatchDescription .appendText("name: ").appendValue(name) .appendText(" != ").appendValue(item.name().name()); } if (!item.step().contains(step)) { mismatchDescription .appendText("step: ").appendValue(step) .appendText(" != ").appendValue(item.step()); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.visor.node; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.List; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.visor.VisorDataTransferObject; import org.apache.ignite.internal.visor.cache.VisorCache; import org.apache.ignite.internal.visor.cache.VisorMemoryMetrics; import org.apache.ignite.internal.visor.event.VisorGridEvent; import org.apache.ignite.internal.visor.igfs.VisorIgfs; import org.apache.ignite.internal.visor.igfs.VisorIgfsEndpoint; import org.apache.ignite.internal.visor.util.VisorExceptionWrapper; /** * Data collector job result. */ public class VisorNodeDataCollectorJobResult extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Grid name. */ private String gridName; /** Node topology version. */ private long topVer; /** Task monitoring state collected from node. */ private boolean taskMonitoringEnabled; /** Node events. */ private List<VisorGridEvent> evts = new ArrayList<>(); /** Exception while collecting node events. */ private VisorExceptionWrapper evtsEx; /** Node data region metrics. */ private List<VisorMemoryMetrics> memoryMetrics = new ArrayList<>(); /** Exception while collecting memory metrics. */ private VisorExceptionWrapper memoryMetricsEx; /** Node caches. */ private List<VisorCache> caches = new ArrayList<>(); /** Exception while collecting node caches. */ private VisorExceptionWrapper cachesEx; /** Node IGFSs. */ private List<VisorIgfs> igfss = new ArrayList<>(); /** All IGFS endpoints collected from nodes. */ private List<VisorIgfsEndpoint> igfsEndpoints = new ArrayList<>(); /** Exception while collecting node IGFSs. */ private VisorExceptionWrapper igfssEx; /** Errors count. */ private long errCnt; /** Topology version of latest completed partition exchange. */ private VisorAffinityTopologyVersion readyTopVer; /** Whether pending exchange future exists. */ private boolean hasPendingExchange; /** Persistence metrics. */ private VisorPersistenceMetrics persistenceMetrics; /** Exception while collecting persistence metrics. */ private VisorExceptionWrapper persistenceMetricsEx; /** * Default constructor. */ public VisorNodeDataCollectorJobResult() { // No-op. } /** * @return Grid name. */ public String getGridName() { return gridName; } /** * @param gridName New grid name value. */ public void setGridName(String gridName) { this.gridName = gridName; } /** * @return Current topology version. */ public long getTopologyVersion() { return topVer; } /** * @param topVer New topology version value. */ public void setTopologyVersion(long topVer) { this.topVer = topVer; } /** * @return Current task monitoring state. */ public boolean isTaskMonitoringEnabled() { return taskMonitoringEnabled; } /** * @param taskMonitoringEnabled New value of task monitoring state. */ public void setTaskMonitoringEnabled(boolean taskMonitoringEnabled) { this.taskMonitoringEnabled = taskMonitoringEnabled; } /** * @return Collection of collected events. */ public List<VisorGridEvent> getEvents() { return evts; } /** * @return Exception caught during collecting events. */ public VisorExceptionWrapper getEventsEx() { return evtsEx; } /** * @param evtsEx Exception caught during collecting events. */ public void setEventsEx(VisorExceptionWrapper evtsEx) { this.evtsEx = evtsEx; } /** * @return Collected data region metrics. */ public List<VisorMemoryMetrics> getMemoryMetrics() { return memoryMetrics; } /** * @return Exception caught during collecting memory metrics. */ public VisorExceptionWrapper getMemoryMetricsEx() { return memoryMetricsEx; } /** * @param memoryMetricsEx Exception caught during collecting memory metrics. */ public void setMemoryMetricsEx(VisorExceptionWrapper memoryMetricsEx) { this.memoryMetricsEx = memoryMetricsEx; } /** * @return Collected cache metrics. */ public List<VisorCache> getCaches() { return caches; } /** * @return Exception caught during collecting caches metrics. */ public VisorExceptionWrapper getCachesEx() { return cachesEx; } /** * @param cachesEx Exception caught during collecting caches metrics. */ public void setCachesEx(VisorExceptionWrapper cachesEx) { this.cachesEx = cachesEx; } /** * @return Collected IGFSs metrics. */ public List<VisorIgfs> getIgfss() { return igfss; } /** * @return Collected IGFSs endpoints. */ public List<VisorIgfsEndpoint> getIgfsEndpoints() { return igfsEndpoints; } /** * @return Exception caught during collecting IGFSs metrics. */ public VisorExceptionWrapper getIgfssEx() { return igfssEx; } /** * @param igfssEx Exception caught during collecting IGFSs metrics. */ public void setIgfssEx(VisorExceptionWrapper igfssEx) { this.igfssEx = igfssEx; } /** * @return Errors count. */ public long getErrorCount() { return errCnt; } /** * @param errCnt Errors count. */ public void setErrorCount(long errCnt) { this.errCnt = errCnt; } /** * @return Topology version of latest completed partition exchange. */ public VisorAffinityTopologyVersion getReadyAffinityVersion() { return readyTopVer; } /** * @param readyTopVer Topology version of latest completed partition exchange. */ public void setReadyAffinityVersion(VisorAffinityTopologyVersion readyTopVer) { this.readyTopVer = readyTopVer; } /** * @return Whether pending exchange future exists. */ public boolean isHasPendingExchange() { return hasPendingExchange; } /** * @param hasPendingExchange Whether pending exchange future exists. */ public void setHasPendingExchange(boolean hasPendingExchange) { this.hasPendingExchange = hasPendingExchange; } /** * Get persistence metrics. */ public VisorPersistenceMetrics getPersistenceMetrics() { return persistenceMetrics; } /** * Set persistence metrics. * * @param persistenceMetrics Persistence metrics. */ public void setPersistenceMetrics(VisorPersistenceMetrics persistenceMetrics) { this.persistenceMetrics = persistenceMetrics; } /** * @return Exception caught during collecting persistence metrics. */ public VisorExceptionWrapper getPersistenceMetricsEx() { return persistenceMetricsEx; } /** * @param persistenceMetricsEx Exception caught during collecting persistence metrics. */ public void setPersistenceMetricsEx(VisorExceptionWrapper persistenceMetricsEx) { this.persistenceMetricsEx = persistenceMetricsEx; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeString(out, gridName); out.writeLong(topVer); out.writeBoolean(taskMonitoringEnabled); U.writeCollection(out, evts); out.writeObject(evtsEx); U.writeCollection(out, memoryMetrics); out.writeObject(memoryMetricsEx); U.writeCollection(out, caches); out.writeObject(cachesEx); U.writeCollection(out, igfss); U.writeCollection(out, igfsEndpoints); out.writeObject(igfssEx); out.writeLong(errCnt); out.writeObject(readyTopVer); out.writeBoolean(hasPendingExchange); out.writeObject(persistenceMetrics); out.writeObject(persistenceMetricsEx); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { gridName = U.readString(in); topVer = in.readLong(); taskMonitoringEnabled = in.readBoolean(); evts = U.readList(in); evtsEx = (VisorExceptionWrapper)in.readObject(); memoryMetrics = U.readList(in); memoryMetricsEx = (VisorExceptionWrapper)in.readObject(); caches = U.readList(in); cachesEx = (VisorExceptionWrapper)in.readObject(); igfss = U.readList(in); igfsEndpoints = U.readList(in); igfssEx = (VisorExceptionWrapper)in.readObject(); errCnt = in.readLong(); readyTopVer = (VisorAffinityTopologyVersion)in.readObject(); hasPendingExchange = in.readBoolean(); persistenceMetrics = (VisorPersistenceMetrics)in.readObject(); persistenceMetricsEx = (VisorExceptionWrapper)in.readObject(); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(VisorNodeDataCollectorJobResult.class, this); } }
package jar; import java.awt.Color; import java.awt.Graphics2D; import java.util.HashMap; import java.util.Map; import robocode.AdvancedRobot; import robocode.BattleEndedEvent; import robocode.Bullet; import robocode.BulletHitBulletEvent; import robocode.BulletHitEvent; import robocode.BulletMissedEvent; import robocode.DeathEvent; import robocode.HitByBulletEvent; import robocode.HitRobotEvent; import robocode.HitWallEvent; import robocode.RobotDeathEvent; import robocode.RoundEndedEvent; import robocode.ScannedRobotEvent; import robocode.SkippedTurnEvent; import robocode.WinEvent; /* * TODO every bot has an InverseDriver, InverseRaddar, InverseGunner that gets updated when I call bot.update... * TODO these are trying to predict what the bot is doing (including my own special case) * TODO then the main advanced robot (my jar.Vis) just runs its own Driver/Raddar/Gunner to actually generate stuff */ // jar.Vis public class Vis extends AdvancedRobot { boolean printEvents = true; // Battle Properties double room_width, room_height; double time; boolean debug = true; boolean fire_gun = false; boolean oneVoneAssumption = true; long millis_test = 1; long run_avg = 67; long min_skip = 36; // Robot Properties Bot bot; Driver d; Gunner g; Raddar r; // Enemy Robots Map<String, Bot> bots; public void run() { // "Constructor" this.setRotateFree(); this.setColor(Color.ORANGE); bots = new HashMap<String, Bot>(); bot = new Bot(this); d = new Driver(bot); g = new Gunner(bot); r = new Raddar(bot); // Battle Properties room_width = this.getBattleFieldWidth(); room_height = this.getBattleFieldHeight(); setTurnRadarRightRadians(Math.PI*2); while(getRadarTurnRemainingRadians() > 0.005) { // While the robot is doing it's initial scan bot.update(this); execute(); } while (true) { // default actions. Overwrite with better ones setTurnLeftRadians(d.angular()); setAhead(d.linear()); setTurnGunLeftRadians(g.angular()); // setTurnRadarLeftRadians(r.angular()); if(r.fire()) { System.out.println("Trying to fire gun..."); this.fire(1.0); } bot.update(this); long start_time = System.nanoTime(); // System.out.println("Begin wait ("+millis_test+") @ "+start_time/1000000); while (System.nanoTime() - start_time < 1000000*millis_test && System.nanoTime() - start_time > 0) { // wait } // System.out.println("End wait ("+millis_test+") @ "+System.nanoTime()/1000000); // millis_test += 1; execute(); } /* setTurnGunLeftRadians(1.0); setTurnLeftRadians(1.0); */ } /* * Debug printing options */ private void printEvent(robocode.Event e) { System.out.println(""+System.nanoTime()+" "+e.getClass()); } /* * Utilities */ public void setRotateFree() { this.setAdjustGunForRobotTurn(true); this.setAdjustRadarForGunTurn(true); this.setAdjustRadarForRobotTurn(true); } public void setColor(Color c) { // body, gun, radar, bullet, scan arc this.setColors(c, c, c, c, c); } public double distance(double x, double y) { return Math.sqrt(x*x-y*y); } public double flip_rotation(double other_heading) { double temp = -other_heading + Math.PI/2; while (temp > Math.PI * 2) { temp = temp - Math.PI * 2; } while (temp < -Math.PI * 2) { temp = temp + Math.PI * 2; } return temp; } /* * Event Handlers */ public void onBattleEnded(BattleEndedEvent bee) { if (printEvents) printEvent(bee); } public void onScannedRobot(ScannedRobotEvent sre) { if (printEvents) printEvent(sre); bot.update(this, sre); // simulate a scan data for that robot ScannedRobotEvent flipped = new ScannedRobotEvent(this.getName(), this.getEnergy(), sre.getBearingRadians()+Math.PI, sre.getDistance(), this.getHeadingRadians(), this.getVelocity(), false); if (!bots.containsKey(sre.getName())) { bots.put(sre.getName(), new Bot(sre.getName())); } double robocode_heading = sre.getBearingRadians() + this.getHeadingRadians(); double true_heading = flip_rotation(robocode_heading); double other_x = this.getX() + sre.getDistance()*Math.cos(true_heading); double other_y = this.getY() + sre.getDistance()*Math.sin(true_heading); bots.get(sre.getName()).update(flipped, other_x, other_y, sre.getHeadingRadians()); if (oneVoneAssumption) { // run a tight laser scan double robocode_current_radar = this.getRadarHeadingRadians(); double other_heading = flip_rotation(sre.getHeadingRadians()); // I have other_x, other_y double dx = other_x+sre.getVelocity()*Math.cos(other_heading) - this.getX(); double dy = other_y+sre.getVelocity()*Math.sin(other_heading) - this.getY(); System.out.println("vx, vy | "+(sre.getVelocity()*Math.cos(other_heading))+","+ (sre.getVelocity()*Math.sin(other_heading))); System.out.println("dx, dy | "+dx+","+dy); double goal_radar = Math.atan2(dy, dx); double robocode_goal_radar = flip_rotation(goal_radar); double radar_delta = robocode_goal_radar - robocode_current_radar; System.out.println("delta: "+radar_delta); double scale = 0.00001; while (radar_delta > Math.PI*2) { radar_delta = radar_delta - Math.PI*2; } while (radar_delta < -Math.PI*2) { radar_delta = radar_delta + Math.PI*2; } if (radar_delta > Math.PI) { radar_delta = -Math.PI*2 + radar_delta; } if (radar_delta < -Math.PI) { radar_delta = Math.PI*2 + radar_delta; } if (radar_delta >= 0.0 && radar_delta < scale) { radar_delta = scale; } else if (radar_delta <= 0.0 && radar_delta > -scale) { radar_delta = -scale; } this.setTurnRadarRightRadians(radar_delta); } } public void onBulletHit(BulletHitEvent bhe) { if (printEvents) printEvent(bhe); // when my bullet hits another robot String otherName = bhe.getName(); // double otherEnergy = bhe.getEnergy(); // Bullet myBullet = bhe.getBullet(); // double x = myBullet.getX(); // double y = myBullet.getY(); // double heading = myBullet.getHeadingRadians(); // boolean active = myBullet.isActive(); bot.update(bhe); HitByBulletEvent flipped = toHitByBullet(this, bhe); if (!bots.containsKey(otherName)) { // send synthesized data to the other Bot model bots.put(otherName, new Bot(otherName)); } bots.get(otherName).update(this, flipped); } private HitByBulletEvent toHitByBullet(Vis self, BulletHitEvent bhe) { double otherX = self.bot.robotData.get(bhe.getName()).last().x; double otherY = self.bot.robotData.get(bhe.getName()).last().y; double otherHeading = self.bot.robotData.get(bhe.getName()).last().heading; double bulletX = bhe.getBullet().getX(); double bulletY = bhe.getBullet().getY(); double bearing = Math.atan2(bulletY-otherY, bulletX-otherX) - otherHeading; return new HitByBulletEvent(bearing, bhe.getBullet()); } public void onBulletHitBullet(BulletHitBulletEvent bhbe) { // when my bullet hits another bullet if (printEvents) printEvent(bhbe); // Bullet myBullet = bhbe.getBullet(); Bullet otherBullet = bhbe.getHitBullet(); String otherName = otherBullet.getName(); // double x = myBullet.getX(); // double y = myBullet.getY(); // // double myHeading = myBullet.getHeadingRadians(); // double otherHeading = otherBullet.getHeadingRadians(); // // double myVelocity = myBullet.getVelocity(); // double otherVelocity = otherBullet.getVelocity(); bot.update(bhbe); BulletHitBulletEvent flipped = flipBHBE(bhbe); if (!bots.containsKey(otherName)) { // simulate a bullet hit bullet event for another robot bots.put(otherName, new Bot(otherName)); } bots.get(otherName).update(this, flipped); } private BulletHitBulletEvent flipBHBE(BulletHitBulletEvent bhbe) { return new BulletHitBulletEvent(bhbe.getHitBullet(), bhbe.getBullet()); } public void onBulletMissed(BulletMissedEvent bme) { // when my bullet hits the wall (misses) if (printEvents) printEvent(bme); Bullet myBullet = bme.getBullet(); double x = myBullet.getX(); double y = myBullet.getY(); double myHeading = myBullet.getHeadingRadians(); double myVelocity = myBullet.getVelocity(); bot.update(bme); } public void onHitByBullet(HitByBulletEvent hbbe) { // when my robot is hit by another bullet if (printEvents) printEvent(hbbe); bot.update(hbbe); String otherName = hbbe.getName(); BulletHitEvent flipped = toBulletHitEvent(hbbe); if (!bots.containsKey(otherName)) { bots.put(otherName, new Bot(otherName)); } bots.get(otherName).update(this, flipped); } private BulletHitEvent toBulletHitEvent(HitByBulletEvent hbbe) { return new BulletHitEvent(this.getName(), this.getEnergy(), hbbe.getBullet()); } public void onHitRobot(HitRobotEvent hre) { // when my robot hits another robot if (printEvents) printEvent(hre); bot.update(hre); String otherName = hre.getName(); HitRobotEvent flipped = flipHRE(hre); if (!bots.containsKey(otherName)) { bots.put(otherName, new Bot(otherName)); } bots.get(otherName).update(this, flipped); } private HitRobotEvent flipHRE(HitRobotEvent hre) { return new HitRobotEvent(this.getName(), hre.getBearingRadians()+Math.PI, this.getEnergy(), !hre.isMyFault()); } public void onHitWall(HitWallEvent hwe) { // when my robot hits the wall if (printEvents) printEvent(hwe); bot.update(hwe); } /* * Game Events */ public void onSkippedTurn(SkippedTurnEvent ste) { if (printEvents) printEvent(ste); run_avg = (run_avg + millis_test)/2; if (millis_test < min_skip) { min_skip = millis_test; } System.out.println("millis_test: last: "+millis_test+" avg: "+run_avg+" min: "+min_skip); millis_test = millis_test/2; } public void onDeath(DeathEvent de) { // when my robot dies/loses if (printEvents) printEvent(de); bot.update(de); } public void onWin(WinEvent we) { // when my robot wins if (printEvents) printEvent(we); bot.update(we); } public void onRobotDeath(RobotDeathEvent rde) { // when another robot dies if (printEvents) printEvent(rde); bot.update(rde); } public void onRoundEnded(RoundEndedEvent ree) { // called when a round ends if (printEvents) printEvent(ree); bot.update(ree); } /* * Visual Effects */ public void onPaint(Graphics2D g) { // when my robot is painted System.out.println("Print Robot Model"); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.tools.util.threeside; import com.intellij.diff.DiffContext; import com.intellij.diff.DiffDialogHints; import com.intellij.diff.DiffManager; import com.intellij.diff.contents.DiffContent; import com.intellij.diff.contents.DocumentContent; import com.intellij.diff.requests.ContentDiffRequest; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.diff.tools.util.DiffDataKeys; import com.intellij.diff.tools.util.FocusTrackerSupport.ThreesideFocusTrackerSupport; import com.intellij.diff.tools.util.SimpleDiffPanel; import com.intellij.diff.tools.util.SyncScrollSupport; import com.intellij.diff.tools.util.SyncScrollSupport.ThreesideSyncScrollSupport; import com.intellij.diff.tools.util.base.InitialScrollPositionSupport; import com.intellij.diff.tools.util.base.TextDiffViewerBase; import com.intellij.diff.util.DiffUtil; import com.intellij.diff.util.Side; import com.intellij.diff.util.ThreeSide; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diff.DiffBundle; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.VisibleAreaEvent; import com.intellij.openapi.editor.event.VisibleAreaListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; public abstract class ThreesideTextDiffViewer extends TextDiffViewerBase { public static final Logger LOG = Logger.getInstance(ThreesideTextDiffViewer.class); @NotNull private final EditorFactory myEditorFactory = EditorFactory.getInstance(); @NotNull protected final SimpleDiffPanel myPanel; @NotNull protected final ThreesideTextContentPanel myContentPanel; @NotNull private final List<EditorEx> myEditors; @NotNull private final List<DocumentContent> myActualContents; @NotNull private final MyVisibleAreaListener myVisibleAreaListener1 = new MyVisibleAreaListener(Side.LEFT); @NotNull private final MyVisibleAreaListener myVisibleAreaListener2 = new MyVisibleAreaListener(Side.RIGHT); @NotNull protected final MySetEditorSettingsAction myEditorSettingsAction; @NotNull private final ThreesideFocusTrackerSupport myFocusTrackerSupport; @Nullable private ThreesideSyncScrollSupport mySyncScrollSupport; public ThreesideTextDiffViewer(@NotNull DiffContext context, @NotNull ContentDiffRequest request) { super(context, request); List<DiffContent> contents = myRequest.getContents(); myActualContents = ContainerUtil.newArrayList((DocumentContent)contents.get(0), (DocumentContent)contents.get(1), (DocumentContent)contents.get(2)); myEditors = createEditors(); List<JComponent> titlePanel = DiffUtil.createTextTitles(myRequest, getEditors()); myFocusTrackerSupport = new ThreesideFocusTrackerSupport(getEditors()); myContentPanel = new ThreesideTextContentPanel(getEditors(), titlePanel); myPanel = new SimpleDiffPanel(myContentPanel, this, context); //new MyFocusOppositePaneAction().setupAction(myPanel, this); // TODO myEditorSettingsAction = new MySetEditorSettingsAction(); myEditorSettingsAction.applyDefaults(); } @Override @CalledInAwt protected void onDispose() { super.onDispose(); destroyEditors(); } @Override @CalledInAwt protected void processContextHints() { super.processContextHints(); myFocusTrackerSupport.processContextHints(myRequest, myContext); } @Override @CalledInAwt protected void updateContextHints() { super.updateContextHints(); myFocusTrackerSupport.updateContextHints(myRequest, myContext); } @NotNull protected List<EditorEx> createEditors() { boolean[] forceReadOnly = checkForceReadOnly(); List<EditorEx> editors = new ArrayList<EditorEx>(3); for (int i = 0; i < getActualContents().size(); i++) { DocumentContent content = getActualContents().get(i); EditorEx editor = DiffUtil.createEditor(content.getDocument(), myProject, forceReadOnly[i], true); DiffUtil.configureEditor(editor, content, myProject); editors.add(editor); if (Registry.is("diff.divider.repainting.disable.blitting")) { editor.getScrollPane().getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); } } editors.get(0).setVerticalScrollbarOrientation(EditorEx.VERTICAL_SCROLLBAR_LEFT); ((EditorMarkupModel)editors.get(1).getMarkupModel()).setErrorStripeVisible(false); return editors; } private void destroyEditors() { for (EditorEx editor : getEditors()) { myEditorFactory.releaseEditor(editor); } } // // Listeners // @CalledInAwt @Override protected void installEditorListeners() { super.installEditorListeners(); getEditor(ThreeSide.LEFT).getScrollingModel().addVisibleAreaListener(myVisibleAreaListener1); getEditor(ThreeSide.BASE).getScrollingModel().addVisibleAreaListener(myVisibleAreaListener1); getEditor(ThreeSide.BASE).getScrollingModel().addVisibleAreaListener(myVisibleAreaListener2); getEditor(ThreeSide.RIGHT).getScrollingModel().addVisibleAreaListener(myVisibleAreaListener2); SyncScrollSupport.SyncScrollable scrollable1 = getSyncScrollable(Side.LEFT); SyncScrollSupport.SyncScrollable scrollable2 = getSyncScrollable(Side.RIGHT); if (scrollable1 != null && scrollable2 != null) { mySyncScrollSupport = new ThreesideSyncScrollSupport(getEditors(), scrollable1, scrollable2); } } @CalledInAwt @Override public void destroyEditorListeners() { super.destroyEditorListeners(); getEditor(ThreeSide.LEFT).getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener1); getEditor(ThreeSide.BASE).getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener1); getEditor(ThreeSide.BASE).getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener2); getEditor(ThreeSide.RIGHT).getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener2); mySyncScrollSupport = null; } protected void disableSyncScrollSupport(boolean disable) { if (mySyncScrollSupport != null) { mySyncScrollSupport.setDisabled(disable); } } // // Diff // @Override protected void onDocumentChange(@NotNull DocumentEvent event) { super.onDocumentChange(event); myContentPanel.repaintDividers(); } // // Getters // @NotNull @Override public JComponent getComponent() { return myPanel; } @Nullable @Override public JComponent getPreferredFocusedComponent() { return getCurrentEditor().getContentComponent(); } @NotNull public EditorEx getCurrentEditor() { return getEditor(getCurrentSide()); } @NotNull public DocumentContent getCurrentContent() { return getCurrentSide().select(getActualContents()); } @NotNull @Override protected List<? extends EditorEx> getEditors() { return myEditors; } @NotNull protected EditorEx getEditor(@NotNull ThreeSide side) { return side.select(myEditors); } @NotNull public List<DocumentContent> getActualContents() { return myActualContents; } @NotNull public ThreeSide getCurrentSide() { return myFocusTrackerSupport.getCurrentSide(); } public void setCurrentSide(@NotNull ThreeSide side) { myFocusTrackerSupport.setCurrentSide(side); } // // Abstract // @CalledInAwt protected void scrollToLine(@NotNull ThreeSide side, int line) { Editor editor = getEditor(side); DiffUtil.scrollEditor(editor, line, false); setCurrentSide(side); } @Nullable protected abstract SyncScrollSupport.SyncScrollable getSyncScrollable(@NotNull Side side); // // Misc // @Nullable @Override protected OpenFileDescriptor getOpenFileDescriptor() { EditorEx editor = getCurrentEditor(); int offset = editor.getCaretModel().getOffset(); return getCurrentContent().getOpenFileDescriptor(offset); } public static boolean canShowRequest(@NotNull DiffContext context, @NotNull DiffRequest request) { if (!(request instanceof ContentDiffRequest)) return false; List<DiffContent> contents = ((ContentDiffRequest)request).getContents(); if (contents.size() != 3) return false; boolean canShow = true; boolean wantShow = false; for (DiffContent content : contents) { canShow &= canShowContent(content); wantShow |= wantShowContent(content); } return canShow && wantShow; } public static boolean canShowContent(@NotNull DiffContent content) { if (content instanceof DocumentContent) return true; return false; } public static boolean wantShowContent(@NotNull DiffContent content) { if (content instanceof DocumentContent) return true; return false; } // // Actions // protected class ShowLeftBasePartialDiffAction extends ShowPartialDiffAction { public ShowLeftBasePartialDiffAction() { super(ThreeSide.LEFT, ThreeSide.BASE, DiffBundle.message("merge.partial.diff.action.name.0.1"), null, AllIcons.Diff.LeftDiff); } } protected class ShowBaseRightPartialDiffAction extends ShowPartialDiffAction { public ShowBaseRightPartialDiffAction() { super(ThreeSide.BASE, ThreeSide.RIGHT, DiffBundle.message("merge.partial.diff.action.name.1.2"), null, AllIcons.Diff.RightDiff); } } protected class ShowLeftRightPartialDiffAction extends ShowPartialDiffAction { public ShowLeftRightPartialDiffAction() { super(ThreeSide.LEFT, ThreeSide.RIGHT, DiffBundle.message("merge.partial.diff.action.name"), null, AllIcons.Diff.BranchDiff); } } protected class ShowPartialDiffAction extends DumbAwareAction { @NotNull private final ThreeSide mySide1; @NotNull private final ThreeSide mySide2; public ShowPartialDiffAction(@NotNull ThreeSide side1, @NotNull ThreeSide side2, @NotNull String text, @Nullable String description, @NotNull Icon icon) { super(text, description, icon); mySide1 = side1; mySide2 = side2; } @Override public void actionPerformed(AnActionEvent e) { List<DiffContent> contents = myRequest.getContents(); List<String> titles = myRequest.getContentTitles(); DiffRequest request = new SimpleDiffRequest(myRequest.getTitle(), mySide1.select(contents), mySide2.select(contents), mySide1.select(titles), mySide2.select(titles)); DiffManager.getInstance().showDiff(myProject, request, new DiffDialogHints(null, myPanel)); } } // // Helpers // @Nullable @Override public Object getData(@NonNls String dataId) { if (DiffDataKeys.CURRENT_EDITOR.is(dataId)) { return getCurrentEditor(); } else if (CommonDataKeys.VIRTUAL_FILE.is(dataId)) { return DiffUtil.getVirtualFile(myRequest, getCurrentSide()); } else if (DiffDataKeys.CURRENT_CONTENT.is(dataId)) { return getCurrentContent(); } return super.getData(dataId); } private class MyVisibleAreaListener implements VisibleAreaListener { @NotNull Side mySide; public MyVisibleAreaListener(@NotNull Side side) { mySide = side; } @Override public void visibleAreaChanged(VisibleAreaEvent e) { if (mySyncScrollSupport != null) mySyncScrollSupport.visibleAreaChanged(e); if (Registry.is("diff.divider.repainting.fix")) { myContentPanel.repaint(); } else { myContentPanel.repaintDivider(mySide); } } } protected abstract class MyInitialScrollPositionHelper extends InitialScrollPositionSupport.ThreesideInitialScrollHelper { @NotNull @Override protected List<? extends Editor> getEditors() { return ThreesideTextDiffViewer.this.getEditors(); } @Override protected void disableSyncScroll(boolean value) { disableSyncScrollSupport(value); } @Override protected boolean doScrollToLine() { if (myScrollToLine == null) return false; ThreeSide side = myScrollToLine.first; Integer line = myScrollToLine.second; if (getEditor(side) == null) return false; scrollToLine(side, line); return true; } } }
/* * 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/resourcemanager/v3/tag_keys.proto package com.google.cloud.resourcemanager.v3; /** * * * <pre> * Runtime operation information for creating a TagKey. * </pre> * * Protobuf type {@code google.cloud.resourcemanager.v3.CreateTagKeyMetadata} */ public final class CreateTagKeyMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.resourcemanager.v3.CreateTagKeyMetadata) CreateTagKeyMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use CreateTagKeyMetadata.newBuilder() to construct. private CreateTagKeyMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateTagKeyMetadata() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateTagKeyMetadata(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CreateTagKeyMetadata( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.resourcemanager.v3.TagKeysProto .internal_static_google_cloud_resourcemanager_v3_CreateTagKeyMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.resourcemanager.v3.TagKeysProto .internal_static_google_cloud_resourcemanager_v3_CreateTagKeyMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.class, com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata)) { return super.equals(obj); } com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata other = (com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Runtime operation information for creating a TagKey. * </pre> * * Protobuf type {@code google.cloud.resourcemanager.v3.CreateTagKeyMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.resourcemanager.v3.CreateTagKeyMetadata) com.google.cloud.resourcemanager.v3.CreateTagKeyMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.resourcemanager.v3.TagKeysProto .internal_static_google_cloud_resourcemanager_v3_CreateTagKeyMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.resourcemanager.v3.TagKeysProto .internal_static_google_cloud_resourcemanager_v3_CreateTagKeyMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.class, com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.Builder.class); } // Construct using com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.resourcemanager.v3.TagKeysProto .internal_static_google_cloud_resourcemanager_v3_CreateTagKeyMetadata_descriptor; } @java.lang.Override public com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata getDefaultInstanceForType() { return com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.getDefaultInstance(); } @java.lang.Override public com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata build() { com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata buildPartial() { com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata result = new com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata) { return mergeFrom((com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata other) { if (other == com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.resourcemanager.v3.CreateTagKeyMetadata) } // @@protoc_insertion_point(class_scope:google.cloud.resourcemanager.v3.CreateTagKeyMetadata) private static final com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata(); } public static com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateTagKeyMetadata> PARSER = new com.google.protobuf.AbstractParser<CreateTagKeyMetadata>() { @java.lang.Override public CreateTagKeyMetadata parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CreateTagKeyMetadata(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CreateTagKeyMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateTagKeyMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package ejb_generated; import static javax.persistence.GenerationType.IDENTITY; import static javax.persistence.CascadeType.ALL; import javax.persistence.CascadeType; import java.util.HashSet; import java.util.Set; import javax.persistence.Enumerated; import javax.persistence.EnumType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.ManyToMany; import javax.persistence.JoinTable; /** Class generated using Kroki EJBGenerator @Author KROKI Team Creation date: 06.06.2016 13:28:38h **/ @Entity @Table(name = "C1_GEOGRAPHIC_BOUNDING_BOX") public class CfGeoBBox implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "ID", unique = true, nullable = false) protected java.lang.Long id; @Column(name = "cfGeoBBoxId", unique = false, nullable = false , length = 128, precision = 0,columnDefinition = "CHAR") protected java.lang.String ka_geographic_bounding_box_identifier; @Column(name = "cfWBLong", unique = false, nullable = false ,columnDefinition = "FLOAT") protected java.math.BigDecimal ka_west_bound_longitude; @Column(name = "cfEBLong", unique = false, nullable = false ,columnDefinition = "FLOAT") protected java.math.BigDecimal ka_east_bound_longitude; @Column(name = "cfSBLat", unique = false, nullable = false ,columnDefinition = "FLOAT") protected java.math.BigDecimal ka_south_bound_latitude; @Column(name = "cfNBLat", unique = false, nullable = false ,columnDefinition = "FLOAT") protected java.math.BigDecimal ka_north_bound_latitude; @Column(name = "cfMinElev", unique = false, nullable = false ,columnDefinition = "FLOAT") protected java.math.BigDecimal ka_minimum_elevation; @Column(name = "cfMaxElev", unique = false, nullable = false ,columnDefinition = "FLOAT") protected java.math.BigDecimal ka_maximum_elevation; @Column(name = "cfURI", unique = false, nullable = false , length = 128, precision = 0,columnDefinition = "CHAR") protected java.lang.String ka_uniform_resource_identifier; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfgeobbox_geobbox_geographicBoundingBox1") protected Set<CfGeoBBox_GeoBBox> cfgeobbox_geobbox_geographicBoundingBox1Set; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfgeobbox_geobbox_geographicBoundingBox2") protected Set<CfGeoBBox_GeoBBox> cfgeobbox_geobbox_geographicBoundingBox2Set; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfgeobbox_class_geographicBoundingBox") protected Set<CfGeoBBox_Class> cfgeobbox_class_geographicBoundingBoxSet; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfgeobboxdescr_geographicBoundingBox") protected Set<CfGeoBBoxDescr> cfgeobboxdescr_geographicBoundingBoxSet; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfgeobboxkeyw_geographicBoundingBox") protected Set<CfGeoBBoxKeyw> cfgeobboxkeyw_geographicBoundingBoxSet; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfgeobboxname_geographicBoundingBox") protected Set<CfGeoBBoxName> cfgeobboxname_geographicBoundingBoxSet; @OneToMany(cascade = { ALL }, fetch = FetchType.LAZY, mappedBy = "cfpaddr_geobbox_geographicBoundingBox") protected Set<CfPAddr_GeoBBox> cfpaddr_geobbox_geographicBoundingBoxSet; public CfGeoBBox(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public java.lang.String getKa_geographic_bounding_box_identifier() { return this.ka_geographic_bounding_box_identifier; } public void setKa_geographic_bounding_box_identifier(java.lang.String ka_geographic_bounding_box_identifier) { this.ka_geographic_bounding_box_identifier = ka_geographic_bounding_box_identifier; } public java.math.BigDecimal getKa_west_bound_longitude() { return this.ka_west_bound_longitude; } public void setKa_west_bound_longitude(java.math.BigDecimal ka_west_bound_longitude) { this.ka_west_bound_longitude = ka_west_bound_longitude; } public java.math.BigDecimal getKa_east_bound_longitude() { return this.ka_east_bound_longitude; } public void setKa_east_bound_longitude(java.math.BigDecimal ka_east_bound_longitude) { this.ka_east_bound_longitude = ka_east_bound_longitude; } public java.math.BigDecimal getKa_south_bound_latitude() { return this.ka_south_bound_latitude; } public void setKa_south_bound_latitude(java.math.BigDecimal ka_south_bound_latitude) { this.ka_south_bound_latitude = ka_south_bound_latitude; } public java.math.BigDecimal getKa_north_bound_latitude() { return this.ka_north_bound_latitude; } public void setKa_north_bound_latitude(java.math.BigDecimal ka_north_bound_latitude) { this.ka_north_bound_latitude = ka_north_bound_latitude; } public java.math.BigDecimal getKa_minimum_elevation() { return this.ka_minimum_elevation; } public void setKa_minimum_elevation(java.math.BigDecimal ka_minimum_elevation) { this.ka_minimum_elevation = ka_minimum_elevation; } public java.math.BigDecimal getKa_maximum_elevation() { return this.ka_maximum_elevation; } public void setKa_maximum_elevation(java.math.BigDecimal ka_maximum_elevation) { this.ka_maximum_elevation = ka_maximum_elevation; } public java.lang.String getKa_uniform_resource_identifier() { return this.ka_uniform_resource_identifier; } public void setKa_uniform_resource_identifier(java.lang.String ka_uniform_resource_identifier) { this.ka_uniform_resource_identifier = ka_uniform_resource_identifier; } public Set<CfGeoBBox_GeoBBox> getCfgeobbox_geobbox_geographicBoundingBox1Set() { return this.cfgeobbox_geobbox_geographicBoundingBox1Set; } public void setCfgeobbox_geobbox_geographicBoundingBox1Set(Set<CfGeoBBox_GeoBBox> cfgeobbox_geobbox_geographicBoundingBox1Set) { this.cfgeobbox_geobbox_geographicBoundingBox1Set = cfgeobbox_geobbox_geographicBoundingBox1Set; } public Set<CfGeoBBox_GeoBBox> getCfgeobbox_geobbox_geographicBoundingBox2Set() { return this.cfgeobbox_geobbox_geographicBoundingBox2Set; } public void setCfgeobbox_geobbox_geographicBoundingBox2Set(Set<CfGeoBBox_GeoBBox> cfgeobbox_geobbox_geographicBoundingBox2Set) { this.cfgeobbox_geobbox_geographicBoundingBox2Set = cfgeobbox_geobbox_geographicBoundingBox2Set; } public Set<CfGeoBBox_Class> getCfgeobbox_class_geographicBoundingBoxSet() { return this.cfgeobbox_class_geographicBoundingBoxSet; } public void setCfgeobbox_class_geographicBoundingBoxSet(Set<CfGeoBBox_Class> cfgeobbox_class_geographicBoundingBoxSet) { this.cfgeobbox_class_geographicBoundingBoxSet = cfgeobbox_class_geographicBoundingBoxSet; } public Set<CfGeoBBoxDescr> getCfgeobboxdescr_geographicBoundingBoxSet() { return this.cfgeobboxdescr_geographicBoundingBoxSet; } public void setCfgeobboxdescr_geographicBoundingBoxSet(Set<CfGeoBBoxDescr> cfgeobboxdescr_geographicBoundingBoxSet) { this.cfgeobboxdescr_geographicBoundingBoxSet = cfgeobboxdescr_geographicBoundingBoxSet; } public Set<CfGeoBBoxKeyw> getCfgeobboxkeyw_geographicBoundingBoxSet() { return this.cfgeobboxkeyw_geographicBoundingBoxSet; } public void setCfgeobboxkeyw_geographicBoundingBoxSet(Set<CfGeoBBoxKeyw> cfgeobboxkeyw_geographicBoundingBoxSet) { this.cfgeobboxkeyw_geographicBoundingBoxSet = cfgeobboxkeyw_geographicBoundingBoxSet; } public Set<CfGeoBBoxName> getCfgeobboxname_geographicBoundingBoxSet() { return this.cfgeobboxname_geographicBoundingBoxSet; } public void setCfgeobboxname_geographicBoundingBoxSet(Set<CfGeoBBoxName> cfgeobboxname_geographicBoundingBoxSet) { this.cfgeobboxname_geographicBoundingBoxSet = cfgeobboxname_geographicBoundingBoxSet; } public Set<CfPAddr_GeoBBox> getCfpaddr_geobbox_geographicBoundingBoxSet() { return this.cfpaddr_geobbox_geographicBoundingBoxSet; } public void setCfpaddr_geobbox_geographicBoundingBoxSet(Set<CfPAddr_GeoBBox> cfpaddr_geobbox_geographicBoundingBoxSet) { this.cfpaddr_geobbox_geographicBoundingBoxSet = cfpaddr_geobbox_geographicBoundingBoxSet; } }
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth.trace; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.concurrent.Callable; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.SpanNamer; import org.springframework.cloud.sleuth.SpanReporter; import org.springframework.cloud.sleuth.TraceKeys; import org.springframework.cloud.sleuth.Tracer; import org.springframework.cloud.sleuth.instrument.async.SpanContinuingTraceCallable; import org.springframework.cloud.sleuth.instrument.async.SpanContinuingTraceRunnable; import org.springframework.cloud.sleuth.log.SpanLogger; import org.springframework.cloud.sleuth.util.ExceptionUtils; import org.springframework.cloud.sleuth.util.SpanNameUtil; /** * Default implementation of {@link Tracer} * * @author Spencer Gibb * @since 1.0.0 */ public class DefaultTracer implements Tracer { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private static final int MAX_CHARS_IN_SPAN_NAME = 50; private final Sampler defaultSampler; private final Random random; private final SpanNamer spanNamer; private final SpanLogger spanLogger; private final SpanReporter spanReporter; private final TraceKeys traceKeys; private final boolean traceId128; @Deprecated public DefaultTracer(Sampler defaultSampler, Random random, SpanNamer spanNamer, SpanLogger spanLogger, SpanReporter spanReporter) { this(defaultSampler, random, spanNamer, spanLogger, spanReporter, false); } @Deprecated public DefaultTracer(Sampler defaultSampler, Random random, SpanNamer spanNamer, SpanLogger spanLogger, SpanReporter spanReporter, boolean traceId128) { this(defaultSampler, random, spanNamer, spanLogger, spanReporter, traceId128, null); } public DefaultTracer(Sampler defaultSampler, Random random, SpanNamer spanNamer, SpanLogger spanLogger, SpanReporter spanReporter, TraceKeys traceKeys) { this(defaultSampler, random, spanNamer, spanLogger, spanReporter, false, traceKeys); } public DefaultTracer(Sampler defaultSampler, Random random, SpanNamer spanNamer, SpanLogger spanLogger, SpanReporter spanReporter, boolean traceId128, TraceKeys traceKeys) { this.defaultSampler = defaultSampler; this.random = random; this.spanNamer = spanNamer; this.spanLogger = spanLogger; this.spanReporter = spanReporter; this.traceId128 = traceId128; this.traceKeys = traceKeys != null ? traceKeys : new TraceKeys(); } @Override public Span createSpan(String name, Span parent) { if (parent == null) { return createSpan(name); } return continueSpan(createChild(parent, name)); } @Override public Span createSpan(String name) { return this.createSpan(name, this.defaultSampler); } @Override public Span createSpan(String name, Sampler sampler) { String shortenedName = SpanNameUtil.shorten(name); Span span; if (isTracing()) { span = createChild(getCurrentSpan(), shortenedName); } else { long id = createId(); span = Span.builder().name(shortenedName) .traceIdHigh(this.traceId128 ? createId() : 0L) .traceId(id) .spanId(id).build(); if (sampler == null) { sampler = this.defaultSampler; } span = sampledSpan(span, sampler); this.spanLogger.logStartedSpan(null, span); } return continueSpan(span); } @Override public Span detach(Span span) { if (span == null) { return null; } Span cur = SpanContextHolder.getCurrentSpan(); if (cur == null) { if (log.isTraceEnabled()) { log.trace("Span in the context is null so something has already detached the span. Won't do anything about it"); } return null; } if (!span.equals(cur)) { ExceptionUtils.warn("Tried to detach trace span but " + "it is not the current span: " + span + ". You may have forgotten to close or detach " + cur); } else { SpanContextHolder.removeCurrentSpan(); } return span.getSavedSpan(); } @Override public Span close(Span span) { if (span == null) { return null; } Span cur = SpanContextHolder.getCurrentSpan(); final Span savedSpan = span.getSavedSpan(); if (!span.equals(cur)) { ExceptionUtils.warn( "Tried to close span but it is not the current span: " + span + ". You may have forgotten to close or detach " + cur); } else { span.stop(); if (savedSpan != null && span.getParents().contains(savedSpan.getSpanId())) { this.spanReporter.report(span); this.spanLogger.logStoppedSpan(savedSpan, span); } else { if (!span.isRemote()) { this.spanReporter.report(span); this.spanLogger.logStoppedSpan(null, span); } } SpanContextHolder.close(new SpanContextHolder.SpanFunction() { @Override public void apply(Span span) { DefaultTracer.this.spanLogger.logStoppedSpan(savedSpan, span); } }); } return savedSpan; } Span createChild(Span parent, String name) { String shortenedName = SpanNameUtil.shorten(name); long id = createId(); if (parent == null) { Span span = Span.builder().name(shortenedName) .traceIdHigh(this.traceId128 ? createId() : 0L) .traceId(id) .spanId(id).build(); span = sampledSpan(span, this.defaultSampler); this.spanLogger.logStartedSpan(null, span); return span; } else { if (!isTracing()) { SpanContextHolder.push(parent, true); } Span span = Span.builder().name(shortenedName) .traceIdHigh(parent.getTraceIdHigh()) .traceId(parent.getTraceId()).parent(parent.getSpanId()).spanId(id) .processId(parent.getProcessId()).savedSpan(parent) .exportable(parent.isExportable()) .baggage(parent.getBaggage()) .build(); this.spanLogger.logStartedSpan(parent, span); return span; } } private Span sampledSpan(Span span, Sampler sampler) { if (!sampler.isSampled(span)) { // Copy everything, except set exportable to false return Span.builder() .begin(span.getBegin()) .traceIdHigh(span.getTraceIdHigh()) .traceId(span.getTraceId()) .spanId(span.getSpanId()) .name(span.getName()) .exportable(false).build(); } return span; } private long createId() { return this.random.nextLong(); } @Override public Span continueSpan(Span span) { if (span != null) { this.spanLogger.logContinuedSpan(span); } else { return null; } Span newSpan = createContinuedSpan(span, SpanContextHolder.getCurrentSpan()); SpanContextHolder.setCurrentSpan(newSpan); return newSpan; } private Span createContinuedSpan(Span span, Span saved) { if (saved == null && span.getSavedSpan() != null) { saved = span.getSavedSpan(); } return new Span(span, saved); } @Override public Span getCurrentSpan() { return SpanContextHolder.getCurrentSpan(); } @Override public boolean isTracing() { return SpanContextHolder.isTracing(); } @Override public void addTag(String key, String value) { Span s = getCurrentSpan(); if (s != null && s.isExportable()) { s.tag(key, value); } } /** * Wrap the callable in a TraceCallable, if tracing. * * @return The callable provided, wrapped if tracing, 'callable' if not. */ @Override public <V> Callable<V> wrap(Callable<V> callable) { if (isTracing()) { return new SpanContinuingTraceCallable<>(this, this.traceKeys, this.spanNamer, callable); } return callable; } /** * Wrap the runnable in a TraceRunnable, if tracing. * * @return The runnable provided, wrapped if tracing, 'runnable' if not. */ @Override public Runnable wrap(Runnable runnable) { if (isTracing()) { return new SpanContinuingTraceRunnable(this, this.traceKeys, this.spanNamer, runnable); } return runnable; } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.concatfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.value.ValueMetaFactory; import org.pentaho.di.trans.step.StepInjectionMetaEntry; import org.pentaho.di.trans.step.StepMetaInjectionInterface; import org.pentaho.di.trans.steps.textfileoutput.TextFileField; /** * This takes care of the external metadata injection into the TableOutputMeta class * * @author Chris */ public class ConcatFieldsMetaInjection implements StepMetaInjectionInterface { private enum Entry { TARGET_FIELDNAME( ValueMetaInterface.TYPE_STRING, "The target field name" ), TARGET_LENGTH( ValueMetaInterface.TYPE_STRING, "The length of the target field" ), SEPARATOR( ValueMetaInterface.TYPE_STRING, "The separator" ), ENCLOSURE( ValueMetaInterface.TYPE_STRING, "The enclosure" ), REMOVE_FIELDS( ValueMetaInterface.TYPE_STRING, "Remove selected fields? (Y/N)" ), FORCE_ENCLOSURE( ValueMetaInterface.TYPE_STRING, "Force the enclosure around fields? (Y/N)" ), DISABLE_ENCLOSURE_FIX( ValueMetaInterface.TYPE_STRING, "Disable the enclosure fix? (Y/N)" ), HEADER( ValueMetaInterface.TYPE_STRING, "Include header row? (Y/N)" ), FOOTER( ValueMetaInterface.TYPE_STRING, "Include footer row? (Y/N)" ), ENCODING( ValueMetaInterface.TYPE_STRING, "Encoding type (for allowed values see: http://wiki.pentaho.com/display/EAI/Concat+Fields)" ), RIGHT_PAD_FIELDS( ValueMetaInterface.TYPE_STRING, "Right pad fields? (Y/N)" ), FAST_DATA_DUMP( ValueMetaInterface.TYPE_STRING, "Fast data dump? (Y/N)" ), SPLIT_EVERY( ValueMetaInterface.TYPE_STRING, "Split every ... rows" ), ADD_ENDING_LINE( ValueMetaInterface.TYPE_STRING, "Add ending line after last row" ), CONCAT_FIELDS( ValueMetaInterface.TYPE_NONE, "The fields to concatenate" ), CONCAT_FIELD( ValueMetaInterface.TYPE_NONE, "One field to concatenate" ), CONCAT_FIELDNAME( ValueMetaInterface.TYPE_STRING, "Field to concatenate" ), CONCAT_TYPE( ValueMetaInterface.TYPE_STRING, "Field type (for allowed values see: http://wiki.pentaho.com/display/EAI/Concat+Fields)" ), CONCAT_FORMAT( ValueMetaInterface.TYPE_STRING, "Field format" ), CONCAT_LENGTH( ValueMetaInterface.TYPE_STRING, "Field length" ), CONCAT_PRECISION( ValueMetaInterface.TYPE_STRING, "Field precision" ), CONCAT_CURRENCY( ValueMetaInterface.TYPE_STRING, "Field currency symbol" ), CONCAT_DECIMAL( ValueMetaInterface.TYPE_STRING, "Field decimal symbol" ), CONCAT_GROUP( ValueMetaInterface.TYPE_STRING, "Field grouping symbol" ), CONCAT_TRIM( ValueMetaInterface.TYPE_STRING, "Field trim type (none,left,both,right)" ), CONCAT_NULL( ValueMetaInterface.TYPE_STRING, "Value to replace nulls with" ); private int valueType; private String description; private Entry( int valueType, String description ) { this.valueType = valueType; this.description = description; } /** * @return the valueType */ public int getValueType() { return valueType; } /** * @return the description */ public String getDescription() { return description; } public static Entry findEntry( String key ) { return Entry.valueOf( key ); } } private ConcatFieldsMeta meta; public ConcatFieldsMetaInjection( ConcatFieldsMeta meta ) { this.meta = meta; } @Override public List<StepInjectionMetaEntry> getStepInjectionMetadataEntries() throws KettleException { List<StepInjectionMetaEntry> all = new ArrayList<StepInjectionMetaEntry>(); Entry[] topEntries = new Entry[] { Entry.TARGET_FIELDNAME, Entry.TARGET_LENGTH, Entry.SEPARATOR, Entry.ENCLOSURE, Entry.REMOVE_FIELDS, Entry.FORCE_ENCLOSURE, Entry.DISABLE_ENCLOSURE_FIX, Entry.HEADER, Entry.FOOTER, Entry.ENCODING, Entry.RIGHT_PAD_FIELDS, Entry.FAST_DATA_DUMP, Entry.SPLIT_EVERY, Entry.ADD_ENDING_LINE, }; for ( Entry topEntry : topEntries ) { all.add( new StepInjectionMetaEntry( topEntry.name(), topEntry.getValueType(), topEntry.getDescription() ) ); } // The fields // StepInjectionMetaEntry fieldsEntry = new StepInjectionMetaEntry( Entry.CONCAT_FIELDS.name(), ValueMetaInterface.TYPE_NONE, Entry.CONCAT_FIELDS.description ); all.add( fieldsEntry ); StepInjectionMetaEntry fieldEntry = new StepInjectionMetaEntry( Entry.CONCAT_FIELD.name(), ValueMetaInterface.TYPE_NONE, Entry.CONCAT_FIELD.description ); fieldsEntry.getDetails().add( fieldEntry ); Entry[] fieldsEntries = new Entry[] { Entry.CONCAT_FIELDNAME, Entry.CONCAT_TYPE, Entry.CONCAT_LENGTH, Entry.CONCAT_FORMAT, Entry.CONCAT_PRECISION, Entry.CONCAT_CURRENCY, Entry.CONCAT_DECIMAL, Entry.CONCAT_GROUP, Entry.CONCAT_TRIM, Entry.CONCAT_NULL, }; for ( Entry entry : fieldsEntries ) { StepInjectionMetaEntry metaEntry = new StepInjectionMetaEntry( entry.name(), entry.getValueType(), entry.getDescription() ); fieldEntry.getDetails().add( metaEntry ); } return all; } @Override public void injectStepMetadataEntries( List<StepInjectionMetaEntry> all ) throws KettleException { List<String> concatFields = new ArrayList<String>(); List<String> concatTypes = new ArrayList<String>(); List<String> concatLengths = new ArrayList<String>(); List<String> concatFormats = new ArrayList<String>(); List<String> concatPrecisions = new ArrayList<String>(); List<String> concatCurrencies = new ArrayList<String>(); List<String> concatDecimals = new ArrayList<String>(); List<String> concatGroups = new ArrayList<String>(); List<String> concatTrims = new ArrayList<String>(); List<String> concatNulls = new ArrayList<String>(); // Parse the fields, inject into the meta class.. // for ( StepInjectionMetaEntry lookFields : all ) { Entry fieldsEntry = Entry.findEntry( lookFields.getKey() ); if ( fieldsEntry == null ) { continue; } String lookValue = (String) lookFields.getValue(); switch ( fieldsEntry ) { case CONCAT_FIELDS: for ( StepInjectionMetaEntry lookField : lookFields.getDetails() ) { Entry fieldEntry = Entry.findEntry( lookField.getKey() ); if ( fieldEntry == Entry.CONCAT_FIELD ) { String concatFieldname = null; String concatType = null; String concatLength = null; String concatFormat = null; String concatPrecision = null; String concatCurrency = null; String concatDecimal = null; String concatGroup = null; String concatTrim = null; String concatNull = null; List<StepInjectionMetaEntry> entries = lookField.getDetails(); for ( StepInjectionMetaEntry entry : entries ) { Entry metaEntry = Entry.findEntry( entry.getKey() ); if ( metaEntry != null ) { String value = (String) entry.getValue(); switch ( metaEntry ) { case CONCAT_FIELDNAME: concatFieldname = value; break; case CONCAT_TYPE: concatType = value; break; case CONCAT_LENGTH: concatLength = value; break; case CONCAT_FORMAT: concatFormat = value; break; case CONCAT_PRECISION: concatPrecision = value; break; case CONCAT_CURRENCY: concatCurrency = value; break; case CONCAT_DECIMAL: concatDecimal = value; break; case CONCAT_GROUP: concatGroup = value; break; case CONCAT_TRIM: concatTrim = value; break; case CONCAT_NULL: concatNull = value; break; default: break; } } } concatFields.add( concatFieldname ); concatTypes.add( concatType ); concatLengths.add( concatLength ); concatFormats.add( concatFormat ); concatPrecisions.add( concatPrecision ); concatCurrencies.add( concatCurrency ); concatDecimals.add( concatDecimal ); concatGroups.add( concatGroup ); concatTrims.add( concatTrim ); concatNulls.add( concatNull ); } } break; case TARGET_FIELDNAME: meta.setTargetFieldName( lookValue ); break; case TARGET_LENGTH: meta.setTargetFieldLength( Const.toInt( lookValue, 0 ) ); break; case SEPARATOR: meta.setSeparator( lookValue ); break; case ENCLOSURE: meta.setEnclosure( lookValue ); break; case REMOVE_FIELDS: meta.setRemoveSelectedFields( "Y".equalsIgnoreCase( lookValue ) ); break; case FORCE_ENCLOSURE: meta.setEnclosureForced( "Y".equalsIgnoreCase( lookValue ) ); break; case DISABLE_ENCLOSURE_FIX: meta.setEnclosureFixDisabled( "Y".equalsIgnoreCase( lookValue ) ); break; case HEADER: meta.setHeaderEnabled( "Y".equalsIgnoreCase( lookValue ) ); break; case FOOTER: meta.setFooterEnabled( "Y".equalsIgnoreCase( lookValue ) ); break; case ENCODING: meta.setEncoding( lookValue ); break; case RIGHT_PAD_FIELDS: meta.setPadded( "Y".equalsIgnoreCase( lookValue ) ); break; case FAST_DATA_DUMP: meta.setFastDump( "Y".equalsIgnoreCase( lookValue ) ); break; case SPLIT_EVERY: meta.setSplitEvery( Const.toInt( lookValue, 0 ) ); break; case ADD_ENDING_LINE: meta.setEndedLine( lookValue ); break; default: break; } } // Pass the grid to the step metadata // if ( concatFields.size() > 0 ) { TextFileField[] tff = new TextFileField[concatFields.size()]; Iterator<String> iConcatFields = concatFields.iterator(); Iterator<String> iConcatTypes = concatTypes.iterator(); Iterator<String> iConcatLengths = concatLengths.iterator(); Iterator<String> iConcatFormats = concatFormats.iterator(); Iterator<String> iConcatPrecisions = concatPrecisions.iterator(); Iterator<String> iConcatCurrencies = concatCurrencies.iterator(); Iterator<String> iConcatDecimals = concatDecimals.iterator(); Iterator<String> iConcatGroups = concatGroups.iterator(); Iterator<String> iConcatTrims = concatTrims.iterator(); Iterator<String> iConcatNulls = concatNulls.iterator(); int i = 0; while ( iConcatFields.hasNext() ) { TextFileField field = new TextFileField(); field.setName( iConcatFields.next() ); field.setType( ValueMetaFactory.getIdForValueMeta( iConcatTypes.next() ) ); field.setFormat( iConcatFormats.next() ); field.setLength( Const.toInt( iConcatLengths.next(), -1 ) ); field.setPrecision( Const.toInt( iConcatPrecisions.next(), -1 ) ); field.setCurrencySymbol( iConcatCurrencies.next() ); field.setDecimalSymbol( iConcatDecimals.next() ); field.setGroupingSymbol( iConcatGroups.next() ); field.setNullString( iConcatNulls.next() ); field.setTrimType( ValueMetaBase.getTrimTypeByDesc( iConcatTrims.next() ) ); tff[i] = field; i++; } meta.setOutputFields( tff ); } } @Override public List<StepInjectionMetaEntry> extractStepMetadataEntries() throws KettleException { return null; } public ConcatFieldsMeta getMeta() { return meta; } }
// Copyright 2015 The Project Buendia 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 distrib- // uted 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 // specific language governing permissions and limitations under the License. package org.openmrs.projectbuendia.webservices.rest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Location; import org.openmrs.Patient; import org.openmrs.PatientIdentifier; import org.openmrs.PatientIdentifierType; import org.openmrs.PersonName; import org.openmrs.User; import org.openmrs.api.LocationService; import org.openmrs.api.PatientService; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.api.Creatable; import org.openmrs.module.webservices.rest.web.resource.api.Listable; import org.openmrs.module.webservices.rest.web.resource.api.Retrievable; import org.openmrs.module.webservices.rest.web.resource.api.Searchable; import org.openmrs.module.webservices.rest.web.resource.api.Updatable; import org.openmrs.module.webservices.rest.web.response.ObjectNotFoundException; import org.openmrs.module.webservices.rest.web.response.ResponseException; import org.openmrs.projectbuendia.Utils; import org.projectbuendia.openmrs.api.ProjectBuendiaService; import org.projectbuendia.openmrs.api.SyncToken; import org.projectbuendia.openmrs.api.db.SyncPage; import org.projectbuendia.openmrs.webservices.rest.RestController; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; /** * Rest API for patients. * <p/> * <p>Expected behavior: * <ul> * <li>GET /patients returns all patients ({@link #getAll(RequestContext)}) * <li>GET /patients/[UUID] returns a single patient ({@link #retrieve(String, RequestContext)}) * <li>GET /patients?id=[id] returns a search for a patient with the specified MSF (i.e. not * OpenMRS) id. * <li>POST /patients creates a patient ({@link #create(SimpleObject, RequestContext)} * <li>POST /patients/[UUID] updates a patient ({@link #update(String, SimpleObject, * RequestContext)}) * </ul> * <p/> * <p>Each operation handles Patient resources in the following JSON form: * <p/> * <pre> * { * "uuid": "e5e755d4-f646-45b6-b9bc-20410e97c87c", // assigned by OpenMRS, not required for * creation * "id": "567", // required unique id specified by user * "sex": "F", // required as "M" or "F", unfortunately * "birthdate": "1990-02-17", // required, but can be estimated * "given_name": "Jane", // required, "Unknown" suggested if not known * "family_name": "Doe", // required, "Unknown" suggested if not known * "assigned_location": { // optional, but highly encouraged * "uuid": "0a49d383-7019-4f1f-bf4b-875f2cd58964", // UUID of the patient's assigned location * } * }, * </pre> * (Results may also contain deprecated fields other than those described above.) * <p/> * <p>If an error occurs, the response will contain the following: * <pre> * { * "error": { * "message": "[error message]", * "code": "[breakpoint]", * "detail": "[stack trace]" * } * } * </pre> */ @Resource( name = RestController.REST_VERSION_1_AND_NAMESPACE + "/patients", supportedClass = Patient.class, supportedOpenmrsVersions = "1.10.*,1.11.*" ) public class PatientResource implements Listable, Searchable, Retrievable, Creatable, Updatable { private static final SimpleDateFormat PATIENT_BIRTHDATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); static { PATIENT_BIRTHDATE_FORMAT.setTimeZone(Utils.UTC); } private static final int MAX_PATIENTS_PER_PAGE = 500; private static final String FACILITY_NAME = "Kailahun"; // TODO: Use a real facility name. static final RequestLogger logger = RequestLogger.LOGGER; // JSON property names private static final String ID = "id"; private static final String UUID = "uuid"; private static final String SEX = "sex"; private static final String BIRTHDATE = "birthdate"; private static final String GIVEN_NAME = "given_name"; private static final String FAMILY_NAME = "family_name"; private static final String ASSIGNED_LOCATION = "assigned_location"; private static final String PARENT_UUID = "parent_uuid"; private static final String VOIDED = "voided"; private static Log log = LogFactory.getLog(PatientResource.class); private static final Object createPatientLock = new Object(); private final PatientService patientService; private final ProjectBuendiaService buendiaService; public PatientResource() { patientService = Context.getPatientService(); buendiaService = Context.getService(ProjectBuendiaService.class); } @Override public SimpleObject getAll(RequestContext context) throws ResponseException { // #search covers a more general case of of #getAll, so we just forward through. return search(context); } private SimpleObject handleSync(RequestContext context) throws ResponseException { SyncToken syncToken = RequestUtil.mustParseSyncToken(context); Date requestTime = new Date(); SyncPage<Patient> patients = buendiaService.getPatientsModifiedAtOrAfter( syncToken, syncToken != null /* includeVoided */, MAX_PATIENTS_PER_PAGE /* maxResults */); List<SimpleObject> jsonResults = new ArrayList<>(); for (Patient patient : patients.results) { jsonResults.add(patientToJson(patient)); } SyncToken newToken = SyncTokenUtils.clampSyncTokenToBufferedRequestTime(patients.syncToken, requestTime); // If we fetched a full page, there's probably more data available. boolean more = patients.results.size() == MAX_PATIENTS_PER_PAGE; return ResponseUtil.createIncrementalSyncResults(jsonResults, newToken, more); } // TODO: consolidate the incremental sync timestamping / wrapper logic for this and // EncountersResource into the same class. private SimpleObject getSimpleObjectWithResults(List<Patient> patients) { List<SimpleObject> jsonResults = new ArrayList<>(); for (Patient patient : patients) { jsonResults.add(patientToJson(patient)); } SimpleObject wrapper = new SimpleObject(); wrapper.put("results", jsonResults); return wrapper; } protected static SimpleObject patientToJson(Patient patient) { SimpleObject jsonForm = new SimpleObject(); jsonForm.add(UUID, patient.getUuid()); jsonForm.add(VOIDED, patient.isPersonVoided()); if (patient.isPersonVoided()) { // early return, we don't need the rest of the data. return jsonForm; } PatientIdentifier patientIdentifier = patient.getPatientIdentifier(DbUtil.getMsfIdentifierType()); if (patientIdentifier != null) { jsonForm.add(ID, patientIdentifier.getIdentifier()); } jsonForm.add(SEX, patient.getGender()); if (patient.getBirthdate() != null) { jsonForm.add(BIRTHDATE, PATIENT_BIRTHDATE_FORMAT.format(patient.getBirthdate())); } String givenName = patient.getGivenName(); if (!givenName.equals(MISSING_NAME)) { jsonForm.add(GIVEN_NAME, patient.getGivenName()); } String familyName = patient.getFamilyName(); if (!familyName.equals(MISSING_NAME)) { jsonForm.add(FAMILY_NAME, patient.getFamilyName()); } // TODO: refactor so we have a single assigned location with a uuid, // and we walk up the tree to get extra information for the patient. String assignedLocation = DbUtil.getPersonAttributeValue( patient, DbUtil.getAssignedLocationAttributeType()); if (assignedLocation != null) { LocationService locationService = Context.getLocationService(); Location location = locationService.getLocation( Integer.valueOf(assignedLocation)); if (location != null) { SimpleObject locationJson = new SimpleObject(); locationJson.add(UUID, location.getUuid()); if (location.getParentLocation() != null) { locationJson.add(PARENT_UUID, location.getParentLocation().getUuid()); } jsonForm.add(ASSIGNED_LOCATION, locationJson); } } return jsonForm; } public Object create(SimpleObject json, RequestContext context) throws ResponseException { try { logger.request(context, this, "create", json); Object result = createInner(json); logger.reply(context, this, "create", result); return result; } catch (Exception e) { logger.error(context, this, "create", e); throw e; } } private String getFullName(Patient patient) { String given = patient.getGivenName(); given = given.equals(MISSING_NAME) ? "" : given; String family = patient.getFamilyName(); family = family.equals(MISSING_NAME) ? "" : family; return (given + " " + family).trim(); } private Object createInner(SimpleObject json) throws ResponseException { // We really want this to use XForms, but let's have a simple default // implementation for early testing Patient patient; synchronized (createPatientLock) { String id = (String) json.get(ID); if (id != null) { List<PatientIdentifierType> identifierTypes = Collections.singletonList(DbUtil.getMsfIdentifierType()); List<Patient> existing = patientService.getPatients( null, id, identifierTypes, true /* exact identifier match */); if (!existing.isEmpty()) { Patient idMatch = existing.get(0); String name = getFullName(idMatch); throw new InvalidObjectDataException( String.format( "Another patient (%s) already has the ID \"%s\"", name.isEmpty() ? "with no name" : "named " + name, id)); } } String uuid = (String) json.get(UUID); if (uuid != null) { Patient uuidMatch = patientService.getPatientByUuid(uuid); if (uuidMatch != null) { String name = getFullName(uuidMatch); throw new InvalidObjectDataException(String.format( "Another patient (%s) already has the UUID \"%s\"", name.isEmpty() ? "with no name" : "named " + name, uuid)); } } patient = jsonToPatient(json); patientService.savePatient(patient); } // Observation for first symptom date ObservationsHandler.addEncounter( (List) json.get("observations"), null, patient, patient.getDateCreated(), "Initial triage", "ADULTINITIAL", LocationResource.TRIAGE_UUID, (String) json.get("enterer_id")); return patientToJson(patient); } private static String normalizeSex(String sex) { if (sex == null) { return "U"; } else if (sex.trim().matches("^[FfMmOoUu]")) { return sex.trim().substring(0, 1).toUpperCase(); // F, M, O, and U are valid } else { return "U"; } } /** OpenMRS refuses to store empty names, so we use "." to represent a missing name. */ private static final String MISSING_NAME = "."; /** Normalizes a name to something OpenMRS will accept. */ private static String normalizeName(String name) { name = (name == null) ? "" : name.trim(); return name.isEmpty() ? MISSING_NAME : name; } protected static Patient jsonToPatient(SimpleObject json) { Patient patient = new Patient(); patient.setCreator(Context.getAuthenticatedUser()); patient.setDateCreated(new Date()); if (json.containsKey(UUID)) { patient.setUuid((String) json.get(UUID)); } String sex = (String) json.get(SEX); // OpenMRS calls it "gender"; we use it for physical sex (as other implementations do). patient.setGender(normalizeSex(sex)); if (json.containsKey(BIRTHDATE)) { patient.setBirthdate(Utils.parseLocalDate((String) json.get(BIRTHDATE), BIRTHDATE)); } PersonName pn = new PersonName(); pn.setGivenName(normalizeName((String) json.get(GIVEN_NAME))); pn.setFamilyName(normalizeName((String) json.get(FAMILY_NAME))); pn.setCreator(patient.getCreator()); pn.setDateCreated(patient.getDateCreated()); patient.addName(pn); // OpenMRS requires that every patient have a preferred identifier. If no MSF identifier // is specified, we use a timestamp as a stand-in unique identifier. PatientIdentifier identifier = new PatientIdentifier(); identifier.setCreator(patient.getCreator()); identifier.setDateCreated(patient.getDateCreated()); // TODO/generalize: Instead of getting the root location by a hardcoded // name (almost certainly an inappropriate name), change the helper // function to DbUtil.getRootLocation(). identifier.setLocation(DbUtil.getLocationByName(FACILITY_NAME, null)); if (json.containsKey(ID)) { identifier.setIdentifier((String) json.get(ID)); identifier.setIdentifierType(DbUtil.getMsfIdentifierType()); } else { identifier.setIdentifier("" + new Date().getTime()); identifier.setIdentifierType(DbUtil.getTimestampIdentifierType()); } identifier.setPreferred(true); patient.addIdentifier(identifier); // Set assigned location last, as doing so saves the patient, which could fail // if performed in the middle of patient creation. if (json.containsKey(ASSIGNED_LOCATION)) { String assignedLocationUuid = null; Object assignedLocation = json.get(ASSIGNED_LOCATION); if (assignedLocation instanceof String) { assignedLocationUuid = (String) assignedLocation; } if (assignedLocation instanceof Map) { assignedLocationUuid = (String) ((Map) assignedLocation).get(UUID); } if (assignedLocationUuid != null) { setLocation(patient, assignedLocationUuid); } } return patient; } private static void setLocation(Patient patient, String locationUuid) { // Apply the given assigned location to a patient, if locationUuid is not null. if (locationUuid == null) return; Location location = Context.getLocationService().getLocationByUuid(locationUuid); if (location != null) { DbUtil.setPersonAttributeValue(patient, DbUtil.getAssignedLocationAttributeType(), Integer.toString(location.getId())); } } @Override public String getUri(Object instance) { Patient patient = (Patient) instance; Resource res = getClass().getAnnotation(Resource.class); return RestConstants.URI_PREFIX + res.name() + "/" + patient.getUuid(); } @Override public SimpleObject search(RequestContext context) throws ResponseException { // If there's an ID, run an actual search, otherwise, run a sync. String patientId = context.getParameter("id"); if (patientId != null) { try { logger.request(context, this, "search"); SimpleObject result = searchInner(patientId); logger.reply(context, this, "search", result); return result; } catch (Exception e) { logger.error(context, this, "search", e); throw e; } } else { try { logger.request(context, this, "handleSync"); SimpleObject result = handleSync(context); logger.reply(context, this, "handleSync", result); return result; } catch (Exception e) { logger.error(context, this, "handleSync", e); throw e; } } } private SimpleObject searchInner(String patientId) throws ResponseException { List<PatientIdentifierType> idTypes = Collections.singletonList(DbUtil.getMsfIdentifierType()); List<Patient> patients = patientService.getPatients(null, patientId, idTypes, false); return getSimpleObjectWithResults(patients); } @Override public Object retrieve(String uuid, RequestContext context) throws ResponseException { try { logger.request(context, this, "retrieve", uuid); Object result = retrieveInner(uuid); logger.reply(context, this, "retrieve", result); return result; } catch (Exception e) { logger.error(context, this, "retrieve", e); throw e; } } private Object retrieveInner(String uuid) throws ResponseException { Patient patient = patientService.getPatientByUuid(uuid); if (patient == null) { throw new ObjectNotFoundException(); } return patientToJson(patient); } @Override public List<Representation> getAvailableRepresentations() { return Collections.singletonList(Representation.DEFAULT); } @Override public Object update(String uuid, SimpleObject simpleObject, RequestContext context) throws ResponseException { try { logger.request(context, this, "update", uuid + ", " + simpleObject); Object result = updateInner(uuid, simpleObject); logger.reply(context, this, "update", result); return result; } catch (Exception e) { logger.error(context, this, "update", e); throw e; } } /** * Receives a SimpleObject that is parsed from the Gson serialization of a client-side * Patient bean. It has the following semantics: * <ul> * <li>Any field set overwrites the current content * <li>Any field with a key but value == null deletes the current content * <li>Any field whose key is not present leaves the current content unchanged * <li>Subfields of location and age are not merged; instead the whole item is replaced * <li>If the client requests a change that is illegal, that is an error. Really the * whole call should fail, but for now there may be partial updates * </ul> */ private Object updateInner(String uuid, SimpleObject simpleObject) throws ResponseException { Patient patient = patientService.getPatientByUuid(uuid); if (patient == null) { throw new ObjectNotFoundException(); } applyEdits(patient, simpleObject); return patientToJson(patient); } /** Applies edits to a Patient. Returns true if any changes were made. */ protected void applyEdits(Patient patient, SimpleObject edits) { boolean changedPatient = false; String newGivenName = null; String newFamilyName = null; String newId = null; for (Map.Entry<String, Object> entry : edits.entrySet()) { switch (entry.getKey()) { // ==== JSON keys that update attributes of the Patient entity. case FAMILY_NAME: newFamilyName = (String) entry.getValue(); break; case GIVEN_NAME: newGivenName = (String) entry.getValue(); break; case ASSIGNED_LOCATION: Map assignedLocation = (Map) entry.getValue(); setLocation(patient, (String) assignedLocation.get(UUID)); break; case BIRTHDATE: patient.setBirthdate(Utils.parseLocalDate((String) entry.getValue(), BIRTHDATE)); changedPatient = true; break; case ID: newId = (String) entry.getValue(); break; default: log.warn("Property is nonexistent or not updatable; ignoring: " + entry); break; } } PatientIdentifier identifier = patient.getPatientIdentifier(DbUtil.getMsfIdentifierType()); if (newId != null && (identifier == null || !newId.equals(identifier.getIdentifier()))) { synchronized (createPatientLock) { List<PatientIdentifierType> identifierTypes = Collections.singletonList(DbUtil.getMsfIdentifierType()); List<Patient> existing = patientService.getPatients( null, newId, identifierTypes, true /* exact identifier match */); if (!existing.isEmpty()) { Patient idMatch = existing.get(0); String name = getFullName(idMatch); throw new InvalidObjectDataException( String.format( "Another patient (%s) already has the ID \"%s\"", name.isEmpty() ? "with no name" : "named " + name, newId)); } if (identifier != null) { patient.removeIdentifier(identifier); } identifier = new PatientIdentifier(); identifier.setCreator(patient.getCreator()); identifier.setDateCreated(patient.getDateCreated()); // TODO/generalize: Instead of getting the root location by a hardcoded // name (almost certainly an inappropriate name), change the helper // function to DbUtil.getRootLocation(). identifier.setLocation(DbUtil.getLocationByName(FACILITY_NAME, null)); identifier.setIdentifier(newId); identifier.setIdentifierType(DbUtil.getMsfIdentifierType()); identifier.setPreferred(true); patient.addIdentifier(identifier); patientService.savePatient(patient); } changedPatient = true; } if (newGivenName != null || newFamilyName != null) { PersonName oldName = patient.getPersonName(); if (!normalizeName(newGivenName).equals(oldName.getGivenName()) || !normalizeName(newFamilyName).equals(oldName.getFamilyName())) { PersonName newName = new PersonName(); newName.setGivenName( newGivenName != null ? normalizeName(newGivenName) : oldName.getGivenName()); newName.setFamilyName( newFamilyName != null ? normalizeName(newFamilyName) : oldName.getFamilyName()); patient.addName(newName); oldName.setVoided(true); changedPatient = true; } } if (changedPatient) { patientService.savePatient(patient); } } }
/* * Copyright 2012 Benjamin Glatzel <benjamin.glatzel@me.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.rendering.gui.widgets; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.newdawn.slick.Color; import org.terasology.asset.Assets; import org.terasology.logic.manager.ShaderManager; import org.terasology.math.TeraMath; import org.terasology.performanceMonitor.PerformanceMonitor; import org.terasology.rendering.assets.Font; import org.terasology.rendering.gui.framework.UIDisplayContainer; import org.terasology.rendering.gui.framework.events.ChangedListener; import javax.vecmath.Vector2f; import javax.vecmath.Vector4f; import java.util.ArrayList; import java.util.List; import static org.lwjgl.opengl.GL11.glDisable; /** * Simple text element supporting text shadowing. * * @author Benjamin Glatzel <benjamin.glatzel@me.com> * @author Marcel Lehwald <marcel.lehwald@googlemail.com> */ public class UILabel extends UIDisplayContainer { private final ArrayList<ChangedListener> changedListeners = new ArrayList<ChangedListener>(); protected StringBuilder text = new StringBuilder(); //wrapping private final List<Integer> wrapPosition = new ArrayList<Integer>(); private boolean isWrap = false; //font private Font font = Assets.getFont("engine:default"); private Color color = new Color(Color.white); //shadow private boolean enableShadow = false; private Color shadowColor = new Color(Color.black); private final Vector2f shadowOffset = new Vector2f(1, 0); //other private Vector2f lastSize = new Vector2f(0f, 0f); private Vector4f margin = new Vector4f(0f, 0f, 0f, 0f); public UILabel() { super(); setText(""); } public UILabel(String text) { setText(text); } public UILabel(String text, Color shadowColor) { setText(text); this.enableShadow = true; this.shadowColor = shadowColor; } public void render() { super.render(); PerformanceMonitor.startActivity("Render UIText"); ShaderManager.getInstance().enableDefaultTextured(); if (enableShadow) { font.drawString(TeraMath.floorToInt(shadowOffset.x + margin.w), TeraMath.floorToInt(1 + shadowOffset.y + margin.x), text.toString(), shadowColor); } font.drawString(TeraMath.floorToInt(margin.w), TeraMath.floorToInt(margin.x), text.toString(), color); // TODO: Also ugly.. glDisable(GL11.GL_TEXTURE_2D); PerformanceMonitor.endActivity(); } /** * Calculate the width of the given text. * * @param text The text to calculate the width. * @return Returns the width of the given text. */ private int calcTextWidth(String text) { return font.getWidth(text); } /** * Calculate the height of the given text. * * @param text The text to calculate the height. * @return Returns the height of the given text. */ private int calcTextHeight(String text) { //fix because the slick library is calculating the height of text wrong if the last/first character is a new line.. if (!text.isEmpty() && (text.charAt(text.length() - 1) == '\n' || text.charAt(text.length() - 1) == ' ')) { text += "i"; } if (!text.isEmpty() && text.charAt(0) == '\n') { text = "i" + text; } if (text.isEmpty()) { text = "i"; } return font.getHeight(text); } @Override public void layout() { super.layout(); //so the wrapped label will calculate the wrap position again if the parent or display was resized if (isWrap) { if (positionType == EPositionType.RELATIVE && getParent() != null) { if (lastSize.x != getParent().getSize().x || lastSize.y != getParent().getSize().y) { lastSize.x = getParent().getSize().x; lastSize.y = getParent().getSize().y; setText(getText()); } } else if (positionType == EPositionType.ABSOLUTE) { if (lastSize.x != Display.getWidth() || lastSize.y != Display.getHeight()) { lastSize.x = Display.getWidth(); lastSize.y = Display.getHeight(); setText(getText()); } } } } /** * Wraps the text to the with of the wrapWidth. * * @param text The text to wrap. * @return Returns the wrapped text. */ private String wrapText(String text) { //wrap text if (isWrap()) { int lastSpace = 0; int lastWrap = 0; StringBuilder wrapText = new StringBuilder(text + " "); wrapPosition.clear(); float wrapWidth = getSize().x - margin.y - margin.w; if (wrapWidth > 0) { //loop through whole text for (int i = 0; i < wrapText.length(); i++) { //check if character is a space -> text can only be wrapped at spaces if (wrapText.charAt(i) == ' ') { //check if the string (from the beginning of the new line) is bigger than the container width if (calcTextWidth(wrapText.substring(lastWrap, i)) > wrapWidth) { //than wrap the text at the previous space wrapText.insert(lastSpace + 1, '\n'); wrapPosition.add(new Integer(lastSpace + 1)); lastWrap = lastSpace + 1; } lastSpace = i; } else if (wrapText.charAt(i) == '\n') { lastSpace = i; lastWrap = i; } } } wrapText.replace(wrapText.length() - 1, wrapText.length(), ""); return wrapText.toString(); } //no wrap else { return text; } } /** * Get the displayed text of the label. * * @return Returns the text. */ public String getText() { StringBuilder str = new StringBuilder(text.toString()); for (int i = 0; i < wrapPosition.size(); i++) { str.replace(wrapPosition.get(i) - i, wrapPosition.get(i) + 1 - i, ""); } return str.toString(); } /** * Set the text of the label. * * @param text The text to set. */ public void setText(String text) { this.text = new StringBuilder(wrapText(text)); if (isWrap) { String unitX = "px"; if (unitSizeX == EUnitType.PERCENTAGE) { unitX = "%"; } setSize(sizeOriginal.x + unitX, (calcTextHeight(this.text.toString()) + margin.x + margin.z) + "px"); } else { setSize(new Vector2f(calcTextWidth(this.text.toString()) + margin.y + margin.w, calcTextHeight(this.text.toString()) + margin.x + margin.z)); } notifyChangedListeners(); } /** * Append a text to the current displayed text of the label. * * @param text The text to append. */ public void appendText(String text) { setText(getText() + text); } /** * Insert a text at a specific position into the current displayed text of the label. * * @param offset The offset, where to insert the text at. * @param text The text to insert. */ public void insertText(int offset, String text) { StringBuilder builder = new StringBuilder(getText()); builder.insert(offset, text); setText(builder.toString()); } /** * Replace a string defined by its start and end index. * * @param start The start index. * @param end The end index. * @param text The text to replace with. */ public void replaceText(int start, int end, String text) { StringBuilder builder = new StringBuilder(getText()); builder.replace(start, end, text); setText(builder.toString()); } /** * Get the text color. * * @return Returns the text color. */ public Color getColor() { return color; } /** * Set the text color. * * @param color The color to set. */ public void setColor(Color color) { this.color = color; } /** * Get the shadow color. * * @return Returns the shadow color. */ public Color getTextShadowColor() { return shadowColor; } /** * Set the shadow color. * * @param shadowColor The shadow color to set. */ public void setTextShadowColor(Color shadowColor) { this.shadowColor = shadowColor; } /** * Check whether the text has a shadow. * * @return Returns true if the text has a shadow. */ public boolean isTextShadow() { return enableShadow; } /** * Set whether the text has a color. * * @param enable True to enable the shadow of the text. */ public void setTextShadow(boolean enable) { this.enableShadow = enable; } /** * Get the font. * * @return Returns the font. */ public Font getFont() { return font; } /** * Set the font. * * @param font The font to set. */ public void setFont(Font font) { this.font = font; } /** * Get the margin which will be around the text. * * @return Returns the margin. */ public Vector4f getMargin() { return margin; } /** * Set the margin which will be around the text. * * @param margin The margin. */ public void setMargin(Vector4f margin) { this.margin = margin; } /** * Check whether the text will be wrapped. The width where the text will be wrapped can be set by using setWrapWidth(). * * @return Returns Returns true if the text will be wrapped. */ public boolean isWrap() { return isWrap; } /** * Set whether the text will be wrapped. The width where the text will be wrapped can be set by using setWrapWidth(). * * @param isWrap True to enable text wrapping. */ public void setWrap(boolean isWrap) { this.isWrap = isWrap; } /* Event listeners */ private void notifyChangedListeners() { for (ChangedListener listener : changedListeners) { listener.changed(this); } } public void addChangedListener(ChangedListener listener) { changedListeners.add(listener); } public void removeChangedListener(ChangedListener listener) { changedListeners.remove(listener); } }
package com.percero.agents.auth.services; import com.percero.agents.auth.helpers.IAccountHelper; import com.percero.agents.auth.hibernate.AssociationExample; import com.percero.agents.auth.hibernate.AuthHibernateUtils; import com.percero.agents.auth.hibernate.BaseDataObjectPropertySelector; import com.percero.agents.auth.vo.*; import com.percero.agents.sync.access.IAccessManager; import org.apache.log4j.Logger; import org.hibernate.*; import org.hibernate.exception.LockAcquisitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.*; /** * The AuthService is responsible for managing authentication of users within the Percero framework. The AuthService * maintains its own separate database that generically references users. Implementations of IAuthHelper's provide * integration to 3rd party auth providers/services (Google, Facebook, LinkedIn, etc.). Custom IAuthHelper's can * also be provided for custom auth integrations (database, LDAP, etc.). * * @author Collin Brown * */ @Component public class AuthService implements IAuthService { // TODO: Better manage Hibernate Sessions (opening and closing). private static Logger log = Logger.getLogger(AuthService.class); @Autowired SessionFactory sessionFactoryAuth; @Autowired DatabaseHelper databaseHelper; @Autowired IAccessManager accessManager; @Autowired @Value("$pf{anonAuth.enabled:false}") Boolean anonAuthEnabled = false; @Autowired @Value("$pf{anonAuth.code:ANON}") String anonAuthCode = "ANON"; @Autowired @Value("$pf{anonAuth.roleNames:}") String anonAuthRoleNames = ""; @Autowired GoogleHelper googleHelper; @Autowired FacebookHelper facebookHelper; @Autowired LinkedInHelper linkedInHelper; @Autowired GitHubHelper githubHelper; @Autowired IAccountHelper accountHelper; @Autowired @Value("$pf{auth.maxUserTokenCleanupCount:500}") private Integer maxUserTokenCleanupCount = 500; public void setSessionFactoryAuth(SessionFactory value) { sessionFactoryAuth = value; } public AuthService() { } @SuppressWarnings("rawtypes") protected List findByExample(Object theQueryObject, List<String> excludeProperties) { Session s = null; try { s = sessionFactoryAuth.openSession(); Criteria criteria = s.createCriteria(theQueryObject.getClass()); AssociationExample example = AssociationExample .create(theQueryObject); BaseDataObjectPropertySelector propertySelector = new BaseDataObjectPropertySelector( excludeProperties); example.setPropertySelector(propertySelector); criteria.add(example); List result = criteria.list(); return (List) AuthHibernateUtils.cleanObject(result); } catch (Exception e) { log.error("Unable to findByExample", e); } finally { if (s != null) s.close(); } return null; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#authenticateOAuthCode(com.com.percero.agents.auth.vo.AuthProvider, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.com.percero.agents.auth.vo.OAuthToken) */ public OAuthResponse authenticateOAuthCode(String authProviderID, String code, String clientId, String deviceId, String redirectUrl, OAuthToken requestToken){ Object accessTokenResult = getServiceProviderAccessToken(authProviderID, code, redirectUrl, requestToken); if (accessTokenResult == null) return null; if (accessTokenResult instanceof ServiceUser) { ServiceUser serviceUser = (ServiceUser) accessTokenResult; serviceUser.setAuthProviderID(authProviderID); return setupServiceUser(authProviderID, serviceUser, clientId, deviceId); } else if (accessTokenResult instanceof OAuthToken){ OAuthToken token = (OAuthToken) accessTokenResult; return authenticateOAuthAccessToken(authProviderID, token.getToken(), token.getTokenSecret(), clientId, deviceId, false); } else { log.error("Invalid access token result in authenticateOAuthCode"); return null; } } protected Object getServiceProviderAccessToken(String authProviderID, String code, String redirectUrl, OAuthToken requestToken) { OAuthToken token = null; try { /*if (authProviderID.equals(AuthProvider.LINKEDIN)) { // LinkedInHelper linkedInHelper = new LinkedInHelper(); // token = linkedInHelper.getAccessToken(svcOAuth.getAppKey(), svcOAuthSecret.getAppToken(), code, requestToken); } // else if (svcOAuth.getServiceApplication().getServiceProvider().getName().equalsIgnoreCase(FacebookHelper.SERVICE_PROVIDER_NAME)) { // //oauthToken = FacebookHelper.getRequestToken(svcOauth.getAppKey(), svcOauthSecret.getAppToken()); // throw new IllegalArgumentException("Facebook OAuth Not supported"); // } else */ if (authProviderID.equals(AuthProvider.GOOGLE.toString())) { ServiceUser serviceUser = googleHelper.authenticateOAuthCode(code, redirectUrl); return serviceUser; } else if (authProviderID.equals(AuthProvider.LINKEDIN.toString())) { ServiceUser serviceUser = linkedInHelper.authenticateOAuthCode(code, redirectUrl); return serviceUser; } else if (authProviderID.equals(AuthProvider.FACEBOOK.toString())) { ServiceUser serviceUser = facebookHelper.authenticateOAuthCode(code, redirectUrl); return serviceUser; } else if (authProviderID.equals(AuthProvider.GITHUB.toString())) { String accessToken = githubHelper.getAccessTokenResponse(code, redirectUrl); token = new OAuthToken(); token.setToken(accessToken); } else if(authProviderID.equals(AuthProvider.ANON.toString())){ token = new OAuthToken(); token.setToken("ANON"); token.setTokenSecret("ANON"); } } catch (Exception e) { e.printStackTrace(); } return token; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#authenticateBasicOAuth(com.com.percero.agents.auth.vo.AuthProvider, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.com.percero.agents.auth.vo.OAuthToken) */ public OAuthResponse authenticateBasicOAuth(String authProviderID, String userName, String password, String scopes, String appUrl, String clientId, String deviceId, OAuthToken requestToken){ OAuthToken token = getServiceProviderAccessTokenViaBasicAuth(authProviderID, userName, password, scopes, appUrl, requestToken); if (token == null) return null; return authenticateOAuthAccessToken(authProviderID, token.getToken(), token.getTokenSecret(), clientId, deviceId, false); } protected OAuthToken getServiceProviderAccessTokenViaBasicAuth(String authProviderID, String userName, String password, String scopes, String appUrl, OAuthToken requestToken) { OAuthToken token = null; try { if (authProviderID.equals(AuthProvider.GITHUB)) { String accessToken = githubHelper.getBasicAccessTokenResponse(userName, password, scopes, appUrl); token = new OAuthToken(); token.setToken(accessToken); } else if(authProviderID.equals(AuthProvider.ANON)){ token = new OAuthToken(); token.setToken("ANON"); token.setTokenSecret("ANON"); } else { throw new IllegalArgumentException(authProviderID + " OAuth Not supported"); } } catch (Exception e) { e.printStackTrace(); } return token; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#authenticateOAuthAccessToken(com.com.percero.agents.auth.vo.AuthProvider, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ public OAuthResponse authenticateOAuthAccessToken(String authProviderID, String accessToken, String refreshToken, String clientId, String deviceId) { return authenticateOAuthAccessToken(authProviderID, accessToken, refreshToken, clientId, deviceId, true); } public OAuthResponse authenticateOAuthAccessToken(String authProviderID, String accessToken, String refreshToken, String clientId, String deviceId, Boolean canOverideAccessToken) { /** * The client may not actually have the refresh token. If not then we need to find it, because without a valid * refresh token then any "Auto-login" will fail after the token expires... which can cause client connections * to go stale without them knowing it. * * In the case where multiple devices are connected as the same user a device may have the wrong accessToken. So use the * good one. * * We only want to do this when we are doing a "TRUE" auth by access token (not by OAuth code, which delegates to this function). * That is why we include canOverideAccessToken. */ if(canOverideAccessToken && (refreshToken == null || refreshToken.isEmpty())){ Session session = sessionFactoryAuth.getCurrentSession(); session.beginTransaction(); User user = (User) (session.createQuery("select distinct(ut.user) from UserToken ut where clientId=:clientId OR deviceId=:deviceId") .setParameter("clientId", clientId) .setParameter("deviceId", deviceId) ).uniqueResult(); if(user != null){ for(Object ob : user.getUserAccounts()){ UserAccount ua = (UserAccount)ob; if(ua.getAuthProviderID().equals(authProviderID)){ refreshToken = ua.getRefreshToken(); accessToken = ua.getAccessToken(); break; } } } } ServiceUser serviceUser = getServiceProviderServiceUser(accessToken, refreshToken, "", authProviderID); if (serviceUser == null) return null; else return setupServiceUser(authProviderID, serviceUser, clientId, deviceId); } public OAuthResponse setupServiceUser(String authProviderID, ServiceUser serviceUser, String clientId, String deviceId) { OAuthResponse result = null; UserToken userToken = null; /** * The client may not actually have the refresh token. If not then we need to find it, because without a valid * refresh token then any "Auto-login" will fail after the token expires... which can cause client connections * to go stale without them knowing it. * * In the case where multiple devices are connected as the same user a device may have the wrong accessToken. So use the * good one. */ if(!StringUtils.hasText(serviceUser.getRefreshToken()) && StringUtils.hasText(clientId)){ Session session = sessionFactoryAuth.getCurrentSession(); session.beginTransaction(); User user = (User) (session.createQuery("select distinct(ut.user) from UserToken ut where clientId=:clientId OR deviceId=:deviceId") .setParameter("clientId", clientId) .setParameter("deviceId", deviceId) ).uniqueResult(); if(user != null){ for(Object ob : user.getUserAccounts()){ UserAccount ua = (UserAccount)ob; if(ua.getAuthProviderID().equals(authProviderID)){ serviceUser.setRefreshToken(ua.getRefreshToken()); serviceUser.setAccessToken(ua.getAccessToken()); break; } } } } if (serviceUser != null && serviceUser.getId() != null && serviceUser.getId().length() > 0) { // The access token may have been updated for this ServiceUser. String accountId = serviceUser.getId(); if (accountId != null && accountId.trim().length() > 0) { // TODO: We need to know the ServiceProvider and ServiceApplication here. // Without setting the queryUserAccount.ServiceProvider, updateUserAccountToken will fail if the UserAccount does not already exist. UserAccount queryUserAccount = new UserAccount(); queryUserAccount.setAccountId(accountId); queryUserAccount.setAccessToken(serviceUser.getAccessToken()); queryUserAccount.setRefreshToken(serviceUser.getRefreshToken()); queryUserAccount.setAuthProviderID(serviceUser.getAuthProviderID()); UserAccount theFoundUserAccount = updateUserAccountToken(queryUserAccount, true, serviceUser); if (theFoundUserAccount != null) { try { // Validate the user in the project database (by // checking the IUserAnchor class) // In the case that the UserAnchor object already exists // in the project database but is NOT linked to the // User, we need to link it here. Object validateUserResult = accountHelper.validateUser(null, theFoundUserAccount.getUser().getID(), this); System.out.println(validateUserResult); } catch (Exception e) { log.warn("Error validating user", e); } // Now check Service Application Roles. Boolean foundMatchingRole = validateUserRoles(serviceUser, theFoundUserAccount.getUser().getID()); if (foundMatchingRole) { userToken = loginUserAccount(theFoundUserAccount, clientId, deviceId); result = new OAuthResponse(); result.userToken = userToken; result.accessToken = serviceUser.getAccessToken(); result.refreshToken = serviceUser.getRefreshToken(); } else { log.warn("Unable to validate user " + serviceUser.getName() + ". No valid role found."); } } else { log.debug("Unable to find user account for ServiceUser " + serviceUser.getName()); } } } return result; } // TODO: Need to check the Service Application only, NOT ALL Service Applications for this Service Provider. protected Boolean validateUserRoles(ServiceUser serviceUser, String userId) { // Get list of role names required for this Auth authProviderID List<SvcAppRole> authProviderRequiredSvcRoles = getSvcAppRoles(serviceUser.getAuthProviderID()); // If the auth authProviderID requires no valid roles, then we have "foundMatchingRole" Boolean foundMatchingRole = (authProviderRequiredSvcRoles == null || authProviderRequiredSvcRoles.size() == 0); // Only check the ServiceUser roles list if role names for the ServiceUser are valid. if (serviceUser.getAreRoleNamesAccurate() && !foundMatchingRole) { Iterator<SvcAppRole> itrSvcRoles = authProviderRequiredSvcRoles.iterator(); // Check to see if the ServiceUser has at least one role that is in the required auth authProviderID roles list. while(!foundMatchingRole && itrSvcRoles.hasNext()) { SvcAppRole nextSvcAppRole = itrSvcRoles.next(); for(String nextRole : serviceUser.getRoleNames()) { if (nextRole.matches(nextSvcAppRole.getValue())) { foundMatchingRole = true; break; } } } } // Now check existing auth roles for the user. Not all Auth Providers authProviderID roles. if (!foundMatchingRole) { Iterator<SvcAppRole> itrAuthProviderRequiredSvcRoles = authProviderRequiredSvcRoles.iterator(); try { // This is a list of existing roles for this user. List<String> userRoles = accountHelper.getUserRoles(userId); while(!foundMatchingRole && itrAuthProviderRequiredSvcRoles.hasNext()) { SvcAppRole nextAuthProviderRequiredSvcAppRole = itrAuthProviderRequiredSvcRoles.next(); Iterator<String> itrUserRoles = userRoles.iterator(); while (itrUserRoles.hasNext()) { String nextRole = itrUserRoles.next(); if (nextRole.matches(nextAuthProviderRequiredSvcAppRole.getValue())) { foundMatchingRole = true; break; } } if (!foundMatchingRole) { log.debug("Unable to find matching role " + nextAuthProviderRequiredSvcAppRole.getValue() + " for user " + userId); } } } catch(Exception e) { log.error("Unable to get UserRoles for user " + userId, e); } } return foundMatchingRole; } /** * Retrieve the list of valid role names for the specified auth authProviderID (or NONE) * for which a user must have have at least one to access the system. * * @param authProviderID * @return */ @SuppressWarnings("unchecked") protected List<SvcAppRole> getSvcAppRoles(String authProviderID) { Session s = null; List<SvcAppRole> result = null; try { s = sessionFactoryAuth.openSession(); Query query = s.createQuery("FROM SvcAppRole sar WHERE sar.authProvider = :authProvider OR sar.authProvider = NULL"); query.setString("authProvider", authProviderID.toString()); result = (List<SvcAppRole>) query.list(); result = (List<SvcAppRole>) AuthHibernateUtils.cleanObject(result); } catch (Exception e) { log.error("Unable to getSvcAppRoles", e); } finally { if (s != null) s.close(); } return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) private UserAccount updateUserAccountToken(UserAccount theQueryObject, Boolean createIfNotExist, ServiceUser serviceUser) { UserAccount theFoundUserAccount = null; Session s = null; try { List<String> excludeProperties = new ArrayList<String>(); excludeProperties.add("accessToken"); excludeProperties.add("refreshToken"); excludeProperties.add("isAdmin"); excludeProperties.add("isSuspended"); List userAccounts = findByExample(theQueryObject, excludeProperties); // It is possible that this Service Provider (or this use case) does not have an AccessToken, so set one here. if (theQueryObject.getAccessToken() == null || theQueryObject.getAccessToken().length() == 0) theQueryObject.setAccessToken(getRandomId()); if ((userAccounts instanceof List) && ((List) userAccounts).size() > 0) { // Found a valid UserAccount. List userAccountList = (List) userAccounts; theFoundUserAccount = (UserAccount) userAccountList.get(0); // Check the AccessToken. if (!theQueryObject.getAccessToken().equals(theFoundUserAccount.getAccessToken()) ) { theFoundUserAccount.setAccessToken(theQueryObject.getAccessToken()); if(theQueryObject.getRefreshToken() != null && !theQueryObject.getRefreshToken().isEmpty()) theFoundUserAccount.setRefreshToken(theQueryObject.getRefreshToken()); s = sessionFactoryAuth.openSession(); Transaction tx = s.beginTransaction(); tx.begin(); theFoundUserAccount = (UserAccount) s .merge(theFoundUserAccount); tx.commit(); } } else if (createIfNotExist) { s = sessionFactoryAuth.openSession(); User theUser = null; // Attempt to find this user by finding a matching UserIdentifier. if (serviceUser.getIdentifiers() != null && serviceUser.getIdentifiers().size() > 0) { String strFindUserIdentifier = "SELECT ui.user FROM UserIdentifier ui WHERE"; int counter = 0; for(ServiceIdentifier nextServiceIdentifier : serviceUser.getIdentifiers()) { if (counter > 0) strFindUserIdentifier += " OR "; strFindUserIdentifier += " ui.type='" + nextServiceIdentifier.getParadigm() + "' AND ui.userIdentifier='" + nextServiceIdentifier.getValue() + "'"; counter++; } strFindUserIdentifier += ""; Query q = s.createQuery(strFindUserIdentifier); List<User> userList = (List<User>) q.list(); if (userList.size() > 0) { theUser = userList.get(0); } } Transaction tx = s.beginTransaction(); tx.begin(); Date currentDate = new Date(); if (theUser == null) { theUser = new User(); theUser.setID(UUID.randomUUID().toString()); theUser.setDateCreated(currentDate); theUser.setDateModified(currentDate); s.save(theUser); } theFoundUserAccount = new UserAccount(); theFoundUserAccount.setAuthProviderID(serviceUser.getAuthProviderID()); theFoundUserAccount.setUser(theUser); theFoundUserAccount.setDateCreated(currentDate); theFoundUserAccount.setDateModified(currentDate); theFoundUserAccount.setAccessToken(theQueryObject .getAccessToken()); theFoundUserAccount.setRefreshToken(theQueryObject .getRefreshToken()); theFoundUserAccount.setAccountId(theQueryObject .getAccountId()); s.save(theFoundUserAccount); tx.commit(); s.close(); s = sessionFactoryAuth.openSession(); theFoundUserAccount = (UserAccount) s.get(UserAccount.class, theFoundUserAccount.getID()); } if (theFoundUserAccount != null) { theFoundUserAccount = (UserAccount) AuthHibernateUtils .cleanObject(theFoundUserAccount); // Now enter in the UserIdentifiers for this User. if (serviceUser.getIdentifiers() != null && serviceUser.getIdentifiers().size() > 0) { if (s == null) s = sessionFactoryAuth.openSession(); Transaction tx = s.beginTransaction(); Query q = null; for(ServiceIdentifier nextServiceIdentifier : serviceUser.getIdentifiers()) { q = s.createQuery("FROM UserIdentifier ui WHERE ui.userIdentifier=:uid AND ui.type=:paradigm"); q.setString("uid", nextServiceIdentifier.getValue()); q.setString("paradigm", nextServiceIdentifier.getParadigm()); List<UserIdentifier> userIdenditifierList = (List<UserIdentifier>) q.list(); if (userIdenditifierList.size() == 0) { try { UserIdentifier userIdentifier = new UserIdentifier(); userIdentifier.setType(nextServiceIdentifier.getParadigm()); userIdentifier.setUser(theFoundUserAccount.getUser()); userIdentifier.setUserIdentifier(nextServiceIdentifier.getValue()); s.saveOrUpdate(userIdentifier); } catch(Exception e) { log.warn("Unable to save UserIdentifier for " + serviceUser.getName(), e); } } } tx.commit(); } } } catch (Exception e) { log.error("Unable to run authenticate UserAccount", e); } finally { if (s != null) s.close(); } return theFoundUserAccount; } @SuppressWarnings("rawtypes") private UserToken loginUserAccount(UserAccount theUserAccount, String clientId, String deviceId) { Session s = null; try { if (theUserAccount != null) { UserToken theUserToken = null; if (theUserAccount != null) { Date currentDate = new Date(); UserToken queryUserToken = new UserToken(); queryUserToken.setUser(theUserAccount.getUser()); queryUserToken.setClientId(clientId); List userTokenResult = findByExample(queryUserToken, null); if ( !userTokenResult.isEmpty() ) { theUserToken = (UserToken) userTokenResult.get(0); } if (s == null) s = sessionFactoryAuth.openSession(); Transaction tx = s.beginTransaction(); tx.begin(); if (theUserToken == null) { if (StringUtils.hasText(deviceId)) { // Need to delete all of UserTokens for this User/Device. log.debug("Deleting ALL UserToken's for User " + theUserAccount.getUser().getID() + ", Device " + deviceId); String deleteUserTokenSql = "DELETE FROM UserToken WHERE deviceId=:deviceId AND user=:user"; Query deleteQuery = s.createQuery(deleteUserTokenSql); deleteQuery.setString("deviceId", deviceId); deleteQuery.setEntity("user", theUserAccount.getUser()); deleteQuery.executeUpdate(); } theUserToken = new UserToken(); theUserToken.setUser(theUserAccount.getUser()); theUserToken.setClientId(clientId); theUserToken.setDeviceId(deviceId); theUserToken.setDateCreated(currentDate); theUserToken.setDateModified(currentDate); theUserToken.setToken(getRandomId()); theUserToken.setLastLogin(currentDate); s.save(theUserToken); } else { theUserToken.setToken(getRandomId()); theUserToken.setLastLogin(currentDate); //s.merge(theUserToken); s.saveOrUpdate(theUserToken); } tx.commit(); } return theUserToken; } else { return null; } } catch (LockAcquisitionException lae) { log.error("Unable to run authenticate UserAccount", lae); /** * TODO: Fix this! 2014-09-26 14:45:55,176 [SimpleAsyncTaskExecutor-5] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1213, SQLState: 40001 2014-09-26 14:45:55,177 [SimpleAsyncTaskExecutor-5] ERROR org.hibernate.util.JDBCExceptionReporter - Deadlock found when trying to get lock; try restarting transaction 2014-09-26 14:45:55,180 [SimpleAsyncTaskExecutor-5] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.LockAcquisitionException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:82) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.com.percero.agents.auth.services.AuthService.loginUserAccount(AuthService.java:644) */ } catch (Exception e) { log.error("Unable to run authenticate UserAccount", e); } finally { if (s != null) s.close(); } return null; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#logoutUser(java.lang.String, java.lang.String, java.lang.String) */ public Boolean logoutUser(String aUserId, String aToken, String aClientId) { Boolean result = false; boolean validUser = StringUtils.hasText(aUserId); boolean validClient = StringUtils.hasText(aClientId); boolean validToken = StringUtils.hasText(aToken); // If neither a valid user or a valid client, then no one to logout. if (!validUser && !validClient && !validToken) { log.warn("Invalid user/client/token on AuthService.logoutUser"); return false; } String deleteUserTokenSql = "DELETE FROM UserToken WHERE "; // Match EITHER the ClientID OR the Token if (validClient && validToken) { log.debug("Logging out Client: " + aClientId + ", Token: " + aToken); deleteUserTokenSql += " (clientId=:clientId OR token=:token) "; } else if (validToken) { log.debug("Logging out Token: " + aToken); log.debug("Logging out Token: " + aToken); deleteUserTokenSql += " token=:token "; } else if (validClient) { log.debug("Logging out Client: " + aClientId); deleteUserTokenSql += " clientId=:clientId "; } else if (validUser) { // This will log out ALL of the User's devices, logging them out completely. log.warn("Logging out ALL User " + aUserId + " devices!"); deleteUserTokenSql += " user_ID=:user_ID "; } Session s = null; try { s = sessionFactoryAuth.openSession(); Query deleteQuery = s.createSQLQuery(deleteUserTokenSql); if (validClient && validToken) { deleteQuery.setString("token", aToken); deleteQuery.setString("clientId", aClientId); } else if (validToken) { deleteQuery.setString("token", aToken); } else if (validClient) { deleteQuery.setString("clientId", aClientId); } else if (validUser) { deleteQuery.setString("user_ID", aUserId); } deleteQuery.executeUpdate(); } catch (StaleStateException e) { // Most likely this failed because the userToken has already been deleted from the database. log.debug("Unable to delete UserToken due to StaleStateException: " + e.getMessage()); result = false; } catch (Exception e) { log.error("Unable to delete UserToken", e); result = false; } if (s != null && s.isOpen()) { s.close(); } return result; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#validateUserByToken(java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ // TODO: This function should also validate that the user is valid against the ServiceProvider's API. public boolean validateUserByToken(String regAppKey, String aUserId, String aToken, String aClientId) { log.debug("[AuthService] Validating user " + aUserId + " by token " + aToken + ", client " + aClientId + " NO existing clients"); boolean result = false; if (/*StringUtils.hasText(regAppKey) && */StringUtils.hasText(aUserId) && StringUtils.hasText(aToken)) { Session s = null; try { s = sessionFactoryAuth.openSession(); String strQuery = "SELECT COUNT(ut.ID) FROM UserToken ut WHERE ut.user.ID = :userId AND ut.token = :token AND ut.clientId = :clientId"; Query query = s.createQuery(strQuery); query.setString("userId", aUserId); query.setString("token", aToken); query.setString("clientId", aClientId); Long uniqueResultCount = (Long) query.uniqueResult(); if (uniqueResultCount != null && uniqueResultCount > 0) { if (uniqueResultCount > 1) { log.error("[AuthService] " + uniqueResultCount + " UserTokens found for user " + aUserId + ", token " + aToken + ", client " + aClientId); } result = true; } else log.warn("[AuthService] Invalid User in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId); } catch (Exception e) { log.error("[AuthService] Unable to validateUserByToken", e); result = false; } finally { if (s != null) s.close(); } } else { log.warn("Invalid User in validateUserByToken"); } return result; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#validateUserByToken(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ public boolean validateUserByToken(String regAppKey, String aUserId, String aToken, String aClientId, Set<String> existingClientIds) { log.debug("[AuthService] Validating user " + aUserId + " by token " + aToken + ", client " + aClientId + " " + (existingClientIds != null && !existingClientIds.isEmpty() ? existingClientIds.size() + " existing clients" : " 0 existing clients")); boolean result = false; if (/*StringUtils.hasText(regAppKey) && */StringUtils.hasText(aUserId) && StringUtils.hasText(aToken)) { Session s = null; try { s = sessionFactoryAuth.openSession(); String strQuery = "SELECT COUNT(ut.ID) FROM UserToken ut WHERE ut.user.ID = :userId AND ut.token = :token AND ut.clientId IN (:existingClientIds)"; Query query = s.createQuery(strQuery); query.setString("userId", aUserId); query.setString("token", aToken); query.setParameterList("existingClientIds", existingClientIds); Long uniqueResultCount = (Long) query.uniqueResult(); if (uniqueResultCount != null && uniqueResultCount > 0) { // Now update the UserToken with the new ClientId strQuery = "UPDATE UserToken ut SET ut.clientId=:newClientId WHERE ut.user.ID = :userId AND ut.token = :token AND ut.clientId IN (:existingClientIds)"; query = s.createQuery(strQuery); query.setString("userId", aUserId); query.setString("token", aToken); query.setString("newClientId", aClientId); query.setParameterList("existingClientIds", existingClientIds); int updateResult = query.executeUpdate(); if (updateResult > 0) { result = true; } else { log.warn("[AuthService] Unable to update UserToken in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId); } } else { log.warn("[AuthService] Invalid User in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId); } } catch (Exception e) { log.error("[AuthService] Unable to validateUserByToken", e); result = false; } finally { if (s != null) s.close(); } } else { log.warn("[AuthService] Invalid User in validateUserByToken"); } return result; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#getServiceUsers(java.lang.String) */ @SuppressWarnings("unchecked") public List<ServiceUser> getServiceUsers(String aUserId) { List<ServiceUser> result = new ArrayList<ServiceUser>(); Session s = null; try { s = sessionFactoryAuth.openSession(); User user = new User(); user.setID(aUserId); String userAccountQueryString = "SELECT ua FROM UserAccount ua WHERE user=:user"; Query userAccountQuery = s.createQuery(userAccountQueryString); userAccountQuery.setEntity("user", user); List<UserAccount> userAccounts = userAccountQuery.list(); // Get list of all ServiceApplicationOAuth's for this ServiceProvider. for (UserAccount nextUserAccount : userAccounts) { ServiceUser nextServiceUser = getServiceProviderServiceUser(nextUserAccount, nextUserAccount.getAuthProviderID()); if(nextServiceUser != null) { // Found a valid Service User, add to list and break. result.add(nextServiceUser); break; } } } catch (Exception e) { log.error("Unable to get ServiceUsers", e); } finally { if (s != null) s.close(); } return result; } /* (non-Javadoc) * @see com.com.percero.agents.auth.services.IAuthService#getUserAccounts(java.lang.String) */ @SuppressWarnings("unchecked") public Set<UserAccount> getUserAccounts(String aUserId) { Set<UserAccount> result = new HashSet<UserAccount>(); Session s = null; try { s = sessionFactoryAuth.openSession(); User user = new User(); user.setID(aUserId); String userAccountQueryString = "SELECT ua FROM UserAccount ua WHERE user=:user"; Query userAccountQuery = s.createQuery(userAccountQueryString); userAccountQuery.setEntity("user", user); result.addAll(userAccountQuery.list()); } catch (Exception e) { log.error("Unable to get UserAccounts", e); } finally { if (s != null) s.close(); } return result; } /** * Attempts to get the ServiceUser from the ServiceProvider associated with this UserAccount. * * @param aUserAccount * @return */ public ServiceUser getServiceProviderServiceUser(UserAccount aUserAccount, String authProviderID) { return getServiceProviderServiceUser(aUserAccount.getAccessToken(), aUserAccount.getRefreshToken(), aUserAccount.getAccountId(), authProviderID); } /** * Attempts to get the ServiceUser from the ServiceProvider associated with this accessToken. * * @param accessToken * @param refreshToken * @param accountId * @param authProviderID * @return */ public ServiceUser getServiceProviderServiceUser(String accessToken, String refreshToken, String accountId, String authProviderID) { ServiceUser serviceUser = null; try { if (anonAuthEnabled && StringUtils.hasText(anonAuthCode)) { if (refreshToken != null && refreshToken.equals(anonAuthCode)) { serviceUser = new ServiceUser(); serviceUser.setFirstName("ANON"); serviceUser.setLastName("ANON"); serviceUser.setId("ANON"); serviceUser.setAuthProviderID(AuthProvider.ANON.toString()); serviceUser.setRefreshToken(anonAuthCode); List<String> roles = new ArrayList<String>(); String[] roleNames = anonAuthRoleNames.split(","); for(int i = 0; i < roleNames.length; i++) { if (roleNames[i] != null && !roleNames[i].isEmpty()) roles.add(roleNames[i]); } serviceUser.setRoleNames(roles); serviceUser.setAreRoleNamesAccurate(true); return serviceUser; } } /**if (AuthProvider.LINKEDIN.equals(authProviderID)) { // LinkedInHelper linkedInHelper = new LinkedInHelper(); // ServiceUser liServiceUser = linkedInHelper.getServiceUser( // svcOauth.getAppKey(), svcOauthSecret.getAppToken(), // accessToken, // refreshToken, // svcOauth.getServiceApplication().getAppDomain()); // serviceUser = liServiceUser; } else */if (AuthProvider.FACEBOOK.equals(authProviderID)) { ServiceUser fbServiceUser = facebookHelper.getServiceUser( accessToken, accountId); serviceUser = fbServiceUser; } else if (AuthProvider.GOOGLE.equals(authProviderID)) { ServiceUser glServiceUser = googleHelper.authenticateAccessToken(accessToken, refreshToken, accountId); //ServiceUser glServiceUser = googleHelper.retrieveServiceUser(accountId); serviceUser = glServiceUser; } else if (AuthProvider.GITHUB.equals(authProviderID)) { ServiceUser glServiceUser = githubHelper.getServiceUser(accessToken, refreshToken); serviceUser = glServiceUser; } else if (AuthProvider.LINKEDIN.equals(authProviderID)) { ServiceUser liServiceUser = linkedInHelper.getServiceUser(accessToken, refreshToken); serviceUser = liServiceUser; } else if(AuthProvider.ANON.equals(authProviderID)){ serviceUser = new ServiceUser(); serviceUser.setEmails(new ArrayList<String>()); serviceUser.getEmails().add("blargblarg@com.percero.com"); serviceUser.setAccessToken("blargblarg"); serviceUser.setFirstName("ANONYMOUS"); serviceUser.setId("ANONYMOUS"); serviceUser.setAuthProviderID(AuthProvider.ANON.toString()); } else { log.warn("ServiceProvider not yet supported: " + authProviderID); } } catch (Exception e) { e.printStackTrace(); } if (serviceUser != null) serviceUser.setAuthProviderID(authProviderID); return serviceUser; } /********************************************** * HELPER METHODS **********************************************/ private static String getRandomId() { UUID randomId = UUID.randomUUID(); return randomId.toString(); } /********************************************** * CLEANUP **********************************************/ static final String DELETE_USER_TOKENS_COLLECTION_SQL = "DELETE FROM UserToken WHERE clientId IN (:clientIds)"; private Set<String> previousInvalidClientIds = new HashSet<String>(); // @SuppressWarnings("unchecked") /** * This method checks for any rogue/ghost UserTokens and removes them. */ // @Scheduled(fixedRate=30000) // 30 Seconds @Scheduled(fixedDelay=300000, initialDelay=120000) // 5 Minutes, 2 Minutes private void cleanupUserTokens() { // Session s = null; try { // s = sessionFactoryAuth.openSession(); int firstResultCounter = 0; int maxResults = 30; List<String> clientIdsToDelete = new LinkedList<String>(); Map<String, String> clientDevicesMap = retrieveListOfClientDevicesFromUserTokens(maxResults, firstResultCounter); // String userTokenQueryString = "SELECT DISTINCT(ut.clientId), ut.deviceId FROM UserToken ut ORDER BY ut.clientId"; // Query userTokenQuery = s.createQuery(userTokenQueryString); // userTokenQuery.setMaxResults(maxResults); // userTokenQuery.setFirstResult(firstResultCounter); // // // Gather up all clientIds to remove, then delete at the end. // List<String> clientIdsToDelete = new LinkedList<String>(); // List<Object[]> userTokenClientIds = userTokenQuery.list(); // Map<String, String> clientDevicesMap = new HashMap<String, String>(userTokenClientIds.size()); // if (userTokenClientIds != null) { // Iterator<Object[]> itrUserTokenClientIds = userTokenClientIds.iterator(); // while (itrUserTokenClientIds.hasNext()) { // Object[] nextClientDevice = itrUserTokenClientIds.next(); // if (nextClientDevice != null && nextClientDevice.length >= 2) { // clientDevicesMap.put((String)nextClientDevice[0], (String)nextClientDevice[1]); // } // } // } // while (clientDevicesMap != null && !clientDevicesMap.isEmpty()) { Set<String> validClients = accessManager.validateClientsIncludeFromDeviceHistory(clientDevicesMap); clientDevicesMap.keySet().removeAll(validClients); clientIdsToDelete.addAll(clientDevicesMap.keySet()); // If countToDelete is greater than Max User Token Cleanup Count, execute delete and start again. if (!clientIdsToDelete.isEmpty()) { log.warn("Cleaning up " + clientIdsToDelete.size() + " client UserTokens"); // Logout ALL of these Clients. Iterator<String> itrClientIdsToDelete = clientIdsToDelete.iterator(); while (itrClientIdsToDelete.hasNext()) { String clientId = itrClientIdsToDelete.next(); // Want to give each client a bit of time to login, so // pend the client Id to remove the first time, then // actually remove it the second time. if (previousInvalidClientIds.contains(clientId)) { accessManager.logoutClient(clientId, true); // Force the deletion, since this client is no longer valid. previousInvalidClientIds.remove(clientId); } else { previousInvalidClientIds.add(clientId); } } clientIdsToDelete.clear(); // firstResultCounter = 0; } // else { firstResultCounter += maxResults; // } clientDevicesMap = retrieveListOfClientDevicesFromUserTokens(maxResults, firstResultCounter); // userTokenQuery.setFirstResult(firstResultCounter); // userTokenClientIds = userTokenQuery.list(); // if (userTokenClientIds != null) { // clientDevicesMap = new HashMap<String, String>(userTokenClientIds.size()); // Iterator<Object[]> itrUserTokenClientIds = userTokenClientIds.iterator(); // if (userTokenClientIds != null) { // while (itrUserTokenClientIds.hasNext()) { // Object[] nextClientDevice = itrUserTokenClientIds.next(); // if (nextClientDevice != null && nextClientDevice.length >= 2) { // clientDevicesMap.put((String)nextClientDevice[0], (String)nextClientDevice[1]); // } // } // } // } // else { // clientDevicesMap = null; // } } // if (clientIdsToDelete.size() > 0) { // log.warn("Cleaning up " + clientIdsToDelete.size() + " client UserTokens"); // // // Logout ALL of these Clients. // Iterator<String> itrClientIdsToDelete = clientIdsToDelete.iterator(); // while (itrClientIdsToDelete.hasNext()) { // String clientId = itrClientIdsToDelete.next(); // accessManager.logoutClient(clientId, true); // Force the deletion, since this client is no longer valid. // } //// log.warn("Deleting " + clientIdsToDelete.size() + " client UserTokens"); //// log.debug( "Deleting Client IDs: " + StringUtils.arrayToCommaDelimitedString(clientIdsToDelete.toArray()) ); //// Transaction tx = s.beginTransaction(); //// tx.begin(); //// Query deleteQuery = s.createQuery(DELETE_USER_TOKENS_COLLECTION_SQL); //// deleteQuery.setParameterList("clientIds", clientIdsToDelete); //// deleteQuery.executeUpdate(); //// tx.commit(); // // clientIdsToDelete.clear(); // } } catch (Exception e) { log.error("Unable to get cleanup UserTokens", e); // } finally { // if (s != null) // s.close(); } } @SuppressWarnings("unchecked") private Map<String, String> retrieveListOfClientDevicesFromUserTokens(int maxResults, int firstResultCounter) { Map<String, String> result = null; Session s = null; try { s = sessionFactoryAuth.openSession(); String userTokenQueryString = "SELECT DISTINCT(ut.clientId), ut.deviceId FROM UserToken ut ORDER BY ut.clientId"; Query userTokenQuery = s.createQuery(userTokenQueryString); userTokenQuery.setMaxResults(maxResults); userTokenQuery.setFirstResult(firstResultCounter); // Gather up all clientIds to remove, then delete at the end. List<Object[]> userTokenClientIds = userTokenQuery.list(); result = new HashMap<String, String>(userTokenClientIds.size()); if (userTokenClientIds != null) { Iterator<Object[]> itrUserTokenClientIds = userTokenClientIds.iterator(); while (itrUserTokenClientIds.hasNext()) { Object[] nextClientDevice = itrUserTokenClientIds.next(); if (nextClientDevice != null && nextClientDevice.length >= 2) { result.put((String)nextClientDevice[0], (String)nextClientDevice[1]); } } } } catch (Exception e) { log.error("Unable to retrieve list of Client Devices from UserTokens", e); } finally { if (s != null) s.close(); } return result; } }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver14; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFOxmIpv4DstVer14 implements OFOxmIpv4Dst { private static final Logger logger = LoggerFactory.getLogger(OFOxmIpv4DstVer14.class); // version: 1.4 final static byte WIRE_VERSION = 5; final static int LENGTH = 8; private final static IPv4Address DEFAULT_VALUE = IPv4Address.NONE; // OF message fields private final IPv4Address value; // // Immutable default instance final static OFOxmIpv4DstVer14 DEFAULT = new OFOxmIpv4DstVer14( DEFAULT_VALUE ); // package private constructor - used by readers, builders, and factory OFOxmIpv4DstVer14(IPv4Address value) { if(value == null) { throw new NullPointerException("OFOxmIpv4DstVer14: property value cannot be null"); } this.value = value; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x80001804L; } @Override public IPv4Address getValue() { return value; } @Override public MatchField<IPv4Address> getMatchField() { return MatchField.IPV4_DST; } @Override public boolean isMasked() { return false; } public OFOxm<IPv4Address> getCanonical() { // exact match OXM is always canonical return this; } @Override public IPv4Address getMask()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property mask not supported in version 1.4"); } @Override public OFVersion getVersion() { return OFVersion.OF_14; } public OFOxmIpv4Dst.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmIpv4Dst.Builder { final OFOxmIpv4DstVer14 parentMessage; // OF message fields private boolean valueSet; private IPv4Address value; BuilderWithParent(OFOxmIpv4DstVer14 parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x80001804L; } @Override public IPv4Address getValue() { return value; } @Override public OFOxmIpv4Dst.Builder setValue(IPv4Address value) { this.value = value; this.valueSet = true; return this; } @Override public MatchField<IPv4Address> getMatchField() { return MatchField.IPV4_DST; } @Override public boolean isMasked() { return false; } @Override public OFOxm<IPv4Address> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.4"); } @Override public IPv4Address getMask()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property mask not supported in version 1.4"); } @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFOxmIpv4Dst build() { IPv4Address value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new NullPointerException("Property value must not be null"); // return new OFOxmIpv4DstVer14( value ); } } static class Builder implements OFOxmIpv4Dst.Builder { // OF message fields private boolean valueSet; private IPv4Address value; @Override public long getTypeLen() { return 0x80001804L; } @Override public IPv4Address getValue() { return value; } @Override public OFOxmIpv4Dst.Builder setValue(IPv4Address value) { this.value = value; this.valueSet = true; return this; } @Override public MatchField<IPv4Address> getMatchField() { return MatchField.IPV4_DST; } @Override public boolean isMasked() { return false; } @Override public OFOxm<IPv4Address> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.4"); } @Override public IPv4Address getMask()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property mask not supported in version 1.4"); } @Override public OFVersion getVersion() { return OFVersion.OF_14; } // @Override public OFOxmIpv4Dst build() { IPv4Address value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new NullPointerException("Property value must not be null"); return new OFOxmIpv4DstVer14( value ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmIpv4Dst> { @Override public OFOxmIpv4Dst readFrom(ChannelBuffer bb) throws OFParseError { // fixed value property typeLen == 0x80001804L int typeLen = bb.readInt(); if(typeLen != (int) 0x80001804) throw new OFParseError("Wrong typeLen: Expected=0x80001804L(0x80001804L), got="+typeLen); IPv4Address value = IPv4Address.read4Bytes(bb); OFOxmIpv4DstVer14 oxmIpv4DstVer14 = new OFOxmIpv4DstVer14( value ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", oxmIpv4DstVer14); return oxmIpv4DstVer14; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFOxmIpv4DstVer14Funnel FUNNEL = new OFOxmIpv4DstVer14Funnel(); static class OFOxmIpv4DstVer14Funnel implements Funnel<OFOxmIpv4DstVer14> { private static final long serialVersionUID = 1L; @Override public void funnel(OFOxmIpv4DstVer14 message, PrimitiveSink sink) { // fixed value property typeLen = 0x80001804L sink.putInt((int) 0x80001804); message.value.putTo(sink); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFOxmIpv4DstVer14> { @Override public void write(ChannelBuffer bb, OFOxmIpv4DstVer14 message) { // fixed value property typeLen = 0x80001804L bb.writeInt((int) 0x80001804); message.value.write4Bytes(bb); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFOxmIpv4DstVer14("); b.append("value=").append(value); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFOxmIpv4DstVer14 other = (OFOxmIpv4DstVer14) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } }
/* * Copyright 2012-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.artifact_cache; import com.facebook.buck.artifact_cache.config.CacheReadMode; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rulekey.RuleKey; import com.facebook.buck.io.file.BorrowablePath; import com.facebook.buck.io.file.LazyPath; import com.facebook.buck.util.types.Pair; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; /** * MultiArtifactCache encapsulates a set of ArtifactCache instances such that fetch() succeeds if * any of the ArtifactCaches contain the desired artifact, and store() applies to all * ArtifactCaches. */ public class MultiArtifactCache implements ArtifactCache { private final ImmutableList<ArtifactCache> artifactCaches; private final ImmutableList<ArtifactCache> writableArtifactCaches; private final boolean isStoreSupported; public MultiArtifactCache(ImmutableList<ArtifactCache> artifactCaches) { this.artifactCaches = artifactCaches; this.writableArtifactCaches = artifactCaches .stream() .filter(c -> c.getCacheReadMode().equals(CacheReadMode.READWRITE)) .collect(ImmutableList.toImmutableList()); this.isStoreSupported = this.writableArtifactCaches.size() > 0; } /** * Fetch the artifact matching ruleKey and store it to output. If any of the encapsulated * ArtifactCaches contains the desired artifact, this method succeeds, and it may store the * artifact to one or more of the other encapsulated ArtifactCaches as a side effect. */ @Override public ListenableFuture<CacheResult> fetchAsync( @Nullable BuildTarget target, RuleKey ruleKey, LazyPath output) { ListenableFuture<CacheResult> cacheResult = Futures.immediateFuture(CacheResult.miss()); // This is the list of higher-priority caches that we should write the artifact to. ImmutableList.Builder<ArtifactCache> cachesToFill = ImmutableList.builder(); for (ArtifactCache artifactCache : artifactCaches) { cacheResult = Futures.transformAsync( cacheResult, (result) -> { if (result.getType().isSuccess()) { return Futures.immediateFuture(result); } if (artifactCache.getCacheReadMode().isWritable()) { cachesToFill.add(artifactCache); } return artifactCache.fetchAsync(target, ruleKey, output); }, MoreExecutors.directExecutor()); } // Propagate the artifact to previous writable caches. return Futures.transform( cacheResult, (CacheResult result) -> { if (!result.getType().isSuccess()) { return result; } storeToCaches( cachesToFill.build(), ArtifactInfo.builder().addRuleKeys(ruleKey).setMetadata(result.getMetadata()).build(), BorrowablePath.notBorrowablePath(output.getUnchecked())); return result; }, MoreExecutors.directExecutor()); } @Override public void skipPendingAndFutureAsyncFetches() { for (ArtifactCache artifactCache : artifactCaches) { artifactCache.skipPendingAndFutureAsyncFetches(); } } private static ListenableFuture<Void> storeToCaches( ImmutableList<ArtifactCache> caches, ArtifactInfo info, BorrowablePath output) { // TODO(cjhopman): support BorrowablePath with multiple writable caches. if (caches.size() != 1) { output = BorrowablePath.notBorrowablePath(output.getPath()); } List<ListenableFuture<Void>> storeFutures = Lists.newArrayListWithExpectedSize(caches.size()); for (ArtifactCache artifactCache : caches) { storeFutures.add(artifactCache.store(info, output)); } // Aggregate future to ensure all store operations have completed. return Futures.transform(Futures.allAsList(storeFutures), Functions.constant(null)); } /** Store the artifact to all encapsulated ArtifactCaches. */ @Override public ListenableFuture<Void> store(ArtifactInfo info, BorrowablePath output) { return storeToCaches(writableArtifactCaches, info, output); } @Override public ListenableFuture<Void> store(ImmutableList<Pair<ArtifactInfo, BorrowablePath>> artifacts) { if (writableArtifactCaches.size() != 1) { ImmutableList.Builder<Pair<ArtifactInfo, BorrowablePath>> artifactTemporaryPaths = ImmutableList.builderWithExpectedSize(artifacts.size()); for (int i = 0; i < artifacts.size(); i++) { artifactTemporaryPaths.add( new Pair<>( artifacts.get(i).getFirst(), BorrowablePath.notBorrowablePath(artifacts.get(i).getSecond().getPath()))); } artifacts = artifactTemporaryPaths.build(); } List<ListenableFuture<Void>> storeFutures = Lists.newArrayListWithExpectedSize(writableArtifactCaches.size()); for (ArtifactCache artifactCache : writableArtifactCaches) { storeFutures.add(artifactCache.store(artifacts)); } // Aggregate future to ensure all store operations have completed. return Futures.transform(Futures.allAsList(storeFutures), Functions.constant(null)); } @Override public ListenableFuture<ImmutableMap<RuleKey, CacheResult>> multiContainsAsync( ImmutableSet<RuleKey> ruleKeys) { Map<RuleKey, CacheResult> initialResults = new HashMap<>(ruleKeys.size()); for (RuleKey ruleKey : ruleKeys) { initialResults.put(ruleKey, CacheResult.miss()); } ListenableFuture<Map<RuleKey, CacheResult>> cacheResultFuture = Futures.immediateFuture(initialResults); for (ArtifactCache nextCache : artifactCaches) { cacheResultFuture = Futures.transformAsync( cacheResultFuture, mergedResults -> { ImmutableSet<RuleKey> missingKeys = mergedResults .entrySet() .stream() .filter(e -> !e.getValue().getType().isSuccess()) .map(Map.Entry::getKey) .collect(ImmutableSet.toImmutableSet()); if (missingKeys.isEmpty()) { return Futures.immediateFuture(mergedResults); } ListenableFuture<ImmutableMap<RuleKey, CacheResult>> more = nextCache.multiContainsAsync(missingKeys); return Futures.transform( more, results -> { mergedResults.putAll(results); return mergedResults; }, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor()); } return Futures.transform( cacheResultFuture, ImmutableMap::copyOf, MoreExecutors.directExecutor()); } @Override public ListenableFuture<CacheDeleteResult> deleteAsync(List<RuleKey> ruleKeys) { ArrayList<ListenableFuture<CacheDeleteResult>> futures = new ArrayList<>(); for (ArtifactCache artifactCache : writableArtifactCaches) { futures.add(artifactCache.deleteAsync(ruleKeys)); } return Futures.transform( Futures.allAsList(futures), deleteResults -> { Builder<String> cacheNames = ImmutableList.builder(); for (CacheDeleteResult deleteResult : deleteResults) { cacheNames.addAll(deleteResult.getCacheNames()); } return CacheDeleteResult.builder().setCacheNames(cacheNames.build()).build(); }, MoreExecutors.directExecutor()); } @Override public CacheReadMode getCacheReadMode() { return isStoreSupported ? CacheReadMode.READWRITE : CacheReadMode.READONLY; } @Override public void close() { Optional<RuntimeException> throwable = Optional.empty(); for (ArtifactCache artifactCache : artifactCaches) { try { artifactCache.close(); } catch (RuntimeException e) { throwable = Optional.of(e); } } if (throwable.isPresent()) { throw throwable.get(); } } @VisibleForTesting ImmutableList<ArtifactCache> getArtifactCaches() { return ImmutableList.copyOf(artifactCaches); } }
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.validation; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import static java.awt.RenderingHints.KEY_ANTIALIASING; import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON; /** * Simple graph view */ public class GraphView extends JPanel { private ArrayList<Main.Layout> mLayouts = new ArrayList<>(); private int selectionIndex = -1; private boolean mShowNumberOfWidgets; int margin = 50; float scaleX = 1; float scaleY = 1; int width = 1; int height = 1; private boolean mUseLog10 = false; public void setLayoutMeasures(ArrayList<Main.Layout> layouts) { this.mLayouts.clear(); this.mLayouts.addAll(layouts); repaint(); } public void setSelection(int n) { selectionIndex = n; repaint(); } public void setShowNumberOfWidgets(boolean value) { mShowNumberOfWidgets = value; repaint(); } public void useLog10(boolean selected) { mUseLog10 = selected; repaint(); } @Override public void paint(Graphics gc) { int w = getWidth(); int h = getHeight(); width = w - 2*margin; height = h - 2*margin; Graphics2D g = (Graphics2D) gc; g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g.setColor(new Color(255, 255, 255)); g.fillRect(0, 0, w, h); paintLayout(w, h, g, mLayouts); } private void paintLayout(int w, int h, Graphics2D g, ArrayList<Main.Layout> layouts) { if (layouts == null) { return; } int n = layouts.size(); if (n == 0) { return; } int textLegendX = 50; int textLegendY = h - 20; g.setColor(Color.BLUE); g.drawLine(textLegendX, textLegendY - 3, textLegendX + 30, textLegendY - 3); g.setColor(Color.BLACK); g.drawString("Baseline performances", textLegendX + 40, textLegendY); g.setColor(Color.RED); g.drawLine(textLegendX + 200, textLegendY - 3, textLegendX + 230, textLegendY - 3); g.setColor(Color.BLACK); g.drawString("Current performances", textLegendX + 240, textLegendY); long max = 0; long maxAxis2 = 0; for (int i = 0; i < layouts.size(); i++) { Main.Layout layout = layouts.get(i); max = Math.max(max, layout.m_m.duration); max = Math.max(max, layout.m_m.referenceDuration); maxAxis2 = Math.max(maxAxis2, layout.m_m.numWidgets); } int nLog = (int) Math.log10(max); int logRange = (int) Math.pow(10, nLog); int increment = nLog > 2 ? (int) (Math.pow(10, nLog) / 2f) : 10; while (logRange < max) { logRange += increment; } max = logRange; float intermediateStep = (max / 10.0f); float stepAxis = intermediateStep; g.drawString("ms", 20, 20); float barWidth = width / (float) (n -1); float scaleHeight = height / (float) max; if (mUseLog10) { scaleHeight = height / (float) Math.log10(max); } float axis2Height = max / (float) maxAxis2; scaleY = scaleHeight; scaleX = barWidth; // draw axis float axisLabels = 0; int lastStringY = 0; while (max > axisLabels) { String value = "" + ((int) (axisLabels / 1E3)) / 1000f; FontMetrics metrics = g.getFontMetrics(g.getFont()); int stringHeight = metrics.getHeight(); int stringWidth = metrics.stringWidth(value); if (fY(axisLabels) < lastStringY || lastStringY == 0) { g.setColor(Color.BLACK); g.drawString(value, margin - stringWidth - 5, fY(axisLabels)); lastStringY = fY(axisLabels) - stringHeight; } g.setColor(Color.LIGHT_GRAY); drawLine(g, 0, axisLabels, n, axisLabels); axisLabels += stepAxis; } // draw lines int prex = 0; int prey = 0; int preyOpt = 0; int preyRef = 0; float preAxis2Y = 0; float axis2Y = 0; for (int i = 0; i < layouts.size(); i++) { Main.Layout layout = layouts.get(i); int numWidgets = layout.m_m.numWidgets; int barHeight = (int) (layout.m_m.duration); int barHeightOptimized = (int) (layout.m_m.optimizedDuration); int yRef = (int) (layout.m_m.referenceDuration); axis2Y = (numWidgets * axis2Height); // just draw num widgets scaled up in Y if (i > 0) { if (selectionIndex == i) { g.setColor(Color.LIGHT_GRAY); fillRect(g, prex, 0, 1, (int) max); g.setColor(Color.GREEN); } else { g.setColor(Color.RED); } drawLine(g, prex, prey, i, barHeight); g.setColor(Color.GREEN); drawLine(g, prex, preyOpt, i, barHeightOptimized); if (selectionIndex == i) { g.setColor(Color.GREEN); } else { g.setColor(Color.BLUE); } drawLine(g, prex, preyRef, i, yRef); if (mShowNumberOfWidgets) { g.setColor(Color.lightGray); drawLine(g, prex, preAxis2Y, i, axis2Y); } } prex = i; prey = barHeight; preyOpt = barHeightOptimized; preyRef = yRef; preAxis2Y = axis2Y; } // draw frame g.setColor(Color.BLACK); drawRect(g,0, 0, n, (int) max); } private void fillRect(Graphics2D g, int x, int y, int w, int h) { int fH = 0; if (mUseLog10) { fH = (int) (scaleY * Math.log10(h)); } else { fH = (int) (scaleY * h); } g.fillRect(fX(x), fY(y) - fH, (int) (scaleX * w), fH); } private void drawRect(Graphics2D g, int x, int y, int w, int h) { int fH = 0; if (mUseLog10) { fH = (int) (scaleY * Math.log10(h)); } else { fH = (int) (scaleY * h); } g.drawRect(fX(x), fY(y) - fH, (int) (scaleX * w), fH); } private void drawLine(Graphics2D g, int x1, float y1, int x2, float y2) { g.drawLine(fX(x1), fY(y1), fX(x2), fY(y2)); } private int fH(float h) { return (int) (- scaleY * h) * height; } private int fX(float x) { return (int) (margin + (scaleX * x)); } private int fY(float y) { if (mUseLog10) { if (y == 0) { return (int) (height + margin); } return (int) (height + margin - scaleY * Math.log10(y)); } else { return (int) (height + margin - scaleY * y); } } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actionMacro; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.ide.IdeEventQueue; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.playback.PlaybackContext; import com.intellij.openapi.ui.playback.PlaybackRunner; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupAdapter; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.LightweightWindowEvent; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.CustomStatusBarWidget; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.AnimatedIcon.Recording; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.util.Consumer; import com.intellij.util.messages.MessageBus; import com.intellij.util.ui.AnimatedIcon; import com.intellij.util.ui.BaseButtonBehavior; import com.intellij.util.ui.PositionTracker; import com.intellij.util.ui.UIUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; @State(name = "ActionMacroManager", storages = @Storage("macros.xml")) public class ActionMacroManager implements PersistentStateComponent<Element>, Disposable { private static final Logger LOG = Logger.getInstance(ActionMacroManager.class); private static final String TYPING_SAMPLE = "WWWWWWWWWWWWWWWWWWWW"; private static final String RECORDED = "Recorded: "; private boolean myIsRecording; private final ActionManagerEx myActionManager; private ActionMacro myLastMacro; private ActionMacro myRecordingMacro; private ArrayList<ActionMacro> myMacros = new ArrayList<>(); private String myLastMacroName = null; private boolean myIsPlaying = false; @NonNls private static final String ELEMENT_MACRO = "macro"; private final IdeEventQueue.EventDispatcher myKeyProcessor; private final Set<InputEvent> myLastActionInputEvent = new HashSet<>(); private ActionMacroManager.Widget myWidget; private String myLastTyping = ""; public ActionMacroManager(ActionManagerEx actionManager, @NotNull MessageBus messageBus) { myActionManager = actionManager; messageBus.connect(this).subscribe(AnActionListener.TOPIC, new AnActionListener() { @Override public void beforeActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, final AnActionEvent event) { String id = actionManager.getId(action); if (id == null) return; //noinspection HardCodedStringLiteral if ("StartStopMacroRecording".equals(id)) { myLastActionInputEvent.add(event.getInputEvent()); } else if (myIsRecording) { myRecordingMacro.appendAction(id); String shortcut = null; if (event.getInputEvent() instanceof KeyEvent) { shortcut = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStrokeForEvent((KeyEvent)event.getInputEvent())); } notifyUser(id + (shortcut != null ? " (" + shortcut + ")" : ""), false); myLastActionInputEvent.add(event.getInputEvent()); } } }); myKeyProcessor = new MyKeyPostpocessor(); IdeEventQueue.getInstance().addPostprocessor(myKeyProcessor, null); } @Override public void loadState(@NotNull Element state) { myMacros = new ArrayList<>(); for (Element macroElement : state.getChildren(ELEMENT_MACRO)) { ActionMacro macro = new ActionMacro(); macro.readExternal(macroElement); myMacros.add(macro); } registerActions(); } @Nullable @Override public Element getState() { Element element = new Element("state"); for (ActionMacro macro : myMacros) { Element macroElement = new Element(ELEMENT_MACRO); macro.writeExternal(macroElement); element.addContent(macroElement); } return element; } public static ActionMacroManager getInstance() { return ApplicationManager.getApplication().getComponent(ActionMacroManager.class); } public void startRecording(String macroName) { LOG.assertTrue(!myIsRecording); myIsRecording = true; myRecordingMacro = new ActionMacro(macroName); final StatusBar statusBar = WindowManager.getInstance().getIdeFrame(null).getStatusBar(); myWidget = new Widget(statusBar); statusBar.addWidget(myWidget); } private class Widget implements CustomStatusBarWidget, Consumer<MouseEvent> { private final AnimatedIcon myIcon = new AnimatedIcon("Macro recording", Recording.ICONS.toArray(new Icon[0]), AllIcons.Ide.Macro.Recording_1, Recording.DELAY * Recording.ICONS.size()); private final StatusBar myStatusBar; private final WidgetPresentation myPresentation; private final JPanel myBalloonComponent; private Balloon myBalloon; private final JLabel myText; private Widget(StatusBar statusBar) { myStatusBar = statusBar; myPresentation = new WidgetPresentation() { @Override public String getTooltipText() { return "Macro is being recorded now"; } @Override public Consumer<MouseEvent> getClickConsumer() { return Widget.this; } }; new BaseButtonBehavior(myIcon) { @Override protected void execute(MouseEvent e) { showBalloon(); } }; myBalloonComponent = new NonOpaquePanel(new BorderLayout()); final AnAction stopAction = ActionManager.getInstance().getAction("StartStopMacroRecording"); final DefaultActionGroup group = new DefaultActionGroup(); group.add(stopAction); final ActionToolbar tb = ActionManager.getInstance().createActionToolbar(ActionPlaces.STATUS_BAR_PLACE, group, true); tb.setMiniMode(true); final NonOpaquePanel top = new NonOpaquePanel(new BorderLayout()); top.add(tb.getComponent(), BorderLayout.WEST); myText = new JLabel(RECORDED + "..." + TYPING_SAMPLE, SwingConstants.LEFT); final Dimension preferredSize = myText.getPreferredSize(); myText.setPreferredSize(preferredSize); myText.setText("Macro recording started..."); myLastTyping = ""; top.add(myText, BorderLayout.CENTER); myBalloonComponent.add(top, BorderLayout.CENTER); } private void showBalloon() { if (myBalloon != null) { Disposer.dispose(myBalloon); return; } myBalloon = JBPopupFactory.getInstance().createBalloonBuilder(myBalloonComponent) .setAnimationCycle(200) .setCloseButtonEnabled(true) .setHideOnAction(false) .setHideOnClickOutside(false) .setHideOnFrameResize(false) .setHideOnKeyOutside(false) .setSmallVariant(true) .setShadow(true) .createBalloon(); Disposer.register(myBalloon, new Disposable() { @Override public void dispose() { myBalloon = null; } }); myBalloon.addListener(new JBPopupAdapter() { @Override public void onClosed(@NotNull LightweightWindowEvent event) { if (myBalloon != null) { Disposer.dispose(myBalloon); } } }); myBalloon.show(new PositionTracker<Balloon>(myIcon) { @Override public RelativePoint recalculateLocation(Balloon object) { return new RelativePoint(myIcon, new Point(myIcon.getSize().width / 2, 4)); } }, Balloon.Position.above); } @Override public JComponent getComponent() { return myIcon; } @NotNull @Override public String ID() { return "MacroRecording"; } @Override public void consume(MouseEvent mouseEvent) { } @Override public WidgetPresentation getPresentation(@NotNull PlatformType type) { return myPresentation; } @Override public void install(@NotNull StatusBar statusBar) { showBalloon(); } @Override public void dispose() { Disposer.dispose(myIcon); if (myBalloon != null) { Disposer.dispose(myBalloon); } } public void delete() { if (myBalloon != null) { Disposer.dispose(myBalloon); } myStatusBar.removeWidget(ID()); } public void notifyUser(String text) { myText.setText(text); myText.revalidate(); myText.repaint(); } } public void stopRecording(@Nullable Project project) { LOG.assertTrue(myIsRecording); if (myWidget != null) { myWidget.delete(); myWidget = null; } myIsRecording = false; myLastActionInputEvent.clear(); String macroName; do { macroName = Messages.showInputDialog(project, IdeBundle.message("prompt.enter.macro.name"), IdeBundle.message("title.enter.macro.name"), Messages.getQuestionIcon()); if (macroName == null) { myRecordingMacro = null; return; } if (macroName.isEmpty()) macroName = null; } while (macroName != null && !checkCanCreateMacro(macroName)); myLastMacro = myRecordingMacro; addRecordedMacroWithName(macroName); registerActions(); } private void addRecordedMacroWithName(@Nullable String macroName) { if (macroName != null) { myRecordingMacro.setName(macroName); myMacros.add(myRecordingMacro); myRecordingMacro = null; } else { for (int i = 0; i < myMacros.size(); i++) { ActionMacro macro = myMacros.get(i); if (IdeBundle.message("macro.noname").equals(macro.getName())) { myMacros.set(i, myRecordingMacro); myRecordingMacro = null; break; } } if (myRecordingMacro != null) { myMacros.add(myRecordingMacro); myRecordingMacro = null; } } } public void playbackLastMacro() { if (myLastMacro != null) { playbackMacro(myLastMacro); } } private void playbackMacro(ActionMacro macro) { final IdeFrame frame = WindowManager.getInstance().getIdeFrame(null); assert frame != null; StringBuffer script = new StringBuffer(); ActionMacro.ActionDescriptor[] actions = macro.getActions(); for (ActionMacro.ActionDescriptor each : actions) { each.generateTo(script); } final PlaybackRunner runner = new PlaybackRunner(script.toString(), new PlaybackRunner.StatusCallback.Edt() { @Override public void messageEdt(PlaybackContext context, String text, Type type) { if (type == Type.message || type == Type.error) { StatusBar statusBar = frame.getStatusBar(); if (statusBar != null) { if (context != null) { text = "Line " + context.getCurrentLine() + ": " + text; } statusBar.setInfo(text); } } } }, Registry.is("actionSystem.playback.useDirectActionCall"), true, Registry.is("actionSystem.playback.useTypingTargets")); myIsPlaying = true; runner.run() .doWhenDone(() -> { StatusBar statusBar = frame.getStatusBar(); statusBar.setInfo("Script execution finished"); }) .doWhenProcessed(() -> myIsPlaying = false); } public boolean isRecording() { return myIsRecording; } @Override public void dispose() { IdeEventQueue.getInstance().removePostprocessor(myKeyProcessor); } public ActionMacro[] getAllMacros() { return myMacros.toArray(new ActionMacro[0]); } public void removeAllMacros() { if (myLastMacro != null) { myLastMacroName = myLastMacro.getName(); myLastMacro = null; } myMacros = new ArrayList<>(); } public void addMacro(ActionMacro macro) { myMacros.add(macro); if (myLastMacroName != null && myLastMacroName.equals(macro.getName())) { myLastMacro = macro; myLastMacroName = null; } } public void playMacro(ActionMacro macro) { playbackMacro(macro); myLastMacro = macro; } public boolean hasRecentMacro() { return myLastMacro != null; } public void registerActions() { unregisterActions(); HashSet<String> registeredIds = new HashSet<>(); // to prevent exception if 2 or more targets have the same name ActionMacro[] macros = getAllMacros(); for (final ActionMacro macro : macros) { String actionId = macro.getActionId(); if (!registeredIds.contains(actionId)) { registeredIds.add(actionId); myActionManager.registerAction(actionId, new InvokeMacroAction(macro)); } } } public void unregisterActions() { // unregister Tool actions String[] oldIds = myActionManager.getActionIds(ActionMacro.MACRO_ACTION_PREFIX); for (final String oldId : oldIds) { myActionManager.unregisterAction(oldId); } } public boolean checkCanCreateMacro(String name) { final ActionManagerEx actionManager = (ActionManagerEx)ActionManager.getInstance(); final String actionId = ActionMacro.MACRO_ACTION_PREFIX + name; if (actionManager.getAction(actionId) != null) { if (Messages.showYesNoDialog(IdeBundle.message("message.macro.exists", name), IdeBundle.message("title.macro.name.already.used"), Messages.getWarningIcon()) != Messages.YES) { return false; } actionManager.unregisterAction(actionId); removeMacro(name); } return true; } private void removeMacro(String name) { for (int i = 0; i < myMacros.size(); i++) { ActionMacro macro = myMacros.get(i); if (name.equals(macro.getName())) { myMacros.remove(i); break; } } } public boolean isPlaying() { return myIsPlaying; } private static class InvokeMacroAction extends AnAction { private final ActionMacro myMacro; InvokeMacroAction(ActionMacro macro) { myMacro = macro; getTemplatePresentation().setText(macro.getName(), false); } @Override public void actionPerformed(@NotNull AnActionEvent e) { IdeEventQueue.getInstance().doWhenReady(() -> getInstance().playMacro(myMacro)); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); e.getPresentation().setEnabled(!getInstance().isPlaying()); } } private class MyKeyPostpocessor implements IdeEventQueue.EventDispatcher { @Override public boolean dispatch(@NotNull AWTEvent e) { if (isRecording() && e instanceof KeyEvent) { postProcessKeyEvent((KeyEvent)e); } return false; } public void postProcessKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) return; if (myLastActionInputEvent.contains(e)) { myLastActionInputEvent.remove(e); return; } final boolean modifierKeyIsPressed = e.getKeyCode() == KeyEvent.VK_CONTROL || e.getKeyCode() == KeyEvent.VK_ALT || e.getKeyCode() == KeyEvent.VK_META || e.getKeyCode() == KeyEvent.VK_SHIFT; if (modifierKeyIsPressed) return; final boolean ready = IdeEventQueue.getInstance().getKeyEventDispatcher().isReady(); final boolean isChar = e.getKeyChar() != KeyEvent.CHAR_UNDEFINED && UIUtil.isReallyTypedEvent(e); final boolean hasActionModifiers = e.isAltDown() | e.isControlDown() | e.isMetaDown(); final boolean plainType = isChar && !hasActionModifiers; final boolean isEnter = e.getKeyCode() == KeyEvent.VK_ENTER; if (plainType && ready && !isEnter) { myRecordingMacro.appendKeytyped(e.getKeyChar(), e.getKeyCode(), e.getModifiers()); notifyUser(Character.valueOf(e.getKeyChar()).toString(), true); } else if ((!plainType && ready) || isEnter) { final String stroke = KeyStroke.getKeyStrokeForEvent(e).toString(); final int pressed = stroke.indexOf("pressed"); String key = stroke.substring(pressed + "pressed".length()); String modifiers = stroke.substring(0, pressed); String shortcut = (modifiers.replaceAll("ctrl", "control").trim() + " " + key.trim()).trim(); myRecordingMacro.appendShortcut(shortcut); notifyUser(KeymapUtil.getKeystrokeText(KeyStroke.getKeyStrokeForEvent(e)), false); } } } private void notifyUser(String text, boolean typing) { String actualText = text; if (typing) { int maxLength = TYPING_SAMPLE.length(); myLastTyping += text; if (myLastTyping.length() > maxLength) { myLastTyping = "..." + myLastTyping.substring(myLastTyping.length() - maxLength); } actualText = myLastTyping; } else { myLastTyping = ""; } if (myWidget != null) { myWidget.notifyUser(RECORDED + actualText); } } }
/* * Copyright 2012-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.android; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.FakeBuildRuleParamsBuilder; import com.facebook.buck.rules.FakeOnDiskBuildInfo; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.rules.PathSourcePath; import com.facebook.buck.rules.RuleKey; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.TargetNode; import com.facebook.buck.rules.keys.DefaultRuleKeyFactory; import com.facebook.buck.rules.keys.InputBasedRuleKeyFactory; import com.facebook.buck.testutil.FakeFileHashCache; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.testutil.TargetGraphFactory; import com.facebook.buck.util.cache.DefaultFileHashCache; import com.facebook.buck.util.cache.FileHashCache; import com.facebook.buck.util.cache.StackedFileHashCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import org.hamcrest.Matchers; import org.junit.Test; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Function; public class AndroidResourceTest { @Test public void testRuleKeyForDifferentInputFilenames() throws Exception { BuildTarget buildTarget = BuildTargetFactory.newInstance("//java/src/com/facebook/base:res"); Function<Path, BuildRuleResolver> createResourceRule = (Path resourcePath) -> { FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem(); projectFilesystem.createNewFile(resourcePath); projectFilesystem.createNewFile( Paths.get("java/src/com/facebook/base/assets/drawable/B.xml")); TargetNode<?, ?> resourceNode = AndroidResourceBuilder .createBuilder(buildTarget, projectFilesystem) .setRes(new FakeSourcePath(projectFilesystem, "java/src/com/facebook/base/res")) .setRDotJavaPackage("com.facebook") .setAssets(new FakeSourcePath(projectFilesystem, "java/src/com/facebook/base/assets")) .setManifest( new PathSourcePath( projectFilesystem, Paths.get("java/src/com/facebook/base/AndroidManifest.xml"))) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(resourceNode); return new BuildRuleResolver(targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); }; FakeFileHashCache hashCache = FakeFileHashCache.createFromStrings( ImmutableMap.of( "java/src/com/facebook/base/AndroidManifest.xml", "bbbbbbbbbb", "java/src/com/facebook/base/assets/drawable/B.xml", "aaaaaaaaaaaa", "java/src/com/facebook/base/res/drawable/A.xml", "dddddddddd", "java/src/com/facebook/base/res/drawable/C.xml", "eeeeeeeeee")); BuildRuleResolver resolver1 = createResourceRule.apply( Paths.get("java/src/com/facebook/base/res/drawable/A.xml")); BuildRuleResolver resolver2 = createResourceRule.apply( Paths.get("java/src/com/facebook/base/res/drawable/C.xml")); BuildRule androidResource1 = resolver1.requireRule(buildTarget); SourcePathRuleFinder ruleFinder1 = new SourcePathRuleFinder(resolver1); SourcePathResolver pathResolver1 = new SourcePathResolver(ruleFinder1); BuildRule androidResource2 = resolver2.requireRule(buildTarget); SourcePathRuleFinder ruleFinder2 = new SourcePathRuleFinder(resolver2); SourcePathResolver pathResolver2 = new SourcePathResolver(ruleFinder2); RuleKey ruleKey1 = new DefaultRuleKeyFactory(0, hashCache, pathResolver1, ruleFinder1) .build(androidResource1); RuleKey ruleKey2 = new DefaultRuleKeyFactory(0, hashCache, pathResolver2, ruleFinder2) .build(androidResource2); assertNotEquals( "The two android_resource rules should have different rule keys.", ruleKey1, ruleKey2); } @Test public void testGetRDotJavaPackageWhenPackageIsSpecified() throws IOException { ProjectFilesystem projectFilesystem = FakeProjectFilesystem.createRealTempFilesystem(); BuildTarget buildTarget = BuildTargetFactory.newInstance( projectFilesystem.getRootPath(), "//java/src/com/facebook/base:res"); BuildRuleParams params = new FakeBuildRuleParamsBuilder(buildTarget) .setProjectFilesystem(projectFilesystem) .build(); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder( new BuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ); SourcePathResolver resolver = new SourcePathResolver(ruleFinder); AndroidResource androidResource = new AndroidResource( params, ruleFinder, /* deps */ ImmutableSortedSet.of(), new FakeSourcePath("foo/res"), ImmutableSortedMap.of( Paths.get("values/strings.xml"), new FakeSourcePath("foo/res/values/strings.xml")), /* rDotJavaPackage */ "com.example.android", /* assets */ null, /* assetsSrcs */ ImmutableSortedMap.of(), /* manifestFile */ null, /* hasWhitelistedStrings */ false); projectFilesystem.writeContentsToPath( "com.example.android\n", resolver.getRelativePath(androidResource.getPathToRDotJavaPackageFile())); FakeOnDiskBuildInfo onDiskBuildInfo = new FakeOnDiskBuildInfo(); androidResource.initializeFromDisk(onDiskBuildInfo); assertEquals("com.example.android", androidResource.getRDotJavaPackage()); } @Test public void testGetRDotJavaPackageWhenPackageIsNotSpecified() throws IOException { ProjectFilesystem projectFilesystem = FakeProjectFilesystem.createRealTempFilesystem(); BuildTarget buildTarget = BuildTargetFactory.newInstance( projectFilesystem.getRootPath(), "//java/src/com/facebook/base:res"); BuildRuleParams params = new FakeBuildRuleParamsBuilder(buildTarget) .setProjectFilesystem(projectFilesystem) .build(); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder( new BuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ); SourcePathResolver resolver = new SourcePathResolver(ruleFinder); AndroidResource androidResource = new AndroidResource( params, ruleFinder, /* deps */ ImmutableSortedSet.of(), new FakeSourcePath("foo/res"), ImmutableSortedMap.of( Paths.get("values/strings.xml"), new FakeSourcePath("foo/res/values/strings.xml")), /* rDotJavaPackage */ null, /* assets */ null, /* assetsSrcs */ ImmutableSortedMap.of(), /* manifestFile */ new PathSourcePath( projectFilesystem, Paths.get("foo/AndroidManifest.xml")), /* hasWhitelistedStrings */ false); projectFilesystem.writeContentsToPath( "com.ex.pkg\n", resolver.getRelativePath(androidResource.getPathToRDotJavaPackageFile())); FakeOnDiskBuildInfo onDiskBuildInfo = new FakeOnDiskBuildInfo(); androidResource.initializeFromDisk(onDiskBuildInfo); assertEquals("com.ex.pkg", androidResource.getRDotJavaPackage()); } @Test public void testInputRuleKeyChangesIfDependencySymbolsChanges() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); TargetNode<?, ?> depNode = AndroidResourceBuilder .createBuilder(BuildTargetFactory.newInstance("//:dep"), filesystem) .setManifest(new FakeSourcePath("manifest")) .setRes(Paths.get("res")) .build(); TargetNode<?, ?> resourceNode = AndroidResourceBuilder .createBuilder(BuildTargetFactory.newInstance("//:rule"), filesystem) .setDeps(ImmutableSortedSet.of(depNode.getBuildTarget())) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(depNode, resourceNode); BuildRuleResolver resolver = new BuildRuleResolver(targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); AndroidResource dep = (AndroidResource) resolver.requireRule(depNode.getBuildTarget()); AndroidResource resource = (AndroidResource) resolver.requireRule(resourceNode.getBuildTarget()); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder); FileHashCache fileHashCache = new StackedFileHashCache( ImmutableList.of(DefaultFileHashCache.createDefaultFileHashCache(filesystem))); filesystem.writeContentsToPath( "something", pathResolver.getRelativePath(dep.getPathToTextSymbolsFile())); RuleKey original = new InputBasedRuleKeyFactory( 0, fileHashCache, pathResolver, ruleFinder) .build(resource); fileHashCache.invalidateAll(); filesystem.writeContentsToPath( "something else", pathResolver.getRelativePath(dep.getPathToTextSymbolsFile())); RuleKey changed = new InputBasedRuleKeyFactory( 0, fileHashCache, pathResolver, ruleFinder) .build(resource); assertThat(original, Matchers.not(Matchers.equalTo(changed))); } }
package org.apache.lucene.index; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.AttributeSource; import org.apache.lucene.util.Bits; /** * Abstract class for enumerating a subset of all terms. * * <p>Term enumerations are always ordered by * {@link BytesRef#compareTo}. Each term in the enumeration is * greater than all that precede it.</p> * <p><em>Please note:</em> Consumers of this enum cannot * call {@code seek()}, it is forward only; it throws * {@link UnsupportedOperationException} when a seeking method * is called. */ public abstract class FilteredTermsEnum extends TermsEnum { private BytesRef initialSeekTerm; private boolean doSeek; /** Which term the enum is currently positioned to. */ protected BytesRef actualTerm; /** The delegate {@link TermsEnum}. */ protected final TermsEnum tenum; /** Return value, if term should be accepted or the iteration should * {@code END}. The {@code *_SEEK} values denote, that after handling the current term * the enum should call {@link #nextSeekTerm} and step forward. * @see #accept(BytesRef) */ protected static enum AcceptStatus { /** Accept the term and position the enum at the next term. */ YES, /** Accept the term and advance ({@link FilteredTermsEnum#nextSeekTerm(BytesRef)}) * to the next term. */ YES_AND_SEEK, /** Reject the term and position the enum at the next term. */ NO, /** Reject the term and advance ({@link FilteredTermsEnum#nextSeekTerm(BytesRef)}) * to the next term. */ NO_AND_SEEK, /** Reject the term and stop enumerating. */ END }; /** Return if term is accepted, not accepted or the iteration should ended * (and possibly seek). */ protected abstract AcceptStatus accept(BytesRef term) throws IOException; /** * Creates a filtered {@link TermsEnum} on a terms enum. * @param tenum the terms enumeration to filter. */ public FilteredTermsEnum(final TermsEnum tenum) { this(tenum, true); } /** * Creates a filtered {@link TermsEnum} on a terms enum. * @param tenum the terms enumeration to filter. */ public FilteredTermsEnum(final TermsEnum tenum, final boolean startWithSeek) { assert tenum != null; this.tenum = tenum; doSeek = startWithSeek; } /** * Use this method to set the initial {@link BytesRef} * to seek before iterating. This is a convenience method for * subclasses that do not override {@link #nextSeekTerm}. * If the initial seek term is {@code null} (default), * the enum is empty. * <P>You can only use this method, if you keep the default * implementation of {@link #nextSeekTerm}. */ protected final void setInitialSeekTerm(BytesRef term) { this.initialSeekTerm = term; } /** On the first call to {@link #next} or if {@link #accept} returns * {@link AcceptStatus#YES_AND_SEEK} or {@link AcceptStatus#NO_AND_SEEK}, * this method will be called to eventually seek the underlying TermsEnum * to a new position. * On the first call, {@code currentTerm} will be {@code null}, later * calls will provide the term the underlying enum is positioned at. * This method returns per default only one time the initial seek term * and then {@code null}, so no repositioning is ever done. * <p>Override this method, if you want a more sophisticated TermsEnum, * that repositions the iterator during enumeration. * If this method always returns {@code null} the enum is empty. * <p><em>Please note:</em> This method should always provide a greater term * than the last enumerated term, else the behaviour of this enum * violates the contract for TermsEnums. */ protected BytesRef nextSeekTerm(final BytesRef currentTerm) throws IOException { final BytesRef t = initialSeekTerm; initialSeekTerm = null; return t; } /** * Returns the related attributes, the returned {@link AttributeSource} * is shared with the delegate {@code TermsEnum}. */ @Override public AttributeSource attributes() { return tenum.attributes(); } @Override public BytesRef term() throws IOException { return tenum.term(); } @Override public int docFreq() throws IOException { return tenum.docFreq(); } @Override public long totalTermFreq() throws IOException { return tenum.totalTermFreq(); } /** This enum does not support seeking! * @throws UnsupportedOperationException In general, subclasses do not * support seeking. */ @Override public boolean seekExact(BytesRef term) throws IOException { throw new UnsupportedOperationException(getClass().getName()+" does not support seeking"); } /** This enum does not support seeking! * @throws UnsupportedOperationException In general, subclasses do not * support seeking. */ @Override public SeekStatus seekCeil(BytesRef term) throws IOException { throw new UnsupportedOperationException(getClass().getName()+" does not support seeking"); } /** This enum does not support seeking! * @throws UnsupportedOperationException In general, subclasses do not * support seeking. */ @Override public void seekExact(long ord) throws IOException { throw new UnsupportedOperationException(getClass().getName()+" does not support seeking"); } @Override public long ord() throws IOException { return tenum.ord(); } @Override public PostingsEnum postings(Bits bits, PostingsEnum reuse, int flags) throws IOException { return tenum.postings(bits, reuse, flags); } /** This enum does not support seeking! * @throws UnsupportedOperationException In general, subclasses do not * support seeking. */ @Override public void seekExact(BytesRef term, TermState state) throws IOException { throw new UnsupportedOperationException(getClass().getName()+" does not support seeking"); } /** * Returns the filtered enums term state */ @Override public TermState termState() throws IOException { assert tenum != null; return tenum.termState(); } @SuppressWarnings("fallthrough") @Override public BytesRef next() throws IOException { //System.out.println("FTE.next doSeek=" + doSeek); //new Throwable().printStackTrace(System.out); for (;;) { // Seek or forward the iterator if (doSeek) { doSeek = false; final BytesRef t = nextSeekTerm(actualTerm); //System.out.println(" seek to t=" + (t == null ? "null" : t.utf8ToString()) + " tenum=" + tenum); // Make sure we always seek forward: assert actualTerm == null || t == null || t.compareTo(actualTerm) > 0: "curTerm=" + actualTerm + " seekTerm=" + t; if (t == null || tenum.seekCeil(t) == SeekStatus.END) { // no more terms to seek to or enum exhausted //System.out.println(" return null"); return null; } actualTerm = tenum.term(); //System.out.println(" got term=" + actualTerm.utf8ToString()); } else { actualTerm = tenum.next(); if (actualTerm == null) { // enum exhausted return null; } } // check if term is accepted switch (accept(actualTerm)) { case YES_AND_SEEK: doSeek = true; // term accepted, but we need to seek so fall-through case YES: // term accepted return actualTerm; case NO_AND_SEEK: // invalid term, seek next time doSeek = true; break; case END: // we are supposed to end the enum return null; // NO: we just fall through and iterate again } } } }
package com.gzmelife.app.views; import android.content.Context; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.widget.ScrollerCompat; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.animation.Interpolator; import android.widget.AbsListView; import android.widget.FrameLayout; public class SwipeMenuLayout extends FrameLayout { private static final int CONTENT_VIEW_ID = 1; private static final int MENU_VIEW_ID = 2; private static final int STATE_CLOSE = 0; private static final int STATE_OPEN = 1; private View mContentView; private SwipeMenuView mMenuView; private int mDownX; private int state = STATE_CLOSE; private GestureDetectorCompat mGestureDetector; private OnGestureListener mGestureListener; private boolean isFling; private int MIN_FLING = dp2px(15); private int MAX_VELOCITYX = -dp2px(500); private ScrollerCompat mOpenScroller; private ScrollerCompat mCloseScroller; private int mBaseX; private int position; private Interpolator mCloseInterpolator; private Interpolator mOpenInterpolator; public SwipeMenuLayout(View contentView, SwipeMenuView menuView) { this(contentView, menuView, null, null); } public SwipeMenuLayout(View contentView, SwipeMenuView menuView, Interpolator closeInterpolator, Interpolator openInterpolator) { super(contentView.getContext()); mCloseInterpolator = closeInterpolator; mOpenInterpolator = openInterpolator; mContentView = contentView; mMenuView = menuView; mMenuView.setLayout(this); init(); } private SwipeMenuLayout(Context context, AttributeSet attrs) { super(context, attrs); } private SwipeMenuLayout(Context context) { super(context); } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; mMenuView.setPosition(position); } private void init() { setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { isFling = false; return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO if ((e1.getX() - e2.getX()) > MIN_FLING && velocityX < MAX_VELOCITYX) { isFling = true; } // Log.i("byz", MAX_VELOCITYX + ", velocityX = " + velocityX); return super.onFling(e1, e2, velocityX, velocityY); } }; mGestureDetector = new GestureDetectorCompat(getContext(), mGestureListener); if (mCloseInterpolator != null) { mCloseScroller = ScrollerCompat.create(getContext(), mCloseInterpolator); } else { mCloseScroller = ScrollerCompat.create(getContext()); } if (mOpenInterpolator != null) { mOpenScroller = ScrollerCompat.create(getContext(), mOpenInterpolator); } else { mOpenScroller = ScrollerCompat.create(getContext()); } LayoutParams contentParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mContentView.setLayoutParams(contentParams); if (mContentView.getId() < 1) { mContentView.setId(CONTENT_VIEW_ID); } mMenuView.setId(MENU_VIEW_ID); mMenuView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); addView(mContentView); addView(mMenuView); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } public boolean onSwipe(MotionEvent event) { mGestureDetector.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mDownX = (int) event.getX(); isFling = false; break; case MotionEvent.ACTION_MOVE: // Log.i("byz", "downX = " + mDownX + ", moveX = " + event.getX()); int dis = (int) (mDownX - event.getX()); if (state == STATE_OPEN) { dis += mMenuView.getWidth(); } swipe(dis); break; case MotionEvent.ACTION_UP: if (isFling || (mDownX - event.getX()) > (mMenuView.getWidth() / 2)) { // open smoothOpenMenu(); } else { // close smoothCloseMenu(); return false; } break; } return true; } public boolean isOpen() { return state == STATE_OPEN; } public boolean isActive() { if (mContentView != null) { return mContentView.getLeft() != 0; } return false; } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } private void swipe(int dis) { if (dis > mMenuView.getWidth()) { dis = mMenuView.getWidth(); } if (dis < 0) { dis = 0; } mContentView.layout(-dis, mContentView.getTop(), mContentView.getWidth() - dis, getMeasuredHeight()); mMenuView.layout(mContentView.getWidth() - dis, mMenuView.getTop(), mContentView.getWidth() + mMenuView.getWidth() - dis, mMenuView.getBottom()); } @Override public void computeScroll() { if (state == STATE_OPEN) { if (mOpenScroller.computeScrollOffset()) { swipe(mOpenScroller.getCurrX()); postInvalidate(); } } else { if (mCloseScroller.computeScrollOffset()) { swipe(mBaseX - mCloseScroller.getCurrX()); postInvalidate(); } } } public void smoothCloseMenu() { state = STATE_CLOSE; mBaseX = -mContentView.getLeft(); mCloseScroller.startScroll(0, 0, mBaseX, 0, 350); postInvalidate(); } public void smoothOpenMenu() { state = STATE_OPEN; mOpenScroller.startScroll(-mContentView.getLeft(), 0, mMenuView.getWidth(), 0, 350); postInvalidate(); } public void closeMenu() { if (mCloseScroller.computeScrollOffset()) { mCloseScroller.abortAnimation(); } if (state == STATE_OPEN) { state = STATE_CLOSE; swipe(0); } } public void openMenu() { if (state == STATE_CLOSE) { state = STATE_OPEN; swipe(mMenuView.getWidth()); } } public View getContentView() { return mContentView; } public SwipeMenuView getMenuView() { return mMenuView; } private int dp2px(int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources() .getDisplayMetrics()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mMenuView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mContentView.layout(0, 0, getMeasuredWidth(), mContentView.getMeasuredHeight()); mMenuView.layout(getMeasuredWidth(), 0, getMeasuredWidth() + mMenuView.getMeasuredWidth(), mContentView.getMeasuredHeight()); } public void setMenuHeight(int measuredHeight) { Log.i("byz", "pos = " + position + ", height = " + measuredHeight); LayoutParams params = (LayoutParams) mMenuView.getLayoutParams(); if (params.height != measuredHeight) { params.height = measuredHeight; mMenuView.setLayoutParams(mMenuView.getLayoutParams()); } } }
package org.dynmap.fabric_1_16_4; import net.minecraft.util.math.BlockPos; import net.minecraft.util.registry.RegistryKey; import net.minecraft.world.Heightmap; import net.minecraft.world.LightType; import net.minecraft.world.World; import net.minecraft.world.border.WorldBorder; import org.dynmap.DynmapChunk; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWorld; import org.dynmap.utils.MapChunkCache; import org.dynmap.utils.Polygon; import java.util.List; public class FabricWorld extends DynmapWorld { // TODO: Store this relative to World saves for integrated server public static final String SAVED_WORLDS_FILE = "fabricworlds.yml"; private final DynmapPlugin plugin; private World world; private final boolean skylight; private final boolean isnether; private final boolean istheend; private final String env; private DynmapLocation spawnloc = new DynmapLocation(); private static int maxWorldHeight = 256; // Maximum allows world height public static int getMaxWorldHeight() { return maxWorldHeight; } public static void setMaxWorldHeight(int h) { maxWorldHeight = h; } public static String getWorldName(DynmapPlugin plugin, World w) { RegistryKey<World> rk = w.getRegistryKey(); if (rk == World.OVERWORLD) { // Overworld? return w.getServer().getSaveProperties().getLevelName(); } else if (rk == World.END) { return "DIM1"; } else if (rk == World.NETHER) { return "DIM-1"; } else { return rk.getValue().getNamespace() + "_" + rk.getValue().getPath(); } } public FabricWorld(DynmapPlugin plugin, World w) { this(plugin, getWorldName(plugin, w), w.getHeight(), w.getSeaLevel(), w.getRegistryKey() == World.NETHER, w.getRegistryKey() == World.END, w.getRegistryKey().getValue().getPath()); setWorldLoaded(w); } public FabricWorld(DynmapPlugin plugin, String name, int height, int sealevel, boolean nether, boolean the_end, String deftitle) { super(name, (height > maxWorldHeight) ? maxWorldHeight : height, sealevel); this.plugin = plugin; world = null; setTitle(deftitle); isnether = nether; istheend = the_end; skylight = !(isnether || istheend); if (isnether) { env = "nether"; } else if (istheend) { env = "the_end"; } else { env = "normal"; } } /* Test if world is nether */ @Override public boolean isNether() { return isnether; } public boolean isTheEnd() { return istheend; } /* Get world spawn location */ @Override public DynmapLocation getSpawnLocation() { if (world != null) { spawnloc.x = world.getLevelProperties().getSpawnX(); spawnloc.y = world.getLevelProperties().getSpawnY(); spawnloc.z = world.getLevelProperties().getSpawnZ(); spawnloc.world = this.getName(); } return spawnloc; } /* Get world time */ @Override public long getTime() { if (world != null) return world.getTimeOfDay(); else return -1; } /* World is storming */ @Override public boolean hasStorm() { if (world != null) return world.isRaining(); else return false; } /* World is thundering */ @Override public boolean isThundering() { if (world != null) return world.isThundering(); else return false; } /* World is loaded */ @Override public boolean isLoaded() { return (world != null); } /* Set world to unloaded */ @Override public void setWorldUnloaded() { getSpawnLocation(); world = null; } /* Set world to loaded */ public void setWorldLoaded(World w) { world = w; this.sealevel = w.getSeaLevel(); // Read actual current sealevel from world // Update lighting table for (int i = 0; i < 16; i++) { this.setBrightnessTableEntry(i, w.getDimension().method_28516(i)); } } /* Get light level of block */ @Override public int getLightLevel(int x, int y, int z) { if (world != null) return world.getLightLevel(new BlockPos(x, y, z)); else return -1; } /* Get highest Y coord of given location */ @Override public int getHighestBlockYAt(int x, int z) { if (world != null) { return world.getChunk(x >> 4, z >> 4).getHeightmap(Heightmap.Type.MOTION_BLOCKING).get(x & 15, z & 15); } else return -1; } /* Test if sky light level is requestable */ @Override public boolean canGetSkyLightLevel() { return skylight; } /* Return sky light level */ @Override public int getSkyLightLevel(int x, int y, int z) { if (world != null) { return world.getLightLevel(LightType.SKY, new BlockPos(x, y, z)); } else return -1; } /** * Get world environment ID (lower case - normal, the_end, nether) */ @Override public String getEnvironment() { return env; } /** * Get map chunk cache for world */ @Override public MapChunkCache getChunkCache(List<DynmapChunk> chunks) { if (world != null) { FabricMapChunkCache c = new FabricMapChunkCache(plugin); c.setChunks(this, chunks); return c; } return null; } public World getWorld() { return world; } @Override public Polygon getWorldBorder() { if (world != null) { WorldBorder wb = world.getWorldBorder(); if ((wb != null) && (wb.getSize() < 5.9E7)) { Polygon p = new Polygon(); p.addVertex(wb.getBoundWest(), wb.getBoundNorth()); p.addVertex(wb.getBoundWest(), wb.getBoundSouth()); p.addVertex(wb.getBoundEast(), wb.getBoundSouth()); p.addVertex(wb.getBoundEast(), wb.getBoundNorth()); return p; } } return null; } }
/* Copyright 2014-2016 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 apple.healthkit; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSCoder; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.ProtocolClassMethod; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * HKDocumentType * <p> * Represents a type of HKDocument. */ @Generated @Library("HealthKit") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class HKDocumentType extends HKSampleType { static { NatJ.register(); } @Generated protected HKDocumentType(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Selector("activitySummaryType") public static native HKActivitySummaryType activitySummaryType(); @Generated @Owned @Selector("alloc") public static native HKDocumentType alloc(); @Owned @Generated @Selector("allocWithZone:") public static native HKDocumentType allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("categoryTypeForIdentifier:") public static native HKCategoryType categoryTypeForIdentifier(String identifier); @Generated @Selector("characteristicTypeForIdentifier:") public static native HKCharacteristicType characteristicTypeForIdentifier(String identifier); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("correlationTypeForIdentifier:") public static native HKCorrelationType correlationTypeForIdentifier(String identifier); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("documentTypeForIdentifier:") public static native HKDocumentType documentTypeForIdentifier(String identifier); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native HKDocumentType new_objc(); @Generated @Selector("quantityTypeForIdentifier:") public static native HKQuantityType quantityTypeForIdentifier(String identifier); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("supportsSecureCoding") public static native boolean supportsSecureCoding(); @Generated @Selector("version") @NInt public static native long version_static(); @Generated @Selector("workoutType") public static native HKWorkoutType workoutType(); @Generated @Selector("init") public native HKDocumentType init(); @Generated @Selector("initWithCoder:") public native HKDocumentType initWithCoder(NSCoder coder); @Generated @ProtocolClassMethod("supportsSecureCoding") public boolean _supportsSecureCoding() { return supportsSecureCoding(); } @Generated @Selector("seriesTypeForIdentifier:") public static native HKSeriesType seriesTypeForIdentifier(String identifier); @Generated @Selector("audiogramSampleType") public static native HKAudiogramSampleType audiogramSampleType(); @Generated @Selector("clinicalTypeForIdentifier:") public static native HKClinicalType clinicalTypeForIdentifier(String identifier); @Generated @Selector("electrocardiogramType") public static native HKElectrocardiogramType electrocardiogramType(); }
/* * Copyright (C) 2012 CyberAgent * * 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.aplayer.aplayerandroid; import android.content.Context; import android.content.res.AssetManager; import android.graphics.PointF; import android.graphics.SurfaceTexture; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.util.Log; import java.io.InputStream; import java.nio.FloatBuffer; import java.util.LinkedList; import java.util.NoSuchElementException; public class GPUImageFilter implements SurfaceTexture.OnFrameAvailableListener{ private String TAG=GPUImageFilter.class.getSimpleName(); public static final String NO_FILTER_VERTEX_SHADER = "" + "attribute vec4 position; \n" + "attribute vec4 inputTextureCoordinate; \n" + "varying vec2 textureCoordinate; \n" + " \n" + "void main() \n" + "{ \n" + " gl_Position = position; \n" + " textureCoordinate = inputTextureCoordinate.xy; \n" + "}"; public static final String NO_FILTER_FRAGMENT_SHADER = "" + "varying highp vec2 textureCoordinate;\n" + " \n" + "uniform sampler2D inputImageTexture;\n" + " \n" + "void main()\n" + "{\n" + " gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n" + "}"; public static final String NO_FILTER_FRAGMENT_SHADER2 = "" + "varying highp vec2 textureCoordinate; \n" + "uniform sampler2D inputImageTexture1; \n" + "uniform sampler2D inputImageTexture2; \n" + "void main() \n" + "{ \n" + " gl_FragColor = texture2D(inputImageTexture1, textureCoordinate)*0.5; \n" + " gl_FragColor+= texture2D(inputImageTexture2, textureCoordinate)*0.5; \n" + "}"; private final LinkedList<Runnable> mRunOnDraw; private String mVertexShader; private String mFragmentShader; protected int mGLProgId; protected int mGLAttribPosition; protected int mGLUniformTexture; protected int mGLUniformTexture1; protected int mGLUniformTexture2; protected int mGLAttribTextureCoordinate; protected int mOutputWidth; protected int mOutputHeight; protected int mTextureTarget; private boolean mIsInitialized; private int mSysRenderTexture = -1; private SurfaceTexture mSurfaceTexture; private Object mFrameSyncObject = new Object(); private boolean mFrameAvailable = true; private InputSurface mInputSurface; public GPUImageFilter(InputSurface inputSurface) { this(inputSurface,NO_FILTER_VERTEX_SHADER, NO_FILTER_FRAGMENT_SHADER); } public GPUImageFilter(InputSurface inputSurface,final String vertexShader, final String fragmentShader) { mRunOnDraw = new LinkedList<Runnable>(); mInputSurface = inputSurface; mVertexShader = vertexShader; mFragmentShader = fragmentShader; } public final void init() { OpenGlUtils.checkGlError("init start"); onInitTextureExt(false); onInit(); onInitialized(); OpenGlUtils.checkGlError("init end"); } public final void initExt() { OpenGlUtils.checkGlError("initExt start"); onInitTextureExt(true); onInit(); onInitialized(); OpenGlUtils.checkGlError("initExt end"); } private void onInitTextureExt(boolean isForExternalTextureInput) { mTextureTarget = GLES20.GL_TEXTURE_2D; if (isForExternalTextureInput) { mTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES; mFragmentShader = "#extension GL_OES_EGL_image_external : require\n" + mFragmentShader.replace("uniform sampler2D inputImageTexture;", "uniform samplerExternalOES inputImageTexture;"); int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textures[0]); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); mSysRenderTexture = textures[0]; } } public void onInit() { mGLProgId = OpenGlUtils.loadProgram(mVertexShader, mFragmentShader); mGLAttribPosition = GLES20.glGetAttribLocation(mGLProgId, "position"); mGLUniformTexture = GLES20.glGetUniformLocation(mGLProgId, "inputImageTexture"); mGLAttribTextureCoordinate = GLES20.glGetAttribLocation(mGLProgId, "inputTextureCoordinate"); mIsInitialized = true; } public void onInitialized() { } public void onFrameAvailable(SurfaceTexture st) { Log.i(TAG, "lzmlsf new frame available"); synchronized (mFrameSyncObject) { mFrameAvailable = true; } } public SurfaceTexture GetSurfaceTexture(){ if(mSurfaceTexture == null){ Log.e(TAG, "GetSurface enter"); while (mSysRenderTexture == -1){ try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } } mSurfaceTexture = new SurfaceTexture(mSysRenderTexture); mSurfaceTexture.setOnFrameAvailableListener(this); } return mSurfaceTexture; } public final void destroy() { mIsInitialized = false; GLES20.glDeleteProgram(mGLProgId); onDestroy(); } public void onDestroy() { } public void onOutputSizeChanged(final int width, final int height) { mOutputWidth = width; mOutputHeight = height; } public void draw(final FloatBuffer cubeBuffer, final FloatBuffer textureBuffer){ if(mSysRenderTexture != -1){ if(mFrameAvailable){ mSurfaceTexture.updateTexImage(); } draw(mSysRenderTexture,cubeBuffer,textureBuffer); } } public void draw(final int textureId, final FloatBuffer cubeBuffer, final FloatBuffer textureBuffer) { GLES20.glUseProgram(mGLProgId); runPendingOnDrawTasks(); if (!mIsInitialized) { return; } cubeBuffer.position(0); GLES20.glVertexAttribPointer(mGLAttribPosition, 3, GLES20.GL_FLOAT, false, 0, cubeBuffer); GLES20.glEnableVertexAttribArray(mGLAttribPosition); textureBuffer.position(0); GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, textureBuffer); GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate); if (textureId != OpenGlUtils.NO_TEXTURE) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(mTextureTarget, textureId); GLES20.glUniform1i(mGLUniformTexture, 0); } onDrawArraysPre(); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 6); GLES20.glDisableVertexAttribArray(mGLAttribPosition); GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate); GLES20.glBindTexture(mTextureTarget, 0); Log.i(TAG,"java filter draw textureId = " + textureId); if(mInputSurface != null){ mInputSurface.swapBuffers(); GLES20.glFlush(); } } public void draw(final int textureId1, final int textureId2,final FloatBuffer cubeBuffer, final FloatBuffer textureBuffer) { GLES20.glUseProgram(mGLProgId); runPendingOnDrawTasks(); if (!mIsInitialized) { return; } cubeBuffer.position(0); GLES20.glVertexAttribPointer(mGLAttribPosition, 3, GLES20.GL_FLOAT, false, 0, cubeBuffer); GLES20.glEnableVertexAttribArray(mGLAttribPosition); textureBuffer.position(0); GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, textureBuffer); GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate); if (textureId1 != OpenGlUtils.NO_TEXTURE) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(mTextureTarget, textureId1); GLES20.glUniform1i(mGLUniformTexture1, 0); } if (textureId2 != OpenGlUtils.NO_TEXTURE) { GLES20.glActiveTexture(GLES20.GL_TEXTURE1); GLES20.glBindTexture(mTextureTarget, textureId2); GLES20.glUniform1i(mGLUniformTexture2, 1); } onDrawArraysPre(); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 6); GLES20.glDisableVertexAttribArray(mGLAttribPosition); GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate); GLES20.glBindTexture(mTextureTarget, 0); } protected void onDrawArraysPre() {} protected void runPendingOnDrawTasks() { try { while (!mRunOnDraw.isEmpty()) { mRunOnDraw.removeFirst().run(); } } catch (NoSuchElementException e) { e.printStackTrace(); } } public boolean isInitialized() { return mIsInitialized; } public int getOutputWidth() { return mOutputWidth; } public int getOutputHeight() { return mOutputHeight; } public int getProgram() { return mGLProgId; } public int getAttribPosition() { return mGLAttribPosition; } public int getAttribTextureCoordinate() { return mGLAttribTextureCoordinate; } public int getUniformTexture() { return mGLUniformTexture; } protected void setInteger(final int location, final int intValue) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniform1i(location, intValue); } }); } protected void setFloat(final int location, final float floatValue) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniform1f(location, floatValue); } }); } protected void setFloatVec2(final int location, final float[] arrayValue) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniform2fv(location, 1, FloatBuffer.wrap(arrayValue)); } }); } protected void setFloatVec3(final int location, final float[] arrayValue) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniform3fv(location, 1, FloatBuffer.wrap(arrayValue)); } }); } protected void setFloatVec4(final int location, final float[] arrayValue) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniform4fv(location, 1, FloatBuffer.wrap(arrayValue)); } }); } protected void setFloatArray(final int location, final float[] arrayValue) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniform1fv(location, arrayValue.length, FloatBuffer.wrap(arrayValue)); } }); } protected void setPoint(final int location, final PointF point) { runOnDraw(new Runnable() { @Override public void run() { float[] vec2 = new float[2]; vec2[0] = point.x; vec2[1] = point.y; GLES20.glUniform2fv(location, 1, vec2, 0); } }); } protected void setUniformMatrix3f(final int location, final float[] matrix) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniformMatrix3fv(location, 1, false, matrix, 0); } }); } protected void setUniformMatrix4f(final int location, final float[] matrix) { runOnDraw(new Runnable() { @Override public void run() { GLES20.glUniformMatrix4fv(location, 1, false, matrix, 0); } }); } protected void runOnDraw(final Runnable runnable) { synchronized (mRunOnDraw) { mRunOnDraw.addLast(runnable); } } public static String loadShader(String file, Context context) { try { AssetManager assetManager = context.getAssets(); InputStream ims = assetManager.open(file); String re = convertStreamToString(ims); ims.close(); return re; } catch (Exception e) { e.printStackTrace(); } return ""; } public static String convertStreamToString(InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } }
package net.minecraft.inventory; import net.minecraft.entity.IMerchant; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; public class InventoryMerchant implements IInventory { private final IMerchant theMerchant; private ItemStack[] theInventory = new ItemStack[3]; private final EntityPlayer thePlayer; private MerchantRecipe currentRecipe; private int currentRecipeIndex; public InventoryMerchant(EntityPlayer thePlayerIn, IMerchant theMerchantIn) { this.thePlayer = thePlayerIn; this.theMerchant = theMerchantIn; } /** * Returns the number of slots in the inventory. */ public int getSizeInventory() { return this.theInventory.length; } /** * Returns the stack in the given slot. */ public ItemStack getStackInSlot(int index) { return this.theInventory[index]; } /** * Removes up to a specified number of items from an inventory slot and returns them in a new stack. */ public ItemStack decrStackSize(int index, int count) { if (this.theInventory[index] != null) { if (index == 2) { ItemStack itemstack2 = this.theInventory[index]; this.theInventory[index] = null; return itemstack2; } else if (this.theInventory[index].stackSize <= count) { ItemStack itemstack1 = this.theInventory[index]; this.theInventory[index] = null; if (this.inventoryResetNeededOnSlotChange(index)) { this.resetRecipeAndSlots(); } return itemstack1; } else { ItemStack itemstack = this.theInventory[index].splitStack(count); if (this.theInventory[index].stackSize == 0) { this.theInventory[index] = null; } if (this.inventoryResetNeededOnSlotChange(index)) { this.resetRecipeAndSlots(); } return itemstack; } } else { return null; } } /** * if par1 slot has changed, does resetRecipeAndSlots need to be called? */ private boolean inventoryResetNeededOnSlotChange(int p_70469_1_) { return p_70469_1_ == 0 || p_70469_1_ == 1; } /** * Removes a stack from the given slot and returns it. */ public ItemStack removeStackFromSlot(int index) { if (this.theInventory[index] != null) { ItemStack itemstack = this.theInventory[index]; this.theInventory[index] = null; return itemstack; } else { return null; } } /** * Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections). */ public void setInventorySlotContents(int index, ItemStack stack) { this.theInventory[index] = stack; if (stack != null && stack.stackSize > this.getInventoryStackLimit()) { stack.stackSize = this.getInventoryStackLimit(); } if (this.inventoryResetNeededOnSlotChange(index)) { this.resetRecipeAndSlots(); } } /** * Gets the name of this command sender (usually username, but possibly "Rcon") */ public String getName() { return "mob.villager"; } /** * Returns true if this thing is named */ public boolean hasCustomName() { return false; } /** * Get the formatted ChatComponent that will be used for the sender's username in chat */ public IChatComponent getDisplayName() { return (IChatComponent)(this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatComponentTranslation(this.getName(), new Object[0])); } /** * Returns the maximum stack size for a inventory slot. Seems to always be 64, possibly will be extended. */ public int getInventoryStackLimit() { return 64; } /** * Do not make give this method the name canInteractWith because it clashes with Container */ public boolean isUseableByPlayer(EntityPlayer player) { return this.theMerchant.getCustomer() == player; } public void openInventory(EntityPlayer player) { } public void closeInventory(EntityPlayer player) { } /** * Returns true if automation is allowed to insert the given stack (ignoring stack size) into the given slot. */ public boolean isItemValidForSlot(int index, ItemStack stack) { return true; } /** * For tile entities, ensures the chunk containing the tile entity is saved to disk later - the game won't think it * hasn't changed and skip it. */ public void markDirty() { this.resetRecipeAndSlots(); } public void resetRecipeAndSlots() { this.currentRecipe = null; ItemStack itemstack = this.theInventory[0]; ItemStack itemstack1 = this.theInventory[1]; if (itemstack == null) { itemstack = itemstack1; itemstack1 = null; } if (itemstack == null) { this.setInventorySlotContents(2, (ItemStack)null); } else { MerchantRecipeList merchantrecipelist = this.theMerchant.getRecipes(this.thePlayer); if (merchantrecipelist != null) { MerchantRecipe merchantrecipe = merchantrecipelist.canRecipeBeUsed(itemstack, itemstack1, this.currentRecipeIndex); if (merchantrecipe != null && !merchantrecipe.isRecipeDisabled()) { this.currentRecipe = merchantrecipe; this.setInventorySlotContents(2, merchantrecipe.getItemToSell().copy()); } else if (itemstack1 != null) { merchantrecipe = merchantrecipelist.canRecipeBeUsed(itemstack1, itemstack, this.currentRecipeIndex); if (merchantrecipe != null && !merchantrecipe.isRecipeDisabled()) { this.currentRecipe = merchantrecipe; this.setInventorySlotContents(2, merchantrecipe.getItemToSell().copy()); } else { this.setInventorySlotContents(2, (ItemStack)null); } } else { this.setInventorySlotContents(2, (ItemStack)null); } } } this.theMerchant.verifySellingItem(this.getStackInSlot(2)); } public MerchantRecipe getCurrentRecipe() { return this.currentRecipe; } public void setCurrentRecipeIndex(int currentRecipeIndexIn) { this.currentRecipeIndex = currentRecipeIndexIn; this.resetRecipeAndSlots(); } public int getField(int id) { return 0; } public void setField(int id, int value) { } public int getFieldCount() { return 0; } public void clear() { for (int i = 0; i < this.theInventory.length; ++i) { this.theInventory[i] = null; } } }
/* * Copyright (c) 2015. Thomas Haertel * * Licensed under 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.thomashaertel.device.identification.internal; import android.content.Context; import java.io.File; import java.lang.reflect.Method; import dalvik.system.DexFile; /* * Note: Original code found on StackOverflow - http://stackoverflow.com/questions/2641111/where-is-android-os-systemproperties */ public class SystemPropertiesProxy { /** * This class cannot be instantiated */ private SystemPropertiesProxy() { } /** * Get the value for the given key. * * @param context an Android constant (to retrieve system services) * @param key the key to lookup * @return an empty string if the key isn't found * @throws IllegalArgumentException if the key exceeds 32 characters */ public static String get(Context context, String key) throws IllegalArgumentException { String ret = ""; try { ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties"); //Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1]; paramTypes[0] = String.class; Method get = SystemProperties.getMethod("get", paramTypes); //Parameters Object[] params = new Object[1]; params[0] = new String(key); ret = (String) get.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { ret = ""; //TODO } return ret; } /** * Get the value for the given key. * * @param context an Android constant (to retrieve system services) * @param key the key to lookup * @param def a default value to return * @return if the key isn't found, return def if it isn't null, or an empty string otherwise * @throws IllegalArgumentException if the key exceeds 32 characters */ public static String get(Context context, String key, String def) throws IllegalArgumentException { String ret = def; try { ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties"); //Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = String.class; Method get = SystemProperties.getMethod("get", paramTypes); //Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new String(def); ret = (String) get.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { ret = def; //TODO } return ret; } /** * Get the value for the given key, and return as an integer. * * @param context an Android constant (to retrieve system services) * @param key the key to lookup * @param def a default value to return * @return the key parsed as an integer, or def if the key isn't found or * cannot be parsed * @throws IllegalArgumentException if the key exceeds 32 characters */ public static Integer getInt(Context context, String key, int def) throws IllegalArgumentException { Integer ret = def; try { ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties"); //Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = int.class; Method getInt = SystemProperties.getMethod("getInt", paramTypes); //Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new Integer(def); ret = (Integer) getInt.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { ret = def; //TODO } return ret; } /** * Get the value for the given key, and return as a long. * * @param context an Android constant (to retrieve system services) * @param key the key to lookup * @param def a default value to return * @return the key parsed as a long, or def if the key isn't found or * cannot be parsed * @throws IllegalArgumentException if the key exceeds 32 characters */ public static Long getLong(Context context, String key, long def) throws IllegalArgumentException { Long ret = def; try { ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties"); //Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = long.class; Method getLong = SystemProperties.getMethod("getLong", paramTypes); //Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new Long(def); ret = (Long) getLong.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { ret = def; //TODO } return ret; } /** * Get the value for the given key, returned as a boolean. * Values 'n', 'no', '0', 'false' or 'off' are considered false. * Values 'y', 'yes', '1', 'true' or 'on' are considered true. * (case insensitive). * If the key does not exist, or has any other value, then the default * result is returned. * * @param context an Android constant (to retrieve system services) * @param key the key to lookup * @param def a default value to return * @return the key parsed as a boolean, or def if the key isn't found or is * not able to be parsed as a boolean. * @throws IllegalArgumentException if the key exceeds 32 characters */ public static Boolean getBoolean(Context context, String key, boolean def) throws IllegalArgumentException { Boolean ret = def; try { ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties"); //Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = boolean.class; Method getBoolean = SystemProperties.getMethod("getBoolean", paramTypes); //Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new Boolean(def); ret = (Boolean) getBoolean.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { ret = def; //TODO } return ret; } /** * Set the value for the given key. * * @param context an Android constant (to retrieve system services) * @param key the key to store val * @param val a value to store * @throws IllegalArgumentException if the key exceeds 32 characters * @throws IllegalArgumentException if the value exceeds 92 characters */ public static void set(Context context, String key, String val) throws IllegalArgumentException { try { @SuppressWarnings("unused") DexFile df = new DexFile(new File("/system/app/Settings.apk")); @SuppressWarnings("unused") ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = Class.forName("android.os.SystemProperties"); //Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = String.class; Method set = SystemProperties.getMethod("set", paramTypes); //Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new String(val); set.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { //TODO } } }
package lib.driver.lims.driver_class; import lib.SessionFactoryUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.Collection; import java.util.List; import core.classes.api.user.AdminUser; import core.classes.lims.Category; import core.classes.lims.SpecimenRetentionType; import core.classes.lims.SpecimenType; import core.classes.lims.SubCategory; import core.classes.lims.TestFieldsRange; import core.classes.lims.TestNames; import core.classes.opd.OutPatient; public class TestNamesDBDriver { Session session = SessionFactoryUtil.getSessionFactory().openSession(); public boolean insertNewTest(TestNames testnames, int categoryID, int subcategoryID, int userid) { Transaction tx = null; try { tx = session.beginTransaction(); Category sctype = (Category) session.get(Category.class, categoryID); SubCategory sstype = (SubCategory ) session.get(SubCategory.class, subcategoryID); AdminUser user = (AdminUser) session.get(AdminUser.class, userid); testnames.setfTest_CreateUserID(user); testnames.setfTest_LastUpdateUserID(user); testnames.setfTest_CategoryID(sctype); testnames.setfTest_Sub_CategoryID(sstype); session.save(testnames); tx.commit(); return true; } catch (RuntimeException ex) { if (tx != null && tx.isActive()) { try { tx.rollback(); } catch (HibernateException he) { System.err.println("Error rolling back transaction"); } throw ex; } else if(tx==null) { throw ex; } else return false; } } /** * This method retrieve a list of laboratory tests currently available in the system * * @return lab test list List<TestNames> * @throws Method * throws a {@link RuntimeException} in failing the return, * throws a {@link HibernateException} on error rolling back * transaction. */ public List<TestNames> getTestNamesList() { Transaction tx = null; try { //catID = 2; tx = session.beginTransaction(); Query query = session.createQuery("select t from TestNames t" ); //query.setParameter("catID", catID); List<TestNames> testnamesList = query.list(); tx.commit(); return testnamesList; } catch (RuntimeException ex) { if (tx != null && tx.isActive()) { try { tx.rollback(); } catch (HibernateException he) { System.err.println("Error rolling back transaction"); } throw ex; } else if(tx==null) { throw ex; } else return null; } } public TestNames getTestNameByID(int id) { Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery("select t from TestNames t where t.test_ID="+id); List<TestNames> testNameList = query.list(); if (testNameList.size() == 0) return null; tx.commit(); return (TestNames)testNameList.get(0); } catch (RuntimeException ex) { if (tx != null && tx.isActive()) { try { tx.rollback(); } catch (HibernateException he) { System.err.println("Error rolling back transaction"); } throw ex; } else if (tx==null) { throw ex; } else return null; } } public String getMaxTestID() { Transaction tx = null; try { tx = session.beginTransaction(); Query query1 = session.createQuery("select max(test_ID) from TestNames" ); //query1.setParameter("testID", testObj); List list = query1.list(); tx.commit(); return list.get(0).toString(); } catch (RuntimeException ex) { if (tx != null && tx.isActive()) { try { tx.rollback(); } catch (HibernateException he) { System.err.println("Error rolling back transaction"); } throw ex; } else if (tx==null) { throw ex; } else return null; } } public boolean updateTestNames(int testID, TestNames test,String categoryID, String subCategoryID, int userid) { Transaction tx = null; try { tx = session.beginTransaction(); TestNames tests = (TestNames) session.get(TestNames.class,testID); // Category sctype = (Category) session.get(Category.class, categoryID); // SubCategory sstype = (SubCategory ) session.get(SubCategory.class, subCategoryID); tests.setTest_Name(test.getTest_Name()); // tests.setfTest_CategoryID(sctype); // tests.setfTest_Sub_CategoryID(sstype); tests.setfTest_CreateUserID(test.getfTest_CreateUserID()); tests.setTest_CreatedDate(test.getTest_CreatedDate()); AdminUser user = (AdminUser) session.get(AdminUser.class, userid); tests.setfTest_LastUpdateUserID(user); tests.setTest_LastUpdate(test.getTest_LastUpdate()); session.update(tests); tx.commit(); return true; } catch (Exception ex) { System.out.println(ex.getMessage()); if (tx != null && tx.isActive()) { try { tx.rollback(); } catch (HibernateException he) { System.err.println("Error rolling back transaction"); } throw ex; } if(tx==null) { throw ex; } else return false; } } public boolean DeleteTest(int testID) { // TODO Auto-generated method stub Transaction tx = null; //boolean status=false; try{ TestNames test=new TestNames(); test.setTest_ID(testID); Object object = session.load(TestNames.class, testID); TestNames deletetest = (TestNames) object; System.out.println("Deleting Item "); tx = session.beginTransaction(); session.delete(deletetest); tx.commit(); } catch(Exception e) { e.printStackTrace(); throw e; } return true; } }
/* * Copyright 2016 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.schemaorg.core; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.SchemaOrgTypeImpl; import com.google.schemaorg.ValueType; import com.google.schemaorg.core.datatype.DateTime; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.GoogConstants; import com.google.schemaorg.goog.PopularityScoreSpecification; /** Implementation of {@link AskAction}. */ public class AskActionImpl extends CommunicateActionImpl implements AskAction { private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet(); private static ImmutableSet<String> initializePropertySet() { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add(CoreConstants.PROPERTY_ABOUT); builder.add(CoreConstants.PROPERTY_ACTION_STATUS); builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE); builder.add(CoreConstants.PROPERTY_AGENT); builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME); builder.add(CoreConstants.PROPERTY_DESCRIPTION); builder.add(CoreConstants.PROPERTY_END_TIME); builder.add(CoreConstants.PROPERTY_ERROR); builder.add(CoreConstants.PROPERTY_IMAGE); builder.add(CoreConstants.PROPERTY_IN_LANGUAGE); builder.add(CoreConstants.PROPERTY_INSTRUMENT); builder.add(CoreConstants.PROPERTY_LANGUAGE); builder.add(CoreConstants.PROPERTY_LOCATION); builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE); builder.add(CoreConstants.PROPERTY_NAME); builder.add(CoreConstants.PROPERTY_OBJECT); builder.add(CoreConstants.PROPERTY_PARTICIPANT); builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION); builder.add(CoreConstants.PROPERTY_QUESTION); builder.add(CoreConstants.PROPERTY_RECIPIENT); builder.add(CoreConstants.PROPERTY_RESULT); builder.add(CoreConstants.PROPERTY_SAME_AS); builder.add(CoreConstants.PROPERTY_START_TIME); builder.add(CoreConstants.PROPERTY_TARGET); builder.add(CoreConstants.PROPERTY_URL); builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION); builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE); return builder.build(); } static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<AskAction.Builder> implements AskAction.Builder { @Override public AskAction.Builder addAbout(Thing value) { return addProperty(CoreConstants.PROPERTY_ABOUT, value); } @Override public AskAction.Builder addAbout(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_ABOUT, value.build()); } @Override public AskAction.Builder addAbout(String value) { return addProperty(CoreConstants.PROPERTY_ABOUT, Text.of(value)); } @Override public AskAction.Builder addActionStatus(ActionStatusType value) { return addProperty(CoreConstants.PROPERTY_ACTION_STATUS, value); } @Override public AskAction.Builder addActionStatus(String value) { return addProperty(CoreConstants.PROPERTY_ACTION_STATUS, Text.of(value)); } @Override public AskAction.Builder addAdditionalType(URL value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value); } @Override public AskAction.Builder addAdditionalType(String value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value)); } @Override public AskAction.Builder addAgent(Organization value) { return addProperty(CoreConstants.PROPERTY_AGENT, value); } @Override public AskAction.Builder addAgent(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_AGENT, value.build()); } @Override public AskAction.Builder addAgent(Person value) { return addProperty(CoreConstants.PROPERTY_AGENT, value); } @Override public AskAction.Builder addAgent(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_AGENT, value.build()); } @Override public AskAction.Builder addAgent(String value) { return addProperty(CoreConstants.PROPERTY_AGENT, Text.of(value)); } @Override public AskAction.Builder addAlternateName(Text value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value); } @Override public AskAction.Builder addAlternateName(String value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value)); } @Override public AskAction.Builder addDescription(Text value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value); } @Override public AskAction.Builder addDescription(String value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value)); } @Override public AskAction.Builder addEndTime(DateTime value) { return addProperty(CoreConstants.PROPERTY_END_TIME, value); } @Override public AskAction.Builder addEndTime(String value) { return addProperty(CoreConstants.PROPERTY_END_TIME, Text.of(value)); } @Override public AskAction.Builder addError(Thing value) { return addProperty(CoreConstants.PROPERTY_ERROR, value); } @Override public AskAction.Builder addError(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_ERROR, value.build()); } @Override public AskAction.Builder addError(String value) { return addProperty(CoreConstants.PROPERTY_ERROR, Text.of(value)); } @Override public AskAction.Builder addImage(ImageObject value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public AskAction.Builder addImage(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value.build()); } @Override public AskAction.Builder addImage(URL value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public AskAction.Builder addImage(String value) { return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value)); } @Override public AskAction.Builder addInLanguage(Language value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value); } @Override public AskAction.Builder addInLanguage(Language.Builder value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value.build()); } @Override public AskAction.Builder addInLanguage(Text value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value); } @Override public AskAction.Builder addInLanguage(String value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, Text.of(value)); } @Override public AskAction.Builder addInstrument(Thing value) { return addProperty(CoreConstants.PROPERTY_INSTRUMENT, value); } @Override public AskAction.Builder addInstrument(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_INSTRUMENT, value.build()); } @Override public AskAction.Builder addInstrument(String value) { return addProperty(CoreConstants.PROPERTY_INSTRUMENT, Text.of(value)); } @Override public AskAction.Builder addLanguage(Language value) { return addProperty(CoreConstants.PROPERTY_LANGUAGE, value); } @Override public AskAction.Builder addLanguage(Language.Builder value) { return addProperty(CoreConstants.PROPERTY_LANGUAGE, value.build()); } @Override public AskAction.Builder addLanguage(String value) { return addProperty(CoreConstants.PROPERTY_LANGUAGE, Text.of(value)); } @Override public AskAction.Builder addLocation(Place value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public AskAction.Builder addLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value.build()); } @Override public AskAction.Builder addLocation(PostalAddress value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public AskAction.Builder addLocation(PostalAddress.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value.build()); } @Override public AskAction.Builder addLocation(Text value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public AskAction.Builder addLocation(String value) { return addProperty(CoreConstants.PROPERTY_LOCATION, Text.of(value)); } @Override public AskAction.Builder addMainEntityOfPage(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public AskAction.Builder addMainEntityOfPage(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build()); } @Override public AskAction.Builder addMainEntityOfPage(URL value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public AskAction.Builder addMainEntityOfPage(String value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value)); } @Override public AskAction.Builder addName(Text value) { return addProperty(CoreConstants.PROPERTY_NAME, value); } @Override public AskAction.Builder addName(String value) { return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value)); } @Override public AskAction.Builder addObject(Thing value) { return addProperty(CoreConstants.PROPERTY_OBJECT, value); } @Override public AskAction.Builder addObject(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_OBJECT, value.build()); } @Override public AskAction.Builder addObject(String value) { return addProperty(CoreConstants.PROPERTY_OBJECT, Text.of(value)); } @Override public AskAction.Builder addParticipant(Organization value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value); } @Override public AskAction.Builder addParticipant(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value.build()); } @Override public AskAction.Builder addParticipant(Person value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value); } @Override public AskAction.Builder addParticipant(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, value.build()); } @Override public AskAction.Builder addParticipant(String value) { return addProperty(CoreConstants.PROPERTY_PARTICIPANT, Text.of(value)); } @Override public AskAction.Builder addPotentialAction(Action value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value); } @Override public AskAction.Builder addPotentialAction(Action.Builder value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build()); } @Override public AskAction.Builder addPotentialAction(String value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value)); } @Override public AskAction.Builder addQuestion(Question value) { return addProperty(CoreConstants.PROPERTY_QUESTION, value); } @Override public AskAction.Builder addQuestion(Question.Builder value) { return addProperty(CoreConstants.PROPERTY_QUESTION, value.build()); } @Override public AskAction.Builder addQuestion(String value) { return addProperty(CoreConstants.PROPERTY_QUESTION, Text.of(value)); } @Override public AskAction.Builder addRecipient(Audience value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, value); } @Override public AskAction.Builder addRecipient(Audience.Builder value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, value.build()); } @Override public AskAction.Builder addRecipient(Organization value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, value); } @Override public AskAction.Builder addRecipient(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, value.build()); } @Override public AskAction.Builder addRecipient(Person value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, value); } @Override public AskAction.Builder addRecipient(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, value.build()); } @Override public AskAction.Builder addRecipient(String value) { return addProperty(CoreConstants.PROPERTY_RECIPIENT, Text.of(value)); } @Override public AskAction.Builder addResult(Thing value) { return addProperty(CoreConstants.PROPERTY_RESULT, value); } @Override public AskAction.Builder addResult(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_RESULT, value.build()); } @Override public AskAction.Builder addResult(String value) { return addProperty(CoreConstants.PROPERTY_RESULT, Text.of(value)); } @Override public AskAction.Builder addSameAs(URL value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, value); } @Override public AskAction.Builder addSameAs(String value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value)); } @Override public AskAction.Builder addStartTime(DateTime value) { return addProperty(CoreConstants.PROPERTY_START_TIME, value); } @Override public AskAction.Builder addStartTime(String value) { return addProperty(CoreConstants.PROPERTY_START_TIME, Text.of(value)); } @Override public AskAction.Builder addTarget(EntryPoint value) { return addProperty(CoreConstants.PROPERTY_TARGET, value); } @Override public AskAction.Builder addTarget(EntryPoint.Builder value) { return addProperty(CoreConstants.PROPERTY_TARGET, value.build()); } @Override public AskAction.Builder addTarget(String value) { return addProperty(CoreConstants.PROPERTY_TARGET, Text.of(value)); } @Override public AskAction.Builder addUrl(URL value) { return addProperty(CoreConstants.PROPERTY_URL, value); } @Override public AskAction.Builder addUrl(String value) { return addProperty(CoreConstants.PROPERTY_URL, Text.of(value)); } @Override public AskAction.Builder addDetailedDescription(Article value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value); } @Override public AskAction.Builder addDetailedDescription(Article.Builder value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build()); } @Override public AskAction.Builder addDetailedDescription(String value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value)); } @Override public AskAction.Builder addPopularityScore(PopularityScoreSpecification value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value); } @Override public AskAction.Builder addPopularityScore(PopularityScoreSpecification.Builder value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build()); } @Override public AskAction.Builder addPopularityScore(String value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value)); } @Override public AskAction build() { return new AskActionImpl(properties, reverseMap); } } public AskActionImpl(Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) { super(properties, reverseMap); } @Override public String getFullTypeName() { return CoreConstants.TYPE_ASK_ACTION; } @Override public boolean includesProperty(String property) { return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property) || PROPERTY_SET.contains(GoogConstants.NAMESPACE + property) || PROPERTY_SET.contains(property); } @Override public ImmutableList<SchemaOrgType> getQuestionList() { return getProperty(CoreConstants.PROPERTY_QUESTION); } }
/* * 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.jmeter.protocol.smtp.sampler.protocol; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.io.IOUtils; import org.apache.jmeter.config.Argument; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.TestElementProperty; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * This class performs all tasks necessary to send a message (build message, * prepare connection, send message). Provides getter-/setter-methods for an * SmtpSampler-object to configure transport and message settings. The * send-mail-command itself is started by the SmtpSampler-object. */ public class SendMailCommand { // local vars private static final Logger logger = LoggingManager.getLoggerForClass(); // Use the actual class so the name must be correct. private static final String TRUST_ALL_SOCKET_FACTORY = TrustAllSSLSocketFactory.class.getName(); private boolean useSSL = false; private boolean useStartTLS = false; private boolean trustAllCerts = false; private boolean enforceStartTLS = false; private boolean sendEmlMessage = false; private boolean enableDebug; private String smtpServer; private String smtpPort; private String sender; private List<InternetAddress> replyTo; private String emlMessage; private List<InternetAddress> receiverTo; private List<InternetAddress> receiverCC; private List<InternetAddress> receiverBCC; private CollectionProperty headerFields; private String subject = ""; private boolean useAuthentication = false; private String username; private String password; private boolean useLocalTrustStore; private String trustStoreToUse; private List<File> attachments; private String mailBody; private String timeOut; // Socket read timeout value in milliseconds. This timeout is implemented by java.net.Socket. private String connectionTimeOut; // Socket connection timeout value in milliseconds. This timeout is implemented by java.net.Socket. // case we are measuring real time of spedition private boolean synchronousMode; private Session session; private StringBuilder serverResponse = new StringBuilder(); // TODO this is not populated currently /** send plain body, i.e. not multipart/mixed */ private boolean plainBody; /** * Standard-Constructor */ public SendMailCommand() { headerFields = new CollectionProperty(); attachments = new ArrayList<File>(); } /** * Prepares message prior to be sent via execute()-method, i.e. sets * properties such as protocol, authentication, etc. * * @return Message-object to be sent to execute()-method * @throws MessagingException * @throws IOException */ public Message prepareMessage() throws MessagingException, IOException { Properties props = new Properties(); String protocol = getProtocol(); // set properties using JAF props.setProperty("mail." + protocol + ".host", smtpServer); props.setProperty("mail." + protocol + ".port", getPort()); props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication)); // set timeout props.setProperty("mail." + protocol + ".timeout", getTimeout()); props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout()); if (enableDebug) { props.setProperty("mail.debug","true"); } if (useStartTLS) { props.setProperty("mail.smtp.starttls.enable", "true"); if (enforceStartTLS){ // Requires JavaMail 1.4.2+ props.setProperty("mail.smtp.starttls.require", "true"); } } if (trustAllCerts) { if (useSSL) { props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false"); } } else if (useLocalTrustStore){ File truststore = new File(trustStoreToUse); logger.info("load local truststore - try to load truststore from: "+truststore.getAbsolutePath()); if(!truststore.exists()){ logger.info("load local truststore -Failed to load truststore from: "+truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse); logger.info("load local truststore -Attempting to read truststore from: "+truststore.getAbsolutePath()); if(!truststore.exists()){ logger.info("load local truststore -Failed to load truststore from: "+truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (useSSL) { // Requires JavaMail 1.4.2+ props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { // Requires JavaMail 1.4.2+ props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtp.ssl.socketFactory.fallback", "false"); } } session = Session.getInstance(props, null); Message message; if (sendEmlMessage) { message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage))); } else { message = new MimeMessage(session); // handle body and attachments Multipart multipart = new MimeMultipart(); final int attachmentCount = attachments.size(); if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) { if (attachmentCount == 1) { // i.e. mailBody is empty File first = attachments.get(0); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(first)); message.setText(IOUtils.toString(is)); } finally { IOUtils.closeQuietly(is); } } else { message.setText(mailBody); } } else { BodyPart body = new MimeBodyPart(); body.setText(mailBody); multipart.addBodyPart(body); for (File f : attachments) { BodyPart attach = new MimeBodyPart(); attach.setFileName(f.getName()); attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath()))); multipart.addBodyPart(attach); } message.setContent(multipart); } } // set from field and subject if (null != sender) { message.setFrom(new InternetAddress(sender)); } if (null != replyTo) { InternetAddress[] to = new InternetAddress[replyTo.size()]; message.setReplyTo(replyTo.toArray(to)); } if(null != subject) { message.setSubject(subject); } if (receiverTo != null) { InternetAddress[] to = new InternetAddress[receiverTo.size()]; receiverTo.toArray(to); message.setRecipients(Message.RecipientType.TO, to); } if (receiverCC != null) { InternetAddress[] cc = new InternetAddress[receiverCC.size()]; receiverCC.toArray(cc); message.setRecipients(Message.RecipientType.CC, cc); } if (receiverBCC != null) { InternetAddress[] bcc = new InternetAddress[receiverBCC.size()]; receiverBCC.toArray(bcc); message.setRecipients(Message.RecipientType.BCC, bcc); } for (int i = 0; i < headerFields.size(); i++) { Argument argument = (Argument)((TestElementProperty)headerFields.get(i)).getObjectValue(); message.setHeader(argument.getName(), argument.getValue()); } message.saveChanges(); return message; } /** * Sends message to mailserver, waiting for delivery if using synchronous mode. * * @param message * Message previously prepared by prepareMessage() * @throws MessagingException * @throws IOException * @throws InterruptedException */ public void execute(Message message) throws MessagingException, IOException, InterruptedException { Transport tr = session.getTransport(getProtocol()); SynchronousTransportListener listener = null; if (synchronousMode) { listener = new SynchronousTransportListener(); tr.addTransportListener(listener); } if (useAuthentication) { tr.connect(smtpServer, username, password); } else { tr.connect(); } tr.sendMessage(message, message.getAllRecipients()); if (listener != null /*synchronousMode==true*/) { listener.attend(); // listener cannot be null here } tr.close(); logger.debug("transport closed"); logger.debug("message sent"); return; } /** * Processes prepareMessage() and execute() * * @throws InterruptedException * @throws IOException * @throws MessagingException */ public void execute() throws MessagingException, IOException, InterruptedException { execute(prepareMessage()); } /** * Returns FQDN or IP of SMTP-server to be used to send message - standard * getter * * @return FQDN or IP of SMTP-server */ public String getSmtpServer() { return smtpServer; } /** * Sets FQDN or IP of SMTP-server to be used to send message - to be called * by SmtpSampler-object * * @param smtpServer * FQDN or IP of SMTP-server */ public void setSmtpServer(String smtpServer) { this.smtpServer = smtpServer; } /** * Returns sender-address for current message - standard getter * * @return sender-address */ public String getSender() { return sender; } /** * Sets the sender-address for the current message - to be called by * SmtpSampler-object * * @param sender * Sender-address for current message */ public void setSender(String sender) { this.sender = sender; } /** * Returns subject for current message - standard getter * * @return Subject of current message */ public String getSubject() { return subject; } /** * Sets subject for current message - called by SmtpSampler-object * * @param subject * Subject for message of current message - may be null */ public void setSubject(String subject) { this.subject = subject; } /** * Returns username to authenticate at the mailserver - standard getter * * @return Username for mailserver */ public String getUsername() { return username; } /** * Sets username to authenticate at the mailserver - to be called by * SmtpSampler-object * * @param username * Username for mailserver */ public void setUsername(String username) { this.username = username; } /** * Returns password to authenticate at the mailserver - standard getter * * @return Password for mailserver */ public String getPassword() { return password; } /** * Sets password to authenticate at the mailserver - to be called by * SmtpSampler-object * * @param password * Password for mailserver */ public void setPassword(String password) { this.password = password; } /** * Sets receivers of current message ("to") - to be called by * SmtpSampler-object * * @param receiverTo * List of receivers <InternetAddress> */ public void setReceiverTo(List<InternetAddress> receiverTo) { this.receiverTo = receiverTo; } /** * Returns receivers of current message <InternetAddress> ("cc") - standard * getter * * @return List of receivers */ public List<InternetAddress> getReceiverCC() { return receiverCC; } /** * Sets receivers of current message ("cc") - to be called by * SmtpSampler-object * * @param receiverCC * List of receivers <InternetAddress> */ public void setReceiverCC(List<InternetAddress> receiverCC) { this.receiverCC = receiverCC; } /** * Returns receivers of current message <InternetAddress> ("bcc") - standard * getter * * @return List of receivers */ public List<InternetAddress> getReceiverBCC() { return receiverBCC; } /** * Sets receivers of current message ("bcc") - to be called by * SmtpSampler-object * * @param receiverBCC * List of receivers <InternetAddress> */ public void setReceiverBCC(List<InternetAddress> receiverBCC) { this.receiverBCC = receiverBCC; } /** * Returns if authentication is used to access the mailserver - standard * getter * * @return True if authentication is used to access mailserver */ public boolean isUseAuthentication() { return useAuthentication; } /** * Sets if authentication should be used to access the mailserver - to be * called by SmtpSampler-object * * @param useAuthentication * Should authentication be used to access mailserver? */ public void setUseAuthentication(boolean useAuthentication) { this.useAuthentication = useAuthentication; } /** * Returns if SSL is used to send message - standard getter * * @return True if SSL is used to transmit message */ public boolean getUseSSL() { return useSSL; } /** * Sets SSL to secure the delivery channel for the message - to be called by * SmtpSampler-object * * @param useSSL * Should StartTLS be used to secure SMTP-connection? */ public void setUseSSL(boolean useSSL) { this.useSSL = useSSL; } /** * Returns if StartTLS is used to transmit message - standard getter * * @return True if StartTLS is used to transmit message */ public boolean getUseStartTLS() { return useStartTLS; } /** * Sets StartTLS to secure the delivery channel for the message - to be * called by SmtpSampler-object * * @param useStartTLS * Should StartTLS be used to secure SMTP-connection? */ public void setUseStartTLS(boolean useStartTLS) { this.useStartTLS = useStartTLS; } /** * Returns port to be used for SMTP-connection (standard 25 or 465) - * standard getter * * @return Port to be used for SMTP-connection */ public String getSmtpPort() { return smtpPort; } /** * Sets port to be used for SMTP-connection (standard 25 or 465) - to be * called by SmtpSampler-object * * @param smtpPort * Port to be used for SMTP-connection */ public void setSmtpPort(String smtpPort) { this.smtpPort = smtpPort; } /** * Returns if sampler should trust all certificates - standard getter * * @return True if all Certificates are trusted */ public boolean isTrustAllCerts() { return trustAllCerts; } /** * Determines if SMTP-sampler should trust all certificates, no matter what * CA - to be called by SmtpSampler-object * * @param trustAllCerts * Should all certificates be trusted? */ public void setTrustAllCerts(boolean trustAllCerts) { this.trustAllCerts = trustAllCerts; } /** * Instructs object to enforce StartTLS and not to fallback to plain * SMTP-connection - to be called by SmtpSampler-object * * @param enforceStartTLS * Should StartTLS be enforced? */ public void setEnforceStartTLS(boolean enforceStartTLS) { this.enforceStartTLS = enforceStartTLS; } /** * Returns if StartTLS is enforced to secure the connection, i.e. no * fallback is used (plain SMTP) - standard getter * * @return True if StartTLS is enforced */ public boolean isEnforceStartTLS() { return enforceStartTLS; } /** * Returns headers for current message - standard getter * * @return CollectionProperty of headers for current message */ public CollectionProperty getHeaders() { return headerFields; } /** * Sets headers for current message * * @param headerFields * CollectionProperty of headers for current message */ public void setHeaderFields(CollectionProperty headerFields) { this.headerFields = headerFields; } /** * Adds a header-part to current HashMap of headers - to be called by * SmtpSampler-object * * @param headerName * Key for current header * @param headerValue * Value for current header */ public void addHeader(String headerName, String headerValue) { if (this.headerFields == null){ this.headerFields = new CollectionProperty(); } Argument argument = new Argument(headerName, headerValue); this.headerFields.addItem(argument); } /** * Deletes all current headers in HashMap */ public void clearHeaders() { if (this.headerFields == null){ this.headerFields = new CollectionProperty(); }else{ this.headerFields.clear(); } } /** * Returns all attachment for current message - standard getter * * @return List of attachments for current message */ public List<File> getAttachments() { return attachments; } /** * Adds attachments to current message * * @param attachments * List of files to be added as attachments to current message */ public void setAttachments(List<File> attachments) { this.attachments = attachments; } /** * Adds an attachment to current message - to be called by * SmtpSampler-object * * @param attachment * File-object to be added as attachment to current message */ public void addAttachment(File attachment) { this.attachments.add(attachment); } /** * Clear all attachments for current message */ public void clearAttachments() { this.attachments.clear(); } /** * Returns if synchronous-mode is used for current message (i.e. time for * delivery, ... is measured) - standard getter * * @return True if synchronous-mode is used */ public boolean isSynchronousMode() { return synchronousMode; } /** * Sets the use of synchronous-mode (i.e. time for delivery, ... is * measured) - to be called by SmtpSampler-object * * @param synchronousMode * Should synchronous-mode be used? */ public void setSynchronousMode(boolean synchronousMode) { this.synchronousMode = synchronousMode; } /** * Returns which protocol should be used to transport message (smtps for * SSL-secured connections or smtp for plain SMTP / StartTLS) * * @return Protocol that is used to transport message */ private String getProtocol() { return (useSSL) ? "smtps" : "smtp"; } /** * Returns port to be used for SMTP-connection - returns the * default port for the protocol if no port has been supplied. * * @return Port to be used for SMTP-connection */ private String getPort() { String port = smtpPort.trim(); if (port.length() > 0) { // OK, it has been supplied return port; } if (useSSL){ return "465"; } if (useStartTLS) { return "587"; } return "25"; } /** * @param timeOut the timeOut to set */ public void setTimeOut(String timeOut) { this.timeOut = timeOut; } /** * Returns timeout for the SMTP-connection - returns the * default timeout if no value has been supplied. * * @return Timeout to be set for SMTP-connection */ public String getTimeout() { String timeout = timeOut.trim(); if (timeout.length() > 0) { // OK, it has been supplied return timeout; } return "0"; // Default is infinite timeout (value 0). } /** * @param connectionTimeOut the connectionTimeOut to set */ public void setConnectionTimeOut(String connectionTimeOut) { this.connectionTimeOut = connectionTimeOut; } /** * Returns connection timeout for the SMTP-connection - returns the * default connection timeout if no value has been supplied. * * @return Connection timeout to be set for SMTP-connection */ public String getConnectionTimeout() { String connectionTimeout = connectionTimeOut.trim(); if (connectionTimeout.length() > 0) { // OK, it has been supplied return connectionTimeout; } return "0"; // Default is infinite timeout (value 0). } /** * Assigns the object to use a local truststore for SSL / StartTLS - to be * called by SmtpSampler-object * * @param useLocalTrustStore * Should a local truststore be used? */ public void setUseLocalTrustStore(boolean useLocalTrustStore) { this.useLocalTrustStore = useLocalTrustStore; } /** * Sets the path to the local truststore to be used for SSL / StartTLS - to * be called by SmtpSampler-object * * @param trustStoreToUse * Path to local truststore */ public void setTrustStoreToUse(String trustStoreToUse) { this.trustStoreToUse = trustStoreToUse; } public void setUseEmlMessage(boolean sendEmlMessage) { this.sendEmlMessage = sendEmlMessage; } /** * Sets eml-message to be sent * * @param emlMessage * path to eml-message */ public void setEmlMessage(String emlMessage) { this.emlMessage = emlMessage; } /** * Set the mail body. * * @param body */ public void setMailBody(String body){ mailBody = body; } /** * Set whether to send a plain body (i.e. not multipart/mixed) * * @param plainBody <code>true</code> if sending a plain body (i.e. not multipart/mixed) */ public void setPlainBody(boolean plainBody){ this.plainBody = plainBody; } public String getServerResponse() { return this.serverResponse.toString(); } public void setEnableDebug(boolean selected) { enableDebug = selected; } public void setReplyTo(List<InternetAddress> replyTo) { this.replyTo = replyTo; } }
package com.crawljax.plugins.testilizer.generated.claroline_INIT; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import org.junit.*; import static org.junit.Assert.*; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import com.crawljax.forms.RandomInputValueGenerator; import com.crawljax.util.DomUtils; /* * Generated @ Tue Apr 08 22:59:20 PDT 2014 */ public class GeneratedTestCase56 { private WebDriver driver; private String url; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); private DOMElement element; private DOMElement parentElement; private ArrayList<DOMElement> childrenElements = new ArrayList<DOMElement>(); private String DOM = null; boolean getCoverageReport = false; @Before public void setUp() throws Exception { // Setting the JavaScript code coverage switch getCoverageReport = com.crawljax.plugins.testilizer.Testilizer.getCoverageReport(); if (getCoverageReport) driver = new FirefoxDriver(getProfile()); else driver = new FirefoxDriver(); url = "http://localhost:8888/claroline-1.11.7/index.php?logout=true"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } public static FirefoxProfile getProfile() { FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("network.proxy.http", "localhost"); profile.setPreference("network.proxy.http_port", 3128); profile.setPreference("network.proxy.type", 1); /* use proxy for everything, including localhost */ profile.setPreference("network.proxy.no_proxies_on", ""); return profile; } @After public void tearDown() throws Exception { if (getCoverageReport) ((JavascriptExecutor) driver).executeScript(" if (window.jscoverage_report) {return jscoverage_report('CodeCoverageReport');}"); driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } /* * Test Cases */ @Test public void method56(){ driver.get(url); //From state 0 to state 1 //Eventable{eventType=click, identification=cssSelector button[type="submit"], element=Element{node=[BUTTON: null], tag=BUTTON, text=Enter, attributes={tabindex=3, type=submit}}, source=StateVertexImpl{id=0, name=index}, target=StateVertexImpl{id=1, name=state1}} mutateDOMTree(0); checkState0_OriginalAssertions(); checkState0_ReusedAssertions(); checkState0_GeneratedAssertions(); checkState0_LearnedAssertions(); checkState0_AllAssertions(); checkState0_RandAssertions1(); checkState0_RandAssertions2(); checkState0_RandAssertions3(); checkState0_RandAssertions4(); checkState0_RandAssertions5(); driver.findElement(By.id("login")).clear(); driver.findElement(By.id("login")).sendKeys("nainy"); driver.findElement(By.id("password")).clear(); driver.findElement(By.id("password")).sendKeys("nainy"); driver.findElement(By.cssSelector("button[type=\"submit\"]")).click(); //From state 1 to state 2 //Eventable{eventType=click, identification=text Platform administration, element=Element{node=[A: null], tag=A, text=Platform administration, attributes={href=/claroline-1.11.7/claroline/admin/, target=_top}}, source=StateVertexImpl{id=1, name=state1}, target=StateVertexImpl{id=2, name=state2}} mutateDOMTree(1); checkState1_OriginalAssertions(); checkState1_ReusedAssertions(); checkState1_GeneratedAssertions(); checkState1_LearnedAssertions(); checkState1_AllAssertions(); checkState1_RandAssertions1(); checkState1_RandAssertions2(); checkState1_RandAssertions3(); checkState1_RandAssertions4(); checkState1_RandAssertions5(); driver.findElement(By.linkText("Platform administration")).click(); //From state 2 to state 3 //Eventable{eventType=click, identification=text Manage course categories, element=Element{node=[A: null], tag=A, text=Manage course categories, attributes={href=admin_category.php}}, source=StateVertexImpl{id=2, name=state2}, target=StateVertexImpl{id=3, name=state3}} mutateDOMTree(2); checkState2_OriginalAssertions(); checkState2_ReusedAssertions(); checkState2_GeneratedAssertions(); checkState2_LearnedAssertions(); checkState2_AllAssertions(); checkState2_RandAssertions1(); checkState2_RandAssertions2(); checkState2_RandAssertions3(); checkState2_RandAssertions4(); checkState2_RandAssertions5(); driver.findElement(By.linkText("Manage course categories")).click(); //From state 3 to state 4 //Eventable{eventType=click, identification=text Create a category, element=Element{node=[A: null], tag=A, text=Create a category, attributes={href=/claroline-1.11.7/claroline/admin/admin_category.php?cmd=rqAdd, style=background-image: url(/claroline-1.11.7/web/img/category_new.png?1315407288); background-repeat: no-repeat; background-position: left center; padding-left: 20px;}}, source=StateVertexImpl{id=3, name=state3}, target=StateVertexImpl{id=4, name=state4}} mutateDOMTree(3); checkState3_OriginalAssertions(); checkState3_ReusedAssertions(); checkState3_GeneratedAssertions(); checkState3_LearnedAssertions(); checkState3_AllAssertions(); checkState3_RandAssertions1(); checkState3_RandAssertions2(); checkState3_RandAssertions3(); checkState3_RandAssertions4(); checkState3_RandAssertions5(); driver.findElement(By.linkText("Create a category")).click(); //From state 4 to state 7 //Eventable{eventType=click, identification=cssSelector input[type="submit"], element=Element{node=[INPUT: null], tag=INPUT, text=, attributes={type=submit, value=Ok}}, source=StateVertexImpl{id=4, name=state4}, target=StateVertexImpl{id=7, name=state7}} mutateDOMTree(4); checkState4_OriginalAssertions(); checkState4_ReusedAssertions(); checkState4_GeneratedAssertions(); checkState4_LearnedAssertions(); checkState4_AllAssertions(); checkState4_RandAssertions1(); checkState4_RandAssertions2(); checkState4_RandAssertions3(); checkState4_RandAssertions4(); checkState4_RandAssertions5(); driver.findElement(By.id("category_name")).clear(); driver.findElement(By.id("category_name")).sendKeys("Software Eng"); driver.findElement(By.id("category_code")).clear(); String RandValue = "RND" + new RandomInputValueGenerator().getRandomString(4); driver.findElement(By.id("category_code")).sendKeys(RandValue); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); //From state 7 to state 8 //Eventable{eventType=click, identification=text Logout, element=Element{node=[A: null], tag=A, text=Logout, attributes={href=/claroline-1.11.7/index.php?logout=true, target=_top}}, source=StateVertexImpl{id=7, name=state7}, target=StateVertexImpl{id=8, name=state8}} mutateDOMTree(7); checkState7_OriginalAssertions(); checkState7_ReusedAssertions(); checkState7_GeneratedAssertions(); checkState7_LearnedAssertions(); checkState7_AllAssertions(); checkState7_RandAssertions1(); checkState7_RandAssertions2(); checkState7_RandAssertions3(); checkState7_RandAssertions4(); checkState7_RandAssertions5(); driver.findElement(By.linkText("Logout")).click(); //Sink node at state 8 mutateDOMTree(8); checkState8_OriginalAssertions(); checkState8_ReusedAssertions(); checkState8_GeneratedAssertions(); checkState8_LearnedAssertions(); checkState8_AllAssertions(); checkState8_RandAssertions1(); checkState8_RandAssertions2(); checkState8_RandAssertions3(); checkState8_RandAssertions4(); checkState8_RandAssertions5(); } public void checkState0_OriginalAssertions(){ } public void checkState0_ReusedAssertions(){ } public void checkState0_GeneratedAssertions(){ } public void checkState0_LearnedAssertions(){ } public void checkState0_AllAssertions(){ } public void checkState0_RandAssertions1(){ } public void checkState0_RandAssertions2(){ } public void checkState0_RandAssertions3(){ } public void checkState0_RandAssertions4(){ } public void checkState0_RandAssertions5(){ } public void checkState1_OriginalAssertions(){ } public void checkState1_ReusedAssertions(){ } public void checkState1_GeneratedAssertions(){ } public void checkState1_LearnedAssertions(){ } public void checkState1_AllAssertions(){ } public void checkState1_RandAssertions1(){ } public void checkState1_RandAssertions2(){ } public void checkState1_RandAssertions3(){ } public void checkState1_RandAssertions4(){ } public void checkState1_RandAssertions5(){ } public void checkState2_OriginalAssertions(){ } public void checkState2_ReusedAssertions(){ } public void checkState2_GeneratedAssertions(){ } public void checkState2_LearnedAssertions(){ } public void checkState2_AllAssertions(){ } public void checkState2_RandAssertions1(){ } public void checkState2_RandAssertions2(){ } public void checkState2_RandAssertions3(){ } public void checkState2_RandAssertions4(){ } public void checkState2_RandAssertions5(){ } public void checkState3_OriginalAssertions(){ } public void checkState3_ReusedAssertions(){ } public void checkState3_GeneratedAssertions(){ } public void checkState3_LearnedAssertions(){ } public void checkState3_AllAssertions(){ } public void checkState3_RandAssertions1(){ } public void checkState3_RandAssertions2(){ } public void checkState3_RandAssertions3(){ } public void checkState3_RandAssertions4(){ } public void checkState3_RandAssertions5(){ } public void checkState4_OriginalAssertions(){ } public void checkState4_ReusedAssertions(){ } public void checkState4_GeneratedAssertions(){ } public void checkState4_LearnedAssertions(){ } public void checkState4_AllAssertions(){ } public void checkState4_RandAssertions1(){ } public void checkState4_RandAssertions2(){ } public void checkState4_RandAssertions3(){ } public void checkState4_RandAssertions4(){ } public void checkState4_RandAssertions5(){ } public void checkState7_OriginalAssertions(){ if(!(driver.findElement(By.cssSelector("div.claroDialogBox.boxSuccess")).getText().matches("^[\\s\\S]*Category created[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion } public void checkState7_ReusedAssertions(){ } public void checkState7_GeneratedAssertions(){ } public void checkState7_LearnedAssertions(){ } public void checkState7_AllAssertions(){ if(!(driver.findElement(By.cssSelector("div.claroDialogBox.boxSuccess")).getText().matches("^[\\s\\S]*Category created[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion } public void checkState7_RandAssertions1(){ } public void checkState7_RandAssertions2(){ } public void checkState7_RandAssertions3(){ } public void checkState7_RandAssertions4(){ } public void checkState7_RandAssertions5(){ } public void checkState8_OriginalAssertions(){ } public void checkState8_ReusedAssertions(){ } public void checkState8_GeneratedAssertions(){ } public void checkState8_LearnedAssertions(){ } public void checkState8_AllAssertions(){ } public void checkState8_RandAssertions1(){ } public void checkState8_RandAssertions2(){ } public void checkState8_RandAssertions3(){ } public void checkState8_RandAssertions4(){ } public void checkState8_RandAssertions5(){ } /* * Auxiliary methods */ private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } private boolean isElementPatternTagPresent(DOMElement parent, DOMElement element, ArrayList<DOMElement> children) { try { String source = driver.getPageSource(); Document dom = DomUtils.asDocument(source); NodeList nodeList = dom.getElementsByTagName(element.getTagName()); org.w3c.dom.Element sourceElement = null; for (int i = 0; i < nodeList.getLength(); i++){ sourceElement = (org.w3c.dom.Element) nodeList.item(i); // check parent node's tag and attributes String parentTagName = sourceElement.getParentNode().getNodeName(); if (!parentTagName.equals(parent.getTagName())) continue; // check children nodes' tags HashSet<String> childrenTagNameFromDOM = new HashSet<String>(); for (int j=0; j<sourceElement.getChildNodes().getLength();j++) childrenTagNameFromDOM.add(sourceElement.getChildNodes().item(j).getNodeName()); HashSet<String> childrenTagNameToTest = new HashSet<String>(); for (int k=0; k<children.size();k++) childrenTagNameToTest.add(children.get(k).getTagName()); if (!childrenTagNameToTest.equals(childrenTagNameFromDOM)) continue; return true; } } catch (IOException e) { e.printStackTrace(); } return false; } private boolean isElementPatternFullPresent(DOMElement parent, DOMElement element, ArrayList<DOMElement> children) { try { String source = driver.getPageSource(); Document dom = DomUtils.asDocument(source); NodeList nodeList = dom.getElementsByTagName(element.getTagName()); org.w3c.dom.Element sourceElement = null; for (int i = 0; i < nodeList.getLength(); i++){ // check node's attributes sourceElement = (org.w3c.dom.Element) nodeList.item(i); NamedNodeMap elementAttList = sourceElement.getAttributes(); HashSet<String> elemetAtts = new HashSet<String>(); for (int j = 0; j < elementAttList.getLength(); j++) elemetAtts.add(elementAttList.item(j).getNodeName() + "=\"" + elementAttList.item(j).getNodeValue() + "\""); if (!element.getAttributes().equals(elemetAtts)) continue; // check parent node's tag and attributes String parentTagName = sourceElement.getParentNode().getNodeName(); if (!parentTagName.equals(parent.getTagName())) continue; NamedNodeMap parentAttList = sourceElement.getParentNode().getAttributes(); HashSet<String> parentAtts = new HashSet<String>(); for (int j = 0; j < parentAttList.getLength(); j++) parentAtts.add(parentAttList.item(j).getNodeName() + "=\"" + parentAttList.item(j).getNodeValue() + "\""); if (!parent.getAttributes().equals(parentAtts)) continue; // check children nodes' tags HashSet<String> childrenTagNameFromDOM = new HashSet<String>(); for (int j=0; j<sourceElement.getChildNodes().getLength();j++) childrenTagNameFromDOM.add(sourceElement.getChildNodes().item(j).getNodeName()); HashSet<String> childrenTagNameToTest = new HashSet<String>(); for (int k=0; k<children.size();k++) childrenTagNameToTest.add(children.get(k).getTagName()); if (!childrenTagNameToTest.equals(childrenTagNameFromDOM)) continue; // check children nodes' attributes HashSet<HashSet<String>> childrenAttsFromDOM = new HashSet<HashSet<String>>(); for (int j=0; j<sourceElement.getChildNodes().getLength();j++){ NamedNodeMap childAttListFromDOM = sourceElement.getChildNodes().item(j).getAttributes(); HashSet<String> childAtts = new HashSet<String>(); if (childAttListFromDOM!=null) for (int k = 0; k < childAttListFromDOM.getLength(); k++) childAtts.add(childAttListFromDOM.item(k).getNodeName() + "=\"" + childAttListFromDOM.item(k).getNodeValue() + "\""); childrenAttsFromDOM.add(childAtts); } HashSet<HashSet<String>> childrenAttsToTest = new HashSet<HashSet<String>>(); for (int k=0; k<children.size();k++) childrenAttsToTest.add(children.get(k).getAttributes()); if (!childrenAttsToTest.equals(childrenAttsFromDOM)) continue; return true; } } catch (IOException e) { e.printStackTrace(); } return false; } private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } public class DOMElement { private String tagName; private String textContent; private HashSet<String> attributes = new HashSet<String>(); public DOMElement(String tagName, String textContent, ArrayList<String> attributes){ this.tagName = tagName; this.textContent = textContent; if (attributes.get(0)!="") for (int i=0; i<attributes.size();i++) this.attributes.add(attributes.get(i)); } public String getTagName() { return tagName; } public String getTextContent() { return textContent; } public HashSet<String> getAttributes() { return attributes; } } private void mutateDOMTree(int stateID){ // execute JavaScript code to mutate DOM String code = com.crawljax.plugins.testilizer.Testilizer.mutateDOMTreeCode(stateID); if (code!= null){ long RandomlySelectedDOMElementID = (long) ((JavascriptExecutor)driver).executeScript(code); int MutationOperatorCode = com.crawljax.plugins.testilizer.Testilizer.MutationOperatorCode; int StateToBeMutated = com.crawljax.plugins.testilizer.Testilizer.StateToBeMutated; com.crawljax.plugins.testilizer.Testilizer.SelectedRandomElementInDOM[MutationOperatorCode][StateToBeMutated] = (int) RandomlySelectedDOMElementID; } } }
/* * Copyright 2017-2022 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.transfer.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Each step type has its own <code>StepDetails</code> structure. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CopyStepDetails" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CopyStepDetails implements Serializable, Cloneable, StructuredPojo { /** * <p> * The name of the step, used as an identifier. * </p> */ private String name; /** * <p> * Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. * </p> */ private InputFileLocation destinationFileLocation; /** * <p> * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * </p> */ private String overwriteExisting; /** * <p> * Specifies which file to use as input to the workflow step: either the output from the previous step, or the * originally uploaded file for the workflow. * </p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow step uses * the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> * </ul> */ private String sourceFileLocation; /** * <p> * The name of the step, used as an identifier. * </p> * * @param name * The name of the step, used as an identifier. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the step, used as an identifier. * </p> * * @return The name of the step, used as an identifier. */ public String getName() { return this.name; } /** * <p> * The name of the step, used as an identifier. * </p> * * @param name * The name of the step, used as an identifier. * @return Returns a reference to this object so that method calls can be chained together. */ public CopyStepDetails withName(String name) { setName(name); return this; } /** * <p> * Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. * </p> * * @param destinationFileLocation * Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. */ public void setDestinationFileLocation(InputFileLocation destinationFileLocation) { this.destinationFileLocation = destinationFileLocation; } /** * <p> * Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. * </p> * * @return Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. */ public InputFileLocation getDestinationFileLocation() { return this.destinationFileLocation; } /** * <p> * Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. * </p> * * @param destinationFileLocation * Specifies the location for the file being copied. Only applicable for Copy type workflow steps. Use * <code>${Transfer:username}</code> in this field to parametrize the destination prefix by username. * @return Returns a reference to this object so that method calls can be chained together. */ public CopyStepDetails withDestinationFileLocation(InputFileLocation destinationFileLocation) { setDestinationFileLocation(destinationFileLocation); return this; } /** * <p> * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * </p> * * @param overwriteExisting * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * @see OverwriteExisting */ public void setOverwriteExisting(String overwriteExisting) { this.overwriteExisting = overwriteExisting; } /** * <p> * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * </p> * * @return A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * @see OverwriteExisting */ public String getOverwriteExisting() { return this.overwriteExisting; } /** * <p> * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * </p> * * @param overwriteExisting * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see OverwriteExisting */ public CopyStepDetails withOverwriteExisting(String overwriteExisting) { setOverwriteExisting(overwriteExisting); return this; } /** * <p> * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * </p> * * @param overwriteExisting * A flag that indicates whether or not to overwrite an existing file of the same name. The default is * <code>FALSE</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see OverwriteExisting */ public CopyStepDetails withOverwriteExisting(OverwriteExisting overwriteExisting) { this.overwriteExisting = overwriteExisting.toString(); return this; } /** * <p> * Specifies which file to use as input to the workflow step: either the output from the previous step, or the * originally uploaded file for the workflow. * </p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow step uses * the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> * </ul> * * @param sourceFileLocation * Specifies which file to use as input to the workflow step: either the output from the previous step, or * the originally uploaded file for the workflow.</p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow * step uses the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> */ public void setSourceFileLocation(String sourceFileLocation) { this.sourceFileLocation = sourceFileLocation; } /** * <p> * Specifies which file to use as input to the workflow step: either the output from the previous step, or the * originally uploaded file for the workflow. * </p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow step uses * the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> * </ul> * * @return Specifies which file to use as input to the workflow step: either the output from the previous step, or * the originally uploaded file for the workflow.</p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow * step uses the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> */ public String getSourceFileLocation() { return this.sourceFileLocation; } /** * <p> * Specifies which file to use as input to the workflow step: either the output from the previous step, or the * originally uploaded file for the workflow. * </p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow step uses * the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> * </ul> * * @param sourceFileLocation * Specifies which file to use as input to the workflow step: either the output from the previous step, or * the originally uploaded file for the workflow.</p> * <ul> * <li> * <p> * Enter <code>${previous.file}</code> to use the previous file as the input. In this case, this workflow * step uses the output file from the previous workflow step as input. This is the default value. * </p> * </li> * <li> * <p> * Enter <code>${original.file}</code> to use the originally-uploaded file location as input for this step. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public CopyStepDetails withSourceFileLocation(String sourceFileLocation) { setSourceFileLocation(sourceFileLocation); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getDestinationFileLocation() != null) sb.append("DestinationFileLocation: ").append(getDestinationFileLocation()).append(","); if (getOverwriteExisting() != null) sb.append("OverwriteExisting: ").append(getOverwriteExisting()).append(","); if (getSourceFileLocation() != null) sb.append("SourceFileLocation: ").append(getSourceFileLocation()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CopyStepDetails == false) return false; CopyStepDetails other = (CopyStepDetails) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getDestinationFileLocation() == null ^ this.getDestinationFileLocation() == null) return false; if (other.getDestinationFileLocation() != null && other.getDestinationFileLocation().equals(this.getDestinationFileLocation()) == false) return false; if (other.getOverwriteExisting() == null ^ this.getOverwriteExisting() == null) return false; if (other.getOverwriteExisting() != null && other.getOverwriteExisting().equals(this.getOverwriteExisting()) == false) return false; if (other.getSourceFileLocation() == null ^ this.getSourceFileLocation() == null) return false; if (other.getSourceFileLocation() != null && other.getSourceFileLocation().equals(this.getSourceFileLocation()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getDestinationFileLocation() == null) ? 0 : getDestinationFileLocation().hashCode()); hashCode = prime * hashCode + ((getOverwriteExisting() == null) ? 0 : getOverwriteExisting().hashCode()); hashCode = prime * hashCode + ((getSourceFileLocation() == null) ? 0 : getSourceFileLocation().hashCode()); return hashCode; } @Override public CopyStepDetails clone() { try { return (CopyStepDetails) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.transfer.model.transform.CopyStepDetailsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package com.pg85.otg.config.io; import com.pg85.otg.config.ConfigFunction; import com.pg85.otg.config.ErroredFunction; import com.pg85.otg.config.io.RawSettingValue.ValueType; import com.pg85.otg.config.settingType.Setting; import com.pg85.otg.exceptions.InvalidConfigException; import com.pg85.otg.interfaces.ILogger; import com.pg85.otg.interfaces.IMaterialReader; import com.pg85.otg.interfaces.IPluginConfig; import com.pg85.otg.util.helpers.StringHelper; import com.pg85.otg.util.logging.LogCategory; import com.pg85.otg.util.logging.LogLevel; import java.text.MessageFormat; import java.util.*; /** * The default implementation of {@link SettingsMap}. */ public final class SimpleSettingsMap implements SettingsMap { private final List<RawSettingValue> configFunctions; private SettingsMap fallback; private final String name; /** * Stores all the settings. Settings like Name:Value or Name=Value are * stored as name. Because this is a linked hashmap, * you're guaranteed that the lines will be read in order when iterating * over this map. */ private final Map<String, RawSettingValue> settingsCache; private int dummyKeyIndex = 0; /** * Creates a new settings reader. * @param name Name of the config file, like "WorldConfig" or "Taiga". * //@param isNewConfig True if this config is newly created. */ public SimpleSettingsMap(String name) { this.name = name; this.settingsCache = new LinkedHashMap<String, RawSettingValue>(); this.configFunctions = new ArrayList<RawSettingValue>(); } /** * Returns a dummy key suitable as a key for {@link #settingsCache}. * * <p>Settings are indexed by their name in {@link #settingsCache}, but what * are functions and titles indexed by? There are no useful options here, * so we just use a dummy key. * @return A dummy key. */ private String nextDummyKey() { dummyKeyIndex++; return "__key" + dummyKeyIndex; } @Override public void addConfigFunctions(Collection<? extends ConfigFunction<?>> functions) { for (ConfigFunction<?> function : functions) { RawSettingValue value = RawSettingValue.create(ValueType.FUNCTION, function.toString()); configFunctions.add(value); settingsCache.put(nextDummyKey(), value); } } @Override public <T> List<ConfigFunction<T>> getConfigFunctions(T holder, IConfigFunctionProvider biomeResourcesManager, ILogger logger, IMaterialReader materialReader) { return this.getConfigFunctions(holder, biomeResourcesManager, logger, materialReader, null, null); } @Override public <T> List<ConfigFunction<T>> getConfigFunctions(T holder, IConfigFunctionProvider biomeResourcesManager, ILogger logger, IMaterialReader materialReader, String presetFolderName, IPluginConfig conf) { List<ConfigFunction<T>> result = new ArrayList<ConfigFunction<T>>(configFunctions.size()); for (RawSettingValue configFunctionLine : configFunctions) { String configFunctionString = configFunctionLine.getRawValue(); int bracketIndex = configFunctionString.indexOf('('); String functionName = configFunctionString.substring(0, bracketIndex); String parameters = configFunctionString.substring(bracketIndex + 1, configFunctionString.length() - 1); List<String> args = Arrays.asList(StringHelper.readCommaSeperatedString(parameters)); ConfigFunction<T> function = biomeResourcesManager.getConfigFunction(functionName, holder, args, logger, materialReader); if (function == null) { // Function is in wrong config file, // allowed for config file inheritance. continue; } result.add(function); if (conf == null || presetFolderName == null) { if (logger.getLogCategoryEnabled(LogCategory.CONFIGS) && function instanceof ErroredFunction) { logger.log( LogLevel.ERROR, LogCategory.CONFIGS, MessageFormat.format( "Invalid resource {0} in {1} on line {2}: {3}", functionName, this.name, configFunctionLine.getLineNumber(), ((ErroredFunction<?>)function).error ) ); } } else { if (logger.getLogCategoryEnabled(LogCategory.CONFIGS) && function instanceof ErroredFunction && logger.canLogForPreset(presetFolderName)) { logger.log( LogLevel.ERROR, LogCategory.CONFIGS, MessageFormat.format( "Invalid resource {0} in {1} on line {2}: {3}", functionName, this.name, configFunctionLine.getLineNumber(), ((ErroredFunction<?>)function).error ) ); } } } return result; } @Override public String getName() { return name; } @Override public Collection<RawSettingValue> getRawSettings() { return Collections.unmodifiableCollection(this.settingsCache.values()); } @Override public <S> S getSetting(Setting<S> setting, ILogger logger) { return getSetting(setting, logger, null); } @Override public <S> S getSetting(Setting<S> setting, ILogger logger, IMaterialReader materialReader) { return getSetting(setting, setting.getDefaultValue(materialReader), logger, materialReader); } @Override public <S> S getSetting(Setting<S> setting, S defaultValue, ILogger logger) { return getSetting(setting, defaultValue, logger, null); } @Override public <S> S getSetting(Setting<S> setting, S defaultValue, ILogger logger, IMaterialReader materialReader) { // Try reading the setting from the file RawSettingValue stringWithLineNumber = this.settingsCache.get(setting.getName().toLowerCase()); if (stringWithLineNumber != null) { String stringValue = stringWithLineNumber.getRawValue().split(":", 2)[1].trim(); try { return setting.read(stringValue, materialReader); } catch (InvalidConfigException e) { if(logger.getLogCategoryEnabled(LogCategory.CONFIGS)) { logger.log( LogLevel.ERROR, LogCategory.CONFIGS, MessageFormat.format( "The value \"{0}\" is not valid for the setting {1} in {2} on line {3}: {4}", stringValue, setting, name, stringWithLineNumber.getLineNumber(), e.getMessage() ) ); } } } // Try the fallback if (fallback != null) { return fallback.getSetting(setting, defaultValue, logger, materialReader); } // Return default value return defaultValue; } @Override public boolean hasSetting(Setting<?> setting) { if (settingsCache.containsKey(setting.getName().toLowerCase())) { return true; } if (fallback != null) { return fallback.hasSetting(setting); } return false; } @Override public <S> void putSetting(Setting<S> setting, S value, String... comments) { RawSettingValue settingValue = RawSettingValue.ofPlainSetting(setting, value).withComments(comments); this.settingsCache.put(setting.getName().toLowerCase(), settingValue); } @Override public void renameOldSetting(String oldValue, Setting<?> newValue) { if (this.settingsCache.containsKey(oldValue.toLowerCase())) { this.settingsCache.put(newValue.getName().toLowerCase(), this.settingsCache.get(oldValue.toLowerCase())); } } @Override public void setFallback(SettingsMap reader) { this.fallback = reader; } @Override public void addRawSetting(RawSettingValue value) { switch (value.getType()) { case PLAIN_SETTING: String[] split = value.getRawValue().split(":", 2); String settingName = split[0].toLowerCase().trim(); this.settingsCache.put(settingName, value); break; case FUNCTION: this.configFunctions.add(value); this.settingsCache.put(nextDummyKey(), value); break; default: this.settingsCache.put(nextDummyKey(), value); break; } } @Override public void smallTitle(String title, String... comments) { this.settingsCache.put(nextDummyKey(), RawSettingValue.create(ValueType.SMALL_TITLE, title).withComments(comments)); } @Override public void header1(String title, String... comments) { this.settingsCache.put(nextDummyKey(), RawSettingValue.create(ValueType.BIG_TITLE, title).withComments(comments)); } @Override public void header2(String title, String... comments) { this.settingsCache.put(nextDummyKey(), RawSettingValue.create(ValueType.BIG_TITLE_2, title).withComments(comments)); } @Override public String toString() { return "SimpleSettingsMap [name=" + name + ", fallback=" + fallback + "]"; } }
/* * 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.calcite.util; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * ReflectVisitorTest tests {@link ReflectUtil#invokeVisitor} and * {@link ReflectiveVisitor} and provides a contrived example of how to use * them. */ class ReflectVisitorTest { /** * Tests CarelessNumberNegater. */ @Test void testCarelessNegater() { NumberNegater negater = new CarelessNumberNegater(); Number result; // verify that negater is capable of handling integers result = negater.negate(5); assertEquals( -5, result.intValue()); } /** * Tests CarefulNumberNegater. */ @Test void testCarefulNegater() { NumberNegater negater = new CarefulNumberNegater(); Number result; // verify that negater is capable of handling integers, // and that result comes back with same type result = negater.negate(5); assertEquals( -5, result.intValue()); assertTrue(result instanceof Integer); // verify that negater is capable of handling longs; // even though it doesn't provide an explicit implementation, // it should inherit the one from CarelessNumberNegater result = negater.negate(5L); assertEquals( -5L, result.longValue()); } /** * Tests CluelessNumberNegater. */ @Test void testCluelessNegater() { NumberNegater negater = new CluelessNumberNegater(); Number result; // verify that negater is capable of handling shorts, // and that result comes back with same type result = negater.negate((short) 5); assertEquals( -5, result.shortValue()); assertTrue(result instanceof Short); // verify that negater is NOT capable of handling integers result = negater.negate(5); assertEquals(null, result); } /** * Tests for ambiguity detection in method lookup. */ @Test void testAmbiguity() { NumberNegater negater = new IndecisiveNumberNegater(); Number result; try { result = negater.negate(new AmbiguousNumber()); } catch (IllegalArgumentException ex) { // expected assertTrue(ex.getMessage().contains("ambiguity")); return; } fail("Expected failure due to ambiguity"); } /** * Tests that ambiguity detection in method lookup does not kick in when a * better match is available. */ @Test void testNonAmbiguity() { NumberNegater negater = new SomewhatIndecisiveNumberNegater(); Number result; result = negater.negate(new SomewhatAmbiguousNumber()); assertEquals( 0.0, result.doubleValue(), 0.001); } //~ Inner Interfaces ------------------------------------------------------- /** * An interface for introducing ambiguity into the class hierarchy. */ public interface CrunchableNumber { } /** * An interface for introducing ambiguity into the class hierarchy. */ public interface FudgeableNumber { } /** Sub-interface of {@link FudgeableNumber}. */ public interface DiceyNumber extends FudgeableNumber { } //~ Inner Classes ---------------------------------------------------------- /** * NumberNegater defines the abstract base for a computation object capable * of negating an arbitrary number. Subclasses implement the computation by * publishing methods with the signature "void visit(X x)" where X is a * subclass of Number. */ public abstract class NumberNegater implements ReflectiveVisitor { protected Number result; private final ReflectiveVisitDispatcher<NumberNegater, Number> dispatcher = ReflectUtil.createDispatcher( NumberNegater.class, Number.class); /** * Negates the given number. * * @param n the number to be negated * @return the negated result; not guaranteed to be the same concrete * type as n; null is returned if n's type wasn't handled */ public Number negate(Number n) { // we specify Number.class as the hierarchy root so // that extraneous visit methods are ignored result = null; dispatcher.invokeVisitor( this, n, "visit"); return result; } /** * Negates the given number without using a dispatcher object to cache * applicable methods. The results should be the same as * {@link #negate(Number)}. * * @param n the number to be negated * @return the negated result; not guaranteed to be the same concrete * type as n; null is returned if n's type wasn't handled */ public Number negateWithoutDispatcher(Number n) { // we specify Number.class as the hierarchy root so // that extraneous visit methods are ignored result = null; ReflectUtil.invokeVisitor( this, n, Number.class, "visit"); return result; } } /** * CarelessNumberNegater implements NumberNegater in a careless fashion by * converting its input to a double and then negating that. This can lose * precision for types such as BigInteger. */ public class CarelessNumberNegater extends NumberNegater { public void visit(Number n) { result = -n.doubleValue(); } } /** * CarefulNumberNegater implements NumberNegater in a careful fashion by * providing overloads for each known subclass of Number and returning the * same subclass for the result. Extends CarelessNumberNegater so that it * can still handle unknown types of Number. */ public class CarefulNumberNegater extends CarelessNumberNegater { public void visit(Integer i) { result = -i; assert result instanceof Integer; } public void visit(Short s) { result = -s; assert result instanceof Short; } // ... imagine implementations for other Number subclasses here ... } /** * CluelessNumberNegater implements NumberNegater in a very broken fashion; * does the right thing for Shorts, but attempts to override visit(Object). * This is just here for testing the hierarchyRoot parameter of * invokeVisitor. */ public class CluelessNumberNegater extends NumberNegater { public void visit(Object obj) { result = 42; } public void visit(Short s) { result = (short) -s; assert result instanceof Short; } } /** * IndecisiveNumberNegater implements NumberNegater in such a way that it * doesn't know what to do when presented with an AmbiguousNumber. */ public class IndecisiveNumberNegater extends NumberNegater { public void visit(CrunchableNumber n) { } public void visit(FudgeableNumber n) { } } /** * SomewhatIndecisiveNumberNegater implements NumberNegater in such a way * that it knows what to do when presented with a SomewhatAmbiguousNumber. */ public class SomewhatIndecisiveNumberNegater extends NumberNegater { public void visit(FudgeableNumber n) { } public void visit(AmbiguousNumber n) { result = -n.doubleValue(); assert result instanceof Double; } } /** * A class inheriting two interfaces, leading to ambiguity. */ public class AmbiguousNumber extends BigDecimal implements CrunchableNumber, FudgeableNumber { AmbiguousNumber() { super("0"); } } /** * A class inheriting a root interface (FudgeableNumber) two different ways, * which should not lead to ambiguity in some cases. */ public class SomewhatAmbiguousNumber extends AmbiguousNumber implements DiceyNumber { } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.geometry.partitioning; import org.apache.commons.math3.geometry.Space; /** This class is a factory for {@link Region}. * @param <S> Type of the space. * @version $Id: RegionFactory.java 1416643 2012-12-03 19:37:14Z tn $ * @since 3.0 */ public class RegionFactory<S extends Space> { /** Visitor removing internal nodes attributes. */ private final NodesCleaner nodeCleaner; /** Simple constructor. */ public RegionFactory() { nodeCleaner = new NodesCleaner(); } /** Build a convex region from a collection of bounding hyperplanes. * @param hyperplanes collection of bounding hyperplanes * @return a new convex region, or null if the collection is empty */ public Region<S> buildConvex(final Hyperplane<S> ... hyperplanes) { if ((hyperplanes == null) || (hyperplanes.length == 0)) { return null; } // use the first hyperplane to build the right class final Region<S> region = hyperplanes[0].wholeSpace(); // chop off parts of the space BSPTree<S> node = region.getTree(false); node.setAttribute(Boolean.TRUE); for (final Hyperplane<S> hyperplane : hyperplanes) { if (node.insertCut(hyperplane)) { node.setAttribute(null); node.getPlus().setAttribute(Boolean.FALSE); node = node.getMinus(); node.setAttribute(Boolean.TRUE); } } return region; } /** Compute the union of two regions. * @param region1 first region (will be unusable after the operation as * parts of it will be reused in the new region) * @param region2 second region (will be unusable after the operation as * parts of it will be reused in the new region) * @return a new region, result of {@code region1 union region2} */ public Region<S> union(final Region<S> region1, final Region<S> region2) { final BSPTree<S> tree = region1.getTree(false).merge(region2.getTree(false), new UnionMerger()); tree.visit(nodeCleaner); return region1.buildNew(tree); } /** Compute the intersection of two regions. * @param region1 first region (will be unusable after the operation as * parts of it will be reused in the new region) * @param region2 second region (will be unusable after the operation as * parts of it will be reused in the new region) * @return a new region, result of {@code region1 intersection region2} */ public Region<S> intersection(final Region<S> region1, final Region<S> region2) { final BSPTree<S> tree = region1.getTree(false).merge(region2.getTree(false), new IntersectionMerger()); tree.visit(nodeCleaner); return region1.buildNew(tree); } /** Compute the symmetric difference (exclusive or) of two regions. * @param region1 first region (will be unusable after the operation as * parts of it will be reused in the new region) * @param region2 second region (will be unusable after the operation as * parts of it will be reused in the new region) * @return a new region, result of {@code region1 xor region2} */ public Region<S> xor(final Region<S> region1, final Region<S> region2) { final BSPTree<S> tree = region1.getTree(false).merge(region2.getTree(false), new XorMerger()); tree.visit(nodeCleaner); return region1.buildNew(tree); } /** Compute the difference of two regions. * @param region1 first region (will be unusable after the operation as * parts of it will be reused in the new region) * @param region2 second region (will be unusable after the operation as * parts of it will be reused in the new region) * @return a new region, result of {@code region1 minus region2} */ public Region<S> difference(final Region<S> region1, final Region<S> region2) { final BSPTree<S> tree = region1.getTree(false).merge(region2.getTree(false), new DifferenceMerger()); tree.visit(nodeCleaner); return region1.buildNew(tree); } /** Get the complement of the region (exchanged interior/exterior). * @param region region to complement, it will not modified, a new * region independent region will be built * @return a new region, complement of the specified one */ public Region<S> getComplement(final Region<S> region) { return region.buildNew(recurseComplement(region.getTree(false))); } /** Recursively build the complement of a BSP tree. * @param node current node of the original tree * @return new tree, complement of the node */ private BSPTree<S> recurseComplement(final BSPTree<S> node) { if (node.getCut() == null) { return new BSPTree<S>(((Boolean) node.getAttribute()) ? Boolean.FALSE : Boolean.TRUE); } @SuppressWarnings("unchecked") BoundaryAttribute<S> attribute = (BoundaryAttribute<S>) node.getAttribute(); if (attribute != null) { final SubHyperplane<S> plusOutside = (attribute.getPlusInside() == null) ? null : attribute.getPlusInside().copySelf(); final SubHyperplane<S> plusInside = (attribute.getPlusOutside() == null) ? null : attribute.getPlusOutside().copySelf(); attribute = new BoundaryAttribute<S>(plusOutside, plusInside); } return new BSPTree<S>(node.getCut().copySelf(), recurseComplement(node.getPlus()), recurseComplement(node.getMinus()), attribute); } /** BSP tree leaf merger computing union of two regions. */ private class UnionMerger implements BSPTree.LeafMerger<S> { /** {@inheritDoc} */ public BSPTree<S> merge(final BSPTree<S> leaf, final BSPTree<S> tree, final BSPTree<S> parentTree, final boolean isPlusChild, final boolean leafFromInstance) { if ((Boolean) leaf.getAttribute()) { // the leaf node represents an inside cell leaf.insertInTree(parentTree, isPlusChild); return leaf; } // the leaf node represents an outside cell tree.insertInTree(parentTree, isPlusChild); return tree; } } /** BSP tree leaf merger computing union of two regions. */ private class IntersectionMerger implements BSPTree.LeafMerger<S> { /** {@inheritDoc} */ public BSPTree<S> merge(final BSPTree<S> leaf, final BSPTree<S> tree, final BSPTree<S> parentTree, final boolean isPlusChild, final boolean leafFromInstance) { if ((Boolean) leaf.getAttribute()) { // the leaf node represents an inside cell tree.insertInTree(parentTree, isPlusChild); return tree; } // the leaf node represents an outside cell leaf.insertInTree(parentTree, isPlusChild); return leaf; } } /** BSP tree leaf merger computing union of two regions. */ private class XorMerger implements BSPTree.LeafMerger<S> { /** {@inheritDoc} */ public BSPTree<S> merge(final BSPTree<S> leaf, final BSPTree<S> tree, final BSPTree<S> parentTree, final boolean isPlusChild, final boolean leafFromInstance) { BSPTree<S> t = tree; if ((Boolean) leaf.getAttribute()) { // the leaf node represents an inside cell t = recurseComplement(t); } t.insertInTree(parentTree, isPlusChild); return t; } } /** BSP tree leaf merger computing union of two regions. */ private class DifferenceMerger implements BSPTree.LeafMerger<S> { /** {@inheritDoc} */ public BSPTree<S> merge(final BSPTree<S> leaf, final BSPTree<S> tree, final BSPTree<S> parentTree, final boolean isPlusChild, final boolean leafFromInstance) { if ((Boolean) leaf.getAttribute()) { // the leaf node represents an inside cell final BSPTree<S> argTree = recurseComplement(leafFromInstance ? tree : leaf); argTree.insertInTree(parentTree, isPlusChild); return argTree; } // the leaf node represents an outside cell final BSPTree<S> instanceTree = leafFromInstance ? leaf : tree; instanceTree.insertInTree(parentTree, isPlusChild); return instanceTree; } } /** Visitor removing internal nodes attributes. */ private class NodesCleaner implements BSPTreeVisitor<S> { /** {@inheritDoc} */ public Order visitOrder(final BSPTree<S> node) { return Order.PLUS_SUB_MINUS; } /** {@inheritDoc} */ public void visitInternalNode(final BSPTree<S> node) { node.setAttribute(null); } /** {@inheritDoc} */ public void visitLeafNode(final BSPTree<S> node) { } } }
/** */ package gluemodel.CIM.IEC61970.Informative.InfWork.impl; import gluemodel.CIM.IEC61968.Common.Status; import gluemodel.CIM.IEC61970.Core.impl.IdentifiedObjectImpl; import gluemodel.CIM.IEC61970.Informative.InfERPSupport.ErpBomItemData; import gluemodel.CIM.IEC61970.Informative.InfERPSupport.InfERPSupportPackage; import gluemodel.CIM.IEC61970.Informative.InfGMLSupport.Diagram; import gluemodel.CIM.IEC61970.Informative.InfGMLSupport.InfGMLSupportPackage; import gluemodel.CIM.IEC61970.Informative.InfWork.ConditionFactor; import gluemodel.CIM.IEC61970.Informative.InfWork.Design; import gluemodel.CIM.IEC61970.Informative.InfWork.DesignLocation; import gluemodel.CIM.IEC61970.Informative.InfWork.DesignLocationCU; import gluemodel.CIM.IEC61970.Informative.InfWork.InfWorkPackage; import gluemodel.CIM.IEC61970.Informative.InfWork.MaterialItem; import gluemodel.CIM.IEC61970.Informative.InfWork.MiscCostItem; import gluemodel.CIM.IEC61970.Informative.InfWork.WorkLocation; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; 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.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Design Location</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getSpanLength <em>Span Length</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getConditionFactors <em>Condition Factors</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getMaterialItems <em>Material Items</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getStatus <em>Status</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getDiagrams <em>Diagrams</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getWorkLocations <em>Work Locations</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getDesignLocationCUs <em>Design Location CUs</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getDesigns <em>Designs</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getErpBomItemDatas <em>Erp Bom Item Datas</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignLocationImpl#getMiscCostItems <em>Misc Cost Items</em>}</li> * </ul> * * @generated */ public class DesignLocationImpl extends IdentifiedObjectImpl implements DesignLocation { /** * The default value of the '{@link #getSpanLength() <em>Span Length</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSpanLength() * @generated * @ordered */ protected static final float SPAN_LENGTH_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getSpanLength() <em>Span Length</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSpanLength() * @generated * @ordered */ protected float spanLength = SPAN_LENGTH_EDEFAULT; /** * The cached value of the '{@link #getConditionFactors() <em>Condition Factors</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConditionFactors() * @generated * @ordered */ protected EList<ConditionFactor> conditionFactors; /** * The cached value of the '{@link #getMaterialItems() <em>Material Items</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaterialItems() * @generated * @ordered */ protected EList<MaterialItem> materialItems; /** * The cached value of the '{@link #getStatus() <em>Status</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected Status status; /** * The cached value of the '{@link #getDiagrams() <em>Diagrams</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDiagrams() * @generated * @ordered */ protected EList<Diagram> diagrams; /** * The cached value of the '{@link #getWorkLocations() <em>Work Locations</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWorkLocations() * @generated * @ordered */ protected EList<WorkLocation> workLocations; /** * The cached value of the '{@link #getDesignLocationCUs() <em>Design Location CUs</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDesignLocationCUs() * @generated * @ordered */ protected EList<DesignLocationCU> designLocationCUs; /** * The cached value of the '{@link #getDesigns() <em>Designs</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDesigns() * @generated * @ordered */ protected EList<Design> designs; /** * The cached value of the '{@link #getErpBomItemDatas() <em>Erp Bom Item Datas</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getErpBomItemDatas() * @generated * @ordered */ protected EList<ErpBomItemData> erpBomItemDatas; /** * The cached value of the '{@link #getMiscCostItems() <em>Misc Cost Items</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMiscCostItems() * @generated * @ordered */ protected EList<MiscCostItem> miscCostItems; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DesignLocationImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return InfWorkPackage.Literals.DESIGN_LOCATION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getSpanLength() { return spanLength; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSpanLength(float newSpanLength) { float oldSpanLength = spanLength; spanLength = newSpanLength; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN_LOCATION__SPAN_LENGTH, oldSpanLength, spanLength)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ConditionFactor> getConditionFactors() { if (conditionFactors == null) { conditionFactors = new EObjectWithInverseResolvingEList.ManyInverse<ConditionFactor>(ConditionFactor.class, this, InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS, InfWorkPackage.CONDITION_FACTOR__DESIGN_LOCATIONS); } return conditionFactors; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<MaterialItem> getMaterialItems() { if (materialItems == null) { materialItems = new EObjectWithInverseResolvingEList<MaterialItem>(MaterialItem.class, this, InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS, InfWorkPackage.MATERIAL_ITEM__DESIGN_LOCATION); } return materialItems; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Status getStatus() { if (status != null && status.eIsProxy()) { InternalEObject oldStatus = (InternalEObject)status; status = (Status)eResolveProxy(oldStatus); if (status != oldStatus) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, InfWorkPackage.DESIGN_LOCATION__STATUS, oldStatus, status)); } } return status; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Status basicGetStatus() { return status; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStatus(Status newStatus) { Status oldStatus = status; status = newStatus; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN_LOCATION__STATUS, oldStatus, status)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Diagram> getDiagrams() { if (diagrams == null) { diagrams = new EObjectWithInverseResolvingEList.ManyInverse<Diagram>(Diagram.class, this, InfWorkPackage.DESIGN_LOCATION__DIAGRAMS, InfGMLSupportPackage.DIAGRAM__DESIGN_LOCATIONS); } return diagrams; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<WorkLocation> getWorkLocations() { if (workLocations == null) { workLocations = new EObjectWithInverseResolvingEList.ManyInverse<WorkLocation>(WorkLocation.class, this, InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS, InfWorkPackage.WORK_LOCATION__DESIGN_LOCATIONS); } return workLocations; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<DesignLocationCU> getDesignLocationCUs() { if (designLocationCUs == null) { designLocationCUs = new EObjectWithInverseResolvingEList<DesignLocationCU>(DesignLocationCU.class, this, InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS, InfWorkPackage.DESIGN_LOCATION_CU__DESIGN_LOCATION); } return designLocationCUs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Design> getDesigns() { if (designs == null) { designs = new EObjectWithInverseResolvingEList.ManyInverse<Design>(Design.class, this, InfWorkPackage.DESIGN_LOCATION__DESIGNS, InfWorkPackage.DESIGN__DESIGN_LOCATIONS); } return designs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ErpBomItemData> getErpBomItemDatas() { if (erpBomItemDatas == null) { erpBomItemDatas = new EObjectWithInverseResolvingEList<ErpBomItemData>(ErpBomItemData.class, this, InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS, InfERPSupportPackage.ERP_BOM_ITEM_DATA__DESIGN_LOCATION); } return erpBomItemDatas; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<MiscCostItem> getMiscCostItems() { if (miscCostItems == null) { miscCostItems = new EObjectWithInverseResolvingEList<MiscCostItem>(MiscCostItem.class, this, InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS, InfWorkPackage.MISC_COST_ITEM__DESIGN_LOCATION); } return miscCostItems; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getConditionFactors()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getMaterialItems()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__DIAGRAMS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getDiagrams()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getWorkLocations()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getDesignLocationCUs()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__DESIGNS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getDesigns()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getErpBomItemDatas()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getMiscCostItems()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS: return ((InternalEList<?>)getConditionFactors()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS: return ((InternalEList<?>)getMaterialItems()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__DIAGRAMS: return ((InternalEList<?>)getDiagrams()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS: return ((InternalEList<?>)getWorkLocations()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS: return ((InternalEList<?>)getDesignLocationCUs()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__DESIGNS: return ((InternalEList<?>)getDesigns()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS: return ((InternalEList<?>)getErpBomItemDatas()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS: return ((InternalEList<?>)getMiscCostItems()).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 InfWorkPackage.DESIGN_LOCATION__SPAN_LENGTH: return getSpanLength(); case InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS: return getConditionFactors(); case InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS: return getMaterialItems(); case InfWorkPackage.DESIGN_LOCATION__STATUS: if (resolve) return getStatus(); return basicGetStatus(); case InfWorkPackage.DESIGN_LOCATION__DIAGRAMS: return getDiagrams(); case InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS: return getWorkLocations(); case InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS: return getDesignLocationCUs(); case InfWorkPackage.DESIGN_LOCATION__DESIGNS: return getDesigns(); case InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS: return getErpBomItemDatas(); case InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS: return getMiscCostItems(); } 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 InfWorkPackage.DESIGN_LOCATION__SPAN_LENGTH: setSpanLength((Float)newValue); return; case InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS: getConditionFactors().clear(); getConditionFactors().addAll((Collection<? extends ConditionFactor>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS: getMaterialItems().clear(); getMaterialItems().addAll((Collection<? extends MaterialItem>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__STATUS: setStatus((Status)newValue); return; case InfWorkPackage.DESIGN_LOCATION__DIAGRAMS: getDiagrams().clear(); getDiagrams().addAll((Collection<? extends Diagram>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS: getWorkLocations().clear(); getWorkLocations().addAll((Collection<? extends WorkLocation>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS: getDesignLocationCUs().clear(); getDesignLocationCUs().addAll((Collection<? extends DesignLocationCU>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__DESIGNS: getDesigns().clear(); getDesigns().addAll((Collection<? extends Design>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS: getErpBomItemDatas().clear(); getErpBomItemDatas().addAll((Collection<? extends ErpBomItemData>)newValue); return; case InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS: getMiscCostItems().clear(); getMiscCostItems().addAll((Collection<? extends MiscCostItem>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case InfWorkPackage.DESIGN_LOCATION__SPAN_LENGTH: setSpanLength(SPAN_LENGTH_EDEFAULT); return; case InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS: getConditionFactors().clear(); return; case InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS: getMaterialItems().clear(); return; case InfWorkPackage.DESIGN_LOCATION__STATUS: setStatus((Status)null); return; case InfWorkPackage.DESIGN_LOCATION__DIAGRAMS: getDiagrams().clear(); return; case InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS: getWorkLocations().clear(); return; case InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS: getDesignLocationCUs().clear(); return; case InfWorkPackage.DESIGN_LOCATION__DESIGNS: getDesigns().clear(); return; case InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS: getErpBomItemDatas().clear(); return; case InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS: getMiscCostItems().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case InfWorkPackage.DESIGN_LOCATION__SPAN_LENGTH: return spanLength != SPAN_LENGTH_EDEFAULT; case InfWorkPackage.DESIGN_LOCATION__CONDITION_FACTORS: return conditionFactors != null && !conditionFactors.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__MATERIAL_ITEMS: return materialItems != null && !materialItems.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__STATUS: return status != null; case InfWorkPackage.DESIGN_LOCATION__DIAGRAMS: return diagrams != null && !diagrams.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__WORK_LOCATIONS: return workLocations != null && !workLocations.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__DESIGN_LOCATION_CUS: return designLocationCUs != null && !designLocationCUs.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__DESIGNS: return designs != null && !designs.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__ERP_BOM_ITEM_DATAS: return erpBomItemDatas != null && !erpBomItemDatas.isEmpty(); case InfWorkPackage.DESIGN_LOCATION__MISC_COST_ITEMS: return miscCostItems != null && !miscCostItems.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (spanLength: "); result.append(spanLength); result.append(')'); return result.toString(); } } //DesignLocationImpl
/* * Copyright (c) 2018 Ahome' Innovation Technologies. 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.ait.lienzo.client.core.shape.wires; import com.ait.lienzo.client.core.shape.IDirectionalMultiPointShape; import com.ait.lienzo.client.core.shape.IPrimitive; import com.ait.lienzo.client.core.shape.MultiPath; import com.ait.lienzo.client.core.types.Point2D; import com.ait.lienzo.shared.core.types.ArrowEnd; import com.ait.lienzo.shared.core.types.Direction; public class WiresConnection extends AbstractControlHandle { private WiresMagnet m_magnet; private WiresConnector m_connector; private IDirectionalMultiPointShape<?> m_line; private MultiPath m_endPath; private Point2D m_point; private ArrowEnd m_end; private boolean m_autoConnection; private double m_xOffset; private double m_yOffset; public WiresConnection(final WiresConnector connector, final MultiPath endPath, final ArrowEnd end) { m_connector = connector; m_line = connector.getLine(); m_endPath = endPath; m_end = end; m_point = (end == ArrowEnd.HEAD) ? m_line.getPoint2DArray().get(0) : m_line.getPoint2DArray().get(m_line.getPoint2DArray().size() - 1); m_end = end; } public WiresConnection(final boolean active) { setActive(active); } public WiresConnection move(final double x, final double y) { m_point.setX(x + m_xOffset); m_point.setY(y + m_yOffset); m_line.refresh(); IControlHandle handle; if (m_end == ArrowEnd.HEAD) { handle = m_connector.getPointHandles().getHandle(0); } else { handle = m_connector.getPointHandles().getHandle(m_connector.getPointHandles().size() - 1); } if ((handle != null) && (handle.getControl() != null)) { handle.getControl().setX(x + m_xOffset); handle.getControl().setY(y + m_yOffset); } if (m_line.getLayer() != null) { m_line.getLayer().batch(); } return this; } public ArrowEnd getEnd() { return m_end; } public WiresConnection setEnd(final ArrowEnd end) { m_end = end; return this; } public IDirectionalMultiPointShape<?> getLine() { return m_line; } public WiresConnection setLine(final IDirectionalMultiPointShape<?> line) { m_line = line; return this; } public MultiPath getEndPath() { return m_endPath; } public WiresConnector getConnector() { return m_connector; } public boolean isAutoConnection() { return m_autoConnection; } public WiresConnection setAutoConnection(final boolean autoConnection) { m_autoConnection = autoConnection; return this; } public double getXOffset() { return m_xOffset; } public WiresConnection setXOffset(final double xOffset) { m_xOffset = xOffset; return this; } public double getYOffset() { return m_yOffset; } public WiresConnection setYOffset(final double yOffset) { m_yOffset = yOffset; return this; } public WiresConnection setMagnet(final WiresMagnet magnet) { if (m_magnet != null) { m_magnet.removeHandle(this); } if (magnet != null) { magnet.addHandle(this); final Point2D absLoc = magnet.getControl().getComputedLocation(); move(absLoc.getX() + m_xOffset, absLoc.getY() + m_yOffset); if (m_end == ArrowEnd.TAIL) { m_line.setTailDirection(magnet.getDirection()); } else { m_line.setHeadDirection(magnet.getDirection()); } } else { if (m_end == ArrowEnd.TAIL) { m_line.setTailDirection(Direction.NONE); } else { m_line.setHeadDirection(Direction.NONE); } } m_magnet = magnet; // The Line is only draggable if both Connections are unconnected m_connector.setDraggable(); return this; } public Point2D getPoint() { return m_point; } public WiresConnection setPoint(final Point2D point) { m_point = point; return this; } public WiresMagnet getMagnet() { return m_magnet; } public WiresConnection getOppositeConnection() { return this == m_connector.getHeadConnection() ? m_connector.getTailConnection() : m_connector.getHeadConnection(); } public boolean isSpecialConnection() { return isSpecialConnection(m_autoConnection, null != m_magnet ? m_magnet.getIndex() : null); } public static boolean isSpecialConnection(final boolean auto, final Integer magnet) { return auto || ((magnet != null) && (magnet == 0)); } @Override public IPrimitive<?> getControl() { if (m_end == ArrowEnd.HEAD) { return m_connector.getPointHandles().getHandle(0).getControl(); } else { return m_connector.getPointHandles().getHandle(m_connector.getPointHandles().size() - 1).getControl(); } } @Override public ControlHandleType getType() { return ControlHandleStandardType.HANDLE; } @Override public void destroy() { super.destroy(); } }
/* Copyright (c) 2016 Steven Phillips, Miro Dudik and Rob Schapire Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package density; import gnu.getopt.*; import java.io.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.text.NumberFormat; import javax.swing.*; import javax.swing.event.*; // import com.sun.image.codec.jpeg.*; public class Show { Display theDisplay; boolean blackandwhite = false, visible = true, makeLegend = true, dichromatic = false; String sampleFile=null, testSampleFile=null, sampleName=null, initialFile = null, outputDir = null; String classColors = null, classNames = null; int initialMode = Display.PLAIN, breakpoint = 50; String suffix=""; NumberFormat nf = NumberFormat.getNumberInstance(); JLabel loc = new JLabel(" "); File showingFile=null; Grid showingGrid=null; FileEntry fileEntry, samplesEntry; int sampleRadius = 7, minrows = 1200, mincols = 1600, maxRowsAndCols=1000; JFrame frame; double minval=-1, maxval=-1; public Show(String[] args) { String usage = "Usage: density.Show [-B breakpoint] [-b] [-l] [-s samplefile] [-e testSampleFile] [-S samplename] [-t] [-o outfile] datafile [datafile ...]"; boolean outputToFile = false; int c; Getopt g = new Getopt("Show", args, "A:e:F:B:blos:S:r:v:fO:VxR:C:Lm:M:c:aX:Y:d:Nk:Z:t:n:DpT2"); while ((c=g.getopt()) != -1) { switch(c) { // case 'p': Display.xOffset = Integer.parseInt(g.getOptarg()); break; // case 'P': Display.yOffset = Integer.parseInt(g.getOptarg()); break; case '2': dichromatic = true; break; case 'p': GridIO.compressGrids = false; break; case 'd': Display.divisor = Double.parseDouble(g.getOptarg()); break; case 'X': Display.xline = Double.parseDouble(g.getOptarg()); break; case 'Y': Display.yline = Double.parseDouble(g.getOptarg()); break; case 'F': Display.maxFracDigits = Integer.parseInt(g.getOptarg()); break; case 'k': maxRowsAndCols = Integer.parseInt(g.getOptarg()); break; case 'c': Display.numCategories = Integer.parseInt(g.getOptarg()); break; case 't': suffix="_thumb"; GridIO.maxRowsAndCols = Integer.parseInt(g.getOptarg()); break; case 'A': Display.setCategories(g.getOptarg()); break; case 'N': Display.makeNorth = true; break; case 'a': Display.addTinyVals = false; break; case 'l': initialMode = Display.LOG; break; case 'e': testSampleFile = g.getOptarg(); break; case 's': sampleFile = g.getOptarg(); break; case 'S': sampleName = g.getOptarg(); break; case 'b': blackandwhite = true; break; case 'B': breakpoint = Integer.parseInt(g.getOptarg()); break; case 'o': outputToFile = true; break; case 'O': outputDir = g.getOptarg(); break; case 'r': sampleRadius = Integer.parseInt(g.getOptarg()); break; case 'f' : SampleSet.setNCEAS_FORMAT(); break; case 'x' : visible = false; break; case 'R' : minrows = Integer.parseInt(g.getOptarg()); break; case 'C' : mincols = Integer.parseInt(g.getOptarg()); break; case 'L' : makeLegend = false; break; case 'm' : minval = Double.parseDouble(g.getOptarg()); break; case 'M' : maxval = Double.parseDouble(g.getOptarg()); break; case 'Z' : classColors = g.getOptarg(); break; case 'n' : classNames = g.getOptarg(); break; case 'D' : Display.setNumCategoriesByMax = true; break; case 'T' : Display.toggleSampleColor = false; break; default: System.out.println(usage); System.exit(0); } } if (outputToFile) { visible = false; Grid grid = Grid.vals2Grid(new float[600][600], ""); theDisplay = new Display(grid, minrows, mincols); theDisplay.visible = false; if (blackandwhite) theDisplay.setColorScheme(0); // ugly if (dichromatic) { theDisplay.dichromatic = true; if (classColors!=null) { int[] colors = theDisplay.stringToColors(classColors); theDisplay.dichromaticColors = new Color[] { new Color(colors[0]), new Color(colors[1]) }; } } theDisplay.setBreakpoint(breakpoint); if (!makeLegend) theDisplay.makeLegend=false; if (minval!=-1 || maxval!=-1) { theDisplay.setMinval(minval); theDisplay.setMaxval(maxval); } theDisplay.setMode(initialMode); if (classNames!=null) theDisplay.setClassNames(classNames); if (classColors!=null && !dichromatic) theDisplay.setColorClasses(classColors); for (int i=g.getOptind(); i<args.length; i++) { showFile(new File(args[i])); if (sampleFile!=null && sampleSet==null) setSamples(new File(sampleFile)); if (testSampleFile!=null) setSamples(new File(testSampleFile), true); theDisplay.writeImage(toPngName(true)); } return; } if (args.length > g.getOptind()) { initialFile = args[g.getOptind()]; buildShow(); if (outputToFile) theDisplay.writeImage(toPngName(true)); for (int i=g.getOptind()+1; i<args.length; i++) { fileEntry.setText(args[i]); if (outputToFile) theDisplay.writeImage(toPngName(true)); } } else buildShow(); } SampleSet sampleSet = null, testSampleSet = null; void setSamples(File f) { setSamples(f, false); } void setSamples(File f, boolean isTest) { try { if (isTest) testSampleSet = new SampleSet2(f.getPath(), showingGrid.getDimension(), null); else sampleSet = new SampleSet2(f.getPath(), showingGrid.getDimension(), null); theDisplay.sampleRadius = sampleRadius; showSamples(); theDisplay.makeImage(); } catch (IOException e) { System.out.println("Error reading samples from " + sampleFile); } } void showSamples() { for (SampleSet ss: new SampleSet[] { sampleSet, testSampleSet }) { if (ss!=null) { String species; if (sampleName!=null) species = sampleName; else { String inFile = showingFile.getName(); species = (inFile.endsWith(".asc")||inFile.endsWith(".mxe")) ? inFile.substring(0,inFile.length()-4) : inFile; } Sample[] samples = ss.getSamples(species); if (samples.length==0) { String[] names = ss.getNames(); for (int i=0; i<names.length; i++) if (showingFile.getName().startsWith(names[i])) species = names[i]; samples = ss.getSamples(species); } if (ss==sampleSet) theDisplay.setSamples(samples); else theDisplay.setTestSamples(samples); theDisplay.sampleRadius = sampleRadius; } } } void buildShow() { Grid grid = Grid.vals2Grid(new float[600][600], ""); loc.setHorizontalAlignment(SwingConstants.RIGHT); theDisplay = new Display(grid, minrows, mincols); theDisplay.setMode(initialMode); if (blackandwhite) theDisplay.setColorScheme(0); if (dichromatic) theDisplay.dichromatic = true; if (classNames!=null) theDisplay.setClassNames(classNames); if (classColors!=null&&!dichromatic) theDisplay.setColorClasses(classColors); if (!makeLegend) theDisplay.makeLegend=false; theDisplay.setBreakpoint(breakpoint); if (minval!=-1 || maxval!=-1) { theDisplay.setMinval(minval); theDisplay.setMaxval(maxval); } nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(4); frame = new JFrame(); frame.setTitle("Show"); final Container contentPane = frame.getContentPane(); contentPane.setLayout(new BorderLayout()); gui.layouts.PreferredSizeGridLayout psgl = new gui.layouts.PreferredSizeGridLayout(1, 1); psgl.setBoundableInterface(new gui.layouts.AspectBoundable()); JPanel displayPane = new JPanel(); displayPane.setLayout(psgl); displayPane.add(theDisplay); contentPane.add(displayPane, BorderLayout.CENTER); JPanel controls = new JPanel(); fileEntry = new FileEntry("Grid file:", new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { File f = new File(e.getActionCommand()); showFile(f); }}, Utils.fileFilter); samplesEntry = new FileEntry("Sample file:", new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { File f = new File(e.getActionCommand()); setSamples(f); }}, ".csv"); if (initialFile!=null) fileEntry.setText(initialFile); else theDisplay.makeImage(); if (sampleFile!=null) samplesEntry.setText(sampleFile); if (testSampleFile!=null) setSamples(new File(testSampleFile), true); fileEntry.fileSelectionMode = JFileChooser.FILES_ONLY; samplesEntry.fileSelectionMode = JFileChooser.FILES_ONLY; if (initialFile!=null) fileEntry.fc.setCurrentDirectory(new File(initialFile).getParentFile()); fileEntry.filter = new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { if (f.isDirectory()) return true; return f.getName().endsWith(".asc") || f.getName().endsWith(".mxe"); } public String getDescription() { return (".asc and .mxe files"); } }; samplesEntry.filter = new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { if (f.isDirectory()) return true; return f.getName().endsWith(".csv"); } public String getDescription() { return (".csv files"); } }; controls.add(fileEntry, BorderLayout.NORTH); controls.add(samplesEntry); JButton previous = new JButton("Previous"); previous.addActionListener(nextActionListener(false)); JButton next = new JButton("Next"); next.addActionListener(nextActionListener(true)); controls.add(previous); controls.add(next); final Choice choice = new Choice(); choice.addItem("Log"); choice.addItem("Plain"); choice.addItemListener(new ItemListener () { public void itemStateChanged(ItemEvent e) { theDisplay.setMode(choice.getSelectedIndex()); theDisplay.makeImage(); }}); choice.select(initialMode); controls.add(choice); final JButton save = new JButton("Save"); final JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(myFileFilter("asc")); fc.addChoosableFileFilter(myFileFilter("mxe")); fc.addChoosableFileFilter(myFileFilter("png")); save.addActionListener(new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (showingFile!=null) { fc.setCurrentDirectory(showingFile); fc.setSelectedFile(new File(toPngName(false))); if (JFileChooser.APPROVE_OPTION==fc.showSaveDialog(contentPane)) { String fileName = fc.getSelectedFile().getPath(); if (fileName.endsWith(".asc") || fileName.endsWith(".mxe")) { try { new GridWriter(showingGrid, fileName).writeAll(); } catch (IOException ee) { JOptionPane.showMessageDialog(contentPane, ee.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } else theDisplay.writeImage(fileName); } } }}); controls.add(save); contentPane.add(controls, BorderLayout.NORTH); contentPane.add(loc, BorderLayout.SOUTH); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); if (visible) frame.pack(); if (showingGrid!=null) { GridDimension dim = showingGrid.getDimension(); double rs = maxRowsAndCols / (double) dim.nrows; double cs = maxRowsAndCols / (double) dim.ncols; double min = (rs<cs) ? rs : cs; if (min<1.0) frame.setSize((int) (dim.ncols * min), 50 + (int) (dim.nrows * min)); } frame.setVisible(visible); // theDisplay.setAspectRatio(); } javax.swing.filechooser.FileFilter myFileFilter(final String suffix) { return new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { if (f.isDirectory()) return true; return f.getName().endsWith("."+suffix); } public String getDescription() { return ("."+suffix+" files"); } }; } String toPngName(boolean addDir) { String inFile = showingFile.getName(); String out = (inFile.endsWith(".asc")||inFile.endsWith(".mxe")) ? inFile.substring(0,inFile.length()-4) + suffix + ".png" : inFile+suffix+".png"; if (addDir) out = (outputDir==null) ? (new File(showingFile.getParent(), out)).getPath() : (new File(outputDir + out)).getPath(); return out; } ActionListener nextActionListener(final boolean isNext) { return new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (showingFile!=null) { File[] files = showingFile.getAbsoluteFile().getParentFile().listFiles(Utils.filenameFilter); int i; for (i=0; i<files.length; i++) { if (files[i].getName().equals(showingFile.getName())) break; } if (i<files.length-1 && isNext) { fileEntry.setText(files[i+1].getAbsolutePath()); showSamples(); theDisplay.makeImage(); } if (i>0 && !isNext) { fileEntry.setText(files[i-1].getAbsolutePath()); showSamples(); theDisplay.makeImage(); } }}}; } MouseInputAdapter mml = null; void showFile(File f) { if (!f.exists()) Utils.fatalException("Missing file " + f.getPath(), null); showingFile = f; try { showingGrid = GridIO.readGrid(f.getPath()); } catch (IOException e) { Utils.fatalException("Error reading files",e); } theDisplay.setGrid(showingGrid, minrows, mincols); if (visible) { theDisplay.setSize(theDisplay.getPreferredSize()); frame.getContentPane().setSize(frame.getContentPane().getPreferredSize()); theDisplay.removeMouseMotionListener(mml); theDisplay.removeMouseListener(mml); final GridDimension dim = showingGrid.getDimension(); final Grid grid2=showingGrid; theDisplay.addMouseMotionListener(mml = new MouseInputAdapter() { int pressedx = -1, pressedy = -1; public void mouseMoved(MouseEvent e) { int mapx = getX(e); int mapy = getY(e); // System.out.println(mapx + " " + mapy + " " + theDisplay.getSize().width + " " + theDisplay.getSize().height); double x = dim.toX(mapx); double y = dim.toY(mapy); boolean hasData = grid2.hasData(mapy,mapx); double val = hasData ? grid2.eval(mapy,mapx) : grid2.getNODATA_value(); loc.setText("(" + nf.format(x) + "," + nf.format(y) + "): " + (hasData ? val+"" : " <no data> ")); } public void mousePressed(MouseEvent e) { pressedx = getX(e); pressedy = getY(e); } public void mouseReleased(MouseEvent e) { int x = getX(e), y = getY(e); if (pressedx!=-1 && pressedy!=-1 && x!=pressedx && y!=pressedy) { // System.out.println("Zoom " + x + " " + y + " " + pressedx + " " + pressedy); theDisplay.setZoom(x, pressedx, y, pressedy); theDisplay.makeImage(); } pressedx = pressedy = -1; } public void mouseDragged(MouseEvent e) {} public void mouseClicked(MouseEvent e) { theDisplay.zoomOut(); } }); theDisplay.addMouseListener(mml); } showSamples(); theDisplay.makeImage(); } int getX(MouseEvent e) { return theDisplay.gridcol(theDisplay.windowx2imgx(e.getX())); // return (int)((e.getX()/(double)theDisplay.getWidth())*(theDisplay.getCols() / theDisplay.scale)); } int getY(MouseEvent e) { return theDisplay.gridrow(theDisplay.windowy2imgy(e.getY())); // return (int)((e.getY()/(double)theDisplay.getHeight())*(theDisplay.getRows() / theDisplay.scale)); } public static void main(String args[]) { Show show = new Show(args); } }
package mobapptut.com.camera2videoimage; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.CamcorderProfile; import android.media.Image; import android.media.ImageReader; import android.media.MediaRecorder; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.SystemClock; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Size; import android.util.SparseIntArray; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.widget.Chronometer; import android.widget.ImageButton; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; public class Camera2VideoImageActivity_original extends AppCompatActivity { private static final int REQUEST_CAMERA_PERMISSION_RESULT = 0; private static final int REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT = 1; private static final int STATE_PREVIEW = 0; private static final int STATE_WAIT_LOCK = 1; private int mCaptureState = STATE_PREVIEW; private TextureView mTextureView; private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { setupCamera(width, height); connectCamera(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; private CameraDevice mCameraDevice; private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(CameraDevice camera) { mCameraDevice = camera; mMediaRecorder = new MediaRecorder(); if(mIsRecording) { try { createVideoFileName(); } catch (IOException e) { e.printStackTrace(); } startRecord(); mMediaRecorder.start(); runOnUiThread(new Runnable() { @Override public void run() { mChronometer.setBase(SystemClock.elapsedRealtime()); mChronometer.setVisibility(View.VISIBLE); mChronometer.start(); } }); } else { startPreview(); } // Toast.makeText(getApplicationContext(), // "Camera connection made!", Toast.LENGTH_SHORT).show(); } @Override public void onDisconnected(CameraDevice camera) { camera.close(); mCameraDevice = null; } @Override public void onError(CameraDevice camera, int error) { camera.close(); mCameraDevice = null; } }; private HandlerThread mBackgroundHandlerThread; private Handler mBackgroundHandler; private String mCameraId; private Size mPreviewSize; private Size mVideoSize; private Size mImageSize; private ImageReader mImageReader; private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { mBackgroundHandler.post(new ImageSaver(reader.acquireLatestImage())); } }; private class ImageSaver implements Runnable { private final Image mImage; public ImageSaver(Image image) { mImage = image; } @Override public void run() { ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer(); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(mImageFileName); fileOutputStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } finally { mImage.close(); if(fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } private MediaRecorder mMediaRecorder; private Chronometer mChronometer; private int mTotalRotation; private CameraCaptureSession mPreviewCaptureSession; private CameraCaptureSession.CaptureCallback mPreviewCaptureCallback = new CameraCaptureSession.CaptureCallback() { private void process(CaptureResult captureResult) { switch (mCaptureState) { case STATE_PREVIEW: // Do nothing break; case STATE_WAIT_LOCK: mCaptureState = STATE_PREVIEW; Integer afState = captureResult.get(CaptureResult.CONTROL_AF_STATE); if(afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED || afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) { Toast.makeText(getApplicationContext(), "AF Locked!", Toast.LENGTH_SHORT).show(); startStillCaptureRequest(); } break; } } @Override public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); process(result); } }; private CameraCaptureSession mRecordCaptureSession; private CameraCaptureSession.CaptureCallback mRecordCaptureCallback = new CameraCaptureSession.CaptureCallback() { private void process(CaptureResult captureResult) { switch (mCaptureState) { case STATE_PREVIEW: // Do nothing break; case STATE_WAIT_LOCK: mCaptureState = STATE_PREVIEW; Integer afState = captureResult.get(CaptureResult.CONTROL_AF_STATE); if(afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED || afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) { Toast.makeText(getApplicationContext(), "AF Locked!", Toast.LENGTH_SHORT).show(); startStillCaptureRequest(); } break; } } @Override public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); process(result); } }; private CaptureRequest.Builder mCaptureRequestBuilder; private ImageButton mRecordImageButton; private ImageButton mStillImageButton; private boolean mIsRecording = false; private boolean mIsTimelapse = false; private File mVideoFolder; private String mVideoFileName; private File mImageFolder; private String mImageFileName; private static SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 0); ORIENTATIONS.append(Surface.ROTATION_90, 90); ORIENTATIONS.append(Surface.ROTATION_180, 180); ORIENTATIONS.append(Surface.ROTATION_270, 270); } private static class CompareSizeByArea implements Comparator<Size> { @Override public int compare(Size lhs, Size rhs) { return Long.signum((long) lhs.getWidth() * lhs.getHeight() / (long) rhs.getWidth() * rhs.getHeight()); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera2_video_image); createVideoFolder(); createImageFolder(); mChronometer = (Chronometer) findViewById(R.id.chronometer); mTextureView = (TextureView) findViewById(R.id.textureView); mStillImageButton = (ImageButton) findViewById(R.id.cameraImageButton2); mStillImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { lockFocus(); } }); mRecordImageButton = (ImageButton) findViewById(R.id.videoOnlineImageButton); mRecordImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mIsRecording || mIsTimelapse) { mChronometer.stop(); mChronometer.setVisibility(View.INVISIBLE); mIsRecording = false; mIsTimelapse = false; mRecordImageButton.setImageResource(R.mipmap.btn_video_online); mMediaRecorder.stop(); mMediaRecorder.reset(); startPreview(); } else { mIsRecording = true; mRecordImageButton.setImageResource(R.mipmap.btn_video_busy); checkWriteStoragePermission(); } } }); mRecordImageButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { mIsTimelapse =true; mRecordImageButton.setImageResource(R.mipmap.btn_timelapse); checkWriteStoragePermission(); return true; } }); } @Override protected void onResume() { super.onResume(); startBackgroundThread(); if(mTextureView.isAvailable()) { setupCamera(mTextureView.getWidth(), mTextureView.getHeight()); connectCamera(); } else { mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == REQUEST_CAMERA_PERMISSION_RESULT) { if(grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "Application will not run without camera services", Toast.LENGTH_SHORT).show(); } if(grantResults[1] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "Application will not have audio on record", Toast.LENGTH_SHORT).show(); } } if(requestCode == REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT) { if(grantResults[0] == PackageManager.PERMISSION_GRANTED) { mIsRecording = true; mRecordImageButton.setImageResource(R.mipmap.btn_video_busy); Toast.makeText(this, "Permission successfully granted!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "App needs to save video to run", Toast.LENGTH_SHORT).show(); } } } @Override protected void onPause() { closeCamera(); stopBackgroundThread(); super.onPause(); } @Override public void onWindowFocusChanged(boolean hasFocas) { super.onWindowFocusChanged(hasFocas); View decorView = getWindow().getDecorView(); if(hasFocas) { decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } } private void setupCamera(int width, int height) { CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { for(String cameraId : cameraManager.getCameraIdList()){ CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId); if(cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT){ continue; } StreamConfigurationMap map = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation(); mTotalRotation = sensorToDeviceRotation(cameraCharacteristics, deviceOrientation); boolean swapRotation = mTotalRotation == 90 || mTotalRotation == 270; int rotatedWidth = width; int rotatedHeight = height; if(swapRotation) { rotatedWidth = height; rotatedHeight = width; } mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight); mVideoSize = chooseOptimalSize(map.getOutputSizes(MediaRecorder.class), rotatedWidth, rotatedHeight); mImageSize = chooseOptimalSize(map.getOutputSizes(ImageFormat.JPEG), rotatedWidth, rotatedHeight); mImageReader = ImageReader.newInstance(mImageSize.getWidth(), mImageSize.getHeight(), ImageFormat.JPEG, 1); mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler); mCameraId = cameraId; return; } } catch (CameraAccessException e) { e.printStackTrace(); } } private void connectCamera() { CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler); } else { if(shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA)) { Toast.makeText(this, "Video app required access to camera", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[] {android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }, REQUEST_CAMERA_PERMISSION_RESULT); } } else { cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler); } } catch (CameraAccessException e) { e.printStackTrace(); } } private void startRecord() { try { if(mIsRecording) { setupMediaRecorder(); } else if(mIsTimelapse) { setupTimelapse(); } SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); Surface previewSurface = new Surface(surfaceTexture); Surface recordSurface = mMediaRecorder.getSurface(); mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); mCaptureRequestBuilder.addTarget(previewSurface); mCaptureRequestBuilder.addTarget(recordSurface); mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, recordSurface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) { mRecordCaptureSession = session; try { mRecordCaptureSession.setRepeatingRequest( mCaptureRequestBuilder.build(), null, null ); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(CameraCaptureSession session) { } }, null); } catch (Exception e) { e.printStackTrace(); } } private void startPreview() { SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); Surface previewSurface = new Surface(surfaceTexture); try { mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mCaptureRequestBuilder.addTarget(previewSurface); mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) { mPreviewCaptureSession = session; try { mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(CameraCaptureSession session) { Toast.makeText(getApplicationContext(), "Unable to setup camera preview", Toast.LENGTH_SHORT).show(); } }, null); } catch (CameraAccessException e) { e.printStackTrace(); } } private void startStillCaptureRequest() { try { if(mIsRecording) { mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_VIDEO_SNAPSHOT); } else { mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); } mCaptureRequestBuilder.addTarget(mImageReader.getSurface()); mCaptureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, mTotalRotation); CameraCaptureSession.CaptureCallback stillCaptureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, long timestamp, long frameNumber) { super.onCaptureStarted(session, request, timestamp, frameNumber); try { createImageFileName(); } catch (IOException e) { e.printStackTrace(); } } }; if(mIsRecording) { mRecordCaptureSession.capture(mCaptureRequestBuilder.build(), stillCaptureCallback, null); } else { mPreviewCaptureSession.capture(mCaptureRequestBuilder.build(), stillCaptureCallback, null); } } catch (CameraAccessException e) { e.printStackTrace(); } } private void closeCamera() { if(mCameraDevice != null) { mCameraDevice.close(); mCameraDevice = null; } if(mMediaRecorder != null) { mMediaRecorder.release(); mMediaRecorder = null; } } private void startBackgroundThread() { mBackgroundHandlerThread = new HandlerThread("Camera2VideoImage"); mBackgroundHandlerThread.start(); mBackgroundHandler = new Handler(mBackgroundHandlerThread.getLooper()); } private void stopBackgroundThread() { mBackgroundHandlerThread.quitSafely(); try { mBackgroundHandlerThread.join(); mBackgroundHandlerThread = null; mBackgroundHandler = null; } catch (InterruptedException e) { e.printStackTrace(); } } private static int sensorToDeviceRotation(CameraCharacteristics cameraCharacteristics, int deviceOrientation) { int sensorOrienatation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); deviceOrientation = ORIENTATIONS.get(deviceOrientation); return (sensorOrienatation + deviceOrientation + 360) % 360; } private static Size chooseOptimalSize(Size[] choices, int width, int height) { List<Size> bigEnough = new ArrayList<Size>(); for(Size option : choices) { if(option.getHeight() == option.getWidth() * height / width && option.getWidth() >= width && option.getHeight() >= height) { bigEnough.add(option); } } if(bigEnough.size() > 0) { return Collections.min(bigEnough, new CompareSizeByArea()); } else { return choices[0]; } } private void createVideoFolder() { File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); mVideoFolder = new File(movieFile, "camera2VideoImage"); if(!mVideoFolder.exists()) { mVideoFolder.mkdirs(); } } private File createVideoFileName() throws IOException { String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String prepend = "VIDEO_" + timestamp + "_"; File videoFile = File.createTempFile(prepend, ".mp4", mVideoFolder); mVideoFileName = videoFile.getAbsolutePath(); return videoFile; } private void createImageFolder() { File imageFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); mImageFolder = new File(imageFile, "camera2VideoImage"); if(!mImageFolder.exists()) { mImageFolder.mkdirs(); } } private File createImageFileName() throws IOException { String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String prepend = "IMAGE_" + timestamp + "_"; File imageFile = File.createTempFile(prepend, ".jpg", mImageFolder); mImageFileName = imageFile.getAbsolutePath(); return imageFile; } private void checkWriteStoragePermission() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { try { createVideoFileName(); } catch (IOException e) { e.printStackTrace(); } startRecord(); mMediaRecorder.start(); mChronometer.setBase(SystemClock.elapsedRealtime()); mChronometer.setVisibility(View.VISIBLE); mChronometer.start(); } else { if(shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText(this, "app needs to be able to save videos", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT); } } else { try { createVideoFileName(); } catch (IOException e) { e.printStackTrace(); } startRecord(); mMediaRecorder.start(); mChronometer.setBase(SystemClock.elapsedRealtime()); mChronometer.setVisibility(View.VISIBLE); mChronometer.start(); } } private void setupMediaRecorder() throws IOException { mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mMediaRecorder.setOutputFile(mVideoFileName); mMediaRecorder.setVideoEncodingBitRate(1000000); mMediaRecorder.setVideoFrameRate(30); mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight()); mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); mMediaRecorder.setOrientationHint(mTotalRotation); mMediaRecorder.prepare(); } private void setupTimelapse() throws IOException { mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH)); mMediaRecorder.setOutputFile(mVideoFileName); mMediaRecorder.setCaptureRate(2); mMediaRecorder.setOrientationHint(mTotalRotation); mMediaRecorder.prepare(); } private void lockFocus() { mCaptureState = STATE_WAIT_LOCK; mCaptureRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START); try { if(mIsRecording) { mRecordCaptureSession.capture(mCaptureRequestBuilder.build(), mRecordCaptureCallback, mBackgroundHandler); } else { mPreviewCaptureSession.capture(mCaptureRequestBuilder.build(), mPreviewCaptureCallback, mBackgroundHandler); } } catch (CameraAccessException e) { e.printStackTrace(); } } }
package com.fasterxml.jackson.jr.ob.impl; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.SerializedString; import com.fasterxml.jackson.jr.ob.JSON; import com.fasterxml.jackson.jr.ob.JSONObjectException; import com.fasterxml.jackson.jr.ob.JSON.Feature; import static com.fasterxml.jackson.jr.ob.impl.TypeDetector.*; /** * Object that handles serialization of simple Objects into * JSON. *<p> * Life-cycle is such that initial instance (called blueprint) * is constructed first (including possible configuration * using mutant factory methods). This blueprint object * acts as a factory, and is never used for direct writing; * instead, per-call instance is created by calling * {@link #perOperationInstance}. */ public class JSONWriter { /* /********************************************************************** /* Blueprint config /********************************************************************** */ protected final int _features; /** * Object that is used to resolve types of values dynamically. */ protected final TypeDetector _typeDetector; protected final TreeCodec _treeCodec; protected final boolean _requireSetter; /* /********************************************************************** /* Instance config /********************************************************************** */ protected final JsonGenerator _generator; /* /********************************************************************** /* Blueprint construction /********************************************************************** */ /** * Constructor used for creating differently configured blueprint * instances */ public JSONWriter(int features, TypeDetector td, TreeCodec tc) { _features = features; _typeDetector = td; _treeCodec = tc; _generator = null; _requireSetter = JSON.Feature.WRITE_READONLY_BEAN_PROPERTIES.isDisabled(features); } /** * Constructor for non-blueprint instances */ protected JSONWriter(JSONWriter base, JsonGenerator jgen) { _features = base._features; _typeDetector = base._typeDetector.perOperationInstance(_features); _treeCodec = base._treeCodec; _generator = jgen; _requireSetter = JSON.Feature.WRITE_READONLY_BEAN_PROPERTIES.isDisabled(_features); } /* /********************************************************************** /* Mutant factories for blueprint /********************************************************************** */ public JSONWriter withFeatures(int features) { if (_features == features) { return this; } return _with(features, _typeDetector, _treeCodec); } public JSONWriter with(TypeDetector td) { if (_typeDetector == td) { return this; } return _with(_features, td, _treeCodec); } public JSONWriter with(TreeCodec tc) { if (_treeCodec == tc) { return this; } return _with(_features, _typeDetector, tc); } /** * Overridable method that all mutant factories call if a new instance * is to be constructed */ protected JSONWriter _with(int features, TypeDetector td, TreeCodec tc) { if (getClass() != JSONWriter.class) { // sanity check throw new IllegalStateException("Sub-classes MUST override _with(...)"); } return new JSONWriter(features, td, tc); } /* /********************************************************************** /* New instance creation /********************************************************************** */ public JSONWriter perOperationInstance(JsonGenerator jg) { if (getClass() != JSONWriter.class) { // sanity check throw new IllegalStateException("Sub-classes MUST override perOperationInstance(...)"); } return new JSONWriter(this, jg); } /* /********************************************************************** /* Public entry methods /********************************************************************** */ public void writeValue(Object value) throws IOException, JsonProcessingException { if (value == null) { writeNullValue(); return; } _writeValue(value, _typeDetector.findFullType(value.getClass())); } public void writeField(String fieldName, Object value) throws IOException, JsonProcessingException { if (value == null) { if (Feature.WRITE_NULL_PROPERTIES.isEnabled(_features)) { writeNullField(fieldName); } return; } int type = _typeDetector.findFullType(value.getClass()); switch (type) { // First, structured types: // Structured types: case SER_MAP: writeMapField(fieldName, (Map<?,?>) value); return; case SER_LIST: writeListField(fieldName, (List<?>) value); return; case SER_COLLECTION: writeCollectionField(fieldName, (Collection<?>) value); return; case SER_OBJECT_ARRAY: writeObjectArrayField(fieldName, (Object[]) value); return; case SER_INT_ARRAY: writeIntArrayField(fieldName, (int[]) value); return; case SER_LONG_ARRAY: writeLongArrayField(fieldName, (long[]) value); return; case SER_BOOLEAN_ARRAY: writeBooleanArrayField(fieldName, (boolean[]) value); return; case SER_TREE_NODE: writeTreeNodeField(fieldName, (TreeNode) value); return; // Textual types, similar: case SER_STRING: writeStringField(fieldName, (String) value); return; case SER_CHAR_ARRAY: writeStringField(fieldName, new String((char[]) value)); return; case SER_CHARACTER_SEQUENCE: writeStringField(fieldName, ((CharSequence) value).toString()); return; case SER_BYTE_ARRAY: writeBinaryField(fieldName, (byte[]) value); return; // Number types: case SER_NUMBER_BIG_DECIMAL: writeBigDecimalField(fieldName, (BigDecimal) value); return; case SER_NUMBER_BIG_INTEGER: writeBigIntegerField(fieldName, (BigInteger) value); return; case SER_NUMBER_FLOAT: // fall through case SER_NUMBER_DOUBLE: writeDoubleField(fieldName, ((Number) value).doubleValue()); return; case SER_NUMBER_BYTE: // fall through case SER_NUMBER_SHORT: // fall through case SER_NUMBER_INTEGER: writeIntField(fieldName, ((Number) value).intValue()); return; case SER_NUMBER_LONG: writeLongField(fieldName, ((Number) value).longValue()); return; // Scalar types: case SER_BOOLEAN: writeBooleanField(fieldName, ((Boolean) value).booleanValue()); return; case SER_CHAR: writeStringField(fieldName, String.valueOf(value)); return; case SER_CALENDAR: value = ((Calendar) value).getTime(); // fall through case SER_DATE: writeDateField(fieldName, (Date) value); return; case SER_ENUM: writeEnumField(fieldName, (Enum<?>) value); return; case SER_CLASS: writeStringLikeField(fieldName, ((Class<?>) value).getName(), type); return; case SER_FILE: writeStringLikeField(fieldName, ((File) value).getAbsolutePath(), type); return; case SER_UUID: case SER_URL: case SER_URI: writeStringLikeValue(value.toString(), type); // Others case SER_ITERABLE: writeIterableField(fieldName, (Iterable<?>) value); return; case SER_UNKNOWN: writeUnknownField(fieldName, value); return; } if (type < 0) { // Bean type! BeanDefinition def = _typeDetector.getBeanDefinition(type); if (def == null) { // sanity check throw new IllegalStateException("Internal error: missing BeanDefinition for id "+type +" (class "+value.getClass().getName()+")"); } _generator.writeFieldName(fieldName); writeBeanValue(def, value); return; } throw new IllegalStateException("Unsupported type: "+type); } protected void _writeValue(Object value, int type) throws IOException { switch (type) { // Structured types: case SER_MAP: writeMapValue((Map<?,?>) value); return; case SER_LIST: writeListValue((List<?>) value); return; case SER_COLLECTION: writeCollectionValue((Collection<?>) value); return; case SER_OBJECT_ARRAY: writeObjectArrayValue((Object[]) value); return; case SER_INT_ARRAY: writeIntArrayValue((int[]) value); return; case SER_LONG_ARRAY: writeLongArrayValue((long[]) value); return; case SER_BOOLEAN_ARRAY: writeBooleanArrayValue((boolean[]) value); return; case SER_TREE_NODE: writeTreeNodeValue((TreeNode) value); return; // Textual types, related: case SER_STRING: writeStringValue((String) value); return; case SER_CHAR_ARRAY: writeStringValue(new String((char[]) value)); return; case SER_CHARACTER_SEQUENCE: writeStringValue(((CharSequence) value).toString()); return; case SER_BYTE_ARRAY: writeBinaryValue((byte[]) value); return; // Number types: case SER_NUMBER_FLOAT: // fall through case SER_NUMBER_DOUBLE: writeDoubleValue(((Number) value).doubleValue()); return; case SER_NUMBER_BYTE: // fall through case SER_NUMBER_SHORT: // fall through case SER_NUMBER_INTEGER: writeIntValue(((Number) value).intValue()); return; case SER_NUMBER_LONG: writeLongValue(((Number) value).longValue()); return; case SER_NUMBER_BIG_DECIMAL: writeBigDecimalValue((BigDecimal) value); return; case SER_NUMBER_BIG_INTEGER: writeBigIntegerValue((BigInteger) value); return; // Other scalar types: case SER_BOOLEAN: writeBooleanValue(((Boolean) value).booleanValue()); return; case SER_CHAR: writeStringValue(String.valueOf(value)); return; case SER_CALENDAR: value = ((Calendar) value).getTime(); // fall through case SER_DATE: writeDateValue((Date) value); return; case SER_ENUM: writeEnumValue((Enum<?>) value); return; case SER_CLASS: writeStringLikeValue(((Class<?>) value).getName(), type); return; case SER_FILE: writeStringLikeValue(((File) value).getAbsolutePath(), type); return; // these type should be fine using toString() case SER_UUID: case SER_URL: case SER_URI: writeStringLikeValue(value.toString(), type); return; case SER_ITERABLE: writeIterableValue((Iterable<?>) value); return; case SER_UNKNOWN: writeUnknownValue(value); return; } if (type < 0) { // Bean type! BeanDefinition def = _typeDetector.getBeanDefinition(type); if (def == null) { // sanity check throw new IllegalStateException("Internal error: missing BeanDefinition for id "+type +" (class "+value.getClass().getName()+")"); } writeBeanValue(def, value); return; } throw new IllegalStateException("Unsupported type: "+type+" (class "+value.getClass().getName()+")"); } /* /********************************************************************** /* Overridable concrete typed write methods, structured types /********************************************************************** */ protected void writeCollectionValue(Collection<?> v) throws IOException { _generator.writeStartArray(); for (Object ob : v) { writeValue(ob); } _generator.writeEndArray(); } protected void writeCollectionField(String fieldName, Collection<?> v) throws IOException { _generator.writeFieldName(fieldName); writeCollectionValue(v); } protected void writeIterableValue(Iterable<?> v) throws IOException { _generator.writeStartArray(); for (Object ob : v) { writeValue(ob); } _generator.writeEndArray(); } protected void writeIterableField(String fieldName, Iterable<?> v) throws IOException { _generator.writeFieldName(fieldName); writeIterableValue(v); } protected void writeListValue(List<?> v) throws IOException { _generator.writeStartArray(); for (int i = 0, len = v.size(); i < len; ++i) { writeValue(v.get(i)); } _generator.writeEndArray(); } protected void writeListField(String fieldName, List<?> v) throws IOException { _generator.writeFieldName(fieldName); writeListValue(v); } protected void writeMapValue(Map<?,?> v) throws IOException { _generator.writeStartObject(); if (!v.isEmpty()) { for (Map.Entry<?,?> entry : v.entrySet()) { writeField(keyToString(entry.getKey()), entry.getValue()); } } _generator.writeEndObject(); } protected void writeMapField(String fieldName, Map<?,?> v) throws IOException { _generator.writeFieldName(fieldName); writeMapValue(v); } protected void writeObjectArrayValue(Object[] v) throws IOException { _generator.writeStartArray(); for (int i = 0, len = v.length; i < len; ++i) { writeValue(v[i]); } _generator.writeEndArray(); } protected void writeObjectArrayField(String fieldName, Object[] v) throws IOException { _generator.writeFieldName(fieldName); writeObjectArrayValue(v); } protected void writeIntArrayValue(int[] v) throws IOException { _generator.writeStartArray(); for (int i = 0, len = v.length; i < len; ++i) { _generator.writeNumber(v[i]); } _generator.writeEndArray(); } protected void writeIntArrayField(String fieldName, int[] v) throws IOException { _generator.writeFieldName(fieldName); writeIntArrayValue(v); } protected void writeLongArrayValue(long[] v) throws IOException { _generator.writeStartArray(); for (int i = 0, len = v.length; i < len; ++i) { _generator.writeNumber(v[i]); } _generator.writeEndArray(); } protected void writeLongArrayField(String fieldName, long[] v) throws IOException { _generator.writeFieldName(fieldName); writeLongArrayValue(v); } protected void writeBooleanArrayValue(boolean[] v) throws IOException { _generator.writeStartArray(); for (int i = 0, len = v.length; i < len; ++i) { _generator.writeBoolean(v[i]); } _generator.writeEndArray(); } protected void writeBooleanArrayField(String fieldName, boolean[] v) throws IOException { _generator.writeFieldName(fieldName); writeBooleanArrayValue(v); } protected void writeTreeNodeValue(TreeNode v) throws IOException { if (_treeCodec == null) { throw new JSONObjectException("No TreeCodec configured: can not serializer TreeNode values"); } _treeCodec.writeTree(_generator, v); } protected void writeTreeNodeField(String fieldName, TreeNode v) throws IOException { _generator.writeFieldName(fieldName); writeTreeNodeValue(v); } /* /********************************************************************** /* Overridable concrete typed write methods, primitives /********************************************************************** */ protected void writeBooleanValue(boolean v) throws IOException { _generator.writeBoolean(v); } protected void writeBooleanField(String fieldName, boolean v) throws IOException { _generator.writeBooleanField(fieldName, v); } protected void writeIntValue(int v) throws IOException { _generator.writeNumber(v); } protected void writeIntField(String fieldName, int v) throws IOException { _generator.writeNumberField(fieldName, v); } protected void writeLongValue(long v) throws IOException { _generator.writeNumber(v); } protected void writeBigIntegerValue(BigInteger v) throws IOException { _generator.writeNumber(v); } protected void writeBigIntegerField(String fieldName, BigInteger v) throws IOException { _generator.writeFieldName(fieldName); writeBigIntegerValue(v); } protected void writeLongField(String fieldName, long v) throws IOException { _generator.writeNumberField(fieldName, v); } protected void writeDoubleValue(double v) throws IOException { _generator.writeNumber(v); } protected void writeDoubleField(String fieldName, double v) throws IOException { _generator.writeNumberField(fieldName, v); } protected void writeBigDecimalValue(BigDecimal v) throws IOException { _generator.writeNumber(v); } protected void writeBigDecimalField(String fieldName, BigDecimal v) throws IOException { _generator.writeNumberField(fieldName, v); } /* /********************************************************************** /* Overridable concrete typed write methods, textual /********************************************************************** */ protected void writeStringValue(String v) throws IOException { _generator.writeString(v); } protected void writeStringField(String fieldName, String v) throws IOException { _generator.writeStringField(fieldName, v); } protected void writeStringLikeValue(String v, int actualType) throws IOException { _generator.writeString(v); } protected void writeStringLikeField(String fieldName, String v, int actualType) throws IOException { _generator.writeStringField(fieldName, v); } protected void writeBinaryValue(byte[] data) throws IOException { _generator.writeBinary(data); } protected void writeBinaryField(String fieldName, byte[] data) throws IOException { _generator.writeBinaryField(fieldName, data); } /* /********************************************************************** /* Overridable concrete typed write methods, other /********************************************************************** */ protected void writeNullValue() throws IOException { _generator.writeNull(); } protected void writeNullField(String fieldName) throws IOException { if (Feature.WRITE_NULL_PROPERTIES.isEnabled(_features)) { _generator.writeNullField(fieldName); } } protected void writeNullField(SerializedString fieldName) throws IOException { if (Feature.WRITE_NULL_PROPERTIES.isEnabled(_features)) { _generator.writeFieldName(fieldName); _generator.writeNull(); } } protected void writeDateValue(Date v) throws IOException { // TODO: maybe allow serialization using timestamp? writeStringValue(v.toString()); } protected void writeDateField(String fieldName, Date v) throws IOException { writeStringField(fieldName, v.toString()); } protected void writeEnumValue(Enum<?> v) throws IOException { if (Feature.WRITE_ENUMS_USING_INDEX.isEnabled(_features)) { writeIntValue(v.ordinal()); } else { writeStringValue(v.toString()); } } protected void writeEnumField(String fieldName, Enum<?> v) throws IOException { if (Feature.WRITE_ENUMS_USING_INDEX.isEnabled(_features)) { writeIntField(fieldName, v.ordinal()); } else { writeStringField(fieldName, v.toString()); } } protected void writeBeanValue(BeanDefinition beanDef, Object bean) throws IOException { _generator.writeStartObject(); for (BeanProperty property : beanDef.properties()) { SerializedString name; if (_requireSetter) { name = property.getNameIfHasSetter(); if (name == null) { continue; } } else { name = property.getName(); } Object value = property.getValueFor(bean); if (value == null) { writeNullField(name); continue; } int typeId = property.getTypeId(); if (typeId == 0) { typeId = _typeDetector.findFullType(value.getClass()); } _generator.writeFieldName(name); _writeValue(value, typeId); } _generator.writeEndObject(); } protected void writeUnknownValue(Object data) throws IOException { _checkUnknown(data); writeStringValue(data.toString()); } protected void writeUnknownField(String fieldName, Object data) throws IOException { _checkUnknown(data); writeStringField(fieldName, data.toString()); } protected void _checkUnknown(Object value) throws IOException { if (Feature.FAIL_ON_UNKNOWN_TYPE_WRITE.isEnabled(_features)) { throw new JSONObjectException("Unrecognized type ("+value.getClass().getName() +"), don't know how to write (disable "+Feature.FAIL_ON_UNKNOWN_TYPE_WRITE +" to avoid exception)"); } } /* /********************************************************************** /* Overridable concrete typed write methods; key conversions: /********************************************************************** */ protected String keyToString(Object rawKey) { if (rawKey instanceof String) { return (String) rawKey; } return String.valueOf(rawKey); } }
/* * MIT License * * Copyright (c) 2016 Alibaba Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.alibaba.android.vlayout.layout; import android.graphics.Rect; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import com.alibaba.android.vlayout.LayoutManagerHelper; import com.alibaba.android.vlayout.OrientationHelperEx; import com.alibaba.android.vlayout.VirtualLayoutManager; import com.alibaba.android.vlayout.VirtualLayoutManager.LayoutStateWrapper; import java.util.Arrays; import static com.alibaba.android.vlayout.VirtualLayoutManager.VERTICAL; /** * <pre> * Currently support 1+6(max) layout * * Created by J!nl!n on 2017/3/7. * * 1 + 4 * ------------------------- * | | | | * | | 2 | 3 | * | | | | * | 1 |-------|-------| * | | | | * | | 4 | 5 | * | | | | * ------------------------- * * 1 + 5 * ------------------------- * | | 2 | * | 1 |-----------| * | | 3 | * ------------------------- * | | | | * | 4 | 5 | 6 | * | | | | * ------------------------- * * 1 + 6 * ------------------------- * | | 2 | 3 | * | |-------|-------| * | 1 | 4 | 5 | * | |-------|-------| * | | 6 | 7 | * ------------------------- * </pre> */ public class OnePlusNLayoutHelperEx extends AbstractFullFillLayoutHelper { private static final String TAG = "OnePlusNLayoutHelper"; private Rect mAreaRect = new Rect(); private View[] mChildrenViews; private float[] mColWeights = new float[0]; private float mRowWeight = Float.NaN; public OnePlusNLayoutHelperEx() { setItemCount(0); } public OnePlusNLayoutHelperEx(int itemCount) { this(itemCount, 0, 0, 0, 0); } public OnePlusNLayoutHelperEx(int itemCount, int leftMargin, int topMargin, int rightMargin, int bottomMargin) { setItemCount(itemCount); } /** * {@inheritDoc} * <p/> * Currently, this layout supports maximum children up to 5, otherwise {@link * IllegalArgumentException} * will be thrown * * @param start start position of items handled by this layoutHelper * @param end end position of items handled by this layoutHelper, if end &lt; start or end - * start &gt 4, it will throw {@link IllegalArgumentException} */ @Override public void onRangeChange(int start, int end) { if (end - start < 4) { throw new IllegalArgumentException( "pls use OnePlusNLayoutHelper instead of OnePlusNLayoutHelperEx which childcount <= 5"); } if (end - start > 6) { throw new IllegalArgumentException( "OnePlusNLayoutHelper only supports maximum 7 children now"); } } public void setColWeights(float[] weights) { if (weights != null) { this.mColWeights = Arrays.copyOf(weights, weights.length); } else { this.mColWeights = new float[0]; } } public void setRowWeight(float weight) { this.mRowWeight = weight; } @Override public void layoutViews(RecyclerView.Recycler recycler, RecyclerView.State state, LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper) { // reach the end of this layout final int originCurPos = layoutState.getCurrentPosition(); if (isOutOfRange(originCurPos)) { return; } if (mChildrenViews == null || mChildrenViews.length != getItemCount()) { mChildrenViews = new View[getItemCount()]; } int count = getAllChildren(mChildrenViews, recycler, layoutState, result, helper); if (count != getItemCount()) { Log.w(TAG, "The real number of children is not match with range of LayoutHelper"); } final boolean layoutInVertical = helper.getOrientation() == VERTICAL; final int parentWidth = helper.getContentWidth(); final int parentHeight = helper.getContentHeight(); final int parentHPadding = helper.getPaddingLeft() + helper.getPaddingRight() + getHorizontalMargin() + getHorizontalPadding(); final int parentVPadding = helper.getPaddingTop() + helper.getPaddingBottom() + getVerticalMargin() + getVerticalPadding(); int mainConsumed = 0; if (count == 5) { mainConsumed = handleFive(layoutState, result, helper, layoutInVertical, parentWidth, parentHeight, parentHPadding, parentVPadding); } else if (count == 6) { mainConsumed = handSix(layoutState, result, helper, layoutInVertical, parentWidth, parentHeight, parentHPadding, parentVPadding); } else if (count == 7) { mainConsumed = handSeven(layoutState, result, helper, layoutInVertical, parentWidth, parentHeight, parentHPadding, parentVPadding); } result.mConsumed = mainConsumed; Arrays.fill(mChildrenViews, null); } private float getViewMainWeight(ViewGroup.MarginLayoutParams params, int index) { if (mColWeights.length > index) { return mColWeights[index]; } return Float.NaN; } @Override public int computeAlignOffset(int offset, boolean isLayoutEnd, boolean useAnchor, LayoutManagerHelper helper) { if (getItemCount() == 3) { if (offset == 1 && isLayoutEnd) { Log.w(TAG, "Should not happen after adjust anchor"); return 0; } } else if (getItemCount() == 4) { if (offset == 1 && isLayoutEnd) { return 0; } } if (helper.getOrientation() == VERTICAL) { if (isLayoutEnd) { return mMarginBottom + mPaddingBottom; } else { return -mMarginTop - mPaddingTop; } } else { if (isLayoutEnd) { return mMarginRight + mPaddingRight; } else { return -mMarginLeft - mPaddingLeft; } } } private int handleFive(LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper, boolean layoutInVertical, int parentWidth, int parentHeight, int parentHPadding, int parentVPadding) { int mainConsumed = 0; OrientationHelperEx orientationHelper = helper.getMainOrientationHelper(); final View child1 = mChildrenViews[0]; final VirtualLayoutManager.LayoutParams lp1 = new VirtualLayoutManager.LayoutParams( child1.getLayoutParams()); final View child2 = helper.getReverseLayout() ? mChildrenViews[4] : mChildrenViews[1]; final VirtualLayoutManager.LayoutParams lp2 = new VirtualLayoutManager.LayoutParams( child2.getLayoutParams()); final View child3 = helper.getReverseLayout() ? mChildrenViews[3] : mChildrenViews[2]; final VirtualLayoutManager.LayoutParams lp3 = new VirtualLayoutManager.LayoutParams( child3.getLayoutParams()); final View child4 = helper.getReverseLayout() ? mChildrenViews[2] : mChildrenViews[3]; final VirtualLayoutManager.LayoutParams lp4 = new VirtualLayoutManager.LayoutParams( child4.getLayoutParams()); final View child5 = helper.getReverseLayout() ? mChildrenViews[1] : mChildrenViews[4]; final VirtualLayoutManager.LayoutParams lp5 = new VirtualLayoutManager.LayoutParams( child5.getLayoutParams()); final float weight1 = getViewMainWeight(lp1, 0); final float weight2 = getViewMainWeight(lp1, 1); final float weight3 = getViewMainWeight(lp1, 2); final float weight4 = getViewMainWeight(lp1, 3); final float weight5 = getViewMainWeight(lp1, 4); if (layoutInVertical) { lp2.topMargin = lp1.topMargin; lp3.bottomMargin = lp4.bottomMargin = lp1.bottomMargin; lp3.leftMargin = lp2.leftMargin; lp4.rightMargin = lp2.rightMargin; lp5.rightMargin = lp3.rightMargin; if (!Float.isNaN(mAspectRatio)) { lp1.height = (int) ((parentWidth - parentHPadding) / mAspectRatio); } int availableSpace = parentWidth - parentHPadding - lp1.leftMargin - lp1.rightMargin - lp2.leftMargin - lp2.rightMargin - lp3.leftMargin - lp3.rightMargin; int width1 = Float.isNaN(weight1) ? (int) (availableSpace / 3.0f + 0.5f) : (int) (availableSpace * weight1 / 100 + 0.5f); int width2 = Float.isNaN(weight2) ? (availableSpace - width1) / 2 : (int) (availableSpace * weight2 / 100 + 0.5f); int width3 = Float.isNaN(weight3) ? width2 : (int) (availableSpace * weight3 / 100 + 0.5f); int width4 = Float.isNaN(weight4) ? width2 : (int) (availableSpace * weight4 / 100 + 0.5f); int width5 = Float.isNaN(weight5) ? width2 : (int) (availableSpace * weight5 / 100 + 0.5f); helper.measureChildWithMargins(child1, MeasureSpec.makeMeasureSpec(width1 + lp1.leftMargin + lp1.rightMargin, MeasureSpec.EXACTLY), helper.getChildMeasureSpec(helper.getContentHeight(), lp1.height, true)); int height1 = child1.getMeasuredHeight(); int height2 = Float.isNaN(mRowWeight) ? (int) ((height1 - lp2.bottomMargin - lp3.topMargin) / 2.0f + 0.5f) : (int) ((height1 - lp2.bottomMargin - lp3.topMargin) * mRowWeight / 100 + 0.5f); int height3 = (height1 - lp2.bottomMargin - lp3.topMargin) - height2; helper.measureChildWithMargins(child2, MeasureSpec.makeMeasureSpec(width2 + lp2.leftMargin + lp2.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp2.topMargin + lp2.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child3, MeasureSpec.makeMeasureSpec(width3 + lp3.leftMargin + lp3.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp3.topMargin + lp3.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child4, MeasureSpec.makeMeasureSpec(width4 + lp4.leftMargin + lp4.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp4.topMargin + lp4.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child5, MeasureSpec.makeMeasureSpec(width5 + lp5.leftMargin + lp5.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp5.topMargin + lp5.bottomMargin, MeasureSpec.EXACTLY)); mainConsumed = Math.max(height1 + lp1.topMargin + lp1.bottomMargin, height2 + lp2.topMargin + lp2.bottomMargin + Math .max(height3 + lp3.topMargin + lp3.bottomMargin, height3 + lp4.topMargin + lp4.bottomMargin)) + getVerticalMargin() + getVerticalPadding(); calculateRect(mainConsumed - getVerticalMargin() - getVerticalPadding(), mAreaRect, layoutState, helper); int right1 = mAreaRect.left + orientationHelper .getDecoratedMeasurementInOther(child1); layoutChildWithMargin(child1, mAreaRect.left, mAreaRect.top, right1, mAreaRect.bottom, helper); int right2 = right1 + orientationHelper.getDecoratedMeasurementInOther(child2); layoutChildWithMargin(child2, right1, mAreaRect.top, right2, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child2), helper); int right3 = right2 + orientationHelper.getDecoratedMeasurementInOther(child3); layoutChildWithMargin(child3, right2, mAreaRect.top, right3, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child3), helper); int right4 = right1 + orientationHelper.getDecoratedMeasurementInOther(child4); layoutChildWithMargin(child4, right1, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child4), right4, mAreaRect.bottom, helper); layoutChildWithMargin(child5, right4, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child5), right4 + orientationHelper.getDecoratedMeasurementInOther(child5), mAreaRect.bottom, helper); } else { // TODO: horizontal support } handleStateOnResult(result, child1, child2, child3, child4, child5); return mainConsumed; } private int handSix(LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper, boolean layoutInVertical, int parentWidth, int parentHeight, int parentHPadding, int parentVPadding) { int mainConsumed = 0; OrientationHelperEx orientationHelper = helper.getMainOrientationHelper(); final View child1 = mChildrenViews[0]; final VirtualLayoutManager.LayoutParams lp1 = new VirtualLayoutManager.LayoutParams( child1.getLayoutParams()); final View child2 = helper.getReverseLayout() ? mChildrenViews[5] : mChildrenViews[1]; final VirtualLayoutManager.LayoutParams lp2 = new VirtualLayoutManager.LayoutParams( child2.getLayoutParams()); final View child3 = helper.getReverseLayout() ? mChildrenViews[4] : mChildrenViews[2]; final VirtualLayoutManager.LayoutParams lp3 = new VirtualLayoutManager.LayoutParams( child3.getLayoutParams()); final View child4 = helper.getReverseLayout() ? mChildrenViews[3] : mChildrenViews[3]; final VirtualLayoutManager.LayoutParams lp4 = new VirtualLayoutManager.LayoutParams( child4.getLayoutParams()); final View child5 = helper.getReverseLayout() ? mChildrenViews[2] : mChildrenViews[4]; final VirtualLayoutManager.LayoutParams lp5 = new VirtualLayoutManager.LayoutParams( child5.getLayoutParams()); final View child6 = helper.getReverseLayout() ? mChildrenViews[1] : mChildrenViews[5]; final VirtualLayoutManager.LayoutParams lp6 = new VirtualLayoutManager.LayoutParams( child6.getLayoutParams()); final float weight1 = getViewMainWeight(lp1, 0); final float weight2 = getViewMainWeight(lp1, 1); final float weight3 = getViewMainWeight(lp1, 2); final float weight4 = getViewMainWeight(lp1, 3); final float weight5 = getViewMainWeight(lp1, 4); final float weight6 = getViewMainWeight(lp1, 5); if (layoutInVertical) { lp2.topMargin = lp1.topMargin; lp3.bottomMargin = lp4.bottomMargin = lp1.bottomMargin; lp3.leftMargin = lp2.leftMargin; lp4.rightMargin = lp2.rightMargin; lp5.rightMargin = lp2.rightMargin; if (!Float.isNaN(mAspectRatio)) { lp1.height = (int) ((parentWidth - parentHPadding) / mAspectRatio); } int availableSpace = parentWidth - parentHPadding - lp1.leftMargin - lp1.rightMargin - lp2.leftMargin - lp2.rightMargin; int width1 = Float.isNaN(weight1) ? (int) (availableSpace / 2.0f + 0.5f) : (int) (availableSpace * weight1 / 100 + 0.5f); int width2 = Float.isNaN(weight2) ? availableSpace - width1 : (int) (availableSpace * weight2 / 100 + 0.5f); int width3 = Float.isNaN(weight3) ? width2 : (int) (availableSpace * weight3 / 100 + 0.5); int bottomavailableSpace = parentWidth - parentHPadding - lp4.leftMargin - lp4.rightMargin - lp5.leftMargin - lp5.rightMargin - lp6.leftMargin - lp6.rightMargin; int width4 = Float.isNaN(weight4) ? (int) (bottomavailableSpace / 3.0f + 0.5f) : (int) (availableSpace * weight4 / 100 + 0.5f); int width5 = Float.isNaN(weight5) ? width4 : (int) (availableSpace * weight5 / 100 + 0.5f); int width6 = Float.isNaN(weight6) ? width4 : (int) (availableSpace * weight6 / 100 + 0.5f); helper.measureChildWithMargins(child1, MeasureSpec.makeMeasureSpec(width1 + lp1.leftMargin + lp1.rightMargin, MeasureSpec.EXACTLY), helper.getChildMeasureSpec(helper.getContentHeight(), lp1.height, true)); int height1 = child1.getMeasuredHeight(); int height2 = Float.isNaN(mRowWeight) ? (int) ((height1 - lp2.bottomMargin - lp3.topMargin) / 2.0f + 0.5f) : (int) ((height1 - lp2.bottomMargin - lp3.topMargin) * mRowWeight / 100 + 0.5f); int height3 = (height1 - lp2.bottomMargin - lp3.topMargin) - height2; helper.measureChildWithMargins(child2, MeasureSpec.makeMeasureSpec(width2 + lp2.leftMargin + lp2.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp2.topMargin + lp2.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child3, MeasureSpec.makeMeasureSpec(width3 + lp3.leftMargin + lp3.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp3.topMargin + lp3.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child4, MeasureSpec.makeMeasureSpec(width4 + lp4.leftMargin + lp4.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp4.topMargin + lp4.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child5, MeasureSpec.makeMeasureSpec(width5 + lp5.leftMargin + lp5.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp5.topMargin + lp5.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child6, MeasureSpec.makeMeasureSpec(width6 + lp6.leftMargin + lp6.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height3 + lp6.topMargin + lp6.bottomMargin, MeasureSpec.EXACTLY)); int maxTopHeight = Math.max(height1 + lp1.topMargin + lp1.bottomMargin, (height2 + lp2.topMargin + lp2.bottomMargin) * 2); int maxBottomHeight = Math.max(height3 + lp4.topMargin + lp4.bottomMargin, Math.max(height3 + lp5.topMargin + lp5.bottomMargin, height3 + lp6.topMargin + lp6.bottomMargin)); mainConsumed = maxTopHeight + maxBottomHeight + getVerticalMargin() + getVerticalPadding(); calculateRect(mainConsumed - getVerticalMargin() - getVerticalPadding(), mAreaRect, layoutState, helper); int right1 = mAreaRect.left + orientationHelper .getDecoratedMeasurementInOther(child1); layoutChildWithMargin(child1, mAreaRect.left, mAreaRect.top, right1, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child4), helper); int right2 = right1 + orientationHelper.getDecoratedMeasurementInOther(child2); layoutChildWithMargin(child2, right1, mAreaRect.top, right2, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child2), helper); int right3 = right1 + orientationHelper.getDecoratedMeasurementInOther(child3); layoutChildWithMargin(child3, right1, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child3), right3, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child4), helper); int right4 = mAreaRect.left + orientationHelper.getDecoratedMeasurementInOther(child4); layoutChildWithMargin(child4, mAreaRect.left, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child4), right4, mAreaRect.bottom, helper); int right5 = right4 + orientationHelper.getDecoratedMeasurementInOther(child5); layoutChildWithMargin(child5, right4, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child5), right5, mAreaRect.bottom, helper); int right6 = right5 + orientationHelper.getDecoratedMeasurementInOther(child6); layoutChildWithMargin(child6, right5, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child6), right6, mAreaRect.bottom, helper); } else { // TODO: horizontal support } handleStateOnResult(result, child1, child2, child3, child4, child5, child6); return mainConsumed; } private int handSeven(LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper, boolean layoutInVertical, int parentWidth, int parentHeight, int parentHPadding, int parentVPadding) { int mainConsumed = 0; OrientationHelperEx orientationHelper = helper.getMainOrientationHelper(); final View child1 = mChildrenViews[0]; final VirtualLayoutManager.LayoutParams lp1 = new VirtualLayoutManager.LayoutParams( child1.getLayoutParams()); final View child2 = helper.getReverseLayout() ? mChildrenViews[6] : mChildrenViews[1]; final VirtualLayoutManager.LayoutParams lp2 = new VirtualLayoutManager.LayoutParams( child2.getLayoutParams()); final View child3 = helper.getReverseLayout() ? mChildrenViews[5] : mChildrenViews[2]; final VirtualLayoutManager.LayoutParams lp3 = new VirtualLayoutManager.LayoutParams( child3.getLayoutParams()); final View child4 = helper.getReverseLayout() ? mChildrenViews[4] : mChildrenViews[3]; final VirtualLayoutManager.LayoutParams lp4 = new VirtualLayoutManager.LayoutParams( child4.getLayoutParams()); final View child5 = helper.getReverseLayout() ? mChildrenViews[3] : mChildrenViews[4]; final VirtualLayoutManager.LayoutParams lp5 = new VirtualLayoutManager.LayoutParams( child5.getLayoutParams()); final View child6 = helper.getReverseLayout() ? mChildrenViews[2] : mChildrenViews[5]; final VirtualLayoutManager.LayoutParams lp6 = new VirtualLayoutManager.LayoutParams( child6.getLayoutParams()); final View child7 = helper.getReverseLayout() ? mChildrenViews[1] : mChildrenViews[6]; final VirtualLayoutManager.LayoutParams lp7 = new VirtualLayoutManager.LayoutParams( child7.getLayoutParams()); final float weight1 = getViewMainWeight(lp1, 0); final float weight2 = getViewMainWeight(lp1, 1); final float weight3 = getViewMainWeight(lp1, 2); final float weight4 = getViewMainWeight(lp1, 3); final float weight5 = getViewMainWeight(lp1, 4); final float weight6 = getViewMainWeight(lp1, 5); final float weight7 = getViewMainWeight(lp1, 6); if (layoutInVertical) { if (!Float.isNaN(mAspectRatio)) { lp1.height = (int) ((parentWidth - parentHPadding) / mAspectRatio); } int availableSpace = parentWidth - parentHPadding - lp1.leftMargin - lp1.rightMargin - lp2.leftMargin - lp2.rightMargin - lp3.leftMargin - lp3.rightMargin; int width1 = Float.isNaN(weight1) ? (int) (availableSpace / 3.0f + 0.5f) : (int) (availableSpace * weight1 / 100 + 0.5f); int width2 = Float.isNaN(weight2) ? (availableSpace - width1) / 2 : (int) (availableSpace * weight2 / 100 + 0.5f); int width3 = Float.isNaN(weight3) ? width2 : (int) (availableSpace * weight3 / 100 + 0.5); int width4 = Float.isNaN(weight4) ? width2 : (int) (availableSpace * weight4 / 100 + 0.5f); int width5 = Float.isNaN(weight5) ? width2 : (int) (availableSpace * weight5 / 100 + 0.5f); int width6 = Float.isNaN(weight6) ? width2 : (int) (availableSpace * weight6 / 100 + 0.5f); int width7 = Float.isNaN(weight6) ? width2 : (int) (availableSpace * weight7 / 100 + 0.5f); helper.measureChildWithMargins(child1, MeasureSpec.makeMeasureSpec(width1 + lp1.leftMargin + lp1.rightMargin, MeasureSpec.EXACTLY), helper.getChildMeasureSpec(helper.getContentHeight(), lp1.height, true)); int height1 = child1.getMeasuredHeight(); int height2 = Float.isNaN(mRowWeight) ? (int) ((height1 - lp2.bottomMargin - lp3.topMargin) / 3.0f + 0.5f) : (int) ((height1 - lp2.bottomMargin - lp3.topMargin) * mRowWeight / 100 + 0.5f); helper.measureChildWithMargins(child2, MeasureSpec.makeMeasureSpec(width2 + lp2.leftMargin + lp2.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp2.topMargin + lp2.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child3, MeasureSpec.makeMeasureSpec(width3 + lp3.leftMargin + lp3.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp3.topMargin + lp3.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child4, MeasureSpec.makeMeasureSpec(width4 + lp4.leftMargin + lp4.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp4.topMargin + lp4.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child5, MeasureSpec.makeMeasureSpec(width5 + lp5.leftMargin + lp5.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp5.topMargin + lp5.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child6, MeasureSpec.makeMeasureSpec(width6 + lp6.leftMargin + lp6.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp6.topMargin + lp6.bottomMargin, MeasureSpec.EXACTLY)); helper.measureChildWithMargins(child7, MeasureSpec.makeMeasureSpec(width7 + lp7.leftMargin + lp7.rightMargin, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2 + lp7.topMargin + lp7.bottomMargin, MeasureSpec.EXACTLY)); int maxRightHeight = Math.max(height2 + lp2.topMargin + lp2.bottomMargin, height2 + lp3.topMargin + lp3.bottomMargin) + Math.max(height2 + lp4.topMargin + lp4.bottomMargin, height2 + lp5.topMargin + lp5.bottomMargin) + Math.max(height2 + lp6.topMargin + lp6.bottomMargin, height2 + lp7.topMargin + lp7.bottomMargin); int maxHeight = Math.max(height1 + lp1.topMargin + lp1.bottomMargin, maxRightHeight); mainConsumed = maxHeight + getVerticalMargin() + getVerticalPadding(); calculateRect(mainConsumed - getVerticalMargin() - getVerticalPadding(), mAreaRect, layoutState, helper); int right1 = mAreaRect.left + orientationHelper.getDecoratedMeasurementInOther(child1); layoutChildWithMargin(child1, mAreaRect.left, mAreaRect.top, right1, mAreaRect.bottom, helper); int right2 = right1 + orientationHelper.getDecoratedMeasurementInOther(child2); layoutChildWithMargin(child2, right1, mAreaRect.top, right2, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child2), helper); int right3 = right2 + orientationHelper.getDecoratedMeasurementInOther(child3); layoutChildWithMargin(child3, right2, mAreaRect.top, right3, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child3), helper); int right4 = right1 + orientationHelper.getDecoratedMeasurementInOther(child4); layoutChildWithMargin(child4, right1, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child2), right4, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child6), helper); int right5 = right4 + orientationHelper.getDecoratedMeasurementInOther(child5); layoutChildWithMargin(child5, right4, mAreaRect.top + orientationHelper.getDecoratedMeasurement(child2), right5, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child7), helper); int right6 = right1 + orientationHelper.getDecoratedMeasurementInOther(child6); layoutChildWithMargin(child6, right1, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child6), right6, mAreaRect.bottom, helper); layoutChildWithMargin(child7, right6, mAreaRect.bottom - orientationHelper.getDecoratedMeasurement(child7), right6 + orientationHelper.getDecoratedMeasurementInOther(child7), mAreaRect.bottom, helper); } else { // TODO: horizontal support } handleStateOnResult(result, child1, child2, child3, child4, child5, child6); return mainConsumed; } }
/** * 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.yarn.server.resourcemanager.scheduler.fair; import static org.junit.Assert.*; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueuePlacementRule.NestedUserQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FairSharePolicy; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Test; public class TestAllocationFileLoaderService { final static String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); final static String ALLOC_FILE = new File(TEST_DIR, "test-queues").getAbsolutePath(); @Test public void testGetAllocationFileFromClasspath() { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, "test-fair-scheduler.xml"); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); File allocationFile = allocLoader.getAllocationFile(conf); assertEquals("test-fair-scheduler.xml", allocationFile.getName()); assertTrue(allocationFile.exists()); } @Test (timeout = 10000) public void testReload() throws Exception { PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println(" <queue name=\"queueA\">"); out.println(" <maxRunningApps>1</maxRunningApps>"); out.println(" </queue>"); out.println(" <queue name=\"queueB\" />"); out.println(" <queuePlacementPolicy>"); out.println(" <rule name='default' />"); out.println(" </queuePlacementPolicy>"); out.println("</allocations>"); out.close(); ControlledClock clock = new ControlledClock(); clock.setTime(0); Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService( clock); allocLoader.reloadIntervalMs = 5; allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration allocConf = confHolder.allocConf; // Verify conf QueuePlacementPolicy policy = allocConf.getPlacementPolicy(); List<QueuePlacementRule> rules = policy.getRules(); assertEquals(1, rules.size()); assertEquals(QueuePlacementRule.Default.class, rules.get(0).getClass()); assertEquals(1, allocConf.getQueueMaxApps("root.queueA")); assertEquals(2, allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .size()); assertTrue(allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueA")); assertTrue(allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueB")); confHolder.allocConf = null; // Modify file and advance the clock out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println(" <queue name=\"queueB\">"); out.println(" <maxRunningApps>3</maxRunningApps>"); out.println(" </queue>"); out.println(" <queuePlacementPolicy>"); out.println(" <rule name='specified' />"); out.println(" <rule name='nestedUserQueue' >"); out.println(" <rule name='primaryGroup' />"); out.println(" </rule>"); out.println(" <rule name='default' />"); out.println(" </queuePlacementPolicy>"); out.println("</allocations>"); out.close(); clock.tickMsec(System.currentTimeMillis() + AllocationFileLoaderService.ALLOC_RELOAD_WAIT_MS + 10000); allocLoader.start(); while (confHolder.allocConf == null) { Thread.sleep(20); } // Verify conf allocConf = confHolder.allocConf; policy = allocConf.getPlacementPolicy(); rules = policy.getRules(); assertEquals(3, rules.size()); assertEquals(QueuePlacementRule.Specified.class, rules.get(0).getClass()); assertEquals(QueuePlacementRule.NestedUserQueue.class, rules.get(1) .getClass()); assertEquals(QueuePlacementRule.PrimaryGroup.class, ((NestedUserQueue) (rules.get(1))).nestedRule.getClass()); assertEquals(QueuePlacementRule.Default.class, rules.get(2).getClass()); assertEquals(3, allocConf.getQueueMaxApps("root.queueB")); assertEquals(1, allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .size()); assertTrue(allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueB")); } @Test public void testAllocationFileParsing() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); // Give queue A a minimum of 1024 M out.println("<queue name=\"queueA\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); // Give queue B a minimum of 2048 M out.println("<queue name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("<aclAdministerApps>alice,bob admins</aclAdministerApps>"); out.println("<schedulingPolicy>fair</schedulingPolicy>"); out.println("</queue>"); // Give queue C no minimum out.println("<queue name=\"queueC\">"); out.println("<aclSubmitApps>alice,bob admins</aclSubmitApps>"); out.println("</queue>"); // Give queue D a limit of 3 running apps and 0.4f maxAMShare out.println("<queue name=\"queueD\">"); out.println("<maxRunningApps>3</maxRunningApps>"); out.println("<maxAMShare>0.4</maxAMShare>"); out.println("</queue>"); // Give queue E a preemption timeout of one minute out.println("<queue name=\"queueE\">"); out.println("<minSharePreemptionTimeout>60</minSharePreemptionTimeout>"); out.println("</queue>"); //Make queue F a parent queue without configured leaf queues using the 'type' attribute out.println("<queue name=\"queueF\" type=\"parent\" >"); out.println("</queue>"); // Create hierarchical queues G,H, with different min/fair share preemption // timeouts and preemption thresholds out.println("<queue name=\"queueG\">"); out.println("<fairSharePreemptionTimeout>120</fairSharePreemptionTimeout>"); out.println("<minSharePreemptionTimeout>50</minSharePreemptionTimeout>"); out.println("<fairSharePreemptionThreshold>0.6</fairSharePreemptionThreshold>"); out.println(" <queue name=\"queueH\">"); out.println(" <fairSharePreemptionTimeout>180</fairSharePreemptionTimeout>"); out.println(" <minSharePreemptionTimeout>40</minSharePreemptionTimeout>"); out.println(" <fairSharePreemptionThreshold>0.7</fairSharePreemptionThreshold>"); out.println(" </queue>"); out.println("</queue>"); // Set default limit of apps per queue to 15 out.println("<queueMaxAppsDefault>15</queueMaxAppsDefault>"); // Set default limit of apps per user to 5 out.println("<userMaxAppsDefault>5</userMaxAppsDefault>"); // Set default limit of AMResourceShare to 0.5f out.println("<queueMaxAMShareDefault>0.5f</queueMaxAMShareDefault>"); // Give user1 a limit of 10 jobs out.println("<user name=\"user1\">"); out.println("<maxRunningApps>10</maxRunningApps>"); out.println("</user>"); // Set default min share preemption timeout to 2 minutes out.println("<defaultMinSharePreemptionTimeout>120" + "</defaultMinSharePreemptionTimeout>"); // Set default fair share preemption timeout to 5 minutes out.println("<defaultFairSharePreemptionTimeout>300</defaultFairSharePreemptionTimeout>"); // Set default fair share preemption threshold to 0.4 out.println("<defaultFairSharePreemptionThreshold>0.4</defaultFairSharePreemptionThreshold>"); // Set default scheduling policy to DRF out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>"); out.println("</allocations>"); out.close(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration queueConf = confHolder.allocConf; assertEquals(6, queueConf.getConfiguredQueues().get(FSQueueType.LEAF).size()); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(1024, 0), queueConf.getMinResources("root.queueA")); assertEquals(Resources.createResource(2048, 0), queueConf.getMinResources("root.queueB")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueC")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueD")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueE")); assertEquals(15, queueConf.getQueueMaxApps("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(15, queueConf.getQueueMaxApps("root.queueA")); assertEquals(15, queueConf.getQueueMaxApps("root.queueB")); assertEquals(15, queueConf.getQueueMaxApps("root.queueC")); assertEquals(3, queueConf.getQueueMaxApps("root.queueD")); assertEquals(15, queueConf.getQueueMaxApps("root.queueE")); assertEquals(10, queueConf.getUserMaxApps("user1")); assertEquals(5, queueConf.getUserMaxApps("user2")); assertEquals(.5f, queueConf.getQueueMaxAMShare("root." + YarnConfiguration.DEFAULT_QUEUE_NAME), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueA"), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueB"), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueC"), 0.01); assertEquals(.4f, queueConf.getQueueMaxAMShare("root.queueD"), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueE"), 0.01); // Root should get * ACL assertEquals("*", queueConf.getQueueAcl("root", QueueACL.ADMINISTER_QUEUE).getAclString()); assertEquals("*", queueConf.getQueueAcl("root", QueueACL.SUBMIT_APPLICATIONS).getAclString()); // Unspecified queues should get default ACL assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.ADMINISTER_QUEUE).getAclString()); assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.SUBMIT_APPLICATIONS).getAclString()); // Queue B ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueB", QueueACL.ADMINISTER_QUEUE).getAclString()); // Queue C ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueC", QueueACL.SUBMIT_APPLICATIONS).getAclString()); assertEquals(120000, queueConf.getMinSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueD")); assertEquals(60000, queueConf.getMinSharePreemptionTimeout("root.queueE")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueF")); assertEquals(50000, queueConf.getMinSharePreemptionTimeout("root.queueG")); assertEquals(40000, queueConf.getMinSharePreemptionTimeout("root.queueG.queueH")); assertEquals(300000, queueConf.getFairSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueD")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueE")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueF")); assertEquals(120000, queueConf.getFairSharePreemptionTimeout("root.queueG")); assertEquals(180000, queueConf.getFairSharePreemptionTimeout("root.queueG.queueH")); assertEquals(.4f, queueConf.getFairSharePreemptionThreshold("root"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root." + YarnConfiguration.DEFAULT_QUEUE_NAME), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueA"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueB"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueC"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueD"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueE"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueF"), 0.01); assertEquals(.6f, queueConf.getFairSharePreemptionThreshold("root.queueG"), 0.01); assertEquals(.7f, queueConf.getFairSharePreemptionThreshold("root.queueG.queueH"), 0.01); assertTrue(queueConf.getConfiguredQueues() .get(FSQueueType.PARENT) .contains("root.queueF")); assertTrue(queueConf.getConfiguredQueues().get(FSQueueType.PARENT) .contains("root.queueG")); assertTrue(queueConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueG.queueH")); // Verify existing queues have default scheduling policy assertEquals(DominantResourceFairnessPolicy.NAME, queueConf.getSchedulingPolicy("root").getName()); assertEquals(DominantResourceFairnessPolicy.NAME, queueConf.getSchedulingPolicy("root.queueA").getName()); // Verify default is overriden if specified explicitly assertEquals(FairSharePolicy.NAME, queueConf.getSchedulingPolicy("root.queueB").getName()); // Verify new queue gets default scheduling policy assertEquals(DominantResourceFairnessPolicy.NAME, queueConf.getSchedulingPolicy("root.newqueue").getName()); } @Test public void testBackwardsCompatibleAllocationFileParsing() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); // Give queue A a minimum of 1024 M out.println("<pool name=\"queueA\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</pool>"); // Give queue B a minimum of 2048 M out.println("<pool name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("<aclAdministerApps>alice,bob admins</aclAdministerApps>"); out.println("</pool>"); // Give queue C no minimum out.println("<pool name=\"queueC\">"); out.println("<aclSubmitApps>alice,bob admins</aclSubmitApps>"); out.println("</pool>"); // Give queue D a limit of 3 running apps out.println("<pool name=\"queueD\">"); out.println("<maxRunningApps>3</maxRunningApps>"); out.println("</pool>"); // Give queue E a preemption timeout of one minute and 0.3f threshold out.println("<pool name=\"queueE\">"); out.println("<minSharePreemptionTimeout>60</minSharePreemptionTimeout>"); out.println("<fairSharePreemptionThreshold>0.3</fairSharePreemptionThreshold>"); out.println("</pool>"); // Set default limit of apps per queue to 15 out.println("<queueMaxAppsDefault>15</queueMaxAppsDefault>"); // Set default limit of apps per user to 5 out.println("<userMaxAppsDefault>5</userMaxAppsDefault>"); // Give user1 a limit of 10 jobs out.println("<user name=\"user1\">"); out.println("<maxRunningApps>10</maxRunningApps>"); out.println("</user>"); // Set default min share preemption timeout to 2 minutes out.println("<defaultMinSharePreemptionTimeout>120" + "</defaultMinSharePreemptionTimeout>"); // Set fair share preemption timeout to 5 minutes out.println("<fairSharePreemptionTimeout>300</fairSharePreemptionTimeout>"); // Set default fair share preemption threshold to 0.6f out.println("<defaultFairSharePreemptionThreshold>0.6</defaultFairSharePreemptionThreshold>"); out.println("</allocations>"); out.close(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration queueConf = confHolder.allocConf; assertEquals(5, queueConf.getConfiguredQueues().get(FSQueueType.LEAF).size()); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(1024, 0), queueConf.getMinResources("root.queueA")); assertEquals(Resources.createResource(2048, 0), queueConf.getMinResources("root.queueB")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueC")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueD")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueE")); assertEquals(15, queueConf.getQueueMaxApps("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(15, queueConf.getQueueMaxApps("root.queueA")); assertEquals(15, queueConf.getQueueMaxApps("root.queueB")); assertEquals(15, queueConf.getQueueMaxApps("root.queueC")); assertEquals(3, queueConf.getQueueMaxApps("root.queueD")); assertEquals(15, queueConf.getQueueMaxApps("root.queueE")); assertEquals(10, queueConf.getUserMaxApps("user1")); assertEquals(5, queueConf.getUserMaxApps("user2")); // Unspecified queues should get default ACL assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.ADMINISTER_QUEUE).getAclString()); assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.SUBMIT_APPLICATIONS).getAclString()); // Queue B ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueB", QueueACL.ADMINISTER_QUEUE).getAclString()); // Queue C ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueC", QueueACL.SUBMIT_APPLICATIONS).getAclString()); assertEquals(120000, queueConf.getMinSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueD")); assertEquals(60000, queueConf.getMinSharePreemptionTimeout("root.queueE")); assertEquals(300000, queueConf.getFairSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueD")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueE")); assertEquals(.6f, queueConf.getFairSharePreemptionThreshold("root"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root." + YarnConfiguration.DEFAULT_QUEUE_NAME), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueA"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueB"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueC"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueD"), 0.01); assertEquals(.3f, queueConf.getFairSharePreemptionThreshold("root.queueE"), 0.01); } @Test public void testSimplePlacementPolicyFromConf() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); conf.setBoolean(FairSchedulerConfiguration.ALLOW_UNDECLARED_POOLS, false); conf.setBoolean(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, false); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration allocConf = confHolder.allocConf; QueuePlacementPolicy placementPolicy = allocConf.getPlacementPolicy(); List<QueuePlacementRule> rules = placementPolicy.getRules(); assertEquals(2, rules.size()); assertEquals(QueuePlacementRule.Specified.class, rules.get(0).getClass()); assertEquals(false, rules.get(0).create); assertEquals(QueuePlacementRule.Default.class, rules.get(1).getClass()); } /** * Verify that you can't place queues at the same level as the root queue in * the allocations file. */ @Test (expected = AllocationConfigurationException.class) public void testQueueAlongsideRoot() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println("</queue>"); out.println("<queue name=\"other\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } /** * Verify that you can't include periods as the queue name in the allocations * file. */ @Test (expected = AllocationConfigurationException.class) public void testQueueNameContainingPeriods() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"parent1.child1\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } /** * Verify that you can't have the queue name with whitespace only in the * allocations file. */ @Test (expected = AllocationConfigurationException.class) public void testQueueNameContainingOnlyWhitespace() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\" \">"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } @Test public void testReservableQueue() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"reservable\">"); out.println("<reservation>"); out.println("</reservation>"); out.println("</queue>"); out.println("<queue name=\"other\">"); out.println("</queue>"); out.println("<reservation-agent>DummyAgentName</reservation-agent>"); out.println("<reservation-policy>AnyAdmissionPolicy</reservation-policy>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration allocConf = confHolder.allocConf; String reservableQueueName = "root.reservable"; String nonreservableQueueName = "root.other"; assertFalse(allocConf.isReservable(nonreservableQueueName)); assertTrue(allocConf.isReservable(reservableQueueName)); assertTrue(allocConf.getMoveOnExpiry(reservableQueueName)); assertEquals(ReservationSchedulerConfiguration.DEFAULT_RESERVATION_WINDOW, allocConf.getReservationWindow(reservableQueueName)); assertEquals(100, allocConf.getInstantaneousMaxCapacity (reservableQueueName), 0.0001); assertEquals( "DummyAgentName", allocConf.getReservationAgent(reservableQueueName)); assertEquals(100, allocConf.getAverageCapacity(reservableQueueName), 0.001); assertFalse(allocConf.getShowReservationAsQueues(reservableQueueName)); assertEquals("AnyAdmissionPolicy", allocConf.getReservationAdmissionPolicy(reservableQueueName)); assertEquals(ReservationSchedulerConfiguration .DEFAULT_RESERVATION_PLANNER_NAME, allocConf.getReplanner(reservableQueueName)); assertEquals(ReservationSchedulerConfiguration .DEFAULT_RESERVATION_ENFORCEMENT_WINDOW, allocConf.getEnforcementWindow(reservableQueueName)); } /** * Verify that you can't have dynamic user queue and reservable queue on * the same queue */ @Test (expected = AllocationConfigurationException.class) public void testReservableCannotBeCombinedWithDynamicUserQueue() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"notboth\" type=\"parent\" >"); out.println("<reservation>"); out.println("</reservation>"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } private class ReloadListener implements AllocationFileLoaderService.Listener { public AllocationConfiguration allocConf; @Override public void onReload(AllocationConfiguration info) { allocConf = info; } } }
/* * 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.pig.builtin; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PushbackInputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.LoadStoreCaster; import org.apache.pig.PigWarning; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultBagFactory; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.util.LogUtils; import org.joda.time.DateTime; /** * This abstract class provides standard conversions between utf8 encoded data * and pig data types. It is intended to be extended by load and store * functions (such as {@link PigStorage}). */ public class Utf8StorageConverter implements LoadStoreCaster { protected BagFactory mBagFactory = BagFactory.getInstance(); protected TupleFactory mTupleFactory = TupleFactory.getInstance(); protected final Log mLog = LogFactory.getLog(getClass()); private static final Integer mMaxInt = Integer.valueOf(Integer.MAX_VALUE); private static final Integer mMinInt = Integer.valueOf(Integer.MIN_VALUE); private static final Long mMaxLong = Long.valueOf(Long.MAX_VALUE); private static final Long mMinLong = Long.valueOf(Long.MIN_VALUE); private static final int BUFFER_SIZE = 1024; public Utf8StorageConverter() { } private char findStartChar(char start) throws IOException{ switch (start) { case ')': return '('; case ']': return '['; case '}': return '{'; default: throw new IOException("Unknown start character"); } } private DataBag consumeBag(PushbackInputStream in, ResourceFieldSchema fieldSchema) throws IOException { if (fieldSchema==null) { throw new IOException("Schema is null"); } ResourceFieldSchema[] fss=fieldSchema.getSchema().getFields(); Tuple t; int buf; while ((buf=in.read())!='{') { if (buf==-1) { throw new IOException("Unexpect end of bag"); } } if (fss.length!=1) throw new IOException("Only tuple is allowed inside bag schema"); ResourceFieldSchema fs = fss[0]; DataBag db = DefaultBagFactory.getInstance().newDefaultBag(); while (true) { t = consumeTuple(in, fs); if (t!=null) db.add(t); while ((buf=in.read())!='}'&&buf!=',') { if (buf==-1) { throw new IOException("Unexpect end of bag"); } } if (buf=='}') break; } return db; } private Tuple consumeTuple(PushbackInputStream in, ResourceFieldSchema fieldSchema) throws IOException { if (fieldSchema==null) { throw new IOException("Schema is null"); } int buf; ByteArrayOutputStream mOut; while ((buf=in.read())!='('||buf=='}') { if (buf==-1) { throw new IOException("Unexpect end of tuple"); } if (buf=='}') { in.unread(buf); return null; } } Tuple t = TupleFactory.getInstance().newTuple(); if (fieldSchema.getSchema()!=null && fieldSchema.getSchema().getFields().length!=0) { ResourceFieldSchema[] fss = fieldSchema.getSchema().getFields(); // Interpret item inside tuple one by one based on the inner schema for (int i=0;i<fss.length;i++) { Object field; ResourceFieldSchema fs = fss[i]; int delimit = ','; if (i==fss.length-1) delimit = ')'; if (DataType.isComplex(fs.getType())) { field = consumeComplexType(in, fs); while ((buf=in.read())!=delimit) { if (buf==-1) { throw new IOException("Unexpect end of tuple"); } } } else { mOut = new ByteArrayOutputStream(BUFFER_SIZE); while ((buf=in.read())!=delimit) { if (buf==-1) { throw new IOException("Unexpect end of tuple"); } if (buf==delimit) break; mOut.write(buf); } field = parseSimpleType(mOut.toByteArray(), fs); } t.append(field); } } else { // No inner schema, treat everything inside tuple as bytearray Deque<Character> level = new LinkedList<Character>(); // keep track of nested tuple/bag/map. We do not interpret, save them as bytearray mOut = new ByteArrayOutputStream(BUFFER_SIZE); while (true) { buf=in.read(); if (buf==-1) { throw new IOException("Unexpect end of tuple"); } if (buf=='['||buf=='{'||buf=='(') { level.push((char)buf); mOut.write(buf); } else if (buf==')' && level.isEmpty()) // End of tuple { DataByteArray value = new DataByteArray(mOut.toByteArray()); t.append(value); break; } else if (buf==',' && level.isEmpty()) { DataByteArray value = new DataByteArray(mOut.toByteArray()); t.append(value); mOut.reset(); } else if (buf==']' ||buf=='}'||buf==')') { if (level.peek()==findStartChar((char)buf)) level.pop(); else throw new IOException("Malformed tuple"); mOut.write(buf); } else mOut.write(buf); } } return t; } private Map<String, Object> consumeMap(PushbackInputStream in, ResourceFieldSchema fieldSchema) throws IOException { int buf; while ((buf=in.read())!='[') { if (buf==-1) { throw new IOException("Unexpect end of map"); } } HashMap<String, Object> m = new HashMap<String, Object>(); ByteArrayOutputStream mOut = new ByteArrayOutputStream(BUFFER_SIZE); while (true) { // Read key (assume key can not contains special character such as #, (, [, {, }, ], ) while ((buf=in.read())!='#') { if (buf==-1) { throw new IOException("Unexpect end of map"); } mOut.write(buf); } String key = bytesToCharArray(mOut.toByteArray()); if (key.length()==0) throw new IOException("Map key can not be null"); // Read value mOut.reset(); Deque<Character> level = new LinkedList<Character>(); // keep track of nested tuple/bag/map. We do not interpret, save them as bytearray while (true) { buf=in.read(); if (buf==-1) { throw new IOException("Unexpect end of map"); } if (buf=='['||buf=='{'||buf=='(') { level.push((char)buf); } else if (buf==']' && level.isEmpty()) // End of map break; else if (buf==']' ||buf=='}'||buf==')') { if (level.isEmpty()) throw new IOException("Malformed map"); if (level.peek()==findStartChar((char)buf)) level.pop(); } else if (buf==','&&level.isEmpty()) { // Current map item complete break; } mOut.write(buf); } Object value = null; if (fieldSchema!=null && fieldSchema.getSchema()!=null && mOut.size()>0) { value = bytesToObject(mOut.toByteArray(), fieldSchema.getSchema().getFields()[0]); } else if (mOut.size()>0) { // untyped map value = new DataByteArray(mOut.toByteArray()); } m.put(key, value); mOut.reset(); if (buf==']') break; } return m; } private Object bytesToObject(byte[] b, ResourceFieldSchema fs) throws IOException { Object field; if (DataType.isComplex(fs.getType())) { ByteArrayInputStream bis = new ByteArrayInputStream(b); PushbackInputStream in = new PushbackInputStream(bis); field = consumeComplexType(in, fs); } else { field = parseSimpleType(b, fs); } return field; } private Object consumeComplexType(PushbackInputStream in, ResourceFieldSchema complexFieldSchema) throws IOException { Object field; switch (complexFieldSchema.getType()) { case DataType.BAG: field = consumeBag(in, complexFieldSchema); break; case DataType.TUPLE: field = consumeTuple(in, complexFieldSchema); break; case DataType.MAP: field = consumeMap(in, complexFieldSchema); break; default: throw new IOException("Unknown complex data type"); } return field; } private Object parseSimpleType(byte[] b, ResourceFieldSchema simpleFieldSchema) throws IOException { Object field; switch (simpleFieldSchema.getType()) { case DataType.INTEGER: field = bytesToInteger(b); break; case DataType.LONG: field = bytesToLong(b); break; case DataType.FLOAT: field = bytesToFloat(b); break; case DataType.DOUBLE: field = bytesToDouble(b); break; case DataType.CHARARRAY: field = bytesToCharArray(b); break; case DataType.BYTEARRAY: field = new DataByteArray(b); break; case DataType.BOOLEAN: field = bytesToBoolean(b); break; case DataType.BIGINTEGER: field = bytesToBigInteger(b); break; case DataType.BIGDECIMAL: field = bytesToBigDecimal(b); case DataType.DATETIME: field = bytesToDateTime(b); break; default: throw new IOException("Unknown simple data type"); } return field; } @Override public DataBag bytesToBag(byte[] b, ResourceFieldSchema schema) throws IOException { if(b == null) return null; DataBag db; try { ByteArrayInputStream bis = new ByteArrayInputStream(b); PushbackInputStream in = new PushbackInputStream(bis); db = consumeBag(in, schema); } catch (IOException e) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to type bag, caught ParseException <" + e.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } return db; } @Override public String bytesToCharArray(byte[] b) throws IOException { if(b == null) return null; return new String(b, "UTF-8"); } @Override public Double bytesToDouble(byte[] b) { if(b == null || b.length == 0) { return null; } try { return Double.valueOf(new String(b)); } catch (NumberFormatException nfe) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to double, caught NumberFormatException <" + nfe.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } } @Override public Float bytesToFloat(byte[] b) throws IOException { if(b == null || b.length == 0) { return null; } String s; if (b.length > 0 && (b[b.length - 1] == 'F' || b[b.length - 1] == 'f')) { s = new String(b, 0, b.length - 1); } else { s = new String(b); } try { return Float.valueOf(s); } catch (NumberFormatException nfe) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to float, caught NumberFormatException <" + nfe.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } } @Override public Boolean bytesToBoolean(byte[] b) throws IOException { if(b == null) return null; String s = new String(b); if (s.equalsIgnoreCase("true")) { return Boolean.TRUE; } else if (s.equalsIgnoreCase("false")) { return Boolean.FALSE; } else { return null; } } /** * Sanity check of whether this number is a valid integer or long. * @param number the number to check * @return true if it doesn't contain any invalid characters, i.e. only contains digits and '-' */ private static boolean sanityCheckIntegerLong(String number){ for (int i=0; i < number.length(); i++){ if (number.charAt(i) >= '0' && number.charAt(i) <='9' || i == 0 && number.charAt(i) == '-'){ // valid one } else{ // contains invalid characters, must not be a integer or long. return false; } } return true; } @Override public Integer bytesToInteger(byte[] b) throws IOException { if(b == null || b.length == 0) { return null; } String s = new String(b); s = s.trim(); Integer ret = null; // See PIG-2835. Using exception handling to check if it's a double is very expensive. // So we write our sanity check. if (sanityCheckIntegerLong(s)){ try { ret = Integer.valueOf(s); } catch (NumberFormatException nfe) { } } if (ret == null){ // It's possible that this field can be interpreted as a double. // Unfortunately Java doesn't handle this in Integer.valueOf. So // we need to try to convert it to a double and if that works then // go to an int. try { Double d = Double.valueOf(s); // Need to check for an overflow error if (Double.compare(d.doubleValue(), mMaxInt.doubleValue() + 1) >= 0 || Double.compare(d.doubleValue(), mMinInt.doubleValue() - 1) <= 0) { LogUtils.warn(this, "Value " + d + " too large for integer", PigWarning.TOO_LARGE_FOR_INT, mLog); return null; } return Integer.valueOf(d.intValue()); } catch (NumberFormatException nfe2) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to int, caught NumberFormatException <" + nfe2.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } } return ret; } @Override public Long bytesToLong(byte[] b) throws IOException { if (b == null || b.length == 0) { return null; } String s = new String(b).trim(); if(s.endsWith("l") || s.endsWith("L")) { s = s.substring(0, s.length()-1); } // See PIG-2835. Using exception handling to check if it's a double is very expensive. // So we write our sanity check. Long ret = null; if (sanityCheckIntegerLong(s)) { try { ret = Long.valueOf(s); } catch (NumberFormatException nfe) { } } if (ret == null) { // It's possible that this field can be interpreted as a double. // Unfortunately Java doesn't handle this in Long.valueOf. So // we need to try to convert it to a double and if that works then // go to an long. try { Double d = Double.valueOf(s); // Need to check for an overflow error if (Double.compare(d.doubleValue(), mMaxLong.doubleValue() + 1) > 0 || Double.compare(d.doubleValue(), mMinLong.doubleValue() - 1) < 0) { LogUtils.warn(this, "Value " + d + " too large for long", PigWarning.TOO_LARGE_FOR_INT, mLog); return null; } return Long.valueOf(d.longValue()); } catch (NumberFormatException nfe2) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to long, caught NumberFormatException <" + nfe2.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } } return ret; } @Override public DateTime bytesToDateTime(byte[] b) throws IOException { if (b == null) { return null; } try { String dtStr = new String(b); return ToDate.extractDateTime(dtStr); } catch (IllegalArgumentException e) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to datetime, caught IllegalArgumentException <" + e.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } } @Override public Map<String, Object> bytesToMap(byte[] b, ResourceFieldSchema fieldSchema) throws IOException { if(b == null) return null; Map<String, Object> map; try { ByteArrayInputStream bis = new ByteArrayInputStream(b); PushbackInputStream in = new PushbackInputStream(bis); map = consumeMap(in, fieldSchema); } catch (IOException e) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to type map, caught ParseException <" + e.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } return map; } @Override public Tuple bytesToTuple(byte[] b, ResourceFieldSchema fieldSchema) throws IOException { if(b == null) return null; Tuple t; try { ByteArrayInputStream bis = new ByteArrayInputStream(b); PushbackInputStream in = new PushbackInputStream(bis); t = consumeTuple(in, fieldSchema); } catch (IOException e) { LogUtils.warn(this, "Unable to interpret value " + Arrays.toString(b) + " in field being " + "converted to type tuple, caught ParseException <" + e.getMessage() + "> field discarded", PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog); return null; } return t; } @Override public BigInteger bytesToBigInteger(byte[] b) throws IOException { if (b == null || b.length == 0) { return null; } return new BigInteger(new String(b)); } @Override public BigDecimal bytesToBigDecimal(byte[] b) throws IOException { if (b == null || b.length == 0) { return null; } return new BigDecimal(new String(b)); } @Override public byte[] toBytes(DataBag bag) throws IOException { return bag.toString().getBytes(); } @Override public byte[] toBytes(String s) throws IOException { return s.getBytes(); } @Override public byte[] toBytes(Double d) throws IOException { return d.toString().getBytes(); } @Override public byte[] toBytes(Float f) throws IOException { return f.toString().getBytes(); } @Override public byte[] toBytes(Integer i) throws IOException { return i.toString().getBytes(); } @Override public byte[] toBytes(Long l) throws IOException { return l.toString().getBytes(); } @Override public byte[] toBytes(Boolean b) throws IOException { return b.toString().getBytes(); } @Override public byte[] toBytes(DateTime dt) throws IOException { return dt.toString().getBytes(); } @Override public byte[] toBytes(Map<String, Object> m) throws IOException { return DataType.mapToString(m).getBytes(); } @Override public byte[] toBytes(Tuple t) throws IOException { return t.toString().getBytes(); } @Override public byte[] toBytes(DataByteArray a) throws IOException { return a.get(); } @Override public byte[] toBytes(BigInteger bi) throws IOException { return bi.toString().getBytes(); } @Override public byte[] toBytes(BigDecimal bd) throws IOException { return bd.toString().getBytes(); } }
/* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package java.util; import static def.dom.Globals.window; import static jsweet.util.Lang.$apply; import static jsweet.util.Lang.$new; import static jsweet.util.Lang.string; import java.io.Serializable; /** * Represents a date and time. */ @SuppressWarnings("serial") public class Date implements Cloneable, Comparable<Date>, Serializable { /** * Encapsulates static data to avoid Date itself having a static * initializer. */ private static class StringData { public static final String[] DAYS = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; public static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; } public static long parse(String s) { double parsed = $apply(jsdateClass().$get("parse"), s); if (Double.isNaN(parsed)) { throw new IllegalArgumentException(); } return (long) parsed; } // CHECKSTYLE_OFF: Matching the spec. public static long UTC(int year, int month, int date, int hrs, int min, int sec) { return (long) $apply(jsdateClass().$get("UTC"), year + 1900, month, date, hrs, min, sec, 0); } // CHECKSTYLE_ON /** * Ensure a number is displayed with two digits. * * @return a two-character base 10 representation of the number */ protected static String padTwo(int number) { if (number < 10) { return "0" + number; } else { return String.valueOf(number); } } /** * JavaScript Date instance. */ private final def.js.Object jsdate; static private def.js.Object jsdateClass() { return (def.js.Object) window.$get("Date"); } public Date() { jsdate = $new(jsdateClass()); } public Date(int year, int month, int date) { this(year, month, date, 0, 0, 0); } public Date(int year, int month, int date, int hrs, int min) { this(year, month, date, hrs, min, 0); } public Date(int year, int month, int date, int hrs, int min, int sec) { jsdate = $new(jsdateClass()); $apply(jsdate.$get("setFullYear"), jsdate, year + 1900, month, date); $apply(jsdate.$get("setHours"), jsdate, hrs, min, sec, 0); fixDaylightSavings(hrs); } public Date(long date) { jsdate = $new(jsdateClass(), date); } public Date(String date) { this(Date.parse(date)); } public boolean after(Date when) { return getTime() > when.getTime(); } public boolean before(Date when) { return getTime() < when.getTime(); } public Object clone() { return new Date(getTime()); } @Override public int compareTo(Date other) { return Long.compare(getTime(), other.getTime()); } @Override public boolean equals(Object obj) { return ((obj instanceof Date) && (getTime() == ((Date) obj).getTime())); } public int getDate() { return (int) $apply(jsdate.$get("getDate"), jsdate); } public int getDay() { return (int) $apply(jsdate.$get("getDay"), jsdate); } public int getHours() { return (int) $apply(jsdate.$get("getHours"), jsdate); } public int getMinutes() { return (int) $apply(jsdate.$get("getMinutes"), jsdate); } public int getMonth() { return (int) $apply(jsdate.$get("getMonth"), jsdate); } public int getSeconds() { return (int) $apply(jsdate.$get("getSeconds"), jsdate); } public long getTime() { return (long) $apply(jsdate.$get("getTime"), jsdate); } public int getTimezoneOffset() { return (int) $apply(jsdate.$get("getTimezoneOffset"), jsdate); } public int getYear() { return (int) $apply(jsdate.$get("getFullYear"), jsdate) - 1900; } @Override public int hashCode() { long time = getTime(); return (int) (time ^ (time >>> 32)); } public void setDate(int date) { int hours = getHours(); $apply(jsdate.$get("setDate"), jsdate, date); fixDaylightSavings(hours); } public void setHours(int hours) { $apply(jsdate.$get("setHours"), jsdate, hours); fixDaylightSavings(hours); } public void setMinutes(int minutes) { int hours = getHours() + minutes / 60; $apply(jsdate.$get("setMinutes"), jsdate, minutes); fixDaylightSavings(hours); } public void setMonth(int month) { int hours = getHours(); $apply(jsdate.$get("setMonth"), jsdate, month); fixDaylightSavings(hours); } public void setSeconds(int seconds) { int hours = getHours() + seconds / (60 * 60); $apply(jsdate.$get("setSeconds"), jsdate, seconds); fixDaylightSavings(hours); } public void setTime(long time) { $apply(jsdate.$get("setTime"), jsdate, time); } public void setYear(int year) { int hours = getHours(); $apply(jsdate.$get("setFullYear"), jsdate, year + 1900); fixDaylightSavings(hours); } public String toGMTString() { return $apply(jsdate.$get("getUTCDate"), jsdate) + " " + StringData.MONTHS[(int) $apply(jsdate.$get("getUTCMonth"), jsdate)] + " " + $apply(jsdate.$get("getUTCFullYear"), jsdate) + " " + padTwo((int) $apply(jsdate.$get("getUTCHours"), jsdate)) + ":" + padTwo((int) $apply(jsdate.$get("getUTCMinutes"), jsdate)) + ":" + padTwo((int) $apply(jsdate.$get("getUTCSeconds"), jsdate)) + " GMT"; } public String toLocaleString() { return string(jsdate.toLocaleString()); } @Override public String toString() { // Compute timezone offset. The value that getTimezoneOffset returns is // backwards for the transformation that we want. int offset = -(int) getTimezoneOffset(); String hourOffset = ((offset >= 0) ? "+" : "") + (offset / 60); String minuteOffset = padTwo(Math.abs(offset) % 60); return StringData.DAYS[(int) getDay()] + " " + StringData.MONTHS[(int) getMonth()] + " " + padTwo((int) getDate()) + " " + padTwo((int) getHours()) + ":" + padTwo((int) getMinutes()) + ":" + padTwo((int) getSeconds()) + " GMT" + hourOffset + minuteOffset + " " + $apply(jsdate.$get("getFullYear"), jsdate); } private static final long ONE_HOUR_IN_MILLISECONDS = 60 * 60 * 1000; /* * Some browsers have the following behavior: * * GAP // Assume a U.S. time zone with daylight savings // Set a * non-existent time: 2:00 am Sunday March 8, 2009 var date = new Date(2009, * 2, 8, 2, 0, 0); var hours = date.getHours(); // returns 1 * * The equivalent Java code will return 3. * * OVERLAP // Assume a U.S. time zone with daylight savings // Set to an * ambiguous time: 1:30 am Sunday November 1, 2009 var date = new Date(2009, * 10, 1, 1, 30, 0); var nextHour = new Date(date.getTime() + 60*60*1000); * var hours = nextHour.getHours(); // returns 1 * * The equivalent Java code will return 2. * * To compensate, fixDaylightSavings adjusts the date to match Java * semantics. */ /** * Detects if the requested time falls into a non-existent time range due to * local time advancing into daylight savings time or is ambiguous due to * going out of daylight savings. If so, adjust accordingly. */ private void fixDaylightSavings(int requestedHours) { requestedHours %= 24; if (getHours() != requestedHours) { // Hours passed to the constructor don't match the hours in the // created JavaScript Date; this // might be due either because they are outside 0-24 range, there // was overflow from // minutes:secs:millis or because we are in the situation GAP and // has to be fixed. def.js.Object copy = $new(jsdateClass(), getTime()); $apply(copy.$get("setDate"), ((int) $apply(copy.$get("getDate"), copy) + 1)); int timeDiff = (int) $apply(jsdate.$get("getTimezoneOffset"), jsdate) - (int) $apply(copy.$get("getTimezoneOffset"), copy); // If the time zone offset is changing, advance the hours and // minutes from the initially requested time by the change amount if (timeDiff > 0) { // The requested time falls into a non-existent time range due // to // local time advancing into daylight savings time. If so, push // the requested // time forward out of the non-existent range. int timeDiffHours = timeDiff / 60; int timeDiffMinutes = timeDiff % 60; int day = (int) getDate(); int badHours = (int) getHours(); if (badHours + timeDiffHours >= 24) { day++; } def.js.Object newTime = $new(jsdateClass(), (int) $apply(jsdate.$get("getFullYear"), jsdate), getMonth(), day, requestedHours + timeDiffHours, getMinutes() + timeDiffMinutes, getSeconds(), (long) $apply(jsdate.$get("getMilliseconds"), jsdate)); setTime($apply(newTime.$get("getMilliseconds"), newTime)); } } // Check for situation OVERLAP by advancing the clock by 1 hour and see // if getHours() returns // the same. This solves issues like Safari returning '3/21/2015 23:00' // when time is set to // '2/22/2015'. long originalTimeInMillis = getTime(); setTime(originalTimeInMillis + ONE_HOUR_IN_MILLISECONDS); if (getHours() != requestedHours) { // We are not in the duplicated hour, so revert the change. setTime(originalTimeInMillis); } } }
/* Copyright 2010 University of Cambridge * Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in * compliance with this License. * * You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.csp.helper.persistence; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.collectionspace.csp.api.core.CSPRequestCache; import org.collectionspace.csp.api.core.CSPRequestCredentials; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.json.JSONException; import org.json.JSONObject; /** SplittingStorage is an implementation of storage which can be wrapped or used as a base class, which delegates * the execution of methods to another implementation of storage on the basis of the first path component. This * allows different code to execute in different path subtrees. * */ public class SplittingStorage implements ContextualisedStorage { private Map<String,ContextualisedStorage> children=new HashMap<String,ContextualisedStorage>(); public void addChild(String prefix,ContextualisedStorage store) { children.put(prefix,store); } private ContextualisedStorage get(String path) throws ExistException { ContextualisedStorage out=children.get(path); if(out==null) throw new ExistException("No child storage bound to "+path); return out; } private String[] split(String path,boolean missing_is_blank) throws ExistException { // REM - Please document so I don't have to interpret this parsing code each time. if(path.startsWith("/")) path=path.substring(1); String[] out=path.split("/",2); if(out.length<2) { if(missing_is_blank) return new String[]{path,""}; else throw new ExistException("Path is split point, not destination"); } return out; } @Override public void createJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(filePath,true); if("".equals(parts[1])) { // autocreate? get(parts[0]).autocreateJSON(root,creds,cache,"",jsonObject, null /*no path restrictions*/); return; } get(parts[0]).createJSON(root,creds,cache,parts[1],jsonObject); } /** * For each type of storage, this function will get the paths and pagination information, this will be brought together into one object */ @Override public JSONObject getPathsJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String rootPath,JSONObject restriction) throws ExistException, UnimplementedException, UnderlyingStorageException { try{ //XXX THIS SHOULD BE LOOKED AT AND CHANGED !!! JSONObject out = new JSONObject(); JSONObject pagination = new JSONObject(); JSONObject moredata = new JSONObject(); boolean passed = false; List<String[]> separatelists = new ArrayList<String[]>(); String parts[]=split(rootPath,true); if("".equals(parts[0])) { return out.put("listItems",children.keySet().toArray(new String[0])); } else { List<String> list=new ArrayList<String>(); for(Map.Entry<String,ContextualisedStorage> e : children.entrySet()) { if(e.getKey().equals(parts[0])) { ContextualisedStorage storage=e.getValue(); JSONObject data=storage.getPathsJSON(root,creds,cache,parts[1],restriction); if(data==null){ data = new JSONObject(); data.put("listItems", new String[0]) ; } if(data.has("moredata")){ moredata = data.getJSONObject("moredata"); } JSONObject paging = new JSONObject(); if(data.has("pagination")){ paging = data.getJSONObject("pagination"); } if(!passed){ pagination = paging; passed = true; }else{ pagination.put("totalItems",pagination.getInt("totalItems") + paging.getInt("totalItems")); int pageSize = pagination.getInt("pageSize"); int totalinpage = pagination.getInt("itemsInPage") + paging.getInt("itemsInPage"); if(totalinpage > pageSize){ pagination.put("itemsInPage",pageSize); }else{ pagination.put("itemsInPage", totalinpage); } } //create one merged list String[] paths = (String[]) data.get("listItems"); if(paths==null){ continue; } for(String s : paths) { list.add(s); } //keep the separate lists in a field separatelists.add(paths); } } pagination.put("separatelists", separatelists); out.put("moredata", moredata); out.put("pagination", pagination); out.put("listItems",list.toArray(new String[0])); return out; } }catch(JSONException e){ throw new UnderlyingStorageException("Error parsing JSON"); } } @Override public String[] getPaths(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String rootPath,JSONObject restriction) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(rootPath,true); if("".equals(parts[0])) { return children.keySet().toArray(new String[0]); } else { List<String> out=new ArrayList<String>(); for(Map.Entry<String,ContextualisedStorage> e : children.entrySet()) { if(e.getKey().equals(parts[0])) { ContextualisedStorage storage=e.getValue(); String[] paths=storage.getPaths(root,creds,cache,parts[1],restriction); if(paths==null) continue; for(String s : paths) { out.add(s); } } } return out.toArray(new String[0]); } } @Override public JSONObject retrieveJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(filePath,false); return get(parts[0]).retrieveJSON(root,creds,cache,parts[1],restrictions); } @Override public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(filePath,false); get(parts[0]).updateJSON(root,creds,cache,parts[1],jsonObject, restrictions); } @Override public String autocreateJSON( ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject jsonObject, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(filePath,true); // REM return get(parts[0]).autocreateJSON(root,creds,cache,parts[1],jsonObject, restrictions); } @Override public void deleteJSON( ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(filePath,false); get(parts[0]).deleteJSON(root,creds,cache,parts[1]); } @Override public void transitionWorkflowJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, String workflowTransition) throws ExistException, UnimplementedException, UnderlyingStorageException { String parts[]=split(filePath,false); get(parts[0]).transitionWorkflowJSON(root,creds,cache,parts[1],workflowTransition); } }
/** * Copyright 2015 IBM Corp. All Rights Reserved. * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.watson.developer_cloud.natural_language_classifier.v1; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import io.netty.handler.codec.http.HttpHeaders; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockserver.integration.ClientAndServer; import org.mockserver.model.Header; import com.google.gson.JsonObject; import com.ibm.watson.developer_cloud.WatsonServiceTest; import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.Classification; import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.ClassifiedClass; import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.Classifier; import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.Classifiers; import com.ibm.watson.developer_cloud.util.GsonSingleton; import com.ibm.watson.developer_cloud.util.MediaType; /** * The Class NaturalLanguageClassifierTest. */ public class NaturalLanguageClassifierTest extends WatsonServiceTest { /** The Constant log. */ private static final Logger log = Logger.getLogger(NaturalLanguageClassifierTest.class.getName()); /** The service. */ private NaturalLanguageClassifier service; /** The classifier id. */ private String classifierId; /** Mock Server *. */ private ClientAndServer mockServer; /** The Constant CLASSIFY_PATH. (value is "/v1/classifiers/%s/classify") */ private final static String LANGUAGE_CLASSIFY_PATH = "/v1/classifiers/%s/classify"; /** The Constant LANGUAGE_CLASSIFIERS_PATH. (value is "/v1/classifiers/") */ private final static String LANGUAGE_CLASSIFIERS_PATH = "/v1/classifiers"; /** * Start mock server. */ @Before public void startMockServer() { try { mockServer = startClientAndServer(Integer.parseInt(prop.getProperty("mock.server.port"))); service = new NaturalLanguageClassifier(); service.setApiKey(""); service.setEndPoint("http://" + prop.getProperty("mock.server.host") + ":" + prop.getProperty("mock.server.port")); } catch (NumberFormatException e) { log.log(Level.SEVERE, "Error mocking the service", e); } } /** * Stop mock server. */ @After public void stopMockServer() { mockServer.stop(); } /* (non-Javadoc) * @see com.ibm.watson.developer_cloud.WatsonServiceTest#setUp() */ @Override @Before public void setUp() throws Exception { super.setUp(); classifierId = prop.getProperty("natural_language_classifier.classifier_id"); } /** * Test classify. */ @Test public void testClassify() { Classification response = new Classification(); response.setId("testId"); response.setText("is it sunny?"); response.setUrl("http://www.ibm.com"); response.setTopClass("conditions"); List<ClassifiedClass> classes = new ArrayList<ClassifiedClass>(); ClassifiedClass c1 = new ClassifiedClass(); c1.setConfidence(0.98189); c1.setName("class1"); ClassifiedClass c2 = new ClassifiedClass(); c2.setConfidence(0.98188); c2.setName("class2"); classes.add(c1); classes.add(c2); response.setClasses(classes); System.out.println(GsonSingleton.getGson().toJson(response)); StringBuilder text = new StringBuilder().append("is it sunny?"); JsonObject contentJson = new JsonObject(); contentJson.addProperty("text", text.toString()); String path = String .format(LANGUAGE_CLASSIFY_PATH, classifierId); mockServer.when( request().withMethod("POST").withPath(path) .withBody(contentJson.toString()) ) .respond( response().withHeaders(new Header(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .withBody(GsonSingleton.getGson().toJson(response))); Classification c = service.classify(classifierId, text.toString()); Assert.assertNotNull(c); Assert.assertEquals(c, response); } /** * Test get classifier. */ @Test public void testGetClassifier() { System.out.println(GsonSingleton.getGson().toJson("")); Classifier response = new Classifier(); response.setId("testId"); response.setStatus(Classifier.Status.AVAILABLE); response.setUrl("http://gateway.watson.net/"); response.setStatusDescription("The classifier instance is now available and is ready to take classifier requests."); mockServer.when(request().withPath(LANGUAGE_CLASSIFIERS_PATH + "/" + classifierId)).respond( response().withHeaders(new Header(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .withBody(GsonSingleton.getGson().toJson(response))); Classifier c = service.getClassifier(classifierId); Assert.assertNotNull(c); Assert.assertEquals(c, response); } /** * Test get classifiers. */ @Test public void testGetClassifiers() { Map<String, Object> response = new HashMap<String, Object>(); List<Classifier> classifiersResponse = new ArrayList<Classifier>(); Classifier c = new Classifier(); c.setId("testId"); c.setStatus(Classifier.Status.AVAILABLE); c.setUrl("http://gateway.watson.net/"); c.setStatusDescription("The classifier instance is now available and is ready to take classifier requests."); classifiersResponse.add(c); Classifier c1 = new Classifier(); c1.setId("testId1"); c1.setStatus(Classifier.Status.AVAILABLE); c1.setUrl("http://gateway.watson.net/"); c1.setStatusDescription("The classifier instance is now available and is ready to take classifier requests."); classifiersResponse.add(c1); Classifier c2 = new Classifier(); c2.setId("testId2"); c2.setStatus(Classifier.Status.AVAILABLE); c2.setUrl("http://gateway.watson.net/"); c2.setStatusDescription("The classifier instance is now available and is ready to take classifier requests."); classifiersResponse.add(c2); response.put("classifiers", classifiersResponse); mockServer.when(request().withPath(LANGUAGE_CLASSIFIERS_PATH)).respond( response().withHeaders(new Header(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .withBody(GsonSingleton.getGson().toJson(response))); Classifiers classifiers = service.getClassifiers(); Assert.assertNotNull(classifiers.getClassifiers()); Assert.assertFalse(classifiers.getClassifiers().isEmpty()); Assert.assertFalse(classifiers.getClassifiers().contains(classifiersResponse)); } }
package ca.uhn.fhir.jpa.subscription.submit.interceptor; /*- * #%L * HAPI FHIR Subscription Server * %% * Copyright (C) 2014 - 2022 Smile CDR, 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. * #L% */ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.interceptor.api.Hook; import ca.uhn.fhir.interceptor.api.Interceptor; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.api.config.DaoConfig; import ca.uhn.fhir.jpa.api.dao.DaoRegistry; import ca.uhn.fhir.jpa.partition.IRequestPartitionHelperSvc; import ca.uhn.fhir.jpa.partition.SystemRequestDetails; import ca.uhn.fhir.jpa.subscription.match.matcher.matching.SubscriptionMatchingStrategy; import ca.uhn.fhir.jpa.subscription.match.matcher.matching.SubscriptionStrategyEvaluator; import ca.uhn.fhir.jpa.subscription.match.matcher.subscriber.SubscriptionCriteriaParser; import ca.uhn.fhir.jpa.subscription.match.registry.SubscriptionCanonicalizer; import ca.uhn.fhir.jpa.subscription.model.CanonicalSubscription; import ca.uhn.fhir.jpa.subscription.model.CanonicalSubscriptionChannelType; import ca.uhn.fhir.parser.DataFormatException; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import ca.uhn.fhir.util.HapiExtensions; import ca.uhn.fhir.util.SubscriptionUtil; import com.google.common.annotations.VisibleForTesting; import org.hl7.fhir.instance.model.api.IBaseResource; import org.springframework.beans.factory.annotation.Autowired; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; import static org.apache.commons.lang3.StringUtils.isBlank; @Interceptor public class SubscriptionValidatingInterceptor { @Autowired private SubscriptionCanonicalizer mySubscriptionCanonicalizer; @Autowired private DaoRegistry myDaoRegistry; @Autowired private DaoConfig myDaoConfig; @Autowired private SubscriptionStrategyEvaluator mySubscriptionStrategyEvaluator; @Autowired private FhirContext myFhirContext; @Autowired private IRequestPartitionHelperSvc myRequestPartitionHelperSvc; @Hook(Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED) public void resourcePreCreate(IBaseResource theResource, RequestDetails theRequestDetails) { validateSubmittedSubscription(theResource, theRequestDetails); } @Hook(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED) public void resourcePreCreate(IBaseResource theOldResource, IBaseResource theResource, RequestDetails theRequestDetails) { validateSubmittedSubscription(theResource, theRequestDetails); } @VisibleForTesting public void setFhirContextForUnitTest(FhirContext theFhirContext) { myFhirContext = theFhirContext; } @Deprecated public void validateSubmittedSubscription(IBaseResource theSubscription) { validateSubmittedSubscription(theSubscription, null); } public void validateSubmittedSubscription(IBaseResource theSubscription, RequestDetails theRequestDetails) { if (!"Subscription".equals(myFhirContext.getResourceType(theSubscription))) { return; } CanonicalSubscription subscription = mySubscriptionCanonicalizer.canonicalize(theSubscription); boolean finished = false; if (subscription.getStatus() == null) { throw new UnprocessableEntityException("Can not process submitted Subscription - Subscription.status must be populated on this server"); } switch (subscription.getStatus()) { case REQUESTED: case ACTIVE: break; case ERROR: case OFF: case NULL: finished = true; break; } // If the subscription has the cross partition tag && if (SubscriptionUtil.isCrossPartition(theSubscription) && !(theRequestDetails instanceof SystemRequestDetails)) { if (!myDaoConfig.isCrossPartitionSubscription()){ throw new UnprocessableEntityException("Cross partition subscription is not enabled on this server"); } if (!determinePartition(theRequestDetails, theSubscription).isDefaultPartition()) { throw new UnprocessableEntityException("Cross partition subscription must be created on the default partition"); } } mySubscriptionCanonicalizer.setMatchingStrategyTag(theSubscription, null); if (!finished) { validateQuery(subscription.getCriteriaString(), "Subscription.criteria"); if (subscription.getPayloadSearchCriteria() != null) { validateQuery(subscription.getPayloadSearchCriteria(), "Subscription.extension(url='" + HapiExtensions.EXT_SUBSCRIPTION_PAYLOAD_SEARCH_CRITERIA + "')"); } validateChannelType(subscription); try { SubscriptionMatchingStrategy strategy = mySubscriptionStrategyEvaluator.determineStrategy(subscription.getCriteriaString()); mySubscriptionCanonicalizer.setMatchingStrategyTag(theSubscription, strategy); } catch (InvalidRequestException | DataFormatException e) { throw new UnprocessableEntityException("Invalid subscription criteria submitted: " + subscription.getCriteriaString() + " " + e.getMessage()); } if (subscription.getChannelType() == null) { throw new UnprocessableEntityException("Subscription.channel.type must be populated on this server"); } else if (subscription.getChannelType() == CanonicalSubscriptionChannelType.MESSAGE) { validateMessageSubscriptionEndpoint(subscription.getEndpointUrl()); } } } private RequestPartitionId determinePartition(RequestDetails theRequestDetails, IBaseResource theResource) { switch (theRequestDetails.getRestOperationType()) { case CREATE: return myRequestPartitionHelperSvc.determineCreatePartitionForRequest(theRequestDetails, theResource, "Subscription"); case UPDATE: return myRequestPartitionHelperSvc.determineReadPartitionForRequestForRead(theRequestDetails, "Subscription", theResource.getIdElement()); default: return null; } } public void validateQuery(String theQuery, String theFieldName) { if (isBlank(theQuery)) { throw new UnprocessableEntityException(theFieldName + " must be populated"); } SubscriptionCriteriaParser.SubscriptionCriteria parsedCriteria = SubscriptionCriteriaParser.parse(theQuery); if (parsedCriteria == null) { throw new UnprocessableEntityException(theFieldName + " can not be parsed"); } if (parsedCriteria.getType() == SubscriptionCriteriaParser.TypeEnum.STARTYPE_EXPRESSION) { return; } for (String next : parsedCriteria.getApplicableResourceTypes()) { if (!myDaoRegistry.isResourceTypeSupported(next)) { throw new UnprocessableEntityException(theFieldName + " contains invalid/unsupported resource type: " + next); } } if (parsedCriteria.getType() != SubscriptionCriteriaParser.TypeEnum.SEARCH_EXPRESSION) { return; } int sep = theQuery.indexOf('?'); if (sep <= 1) { throw new UnprocessableEntityException(theFieldName + " must be in the form \"{Resource Type}?[params]\""); } String resType = theQuery.substring(0, sep); if (resType.contains("/")) { throw new UnprocessableEntityException(theFieldName + " must be in the form \"{Resource Type}?[params]\""); } } public void validateMessageSubscriptionEndpoint(String theEndpointUrl) { if (theEndpointUrl == null) { throw new UnprocessableEntityException("No endpoint defined for message subscription"); } try { URI uri = new URI(theEndpointUrl); if (!"channel".equals(uri.getScheme())) { throw new UnprocessableEntityException("Only 'channel' protocol is supported for Subscriptions with channel type 'message'"); } String channelName = uri.getSchemeSpecificPart(); if (isBlank(channelName)) { throw new UnprocessableEntityException("A channel name must appear after channel: in a message Subscription endpoint"); } } catch (URISyntaxException e) { throw new UnprocessableEntityException("Invalid subscription endpoint uri " + theEndpointUrl, e); } } @SuppressWarnings("WeakerAccess") protected void validateChannelType(CanonicalSubscription theSubscription) { if (theSubscription.getChannelType() == null) { throw new UnprocessableEntityException("Subscription.channel.type must be populated"); } else if (theSubscription.getChannelType() == CanonicalSubscriptionChannelType.RESTHOOK) { validateChannelPayload(theSubscription); validateChannelEndpoint(theSubscription); } } @SuppressWarnings("WeakerAccess") protected void validateChannelEndpoint(CanonicalSubscription theResource) { if (isBlank(theResource.getEndpointUrl())) { throw new UnprocessableEntityException("Rest-hook subscriptions must have Subscription.channel.endpoint defined"); } } @SuppressWarnings("WeakerAccess") protected void validateChannelPayload(CanonicalSubscription theResource) { if (!isBlank(theResource.getPayloadString()) && EncodingEnum.forContentType(theResource.getPayloadString()) == null) { throw new UnprocessableEntityException("Invalid value for Subscription.channel.payload: " + theResource.getPayloadString()); } } @SuppressWarnings("WeakerAccess") @VisibleForTesting public void setSubscriptionCanonicalizerForUnitTest(SubscriptionCanonicalizer theSubscriptionCanonicalizer) { mySubscriptionCanonicalizer = theSubscriptionCanonicalizer; } @SuppressWarnings("WeakerAccess") @VisibleForTesting public void setDaoRegistryForUnitTest(DaoRegistry theDaoRegistry) { myDaoRegistry = theDaoRegistry; } @VisibleForTesting public void setDaoConfigForUnitTest(DaoConfig theDaoConfig) { myDaoConfig = theDaoConfig; } @VisibleForTesting public void setRequestPartitionHelperSvcForUnitTest(IRequestPartitionHelperSvc theRequestPartitionHelperSvc) { myRequestPartitionHelperSvc = theRequestPartitionHelperSvc; } @VisibleForTesting @SuppressWarnings("WeakerAccess") public void setSubscriptionStrategyEvaluatorForUnitTest(SubscriptionStrategyEvaluator theSubscriptionStrategyEvaluator) { mySubscriptionStrategyEvaluator = theSubscriptionStrategyEvaluator; } }
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; import net.sourceforge.pmd.lang.java.ast.ASTArguments; import net.sourceforge.pmd.lang.java.ast.ASTArrayDimsAndInits; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; /** * 1. Note all private constructors. * 2. Note all instantiations from outside of the class by way of the private * constructor. * 3. Flag instantiations. * <p/> * <p/> * Parameter types can not be matched because they can come as exposed members * of classes. In this case we have no way to know what the type is. We can * make a best effort though which can filter some? * * @author CL Gilbert (dnoyeb@users.sourceforge.net) * @author David Konecny (david.konecny@) * @author Romain PELISSE, belaran@gmail.com, patch bug#1807370 */ public class AccessorClassGenerationRule extends AbstractJavaRule { private List<ClassData> classDataList = new ArrayList<ClassData>(); private int classID = -1; private String packageName; public Object visit(ASTEnumDeclaration node, Object data) { return data; // just skip Enums } public Object visit(ASTCompilationUnit node, Object data) { classDataList.clear(); packageName = node.getScope().getEnclosingSourceFileScope().getPackageName(); return super.visit(node, data); } private static class ClassData { private String className; private List<ASTConstructorDeclaration> privateConstructors; private List<AllocData> instantiations; /** * List of outer class names that exist above this class */ private List<String> classQualifyingNames; public ClassData(String className) { this.className = className; this.privateConstructors = new ArrayList<ASTConstructorDeclaration>(); this.instantiations = new ArrayList<AllocData>(); this.classQualifyingNames = new ArrayList<String>(); } public void addInstantiation(AllocData ad) { instantiations.add(ad); } public Iterator<AllocData> getInstantiationIterator() { return instantiations.iterator(); } public void addConstructor(ASTConstructorDeclaration cd) { privateConstructors.add(cd); } public Iterator<ASTConstructorDeclaration> getPrivateConstructorIterator() { return privateConstructors.iterator(); } public String getClassName() { return className; } public void addClassQualifyingName(String name) { classQualifyingNames.add(name); } public List<String> getClassQualifyingNamesList() { return classQualifyingNames; } } private static class AllocData { private String name; private int argumentCount; private ASTAllocationExpression allocationExpression; private boolean isArray; public AllocData(ASTAllocationExpression node, String aPackageName, List<String> classQualifyingNames) { if (node.jjtGetChild(1) instanceof ASTArguments) { ASTArguments aa = (ASTArguments) node.jjtGetChild(1); argumentCount = aa.getArgumentCount(); //Get name and strip off all superfluous data //strip off package name if it is current package if (!(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) { throw new RuntimeException("BUG: Expected a ASTClassOrInterfaceType, got a " + node.jjtGetChild(0).getClass()); } ASTClassOrInterfaceType an = (ASTClassOrInterfaceType) node.jjtGetChild(0); name = stripString(aPackageName + '.', an.getImage()); //strip off outer class names //try OuterClass, then try OuterClass.InnerClass, then try OuterClass.InnerClass.InnerClass2, etc... String findName = ""; for (ListIterator<String> li = classQualifyingNames.listIterator(classQualifyingNames.size()); li.hasPrevious();) { String aName = li.previous(); findName = aName + '.' + findName; if (name.startsWith(findName)) { //strip off name and exit name = name.substring(findName.length()); break; } } } else if (node.jjtGetChild(1) instanceof ASTArrayDimsAndInits) { //this is incomplete because I dont need it. // child 0 could be primitive or object (ASTName or ASTPrimitiveType) isArray = true; } allocationExpression = node; } public String getName() { return name; } public int getArgumentCount() { return argumentCount; } public ASTAllocationExpression getASTAllocationExpression() { return allocationExpression; } public boolean isArray() { return isArray; } } /** * Outer interface visitation */ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface()) { if (!(node.jjtGetParent().jjtGetParent() instanceof ASTCompilationUnit)) { // not a top level interface String interfaceName = node.getImage(); int formerID = getClassID(); setClassID(classDataList.size()); ClassData newClassData = new ClassData(interfaceName); //store the names of any outer classes of this class in the classQualifyingName List ClassData formerClassData = classDataList.get(formerID); newClassData.addClassQualifyingName(formerClassData.getClassName()); classDataList.add(getClassID(), newClassData); Object o = super.visit(node, data); setClassID(formerID); return o; } else { String interfaceName = node.getImage(); classDataList.clear(); setClassID(0); classDataList.add(getClassID(), new ClassData(interfaceName)); Object o = super.visit(node, data); if (o != null) { processRule(o); } else { processRule(data); } setClassID(-1); return o; } } else if (!(node.jjtGetParent().jjtGetParent() instanceof ASTCompilationUnit)) { // not a top level class String className = node.getImage(); int formerID = getClassID(); setClassID(classDataList.size()); ClassData newClassData = new ClassData(className); // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (formerID == -1 || formerID >= classDataList.size()) { return null; } //store the names of any outer classes of this class in the classQualifyingName List ClassData formerClassData = classDataList.get(formerID); newClassData.addClassQualifyingName(formerClassData.getClassName()); classDataList.add(getClassID(), newClassData); Object o = super.visit(node, data); setClassID(formerID); return o; } // outer classes if ( ! node.isStatic() ) { // See bug# 1807370 String className = node.getImage(); classDataList.clear(); setClassID(0);//first class classDataList.add(getClassID(), new ClassData(className)); } Object o = super.visit(node, data); if (o != null && ! node.isStatic() ) { // See bug# 1807370 processRule(o); } else { processRule(data); } setClassID(-1); return o; } /** * Store all target constructors */ public Object visit(ASTConstructorDeclaration node, Object data) { if (node.isPrivate()) { getCurrentClassData().addConstructor(node); } return super.visit(node, data); } public Object visit(ASTAllocationExpression node, Object data) { // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (classID == -1 || getCurrentClassData() == null) { return data; } AllocData ad = new AllocData(node, packageName, getCurrentClassData().getClassQualifyingNamesList()); if (!ad.isArray()) { getCurrentClassData().addInstantiation(ad); } return super.visit(node, data); } private void processRule(Object ctx) { //check constructors of outerIterator against allocations of innerIterator for (ClassData outerDataSet : classDataList) { for (Iterator<ASTConstructorDeclaration> constructors = outerDataSet.getPrivateConstructorIterator(); constructors.hasNext();) { ASTConstructorDeclaration cd = constructors.next(); for (ClassData innerDataSet : classDataList) { if (outerDataSet == innerDataSet) { continue; } for (Iterator<AllocData> allocations = innerDataSet.getInstantiationIterator(); allocations.hasNext();) { AllocData ad = allocations.next(); //if the constructor matches the instantiation //flag the instantiation as a generator of an extra class if (outerDataSet.getClassName().equals(ad.getName()) && (cd.getParameterCount() == ad.getArgumentCount())) { addViolation(ctx, ad.getASTAllocationExpression()); } } } } } } private ClassData getCurrentClassData() { // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (classID >= classDataList.size()) { return null; } return classDataList.get(classID); } private void setClassID(int id) { classID = id; } private int getClassID() { return classID; } //remove = Fire. //value = someFire.Fighter // 0123456789012345 //index = 4 //remove.size() = 5 //value.substring(0,4) = some //value.substring(4 + remove.size()) = Fighter //return "someFighter" // TODO move this into StringUtil private static String stripString(String remove, String value) { String returnValue; int index = value.indexOf(remove); if (index != -1) { //if the package name can start anywhere but 0 please inform the author because this will break returnValue = value.substring(0, index) + value.substring(index + remove.length()); } else { returnValue = value; } return returnValue; } }
/* * 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.base.Preconditions.checkState; import static com.google.common.truth.Truth.assertThat; import static com.google.javascript.rhino.testing.NodeSubject.assertNode; import com.google.common.collect.Iterables; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.colors.Color; import com.google.javascript.jscomp.colors.StandardColors; import com.google.javascript.jscomp.testing.CodeSubTree; import com.google.javascript.jscomp.testing.TestExternsBuilder; import com.google.javascript.rhino.Node; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link Es6RewriteGenerators}. */ @RunWith(JUnit4.class) public final class Es6RewriteGeneratorsTest extends CompilerTestCase { public Es6RewriteGeneratorsTest() { super( new TestExternsBuilder() .addAsyncIterable() .addArray() .addArguments() .addObject() .addMath() .addExtra( // stubs of runtime libraries lines( "/** @const */", "var $jscomp = {};", "$jscomp.generator = {};", "$jscomp.generator.createGenerator = function() {};", "/** @constructor */", "$jscomp.generator.Context = function() {};", "/** @constructor */", "$jscomp.generator.Context.PropertyIterator = function() {};", "$jscomp.asyncExecutePromiseGeneratorFunction = function(program) {};")) .build()); } @Override @Before public void setUp() throws Exception { super.setUp(); setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015); enableTypeCheck(); enableTypeInfoValidation(); replaceTypesWithColors(); enableMultistageCompilation(); } @Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.setLanguageOut(LanguageMode.ECMASCRIPT3); return options; } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new Es6RewriteGenerators(compiler); } private void rewriteGeneratorBody(String beforeBody, String afterBody) { rewriteGeneratorBodyWithVars(beforeBody, "", afterBody); } /** * Verifies that generator functions are rewritten to a state machine program. */ private void rewriteGeneratorBodyWithVars( String beforeBody, String varDecls, String afterBody) { rewriteGeneratorBodyWithVarsAndReturnType(beforeBody, varDecls, afterBody, "?"); } private void rewriteGeneratorBodyWithVarsAndReturnType( String beforeBody, String varDecls, String afterBody, String returnType) { test( "/** @return {" + returnType + "} */ function *f() {" + beforeBody + "}", lines( "function f() {", varDecls, " return $jscomp.generator.createGenerator(", " f,", " function ($jscomp$generator$context) {", afterBody, " });", "}")); } private void rewriteGeneratorSwitchBody(String beforeBody, String afterBody) { rewriteGeneratorSwitchBodyWithVars(beforeBody, "", afterBody); } /** * Verifies that generator functions are rewriteen to a state machine program contining * {@code switch} statement. * * <p>This is the case when total number of program states is more than 3. */ private void rewriteGeneratorSwitchBodyWithVars( String beforeBody, String varDecls, String afterBody) { rewriteGeneratorBodyWithVars(beforeBody, varDecls, lines( "switch ($jscomp$generator$context.nextAddress) {", " case 1:", afterBody, "}")); } @Test public void testGeneratorForAsyncFunction() { test( lines( "f = function() {", " return $jscomp.asyncExecutePromiseGeneratorFunction(", " function *() {", " var x = 6;", " yield x;", " });", "}"), lines( "f = function () {", " var x;", " return $jscomp.asyncExecutePromiseGeneratorProgram(", " function ($jscomp$generator$context) {", " x = 6;", " return $jscomp$generator$context.yield(x, 0);", " });", "}")); test( lines( "f = function(a) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 0;", " $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 0] = arguments[$jscomp$restIndex];", " }", " {", " var bla$0 = $jscomp$restParams;", " return $jscomp.asyncExecutePromiseGeneratorFunction(", " function *() {", " var x = bla$0[0];", " yield x;", " });", " }", "}"), lines( "f = function (a) {", " var $jscomp$restParams = [];", " for (var $jscomp$restIndex = 0;", " $jscomp$restIndex < arguments.length;", " ++$jscomp$restIndex) {", " $jscomp$restParams[$jscomp$restIndex - 0] = arguments[$jscomp$restIndex];", " }", " {", " var bla$0 = $jscomp$restParams;", " var x;", " return $jscomp.asyncExecutePromiseGeneratorProgram(", " function ($jscomp$generator$context) {", " x = bla$0[0];", " return $jscomp$generator$context.yield(x, 0);", " });", " }", "}")); } @Test public void testUnnamed() { test( lines("f = function *() {};"), lines( "f = function $jscomp$generator$function() {", " return $jscomp.generator.createGenerator(", " $jscomp$generator$function,", " function ($jscomp$generator$context) {", " $jscomp$generator$context.jumpToEnd();", " });", "}")); } @Test public void testSimpleGenerator() { rewriteGeneratorBody( "", " $jscomp$generator$context.jumpToEnd();"); rewriteGeneratorBody("yield;", lines(" return $jscomp$generator$context.yield(void 0, 0);")); rewriteGeneratorBody( "yield 1;", lines( " return $jscomp$generator$context.yield(1, 0);")); test( "/** @param {*} a */ function *f(a, b) {}", lines( "function f(a, b) {", " return $jscomp.generator.createGenerator(", " f,", " function($jscomp$generator$context) {", " $jscomp$generator$context.jumpToEnd();", " });", "}")); rewriteGeneratorBodyWithVars( "var i = 0, j = 2;", "var i, j;", lines( "i = 0, j = 2;", " $jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "var i = 0; yield i; i = 1; yield i; i = i + 1; yield i;", "var i;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " i = 0;", " return $jscomp$generator$context.yield(i, 2);", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " i = 1;", " return $jscomp$generator$context.yield(i, 3);", "}", "i = i + 1;", "return $jscomp$generator$context.yield(i, 0);")); } @Test public void testForLoopWithExtraVarDeclaration() { test( lines( "function *gen() {", " var i = 2;", " yield i;", " use(i);", " for (var i = 0; i < 3; i++) {", " use(i);", " }", "}"), lines( "function gen(){", " var i;", // TODO(bradfordcsmith): avoid duplicate var declarations // It does no real harm at the moment since the normalize pass will clean this up later. " var i;", " return $jscomp.generator.createGenerator(", " gen,", " function($jscomp$generator$context) {", " if ($jscomp$generator$context.nextAddress==1) {", " i=2;", " return $jscomp$generator$context.yield(i,2);", " }", " use(i);", " for (i = 0; i < 3 ; i++) use(i);", " $jscomp$generator$context.jumpToEnd();", " })", "}")); } @Test public void testUnreachableCodeGeneration() { rewriteGeneratorBody( "if (i) return 1; else return 2;", lines( " if (i) {", " return $jscomp$generator$context.return(1);", " } else {", " return $jscomp$generator$context.return(2);", " }", // TODO(b/73762053): Avoid generating unreachable statements. " $jscomp$generator$context.jumpToEnd();")); } @Test public void testReturnGenerator() { test( "function f() { return function *g() {yield 1;} }", lines( "function f() {", " return function g() {", " return $jscomp.generator.createGenerator(", " g,", " function($jscomp$generator$context) {", " return $jscomp$generator$context.yield(1, 0);", " });", " }", "}")); } @Test public void testNestedGenerator() { test( "function *f() { function *g() {yield 2;} yield 1; }", lines( "function f() {", " function g() {", " return $jscomp.generator.createGenerator(", " g,", " function($jscomp$generator$context$1) {", " return $jscomp$generator$context$1.yield(2, 0);", " });", " }", " return $jscomp.generator.createGenerator(", " f,", " function($jscomp$generator$context) {", " return $jscomp$generator$context.yield(1, 0);", " });", "}")); } @Test public void testForLoops() { rewriteGeneratorBodyWithVars( "var i = 0; for (var j = 0; j < 10; j++) { i += j; }", "var i; var j;", lines( "i = 0;", "for (j = 0; j < 10; j++) { i += j; }", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "var i = 0; for (var j = yield; j < 10; j++) { i += j; }", "var i; var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " i = 0;", " return $jscomp$generator$context.yield(void 0, 2);", "}", "for (j = $jscomp$generator$context.yieldResult; j < 10; j++) { i += j; }", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBody( "for (;;) { yield 1; }", lines( " return $jscomp$generator$context.yield(1, 1);")); rewriteGeneratorBodyWithVars( "for (var yieldResult; yieldResult === undefined; yieldResult = yield 1) {}", "var yieldResult;", lines( " if ($jscomp$generator$context.nextAddress == 1) {", " if (!(yieldResult === undefined)) return $jscomp$generator$context.jumpTo(0);", " return $jscomp$generator$context.yield(1,5);", " }", " yieldResult = $jscomp$generator$context.yieldResult;", " return $jscomp$generator$context.jumpTo(1);")); rewriteGeneratorBodyWithVars( "for (var j = 0; j < 10; j++) { yield j; }", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " if (!(j < 10)) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(j, 3);", "}", "j++;", "return $jscomp$generator$context.jumpTo(2);")); rewriteGeneratorBodyWithVars( "var i = 0; for (var j = 0; j < 10; j++) { i += j; yield 5; }", "var i; var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " i = 0;", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " if (!(j < 10)) {", " return $jscomp$generator$context.jumpTo(0);", " }", " i += j;", " return $jscomp$generator$context.yield(5, 3);", "}", "j++;", "return $jscomp$generator$context.jumpTo(2);")); } @Test public void testWhileLoops() { rewriteGeneratorBodyWithVars( "var i = 0; while (i < 10) { i++; i++; i++; } yield i;", " var i;", lines( "i = 0;", "while (i < 10) { i ++; i++; i++; }", "return $jscomp$generator$context.yield(i, 0);")); rewriteGeneratorSwitchBodyWithVars( "var j = 0; while (j < 10) { yield j; j++; } j += 10;", "var j;", lines( " j = 0;", "case 2:", " if (!(j < 10)) {", " $jscomp$generator$context.jumpTo(3);", " break;", " }", " return $jscomp$generator$context.yield(j, 4)", "case 4:", " j++;", " $jscomp$generator$context.jumpTo(2);", " break;", "case 3:", " j += 10;", " $jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "var j = 0; while (j < 10) { yield j; j++; } yield 5", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 4) {", " if (!(j < 10)) {", " return $jscomp$generator$context.yield(5, 0);", " }", " return $jscomp$generator$context.yield(j, 4)", "}", " j++;", " return $jscomp$generator$context.jumpTo(2);")); rewriteGeneratorBodyWithVars( "var j = 0; while (yield) { j++; }", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 4) {", " return $jscomp$generator$context.yield(void 0, 4);", "}", "if (!($jscomp$generator$context.yieldResult)) {", " return $jscomp$generator$context.jumpTo(0);", "}", "j++;", "return $jscomp$generator$context.jumpTo(2);")); } @Test public void testDecomposeComplexYieldExpression() { test( lines( "/* @return {?} */ function *f() {", " var obj = {bar: function(x) {}};", " (yield 5) && obj.bar(yield 5);", "}"), lines( "function f(){", " var obj;", " var JSCompiler_temp$jscomp$0;", " var JSCompiler_temp_const$jscomp$2;", " var JSCompiler_temp_const$jscomp$1;", " var JSCompiler_temp_const$jscomp$3;", " return $jscomp.generator.createGenerator(f, function($jscomp$generator$context) {", " switch($jscomp$generator$context.nextAddress) {", " case 1:", " obj = {bar:function(x) {}};", " return $jscomp$generator$context.yield(5, 2);", " case 2:", " if (!(JSCompiler_temp$jscomp$0 = $jscomp$generator$context.yieldResult)) {", " $jscomp$generator$context.jumpTo(3);", " break;", " }", " JSCompiler_temp_const$jscomp$2 = obj;", " JSCompiler_temp_const$jscomp$1 = JSCompiler_temp_const$jscomp$2.bar;", " JSCompiler_temp_const$jscomp$3 = JSCompiler_temp_const$jscomp$2;", " return $jscomp$generator$context.yield(5, 4);", " case 4:", " JSCompiler_temp$jscomp$0 =", " JSCompiler_temp_const$jscomp$1.call(", " JSCompiler_temp_const$jscomp$3,", " $jscomp$generator$context.yieldResult);", " case 3:", " JSCompiler_temp$jscomp$0;", " $jscomp$generator$context.jumpToEnd();", " }", " });", "}")); } @Test public void testDecomposableExpression() { rewriteGeneratorBodyWithVars( "return a + (a = b) + (b = yield) + a;", lines("var JSCompiler_temp_const$jscomp$0;"), lines( " if ($jscomp$generator$context.nextAddress == 1) {", " JSCompiler_temp_const$jscomp$0 = a + (a = b);", " return $jscomp$generator$context.yield(void 0, 2);", " }", " return $jscomp$generator$context.return(", "JSCompiler_temp_const$jscomp$0 + (b = $jscomp$generator$context.yieldResult) + a);")); rewriteGeneratorSwitchBodyWithVars( "return (yield ((yield 1) + (yield 2)));", lines("var JSCompiler_temp_const$jscomp$0;"), lines( " return $jscomp$generator$context.yield(1, 3);", "case 3:", " JSCompiler_temp_const$jscomp$0=$jscomp$generator$context.yieldResult;", " return $jscomp$generator$context.yield(2, 4);", "case 4:", " return $jscomp$generator$context.yield(", " JSCompiler_temp_const$jscomp$0 + $jscomp$generator$context.yieldResult, 2);", "case 2:", " return $jscomp$generator$context.return($jscomp$generator$context.yieldResult);")); rewriteGeneratorBodyWithVars( "var obj = {bar: function(x) {}}; obj.bar(yield 5);", lines( "var obj;", "var JSCompiler_temp_const$jscomp$1;", "var JSCompiler_temp_const$jscomp$0;"), lines( "if ($jscomp$generator$context.nextAddress == 1) {", " obj = {bar: function(x) {}};", " JSCompiler_temp_const$jscomp$1 = obj;", " JSCompiler_temp_const$jscomp$0 = JSCompiler_temp_const$jscomp$1.bar;", " return $jscomp$generator$context.yield(5, 2);", "}", "JSCompiler_temp_const$jscomp$0.call(", " JSCompiler_temp_const$jscomp$1, $jscomp$generator$context.yieldResult);", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testGeneratorCannotConvertYet() { testError("function *f(b, i) {switch (i) { case yield: return b; }}", Es6ToEs3Util.CANNOT_CONVERT_YET); } @Test public void testThrow() { rewriteGeneratorBody( "throw 1;", "throw 1;"); } @Test public void testLabels() { rewriteGeneratorBody( "l: if (true) { break l; }", lines( " l: if (true) { break l; }", " $jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBody( "l: if (yield) { break l; }", lines( " if ($jscomp$generator$context.nextAddress == 1)", " return $jscomp$generator$context.yield(void 0, 3);", " if ($jscomp$generator$context.yieldResult) {", " return $jscomp$generator$context.jumpTo(0);", " }", " $jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBody( "l: if (yield) { while (1) {break l;} }", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(void 0, 3);", "}", "if ($jscomp$generator$context.yieldResult) {", " while (1) {", " return $jscomp$generator$context.jumpTo(0);", " }", "}", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBody( "l: for (;;) { yield i; continue l; }", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(i, 5);", "}", "return $jscomp$generator$context.jumpTo(1);", "return $jscomp$generator$context.jumpTo(1);")); rewriteGeneratorBody( "l1: l2: if (yield) break l1; else break l2;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(void 0, 3);", "}", "if($jscomp$generator$context.yieldResult) {", " return $jscomp$generator$context.jumpTo(0);", "} else {", " return $jscomp$generator$context.jumpTo(0);", "}", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testUnreachable() { // TODO(skill): The henerator transpilation shold not produce any unreachable code rewriteGeneratorBody( "while (true) {yield; break;}", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " if (!true) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(void 0, 4);", "}", "return $jscomp$generator$context.jumpTo(0);", "return $jscomp$generator$context.jumpTo(1);")); } @Test public void testCaseNumberOptimization() { rewriteGeneratorBodyWithVars( lines( "while (true) {", " var gen = generatorSrc();", " var gotResponse = false;", " for (var response in gen) {", " yield response;", " gotResponse = true;", " }", " if (!gotResponse) {", " return;", " }", "}"), lines( "var gen;", "var gotResponse;", "var response, $jscomp$generator$forin$0;"), lines( "if ($jscomp$generator$context.nextAddress == 1) {", " if (!true) {", " return $jscomp$generator$context.jumpTo(0);", " }", " gen = generatorSrc();", " gotResponse = false;", " $jscomp$generator$forin$0 = $jscomp$generator$context.forIn(gen);", "}", "if ($jscomp$generator$context.nextAddress != 7) {", " if (!((response=$jscomp$generator$forin$0.getNext()) != null)) {", " if (!gotResponse) return $jscomp$generator$context.return();", " return $jscomp$generator$context.jumpTo(1);", " }", " return $jscomp$generator$context.yield(response, 7);", "}", "gotResponse = true;", "return $jscomp$generator$context.jumpTo(4);")); rewriteGeneratorBody( "do { do { do { yield; } while (3) } while (2) } while (1)", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(void 0, 10);", "}", "if (3) {", " return $jscomp$generator$context.jumpTo(1);", "}", "if (2) {", " return $jscomp$generator$context.jumpTo(1);", "}", "if (1) {", " return $jscomp$generator$context.jumpTo(1);", "}", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testIf() { rewriteGeneratorBodyWithVars( "var j = 0; if (yield) { j = 1; }", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", " return $jscomp$generator$context.yield(void 0, 2);", "}", "if ($jscomp$generator$context.yieldResult) { j = 1; }", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "var j = 0; if (j < 1) { j = 5; } else { yield j; }", "var j;", lines( "j = 0;", "if (j < 1) {", " j = 5;", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(j, 0);")); // When "else" doesn't contain yields, it's more optimal to swap "if" and else "blocks" and // negate the condition. rewriteGeneratorBodyWithVars( "var j = 0; if (j < 1) { yield j; } else { j = 5; }", "var j;", lines( "j = 0;", "if (!(j < 1)) {", " j = 5;", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(j, 0);")); // No "else" block, pretend as it's empty rewriteGeneratorBodyWithVars( "var j = 0; if (j < 1) { yield j; }", "var j;", lines( "j = 0;", "if (!(j < 1)) {", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(j, 0);")); rewriteGeneratorBody( "if (i < 1) { yield i; } else { yield 1; }", lines( "if (i < 1) {", " return $jscomp$generator$context.yield(i, 0);", "}", "return $jscomp$generator$context.yield(1, 0);")); rewriteGeneratorSwitchBody( "if (i < 1) { yield i; yield i + 1; i = 10; } else { yield 1; yield 2; i = 5;}", lines( " if (i < 1) {", " return $jscomp$generator$context.yield(i, 6);", " }", " return $jscomp$generator$context.yield(1, 4);", "case 4:", " return $jscomp$generator$context.yield(2, 5);", "case 5:", " i = 5;", " $jscomp$generator$context.jumpTo(0);", " break;", "case 6:", " return $jscomp$generator$context.yield(i + 1, 7)", "case 7:", " i = 10;", " $jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBody( "if (i < 1) { while (true) { yield 1;} } else { while (false) { yield 2;}}", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " if (i < 1) {", " return $jscomp$generator$context.jumpTo(7);", " }", "}", "if ($jscomp$generator$context.nextAddress != 7) {", " if (!false) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(2, 4);", "}", "if (!true) {", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(1, 7);")); rewriteGeneratorBody( "if (i < 1) { if (i < 2) {yield 2; } } else { yield 1; }", lines( "if (i < 1) {", " if (!(i < 2)) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(2, 0);", "}", "return $jscomp$generator$context.yield(1, 0)")); rewriteGeneratorBody( "if (i < 1) { if (i < 2) {yield 2; } else { yield 3; } } else { yield 1; }", lines( "if (i < 1) {", " if (i < 2) {", " return $jscomp$generator$context.yield(2, 0);", " }", " return $jscomp$generator$context.yield(3, 0);", "}", "return $jscomp$generator$context.yield(1, 0)")); } @Test public void testReturn() { rewriteGeneratorBody( "return 1;", "return $jscomp$generator$context.return(1);"); rewriteGeneratorBodyWithVars( "return this;", "var $jscomp$generator$this = this;", lines( "return $jscomp$generator$context.return($jscomp$generator$this);")); rewriteGeneratorBodyWithVars( "return this.test({value: this});", "var $jscomp$generator$this = this;", lines( "return $jscomp$generator$context.return(", " $jscomp$generator$this.test({value: $jscomp$generator$this}));")); rewriteGeneratorBodyWithVars( "return this[yield];", "var $jscomp$generator$this = this;", lines( "if ($jscomp$generator$context.nextAddress == 1)", " return $jscomp$generator$context.yield(void 0, 2);", "return $jscomp$generator$context.return(", " $jscomp$generator$this[$jscomp$generator$context.yieldResult]);")); } @Test public void testBreakContinue() { rewriteGeneratorBodyWithVars( "var j = 0; while (j < 10) { yield j; break; }", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 4) {", " if (!(j < 10)) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(j, 4);", "}", "return $jscomp$generator$context.jumpTo(0);", "return $jscomp$generator$context.jumpTo(2)")); rewriteGeneratorBodyWithVars( "var j = 0; while (j < 10) { yield j; continue; }", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 4) {", " if (!(j < 10)) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(j, 4);", "}", "return $jscomp$generator$context.jumpTo(2);", "return $jscomp$generator$context.jumpTo(2)")); rewriteGeneratorBodyWithVars( "for (var j = 0; j < 10; j++) { yield j; break; }", "var j;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " j = 0;", "}", "if ($jscomp$generator$context.nextAddress != 5) {", " if (!(j < 10)) {", " return $jscomp$generator$context.jumpTo(0);", " }", " return $jscomp$generator$context.yield(j, 5);", "}", "return $jscomp$generator$context.jumpTo(0);", "j++;", "return $jscomp$generator$context.jumpTo(2)")); rewriteGeneratorSwitchBodyWithVars( "for (var j = 0; j < 10; j++) { yield j; continue; }", "var j;", lines( " j = 0;", "case 2:", " if (!(j < 10)) {", " $jscomp$generator$context.jumpTo(0);", " break;", " }", " return $jscomp$generator$context.yield(j, 5);", "case 5:", " $jscomp$generator$context.jumpTo(3);", " break;", "case 3:", " j++;", " $jscomp$generator$context.jumpTo(2)", " break;")); } @Test public void testDoWhileLoops() { rewriteGeneratorBody( "do { yield j; } while (j < 10);", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(j, 4);", "}", "if (j<10) {", " return $jscomp$generator$context.jumpTo(1);", "}", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBody( "do {} while (yield 1);", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(1, 5);", "}", "if ($jscomp$generator$context.yieldResult) {", " return $jscomp$generator$context.jumpTo(1);", "}", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testYieldNoValue() { rewriteGeneratorBody("yield;", "return $jscomp$generator$context.yield(void 0, 0);"); } @Test public void testReturnNoValue() { rewriteGeneratorBody( "return;", "return $jscomp$generator$context.return();"); } @Test public void testYieldExpression() { rewriteGeneratorBody( "return (yield 1);", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(1, 2);", "}", "return $jscomp$generator$context.return($jscomp$generator$context.yieldResult);")); } @Test public void testFunctionInGenerator() { rewriteGeneratorBodyWithVars( "function g() {}", "function g() {}", " $jscomp$generator$context.jumpToEnd();"); } @Test public void testYieldAll() { rewriteGeneratorBody( "yield * n;", lines( " return $jscomp$generator$context.yieldAll(n, 0);")); rewriteGeneratorBodyWithVars( "var i = yield * n;", "var i;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yieldAll(n, 2);", "}", "i = $jscomp$generator$context.yieldResult;", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testYieldArguments() { rewriteGeneratorBodyWithVars( "yield arguments[0];", "var $jscomp$generator$arguments = arguments;", lines( "return $jscomp$generator$context.yield($jscomp$generator$arguments[0], 0);")); } @Test public void testYieldThis() { rewriteGeneratorBodyWithVars( "yield this;", "var $jscomp$generator$this = this;", lines( "return $jscomp$generator$context.yield($jscomp$generator$this, 0);")); } @Test public void testGeneratorShortCircuit() { rewriteGeneratorBodyWithVars( "0 || (yield 1);", "var JSCompiler_temp$jscomp$0;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " if(JSCompiler_temp$jscomp$0 = 0) {", " return $jscomp$generator$context.jumpTo(2);", " }", " return $jscomp$generator$context.yield(1, 3);", "}", "if ($jscomp$generator$context.nextAddress != 2) {", " JSCompiler_temp$jscomp$0=$jscomp$generator$context.yieldResult;", "}", "JSCompiler_temp$jscomp$0;", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "0 && (yield 1);", "var JSCompiler_temp$jscomp$0;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " if(!(JSCompiler_temp$jscomp$0=0)) {", " return $jscomp$generator$context.jumpTo(2);", " }", " return $jscomp$generator$context.yield(1, 3);", "}", "if ($jscomp$generator$context.nextAddress != 2) {", " JSCompiler_temp$jscomp$0=$jscomp$generator$context.yieldResult;", "}", "JSCompiler_temp$jscomp$0;", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "0 ? 1 : (yield 1);", "var JSCompiler_temp$jscomp$0;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " if(0) {", " JSCompiler_temp$jscomp$0 = 1;", " return $jscomp$generator$context.jumpTo(2);", " }", " return $jscomp$generator$context.yield(1, 3);", "}", "if ($jscomp$generator$context.nextAddress != 2) {", " JSCompiler_temp$jscomp$0 = $jscomp$generator$context.yieldResult;", "}", "JSCompiler_temp$jscomp$0;", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testVar() { rewriteGeneratorBodyWithVars( "var a = 10, b, c = yield 10, d = yield 20, f, g='test';", "var a, b; var c; var d, f, g;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " a = 10;", " return $jscomp$generator$context.yield(10, 2);", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " c = $jscomp$generator$context.yieldResult;", " return $jscomp$generator$context.yield(20, 3);", "}", "d = $jscomp$generator$context.yieldResult, g = 'test';", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( lines( "var /** @const */ a = 10, b, c = yield 10, d = yield 20, f, g='test';"), lines( "var /** @const */ a, b;", "var c;", // note that the yields cause the var declarations to be split up "var d, f, g;"), lines( "if ($jscomp$generator$context.nextAddress == 1) {", " a = 10;", " return $jscomp$generator$context.yield(10, 2);", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " c = $jscomp$generator$context.yieldResult;", " return $jscomp$generator$context.yield(20, 3);", "}", "d = $jscomp$generator$context.yieldResult, g = 'test';", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testYieldSwitch() { rewriteGeneratorSwitchBody( lines( "while (1) {", " switch (i) {", " case 1:", " ++i;", " break;", " case 2:", " yield 3;", " continue;", " case 10:", " case 3:", " yield 4;", " case 4:", " return 1;", " case 5:", " return 2;", " default:", " yield 5;", " }", "}"), lines( " if (!1) {", " $jscomp$generator$context.jumpTo(0);", " break;", " }", " switch (i) {", " case 1: ++i; break;", " case 2: return $jscomp$generator$context.jumpTo(4);", " case 10:", " case 3: return $jscomp$generator$context.jumpTo(5);", " case 4: return $jscomp$generator$context.jumpTo(6);", " case 5: return $jscomp$generator$context.return(2);", " default: return $jscomp$generator$context.jumpTo(7);", " }", " $jscomp$generator$context.jumpTo(1);", " break;", "case 4: return $jscomp$generator$context.yield(3, 9);", "case 9:", " $jscomp$generator$context.jumpTo(1);", " break;", "case 5: return $jscomp$generator$context.yield(4, 6);", "case 6: return $jscomp$generator$context.return(1);", "case 7: return $jscomp$generator$context.yield(5, 1);")); rewriteGeneratorBody( lines("switch (yield) {", " default:", " case 1:", " yield 1;}"), lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(void 0, 2);", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " switch ($jscomp$generator$context.yieldResult) {", " default:", " case 1:", " return $jscomp$generator$context.jumpTo(3)", " }", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(1, 0);")); } @Test public void testNoTranslate() { rewriteGeneratorBody( "if (1) { try {} catch (e) {} throw 1; }", lines( "if (1) { try {} catch (e) {} throw 1; }", "$jscomp$generator$context.jumpToEnd();")); } @Test public void testForIn() { rewriteGeneratorBodyWithVars( "for (var i in yield) { }", "var i;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(void 0, 2);", "}", "for (i in $jscomp$generator$context.yieldResult) { }", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "for (var i in j) { yield i; }", "var i, $jscomp$generator$forin$0;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$forin$0 = $jscomp$generator$context.forIn(j);", "}", "if (!((i = $jscomp$generator$forin$0.getNext()) != null)) {", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(i, 2);")); rewriteGeneratorBodyWithVars( "for (var i in yield) { yield i; }", "var i, $jscomp$generator$forin$0;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " return $jscomp$generator$context.yield(void 0, 2)", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " $jscomp$generator$forin$0 = ", " $jscomp$generator$context.forIn($jscomp$generator$context.yieldResult);", "}", "if (!((i = $jscomp$generator$forin$0.getNext()) != null)) {", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.yield(i, 3);")); rewriteGeneratorBodyWithVars( "for (i[yield] in j) {}", "var $jscomp$generator$forin$0; var JSCompiler_temp_const$jscomp$1;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$forin$0 = $jscomp$generator$context.forIn(j);", "}", "if ($jscomp$generator$context.nextAddress != 5) {", " JSCompiler_temp_const$jscomp$1 = i;", " return $jscomp$generator$context.yield(void 0, 5);", "}", "if (!((JSCompiler_temp_const$jscomp$1[$jscomp$generator$context.yieldResult] =", " $jscomp$generator$forin$0.getNext()) != null)) {", " return $jscomp$generator$context.jumpTo(0);", "}", "return $jscomp$generator$context.jumpTo(2);")); } @Test public void testTryCatch() { rewriteGeneratorBodyWithVars( "try {yield 1;} catch (e) {}", "var e;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$context.setCatchFinallyBlocks(2);", " return $jscomp$generator$context.yield(1, 4);", "}", "if ($jscomp$generator$context.nextAddress != 2) {", " return $jscomp$generator$context.leaveTryBlock(0)", "}", "e = $jscomp$generator$context.enterCatchBlock();", "$jscomp$generator$context.jumpToEnd();")); rewriteGeneratorSwitchBodyWithVars( lines( "try {yield 1;} catch (e) {}", "try {yield 1;} catch (e) {}"), "var e;", lines( " $jscomp$generator$context.setCatchFinallyBlocks(2);", " return $jscomp$generator$context.yield(1, 4);", "case 4:", " $jscomp$generator$context.leaveTryBlock(3)", " break;", "case 2:", " e=$jscomp$generator$context.enterCatchBlock();", "case 3:", " $jscomp$generator$context.setCatchFinallyBlocks(5);", " return $jscomp$generator$context.yield(1, 7);", "case 7:", " $jscomp$generator$context.leaveTryBlock(0)", " break;", "case 5:", " e = $jscomp$generator$context.enterCatchBlock();", " $jscomp$generator$context.jumpToEnd();")); rewriteGeneratorBodyWithVars( "l1: try { break l1; } catch (e) { yield; } finally {}", "var e;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$context.setCatchFinallyBlocks(3, 4);", " return $jscomp$generator$context.jumpThroughFinallyBlocks(0);", "}", "if ($jscomp$generator$context.nextAddress != 3) {", " $jscomp$generator$context.enterFinallyBlock();", " return $jscomp$generator$context.leaveFinallyBlock(0);", "}", "e = $jscomp$generator$context.enterCatchBlock();", "return $jscomp$generator$context.yield(void 0, 4)")); } @Test public void testFinally() { rewriteGeneratorBodyWithVars( "try {yield 1;} catch (e) {} finally {b();}", "var e;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$context.setCatchFinallyBlocks(2, 3);", " return $jscomp$generator$context.yield(1, 3);", "}", "if ($jscomp$generator$context.nextAddress != 2) {", " $jscomp$generator$context.enterFinallyBlock();", " b();", " return $jscomp$generator$context.leaveFinallyBlock(0);", "}", "e = $jscomp$generator$context.enterCatchBlock();", "return $jscomp$generator$context.jumpTo(3);")); rewriteGeneratorSwitchBodyWithVars( lines( "try {", " try {", " yield 1;", " throw 2;", " } catch (x) {", " throw yield x;", " } finally {", " yield 5;", " }", "} catch (thrown) {", " yield thrown;", "}"), "var x; var thrown;", lines( " $jscomp$generator$context.setCatchFinallyBlocks(2);", " $jscomp$generator$context.setCatchFinallyBlocks(4, 5);", " return $jscomp$generator$context.yield(1, 7);", "case 7:", " throw 2;", "case 5:", " $jscomp$generator$context.enterFinallyBlock(2);", " return $jscomp$generator$context.yield(5, 8);", "case 8:", " $jscomp$generator$context.leaveFinallyBlock(6);", " break;", "case 4:", " x = $jscomp$generator$context.enterCatchBlock();", " return $jscomp$generator$context.yield(x, 9);", "case 9:", " throw $jscomp$generator$context.yieldResult;", " $jscomp$generator$context.jumpTo(5);", " break;", "case 6:", " $jscomp$generator$context.leaveTryBlock(0);", " break;", "case 2:", " thrown = $jscomp$generator$context.enterCatchBlock();", " return $jscomp$generator$context.yield(thrown,0)")); } /** Tests correctness of type information after transpilation */ @Test public void testYield_withTypes() { Node returnNode = testAndReturnBodyForNumericGenerator( "yield 1 + 2;", "", "return $jscomp$generator$context.yield(1 + 2, 0);"); checkState(returnNode.isReturn(), returnNode); Node callNode = returnNode.getFirstChild(); checkState(callNode.isCall(), callNode); // TODO(b/142881197): we can't give a more accurate type right now. assertNode(callNode).hasColorThat().isEqualTo(StandardColors.UNKNOWN); Node yieldFn = callNode.getFirstChild(); Node jscompGeneratorContext = yieldFn.getFirstChild(); Color generatorContext = Iterables.getOnlyElement( CodeSubTree.findFirstNode( getLastCompiler().getExternsRoot(), (n) -> n.matchesQualifiedName("$jscomp.generator.Context")) .getColor() .getInstanceColors()); assertThat(jscompGeneratorContext.getColor()).isEqualTo(generatorContext); // Check types on "1 + 2" are still present after transpilation Node yieldedValue = callNode.getSecondChild(); // 1 + 2 checkState(yieldedValue.isAdd(), yieldedValue); assertNode(yieldedValue).hasColorThat().isEqualTo(StandardColors.NUMBER); assertNode(yieldedValue.getFirstChild()).hasColorThat().isEqualTo(StandardColors.NUMBER); // 1 assertNode(yieldedValue.getSecondChild()).hasColorThat().isEqualTo(StandardColors.NUMBER); // 2 Node zero = yieldedValue.getNext(); checkState(0 == zero.getDouble(), zero); assertNode(zero).hasColorThat().isEqualTo(StandardColors.NUMBER); } @Test public void testYieldAll_withTypes() { Node returnNode = testAndReturnBodyForNumericGenerator( "yield * [1, 2];", "", "return $jscomp$generator$context.yieldAll([1, 2], 0);"); checkState(returnNode.isReturn(), returnNode); Node callNode = returnNode.getFirstChild(); checkState(callNode.isCall(), callNode); // TODO(b/142881197): we can't give a more accurate type right now. assertNode(callNode).hasColorThat().isEqualTo(StandardColors.UNKNOWN); Node yieldAllFn = callNode.getFirstChild(); checkState(yieldAllFn.isGetProp()); // Check that the original types on "[1, 2]" are still present after transpilation Node yieldedValue = callNode.getSecondChild(); // [1, 2] checkState(yieldedValue.isArrayLit(), yieldedValue); assertNode(yieldedValue) .hasColorThat() .isEqualTo(getLastCompiler().getColorRegistry().get(StandardColors.ARRAY_ID)); // [1, 2] assertNode(yieldedValue.getFirstChild()).hasColorThat().isEqualTo(StandardColors.NUMBER); // 1 assertNode(yieldedValue.getSecondChild()).hasColorThat().isEqualTo(StandardColors.NUMBER); // 2 Node zero = yieldedValue.getNext(); checkState(0 == zero.getDouble(), zero); assertNode(zero).hasColorThat().isEqualTo(StandardColors.NUMBER); } @Test public void testGeneratorForIn_withTypes() { Node case1Node = testAndReturnBodyForNumericGenerator( "for (var i in []) { yield 3; };", "var i, $jscomp$generator$forin$0;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$forin$0 = $jscomp$generator$context.forIn([]);", "}", "if ($jscomp$generator$context.nextAddress != 4) {", " if (!((i = $jscomp$generator$forin$0.getNext()) != null)) {", " return $jscomp$generator$context.jumpTo(4);", " }", " return $jscomp$generator$context.yield(3, 2);", "}", ";", "$jscomp$generator$context.jumpToEnd();")); // $jscomp$generator$forin$0 = $jscomp$generator$context.forIn([]); Node assign = case1Node.getSecondChild().getFirstFirstChild(); checkState(assign.isAssign(), assign); Color propertyIterator = Iterables.getOnlyElement( CodeSubTree.findFirstNode( getLastCompiler().getExternsRoot(), (n) -> n.matchesQualifiedName("$jscomp.generator.Context.PropertyIterator")) .getColor() .getInstanceColors()); assertThat(assign.getColor()).isEqualTo(propertyIterator); assertThat(assign.getFirstChild().getColor()).isEqualTo(propertyIterator); assertThat(assign.getSecondChild().getColor()).isEqualTo(propertyIterator); // if (!((i = $jscomp$generator$forin$0.getNext()) != null)) { Node case2Node = case1Node.getNext(); Node ifNode = case2Node.getSecondChild().getFirstChild(); checkState(ifNode.isIf(), ifNode); Node ifCond = ifNode.getFirstChild(); checkState(ifCond.isNot(), ifCond); assertNode(ifCond).hasColorThat().isEqualTo(StandardColors.BOOLEAN); Node ne = ifCond.getFirstChild(); assertNode(ifCond).hasColorThat().isEqualTo(StandardColors.BOOLEAN); Node lhs = ne.getFirstChild(); // i = $jscomp$generator$forin$0.getNext() assertNode(lhs) .hasColorThat() .hasAlternates(StandardColors.NULL_OR_VOID, StandardColors.STRING); assertNode(lhs) .hasColorThat() .hasAlternates(StandardColors.NULL_OR_VOID, StandardColors.STRING); assertNode(lhs) .hasColorThat() .hasAlternates(StandardColors.NULL_OR_VOID, StandardColors.STRING); Node getNextFn = lhs.getSecondChild().getFirstChild(); assertNode(getNextFn).hasColorThat().isEqualTo(StandardColors.TOP_OBJECT); Node rhs = ne.getSecondChild(); checkState(rhs.isNull(), rhs); assertNode(rhs).hasColorThat().isEqualTo(StandardColors.NULL_OR_VOID); // $jscomp$generator$context.jumpToEnd() Node case4Node = case2Node.getNext(); Node jumpToEndCall = case4Node.getNext().getFirstChild(); checkState(jumpToEndCall.isCall()); Node jumpToEndFn = jumpToEndCall.getFirstChild(); Node jscompGeneratorContext = jumpToEndFn.getFirstChild(); // assertThat(jumpToEndCall.getJSType().toString()).isEqualTo("undefined"); Color generatorContext = Iterables.getOnlyElement( CodeSubTree.findFirstNode( getLastCompiler().getExternsRoot(), (n) -> n.matchesQualifiedName("$jscomp.generator.Context")) .getColor() .getInstanceColors()); assertThat(jscompGeneratorContext.getColor()).isEqualTo(generatorContext); } @Test public void testGeneratorTryCatch_withTypes() { Node case1Node = testAndReturnBodyForNumericGenerator( "try {yield 1;} catch (e) {}", "var e;", lines( "if ($jscomp$generator$context.nextAddress == 1) {", " $jscomp$generator$context.setCatchFinallyBlocks(2);", " return $jscomp$generator$context.yield(1, 4);", "}", "if ($jscomp$generator$context.nextAddress != 2) {", " return $jscomp$generator$context.leaveTryBlock(0)", "}", "e = $jscomp$generator$context.enterCatchBlock();", "$jscomp$generator$context.jumpToEnd();")); Node case2Node = case1Node.getNext().getNext(); // Test that "e = $jscomp$generator$context.enterCatchBlock();" has the unknown type Node eAssign = case2Node.getFirstChild(); checkState(eAssign.isAssign(), eAssign); assertNode(eAssign).hasColorThat().isEqualTo(StandardColors.UNKNOWN); assertNode(eAssign.getFirstChild()).hasColorThat().isEqualTo(StandardColors.UNKNOWN); assertNode(eAssign.getSecondChild()).hasColorThat().isEqualTo(StandardColors.UNKNOWN); Node enterCatchBlockFn = eAssign.getSecondChild().getFirstChild(); checkState(enterCatchBlockFn.isGetProp()); // this is loosely typed, but it's okay because optimizations don't care about callee types. assertNode(enterCatchBlockFn).hasColorThat().isEqualTo(StandardColors.UNKNOWN); } @Test public void testGeneratorMultipleVars_withTypes() { Node exprResultNode = testAndReturnBodyForNumericGenerator( "var a = 1, b = '2';", "var a, b;", "a = 1, b = '2'; $jscomp$generator$context.jumpToEnd();"); Node comma = exprResultNode.getFirstChild(); checkState(comma.isComma(), comma); assertNode(comma).hasColorThat().isEqualTo(StandardColors.STRING); // a = 1 Node assignA = comma.getFirstChild(); checkState(assignA.isAssign(), assignA); assertNode(assignA).hasColorThat().isEqualTo(StandardColors.NUMBER); assertNode(assignA.getFirstChild()).hasColorThat().isEqualTo(StandardColors.NUMBER); assertNode(assignA.getSecondChild()).hasColorThat().isEqualTo(StandardColors.NUMBER); // b = '2'; Node assignB = comma.getSecondChild(); checkState(assignB.isAssign(), assignB); assertNode(assignB).hasColorThat().isEqualTo(StandardColors.STRING); assertNode(assignB.getFirstChild()).hasColorThat().isEqualTo(StandardColors.STRING); assertNode(assignB.getSecondChild()).hasColorThat().isEqualTo(StandardColors.STRING); } /** * Tests that the given generator transpiles to the given body, and does some basic checks on the * transpiled generator. * * @return The first case statement in the switch inside the transpiled generator */ private Node testAndReturnBodyForNumericGenerator( String beforeBody, String varDecls, String afterBody) { rewriteGeneratorBodyWithVarsAndReturnType( beforeBody, varDecls, afterBody, "!Generator<number>"); Node transpiledGenerator = getLastCompiler().getJsRoot().getLastChild().getLastChild(); Node program = getAndCheckGeneratorProgram(transpiledGenerator); Node programBlock = NodeUtil.getFunctionBody(program); return programBlock.getFirstChild(); } /** Get the "program" function from a tranpsiled generator */ private Node getAndCheckGeneratorProgram(Node genFunction) { Node returnNode = genFunction.getLastChild().getLastChild(); Node callNode = returnNode.getFirstChild(); checkState(callNode.isCall(), callNode); Node createGenerator = callNode.getFirstChild(); return createGenerator.getNext().getNext(); } }
/** * Copyright (C) 2014-2018 LinkedIn Corp. (pinot-core@linkedin.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.linkedin.pinot.core.query.aggregation.function; import com.clearspring.analytics.stream.cardinality.CardinalityMergeException; import com.clearspring.analytics.stream.cardinality.HyperLogLog; import com.linkedin.pinot.common.data.FieldSpec; import com.linkedin.pinot.common.utils.DataSchema; import com.linkedin.pinot.core.common.BlockValSet; import com.linkedin.pinot.core.common.ObjectSerDeUtils; import com.linkedin.pinot.core.query.aggregation.AggregationResultHolder; import com.linkedin.pinot.core.query.aggregation.ObjectAggregationResultHolder; import com.linkedin.pinot.core.query.aggregation.groupby.GroupByResultHolder; import com.linkedin.pinot.core.query.aggregation.groupby.ObjectGroupByResultHolder; import javax.annotation.Nonnull; public class DistinctCountHLLAggregationFunction implements AggregationFunction<HyperLogLog, Long> { public static final int DEFAULT_LOG2M = 8; @Nonnull @Override public AggregationFunctionType getType() { return AggregationFunctionType.DISTINCTCOUNTHLL; } @Nonnull @Override public String getColumnName(@Nonnull String column) { return AggregationFunctionType.DISTINCTCOUNTHLL.getName() + "_" + column; } @Override public void accept(@Nonnull AggregationFunctionVisitorBase visitor) { visitor.visit(this); } @Nonnull @Override public AggregationResultHolder createAggregationResultHolder() { return new ObjectAggregationResultHolder(); } @Nonnull @Override public GroupByResultHolder createGroupByResultHolder(int initialCapacity, int maxCapacity) { return new ObjectGroupByResultHolder(initialCapacity, maxCapacity); } @Override public void aggregate(int length, @Nonnull AggregationResultHolder aggregationResultHolder, @Nonnull BlockValSet... blockValSets) { HyperLogLog hyperLogLog = getHyperLogLog(aggregationResultHolder); FieldSpec.DataType valueType = blockValSets[0].getValueType(); switch (valueType) { case INT: int[] intValues = blockValSets[0].getIntValuesSV(); for (int i = 0; i < length; i++) { hyperLogLog.offer(intValues[i]); } break; case LONG: long[] longValues = blockValSets[0].getLongValuesSV(); for (int i = 0; i < length; i++) { hyperLogLog.offer(longValues[i]); } break; case FLOAT: float[] floatValues = blockValSets[0].getFloatValuesSV(); for (int i = 0; i < length; i++) { hyperLogLog.offer(floatValues[i]); } break; case DOUBLE: double[] doubleValues = blockValSets[0].getDoubleValuesSV(); for (int i = 0; i < length; i++) { hyperLogLog.offer(doubleValues[i]); } break; case STRING: String[] stringValues = blockValSets[0].getStringValuesSV(); for (int i = 0; i < length; i++) { hyperLogLog.offer(stringValues[i]); } break; case BYTES: // Serialized HyperLogLog byte[][] bytesValues = blockValSets[0].getBytesValuesSV(); try { for (int i = 0; i < length; i++) { hyperLogLog.addAll(ObjectSerDeUtils.HYPER_LOG_LOG_SER_DE.deserialize(bytesValues[i])); } } catch (Exception e) { throw new RuntimeException("Caught exception while aggregating HyperLogLog", e); } break; default: throw new IllegalStateException("Illegal data type for DISTINCT_COUNT_HLL aggregation function: " + valueType); } } @Override public void aggregateGroupBySV(int length, @Nonnull int[] groupKeyArray, @Nonnull GroupByResultHolder groupByResultHolder, @Nonnull BlockValSet... blockValSets) { FieldSpec.DataType valueType = blockValSets[0].getValueType(); switch (valueType) { case INT: int[] intValues = blockValSets[0].getIntValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKey(groupByResultHolder, groupKeyArray[i], intValues[i]); } break; case LONG: long[] longValues = blockValSets[0].getLongValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKey(groupByResultHolder, groupKeyArray[i], longValues[i]); } break; case FLOAT: float[] floatValues = blockValSets[0].getFloatValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKey(groupByResultHolder, groupKeyArray[i], floatValues[i]); } break; case DOUBLE: double[] doubleValues = blockValSets[0].getDoubleValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKey(groupByResultHolder, groupKeyArray[i], doubleValues[i]); } break; case STRING: String[] stringValues = blockValSets[0].getStringValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKey(groupByResultHolder, groupKeyArray[i], stringValues[i]); } break; case BYTES: // Serialized HyperLogLog byte[][] bytesValues = blockValSets[0].getBytesValuesSV(); try { for (int i = 0; i < length; i++) { setValueForGroupKey(groupByResultHolder, groupKeyArray[i], ObjectSerDeUtils.HYPER_LOG_LOG_SER_DE.deserialize(bytesValues[i])); } } catch (Exception e) { throw new RuntimeException("Caught exception while aggregating HyperLogLog", e); } break; default: throw new IllegalStateException("Illegal data type for DISTINCT_COUNT_HLL aggregation function: " + valueType); } } @Override public void aggregateGroupByMV(int length, @Nonnull int[][] groupKeysArray, @Nonnull GroupByResultHolder groupByResultHolder, @Nonnull BlockValSet... blockValSets) { FieldSpec.DataType valueType = blockValSets[0].getValueType(); switch (valueType) { case INT: int[] intValues = blockValSets[0].getIntValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKeys(groupByResultHolder, groupKeysArray[i], intValues[i]); } break; case LONG: long[] longValues = blockValSets[0].getLongValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKeys(groupByResultHolder, groupKeysArray[i], longValues[i]); } break; case FLOAT: float[] floatValues = blockValSets[0].getFloatValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKeys(groupByResultHolder, groupKeysArray[i], floatValues[i]); } break; case DOUBLE: double[] doubleValues = blockValSets[0].getDoubleValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKeys(groupByResultHolder, groupKeysArray[i], doubleValues[i]); } break; case STRING: String[] singleValues = blockValSets[0].getStringValuesSV(); for (int i = 0; i < length; i++) { setValueForGroupKeys(groupByResultHolder, groupKeysArray[i], singleValues[i]); } break; case BYTES: // Serialized HyperLogLog byte[][] bytesValues = blockValSets[0].getBytesValuesSV(); try { for (int i = 0; i < length; i++) { setValueForGroupKeys(groupByResultHolder, groupKeysArray[i], ObjectSerDeUtils.HYPER_LOG_LOG_SER_DE.deserialize(bytesValues[i])); } } catch (Exception e) { throw new RuntimeException("Caught exception while aggregating HyperLogLog", e); } break; default: throw new IllegalStateException("Illegal data type for DISTINCT_COUNT_HLL aggregation function: " + valueType); } } @Nonnull @Override public HyperLogLog extractAggregationResult(@Nonnull AggregationResultHolder aggregationResultHolder) { HyperLogLog hyperLogLog = aggregationResultHolder.getResult(); if (hyperLogLog == null) { return new HyperLogLog(DEFAULT_LOG2M); } else { return hyperLogLog; } } @Nonnull @Override public HyperLogLog extractGroupByResult(@Nonnull GroupByResultHolder groupByResultHolder, int groupKey) { HyperLogLog hyperLogLog = groupByResultHolder.getResult(groupKey); if (hyperLogLog == null) { return new HyperLogLog(DEFAULT_LOG2M); } else { return hyperLogLog; } } @Nonnull @Override public HyperLogLog merge(@Nonnull HyperLogLog intermediateResult1, @Nonnull HyperLogLog intermediateResult2) { try { intermediateResult1.addAll(intermediateResult2); } catch (Exception e) { throw new RuntimeException("Caught exception while merging HyperLogLog", e); } return intermediateResult1; } @Override public boolean isIntermediateResultComparable() { return false; } @Nonnull @Override public DataSchema.ColumnDataType getIntermediateResultColumnType() { return DataSchema.ColumnDataType.OBJECT; } @Nonnull @Override public Long extractFinalResult(@Nonnull HyperLogLog intermediateResult) { return intermediateResult.cardinality(); } /** * Helper method to set value for a groupKey into the result holder. * * @param groupByResultHolder Result holder * @param groupKey Group-key for which to set the value * @param value Value for the group key */ private static void setValueForGroupKey(@Nonnull GroupByResultHolder groupByResultHolder, int groupKey, Object value) { HyperLogLog hyperLogLog = getHyperLogLog(groupByResultHolder, groupKey); hyperLogLog.offer(value); } /** * Helper method to set HyperLogLog value for a groupKey into the result holder. * * @param groupByResultHolder Result holder * @param groupKey Group-key for which to set the value * @param value HyperLogLog value for the group key */ private static void setValueForGroupKey(@Nonnull GroupByResultHolder groupByResultHolder, int groupKey, HyperLogLog value) throws CardinalityMergeException { HyperLogLog hyperLogLog = getHyperLogLog(groupByResultHolder, groupKey); hyperLogLog.addAll(value); } /** * Helper method to set value for a given array of group keys. * * @param groupByResultHolder Result Holder * @param groupKeys Group keys for which to set the value * @param value Value to set */ private static void setValueForGroupKeys(@Nonnull GroupByResultHolder groupByResultHolder, int[] groupKeys, Object value) { for (int groupKey : groupKeys) { setValueForGroupKey(groupByResultHolder, groupKey, value); } } /** * Helper method to set HyperLogLog value for a given array of group keys. * * @param groupByResultHolder Result Holder * @param groupKeys Group keys for which to set the value * @param value HyperLogLog value to set */ private static void setValueForGroupKeys(@Nonnull GroupByResultHolder groupByResultHolder, int[] groupKeys, HyperLogLog value) throws CardinalityMergeException { for (int groupKey : groupKeys) { setValueForGroupKey(groupByResultHolder, groupKey, value); } } /** * Returns the HyperLogLog from the result holder or creates a new one if it does not exist. * * @param aggregationResultHolder Result holder * @return HyperLogLog from the result holder */ protected static HyperLogLog getHyperLogLog(@Nonnull AggregationResultHolder aggregationResultHolder) { HyperLogLog hyperLogLog = aggregationResultHolder.getResult(); if (hyperLogLog == null) { hyperLogLog = new HyperLogLog(DEFAULT_LOG2M); aggregationResultHolder.setValue(hyperLogLog); } return hyperLogLog; } /** * Returns the HyperLogLog for the given group key. If one does not exist, creates a new one and returns that. * * @param groupByResultHolder Result holder * @param groupKey Group key for which to return the HyperLogLog * @return HyperLogLog for the group key */ protected static HyperLogLog getHyperLogLog(@Nonnull GroupByResultHolder groupByResultHolder, int groupKey) { HyperLogLog hyperLogLog = groupByResultHolder.getResult(groupKey); if (hyperLogLog == null) { hyperLogLog = new HyperLogLog(DEFAULT_LOG2M); groupByResultHolder.setValueForKey(groupKey, hyperLogLog); } return hyperLogLog; } }
package com.yingkan.mydictapp; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.method.ScrollingMovementMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.yingkan.dictionaryAPI.cykService.CykDictRequestParams; import com.yingkan.xml.customDB.WordType.WordTypeXml; import com.yingkan.xml.customDB.customDBXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.nio.charset.Charset; import cz.msebera.android.httpclient.Header; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private AsyncHttpClient client = new AsyncHttpClient(); private GoogleApiClient client2; private CharSequence oriLanguage; private CharSequence desLanguage; private EditText inputWord; private TextView httpResponseShow; private Spinner spinnerOriLanguage; private Spinner spinnerDesLanguage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inputWord = (EditText) findViewById(R.id.InputText); httpResponseShow = (TextView) findViewById(R.id.httpResponseShow); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); Button translate = (Button) findViewById(R.id.Translate); translate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TestReceiver(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); /*Two Spinner configuration*/ spinnerOriLanguage = (Spinner) findViewById(R.id.spinnerOriLanguage); spinnerDesLanguage = (Spinner) findViewById(R.id.spinnerDesLanguage); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languageShortcut, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinnerOriLanguage.setAdapter(adapter); spinnerDesLanguage.setAdapter(adapter); spinnerOriLanguage.setSelection(0); spinnerDesLanguage.setSelection(1); spinnerOriLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { oriLanguage = (CharSequence) parent.getItemAtPosition(position); parent.setSelection(position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spinnerDesLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { parent.setSelection(position); desLanguage = (CharSequence) parent.getItemAtPosition(position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client2.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.yingkan.mydictapp/http/host/path") ); AppIndex.AppIndexApi.start(client2, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.yingkan.mydictapp/http/host/path") ); AppIndex.AppIndexApi.end(client2, viewAction); client2.disconnect(); } private void TestReceiver() { httpResponseShow.setMovementMethod(new ScrollingMovementMethod()); // Glosbe g = new Glosbe(inputWord.getText(), oriLanguage, desLanguage); // String url = g.translateQuery(); CykDictRequestParams getParams = new CykDictRequestParams(inputWord.getText(), oriLanguage, desLanguage); client.get(CykDictRequestParams.server, getParams, new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { // called when response HTTP status is "200 OK" Charset charset = Charset.forName("ISO-8859-1"); // forward to XML parser // String s = new String(response,charset); // httpResponseShow.setText(s); try { WordTypeXml nx = new customDBXmlParser(response).parse(); httpResponseShow.setText(nx.xmlOutput()); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // try { // List<GlosbeXmlCell> listForDisp = new GlosbeXmlParser(response).parse(); // StringBuilder displayText = new StringBuilder(); // if (listForDisp.size() == 0) // httpResponseShow.setText("No match found"); // else { // for (int i = 0; i < listForDisp.size(); i++) { // displayText.append(i + 1).append(") ").append(listForDisp.get(i).toString() + "\n"); // } // httpResponseShow.setText(displayText); // } // } catch (XmlPullParserException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) } @Override public void onRetry(int retryNo) { // called when request is retried } }); } }
package myessentials.chat.api; import myessentials.exception.FormatException; import myessentials.utils.ColorUtils; import net.minecraft.event.HoverEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; /** * An IChatComponent that converts a format to a set of IChatComponents * * Each of the parenthesis pairs represent an IChatComponent with its * own ChatStyle (color, bold, underlined, etc.) * * Example: {2|Entity number }{%s}{2| is the }{7l| %s}{aN|Good bye!} * This format will create the following IChatComponents: * - "Entity number " ; with DARK_GREEN color * - %s ; one of the parameters sent by the caller (as IChatComponent or * IChatFormat, since it's missing the "|" style delimiter character * - " is the " ; with DARK_GREEN color * - %s ; one of the parameters sent by the caller (as String since it HAS "|" style delimiter character) * - "Good bye!" ; with GREEN color and on another line. The modifier "N" * ; represents a new line BEFORE the component it's in * * This ChatComponentFormatted will have the following structure: * - sibling1 ; will be a list of all the elements before the component with * ; the "N" modifier in this case the first 3 components * - sibling2 ; will be a list of the last component until the end */ public class ChatComponentFormatted extends ChatComponentList { private IChatComponent buffer = new ChatComponentList(); public ChatComponentFormatted(String format, Object... args) { this(format, Arrays.asList(args).iterator()); } public ChatComponentFormatted(String format, Iterator args) { String[] components = StringUtils.split(format, "{}"); for (String component : components) { processComponent(component, args); } this.appendSibling(buffer); } private void resetBuffer() { if (buffer.getSiblings().size() != 0) { this.appendSibling(buffer); } buffer = new ChatComponentList(); } private IChatComponent createComponent(String[] parts, Iterator args) { ChatStyle chatStyle = getStyle(parts[0]); String[] textWithHover = parts[1].split(" << "); String actualText = textWithHover[0]; while (actualText.contains("%s")) { actualText = actualText.replaceFirst("%s", Matcher.quoteReplacement(args.next().toString())); } IChatComponent message = new ChatComponentText(actualText).setChatStyle(chatStyle); if (textWithHover.length == 2) { IChatComponent hoverText = new ChatComponentFormatted("{" + textWithHover[1] + "}", args); chatStyle.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverText)); } return message; } private void addComponent(Iterator args) { // TODO: Instead of %s use other identifiers for lists of elements or container (maybe) Object currArg = args.next(); if (currArg instanceof IChatFormat) { buffer.appendSibling(((IChatFormat) currArg).toChatMessage()); } else if (currArg instanceof IChatComponent) { buffer.appendSibling((IChatComponent) currArg); } else if (currArg instanceof ChatComponentContainer) { resetBuffer(); for (IChatComponent message : (ChatComponentContainer) currArg) { this.appendSibling(message); } } } private void processComponent(String componentString, Iterator args) { String[] parts = componentString.split("\\|", 2); if (parts.length == 2) { if (parts[0].contains("N")) { resetBuffer(); } buffer.appendSibling(createComponent(parts, args)); } else if (parts.length == 1 && parts[0].equals("%s")){ addComponent(args); } else { throw new FormatException("Format " + componentString + " is not valid. Valid format: {modifiers|text}"); } } /** * Converts the modifiers String to a ChatStyle * {modifiers| some text} * ^^^^^^^^ ^^^^^^^^^ * STYLE for THIS TEXT */ private ChatStyle getStyle(String modifiers) { ChatStyle chatStyle = new ChatStyle(); for (char c : modifiers.toCharArray()) { applyModifier(chatStyle, c); } return chatStyle; } /** * Applies modifier to the style * Returns whether or not the modifier was valid */ private boolean applyModifier(ChatStyle chatStyle, char modifier) { if (modifier >= '0' && modifier <= '9' || modifier >= 'a' && modifier <= 'f') { chatStyle.setColor(ColorUtils.colorMap.get(modifier)); return true; } switch (modifier) { case 'k': chatStyle.setObfuscated(true); return true; case 'l': chatStyle.setBold(true); return true; case 'm': chatStyle.setStrikethrough(true); return true; case 'n': chatStyle.setUnderlined(true); return true; case 'o': chatStyle.setItalic(true); return true; } return false; } /** * Adds a ChatComponentText between all of the siblings * This can be used for easily displaying a onHoverText on multiple lines */ public ChatComponentFormatted applyDelimiter(String delimiter) { List<IChatComponent> newSiblings = new ArrayList<IChatComponent>(); for (IChatComponent component : (List<IChatComponent>) siblings) { if (newSiblings.size() > 0) { newSiblings.add(new ChatComponentText(delimiter)); } newSiblings.add(component); } this.siblings = newSiblings; return this; } /** * Cut down version of the client-side only method for getting formatting code * from the ChatStyle class * * Why is this client side? */ private String getFormattingCodeForStyle(ChatStyle style) { StringBuilder stringbuilder = new StringBuilder(); if (style.getColor() != null) { stringbuilder.append(style.getColor()); } if (style.getBold()) { stringbuilder.append(EnumChatFormatting.BOLD); } if (style.getItalic()) { stringbuilder.append(EnumChatFormatting.ITALIC); } if (style.getUnderlined()) { stringbuilder.append(EnumChatFormatting.UNDERLINE); } if (style.getObfuscated()) { stringbuilder.append(EnumChatFormatting.OBFUSCATED); } if (style.getStrikethrough()) { stringbuilder.append(EnumChatFormatting.STRIKETHROUGH); } return stringbuilder.toString(); } /** * Gets the formatted String for this component. * Example: {3|This is }{1|some text} * Will convert into: \u00a73This is \u00a71some text * \u00a7 - this is a unicode character used in Minecraft chat formatting */ public String[] getLegacyFormattedText() { String[] result = new String[this.siblings.size()]; int k = 0; for (IChatComponent component : (List<IChatComponent>) this.getSiblings()) { String actualText = ""; for (IChatComponent subComponent : (List<IChatComponent>) component.getSiblings()) { actualText += getFormattingCodeForStyle(subComponent.getChatStyle()); actualText += subComponent.getUnformattedText(); actualText += EnumChatFormatting.RESET; } result[k++] = actualText; } return result; } }
package mireka.smtp.client; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.regex.Pattern; import javax.inject.Inject; import mireka.smtp.EnhancedStatus; import mireka.smtp.SendException; import mireka.transmission.immediate.Upstream; import org.subethamail.smtp.client.PlainAuthenticator; /** * BackendServer specifies another SMTP server which is used as a proxy target * or smarthost. It may be part of an {@link Upstream}. */ public class BackendServer { private static final String IPV6_PREFIX = "[IPv6:"; private static final Pattern dottedQuad = Pattern .compile("\\d{1,3}(\\.\\d{1,3}){3}"); private ClientFactory clientFactory; /** * The host name in the format as it appears in the configuration. This * format is theoretically ambiguous, so it is only appropriate for * informational purposes. */ private String host; /** * The host name formatted in the same way as the remote part of a mailbox. * For example: * <ul> * <li>mail.example.com * <li>[192.0.2.0] * <li>[IPv6:::1] * </ul> */ private String smtpFormattedHost; /** * The IP address which was specified in the host field. It the host field * contains a domain name, then this field is null. */ private InetAddress fixedAddress; private int port = 25; private String user; private String password; /** * {@link BackendServer#setWeight} */ private double weight = 1; /** * {@link BackendServer#setBackup} */ private boolean backup = false; /** * * @throws SendException * if the IP address of the backend server could not be * determined based on its domain name. */ public SmtpClient createClient() throws SendException { SmtpClient client = clientFactory.create(); if (user != null) { PlainAuthenticator authenticator = new PlainAuthenticator(client, user, password); client.setAuthenticator(authenticator); } InetAddress address; try { address = fixedAddress != null ? fixedAddress : InetAddress .getByName(host); } catch (UnknownHostException e) { // without detailed information, assume it is a temporary failure throw new SendException("Resolving the backend " + this.toString() + " domain failed.", e, new EnhancedStatus(450, "4.4.0", "Domain name resolution failed")); } client.setMtaAddress(new MtaAddress(smtpFormattedHost, address, port)); return client; } @Override public String toString() { return host + ":" + port; } /** * @category GETSET */ public String getHost() { return host; } /** * Sets the domain name or IP address of the backend server. The name may * contain a domain name or IPv4 or IPv6 literals in various forms. It * guesses the actual type of the name. * <p> * Examples for legal values: * <ul> * <li>mail.example.com * <li>[192.0.2.0] * <li>192.0.2.0 * <li>[IPv6:::1] * <li>[::1] * <li>::1 * </ul> */ public void setHost(String host) { this.host = host; if (host == null) throw new NullPointerException(); if (host.isEmpty()) throw new IllegalArgumentException(); if (host.charAt(0) == '[') { // literal if (host.charAt(host.length() - 1) != ']') throw new IllegalArgumentException(); if (host.length() > IPV6_PREFIX.length() && IPV6_PREFIX.equalsIgnoreCase(host.substring(0, IPV6_PREFIX.length()))) setHostByAddress(host.substring(IPV6_PREFIX.length(), host.length())); setHostByAddress(host.substring(1, host.length())); } else { if (dottedQuad.matcher(host).matches()) setHostByAddress(host); if (host.contains(":")) setHostByAddress(host); setHostByDomain(host); } } private void setHostByDomain(String domain) { smtpFormattedHost = domain; fixedAddress = null; } private void setHostByAddress(String address) { try { InetAddress inetAddress = InetAddress.getByName(address); if (inetAddress instanceof Inet4Address) { smtpFormattedHost = "[" + address + "]"; } else if (inetAddress instanceof Inet6Address) { smtpFormattedHost = "[IPv6:" + address + "]"; } else { throw new RuntimeException(); } fixedAddress = inetAddress; } catch (UnknownHostException e) { // impossible, the argument is an IP address, not a domain name. throw new RuntimeException("Assertion failed"); } } public ClientFactory getClientFactory() { return clientFactory; } @Inject public void setClientFactory(ClientFactory clientFactory) { this.clientFactory = clientFactory; } /** * @category GETSET */ public int getPort() { return port; } /** * @category GETSET */ public void setPort(int port) { this.port = port; } /** * @category GETSET */ public String getUser() { return user; } /** * @category GETSET */ public void setUser(String user) { this.user = user; } /** * @category GETSET */ public String getPassword() { return password; } /** * @category GETSET */ public void setPassword(String password) { this.password = password; } /** * @category GETSET */ public double getWeight() { return weight; } /** * Relative weight of the server in an Upstream. Default is 1. * * @category GETSET */ public void setWeight(double weight) { this.weight = weight; } /** * @category GETSET */ public boolean isBackup() { return backup; } /** * True indicates that the server should only be used in an Upstream if all * non-backup servers failed. Default is false. * * @category GETSET */ public void setBackup(boolean backup) { this.backup = backup; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.plugins.document.bundlor; import java.util.Set; import com.google.common.collect.Sets; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.spi.state.NodeState; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.jackrabbit.oak.commons.PathUtils.ROOT_PATH; import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE; import static org.apache.jackrabbit.oak.plugins.memory.PropertyStates.createProperty; public class BundlingHandler { private final BundledTypesRegistry registry; private final String path; private final BundlingContext ctx; private final NodeState nodeState; public BundlingHandler(BundledTypesRegistry registry) { this(checkNotNull(registry), BundlingContext.NULL, ROOT_PATH, EMPTY_NODE); } private BundlingHandler(BundledTypesRegistry registry, BundlingContext ctx, String path, NodeState nodeState) { this.registry = registry; this.path = path; this.ctx = ctx; this.nodeState = nodeState; } /** * Returns property path. For non bundling case this is the actual property name * while for bundling case this is the relative path from bundling root */ public String getPropertyPath(String propertyName) { return ctx.isBundling() ? ctx.getPropertyPath(propertyName) : propertyName; } /** * Returns true if and only if current node is bundled in another node */ public boolean isBundledNode(){ return ctx.matcher.depth() > 0; } /** * Returns absolute path of the current node */ public String getNodeFullPath() { return path; } public NodeState getNodeState() { return nodeState; } public Set<PropertyState> getMetaProps() { return ctx.metaProps; } /** * Returns name of properties which needs to be removed or marked as deleted */ public Set<String> getRemovedProps(){ return ctx.removedProps; } public String getRootBundlePath() { return ctx.isBundling() ? ctx.bundlingPath : path; } public BundlingHandler childAdded(String name, NodeState state){ String childPath = childPath(name); BundlingContext childContext; Matcher childMatcher = ctx.matcher.next(name); if (childMatcher.isMatch()) { childContext = createChildContext(childMatcher); childContext.addMetaProp(createProperty(DocumentBundlor.META_PROP_BUNDLING_PATH, childMatcher.getMatchedPath())); } else { DocumentBundlor bundlor = registry.getBundlor(state); if (bundlor != null){ PropertyState bundlorConfig = bundlor.asPropertyState(); childContext = new BundlingContext(childPath, bundlor.createMatcher()); childContext.addMetaProp(bundlorConfig); } else { childContext = BundlingContext.NULL; } } return new BundlingHandler(registry, childContext, childPath, state); } public BundlingHandler childDeleted(String name, NodeState state){ String childPath = childPath(name); BundlingContext childContext; Matcher childMatcher = ctx.matcher.next(name); if (childMatcher.isMatch()) { childContext = createChildContext(childMatcher); removeDeletedChildProperties(state, childContext); } else { childContext = getBundlorContext(childPath, state); if (childContext.isBundling()){ removeBundlingMetaProps(state, childContext); } } return new BundlingHandler(registry, childContext, childPath, state); } public BundlingHandler childChanged(String name, NodeState before, NodeState after){ String childPath = childPath(name); BundlingContext childContext; Matcher childMatcher = ctx.matcher.next(name); if (childMatcher.isMatch()) { childContext = createChildContext(childMatcher); } else { //Use the before state for looking up bundlor config //as after state may have been recreated all together //and bundlor config might have got lost childContext = getBundlorContext(childPath, before); } return new BundlingHandler(registry, childContext, childPath, after); } public boolean isBundlingRoot() { if (ctx.isBundling()){ return ctx.bundlingPath.equals(path); } return true; } @Override public String toString() { String result = path; if (isBundledNode()){ result = path + "( Bundling root - " + getRootBundlePath() + ")"; } return result; } private String childPath(String name){ return PathUtils.concat(path, name); } private BundlingContext createChildContext(Matcher childMatcher) { return ctx.child(childMatcher); } private static BundlingContext getBundlorContext(String path, NodeState state) { BundlingContext result = BundlingContext.NULL; PropertyState bundlorConfig = state.getProperty(DocumentBundlor.META_PROP_PATTERN); if (bundlorConfig != null){ DocumentBundlor bundlor = DocumentBundlor.from(bundlorConfig); result = new BundlingContext(path, bundlor.createMatcher()); } return result; } private static void removeDeletedChildProperties(NodeState state, BundlingContext childContext) { childContext.removeProperty(DocumentBundlor.META_PROP_BUNDLING_PATH); for (PropertyState ps : state.getProperties()){ String propName = ps.getName(); //In deletion never touch child status related meta props //as they are not to be changed once set if (!propName.startsWith(DocumentBundlor.HAS_CHILD_PROP_PREFIX)) { childContext.removeProperty(ps.getName()); } } } private static void removeBundlingMetaProps(NodeState state, BundlingContext childContext) { //Explicitly remove meta prop related to bundling as it would not //be part of normal listing of properties and hence would not be deleted //as part of diff PropertyState bundlorConfig = state.getProperty(DocumentBundlor.META_PROP_PATTERN); if (bundlorConfig != null){ childContext.removeProperty(DocumentBundlor.META_PROP_PATTERN); } } private static class BundlingContext { static final BundlingContext NULL = new BundlingContext("", Matcher.NON_MATCHING); final String bundlingPath; final Matcher matcher; final Set<PropertyState> metaProps = Sets.newHashSet(); final Set<String> removedProps = Sets.newHashSet(); public BundlingContext(String bundlingPath, Matcher matcher) { this.bundlingPath = bundlingPath; this.matcher = matcher; } public BundlingContext child(Matcher matcher){ return new BundlingContext(bundlingPath, matcher); } public boolean isBundling(){ return matcher.isMatch(); } public String getPropertyPath(String propertyName) { return PathUtils.concat(matcher.getMatchedPath(), propertyName); } public void addMetaProp(PropertyState state){ metaProps.add(state); } public void removeProperty(String name){ removedProps.add(name); } } }
/* * 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 vista.Director; import control.ControladorDirector; import java.awt.BorderLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import vista.Formulario.Formulario; /** * * @author master */ public class AdmSecretaria extends javax.swing.JFrame { /** * Creates new form RevSecretaria */ private int id; private ControladorDirector ctrlD; public AdmSecretaria(int id) { initComponents(); ((JPanel) getContentPane()).setOpaque(false); ImageIcon imagen = new ImageIcon(this.getClass().getResource("/imagenes/fondos/fondoAdmSecretaria.png")); JLabel fondo = new JLabel(); fondo.setIcon(imagen); getLayeredPane().add(fondo, JLayeredPane.FRAME_CONTENT_LAYER); fondo.setBounds(0, 0, imagen.getIconWidth(), imagen.getIconHeight()); this.add(fondo, BorderLayout.CENTER); this.setSize(fondo.getWidth(), fondo.getHeight()); this.id=id; ctrlD=new ControladorDirector(); this.setResizable(false); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } private AdmSecretaria() { } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnRegistro = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); etiquetaNombre = new javax.swing.JLabel(); btnSalir = new javax.swing.JButton(); btnEditar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); btnRegistro.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N btnRegistro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/secretaria_3.png"))); // NOI18N btnRegistro.setText("REGISTRAR"); btnRegistro.setBorder(null); btnRegistro.setBorderPainted(false); btnRegistro.setContentAreaFilled(false); btnRegistro.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnRegistro.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnRegistro.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnRegistro.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnRegistroMouseEntered(evt); } }); btnRegistro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegistroActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N jLabel1.setText("Director:"); etiquetaNombre.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N etiquetaNombre.setText("X"); btnSalir.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/cancelar_3.png"))); // NOI18N btnSalir.setText("SALIR"); btnSalir.setActionCommand("btnSalir"); btnSalir.setBorder(null); btnSalir.setBorderPainted(false); btnSalir.setContentAreaFilled(false); btnSalir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalirActionPerformed(evt); } }); btnEditar.setFont(new java.awt.Font("Dialog", 1, 13)); // NOI18N btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/editar.png"))); // NOI18N btnEditar.setText("EDITAR"); btnEditar.setBorder(null); btnEditar.setBorderPainted(false); btnEditar.setContentAreaFilled(false); btnEditar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btnEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btnEditar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnEditarMouseEntered(evt); } }); btnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(etiquetaNombre)) .addGroup(layout.createSequentialGroup() .addGap(105, 105, 105) .addComponent(btnSalir)) .addGroup(layout.createSequentialGroup() .addGap(85, 85, 85) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnRegistro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnEditar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap(106, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(etiquetaNombre)) .addGap(37, 37, 37) .addComponent(btnRegistro) .addGap(30, 30, 30) .addComponent(btnEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE) .addComponent(btnSalir) .addGap(82, 82, 82)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnRegistroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistroActionPerformed // TODO add your handling code here: Formulario f=new Formulario("Registrar", "Secretaria"); f.obtenerID_Director(id); f.setVisible(true); }//GEN-LAST:event_btnRegistroActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // TODO add your handling code here: String nombre=ctrlD.obtenerNombre(id); etiquetaNombre.setText(nombre); }//GEN-LAST:event_formWindowOpened private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed // TODO add your handling code here: this.setVisible(false); }//GEN-LAST:event_btnSalirActionPerformed private void btnRegistroMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRegistroMouseEntered btnRegistro.setToolTipText("Registrar a Secretaria"); }//GEN-LAST:event_btnRegistroMouseEntered private void btnEditarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditarMouseEntered btnEditar.setToolTipText("Actualizar Informacion"); }//GEN-LAST:event_btnEditarMouseEntered private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed ListaSecretaria ls=new ListaSecretaria(); ls.setVisible(true); }//GEN-LAST:event_btnEditarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AdmSecretaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdmSecretaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdmSecretaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdmSecretaria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdmSecretaria().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnEditar; private javax.swing.JButton btnRegistro; private javax.swing.JButton btnSalir; private javax.swing.JLabel etiquetaNombre; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables }
package com.rafkind.paintown.level.objects; import com.rafkind.paintown.exception.LoadException; import com.rafkind.paintown.Token; import com.rafkind.paintown.TokenReader; import com.rafkind.paintown.MaskedImage; import com.rafkind.paintown.level.PropertyEditor; import com.rafkind.paintown.Lambda1; import com.rafkind.paintown.level.Editor; import java.io.*; import java.awt.*; import java.awt.image.*; import java.awt.geom.*; import javax.imageio.*; import java.util.HashMap; import java.util.Iterator; import java.util.ArrayList; import java.util.List; public abstract class Thing { private int x, y; private int id; private int width, height; private String path; private BufferedImage main; private String name; private boolean selected; private static HashMap images = new HashMap(); private List listeners; public Thing( Token token ) throws LoadException { Token coords = token.findToken( "coords" ); if ( coords != null ){ x = coords.readInt( 0 ); y = coords.readInt( 1 ); } Token tid = token.findToken("id"); if (tid != null){ id = tid.readInt(0); Level.checkId(id); } else { id = Level.nextId(); } Token tpath = token.findToken( "path" ); if ( tpath != null ){ setPath( tpath.readString( 0 ) ); main = loadImage( Editor.dataPath( getPath() ), this ); } listeners = new ArrayList(); } public Thing( Thing copy ){ listeners = new ArrayList(); setX( copy.getX() ); setY( copy.getY() ); setId(copy.getId()); setMain( copy.getMain() ); setPath( copy.getPath() ); setName( copy.getName() ); } private void setMain( BufferedImage image ){ main = image; } public BufferedImage getMain(){ return main; } public void setName( String s ){ this.name = s; fireUpdate(); } public int getId(){ return id; } public void setId(int i){ id = i; } public abstract Thing copy(); public String getName(){ return name; } public String toString(){ return "X: " + getX() + " Y: " + getY() + " Name: " + getName(); } private void setPath( String p ){ path = p; } public String getPath(){ return path.replaceAll( "\\\\", "/" ); } public abstract PropertyEditor getEditor(); public int getY(){ return y; } public int getX(){ return x; } public void setY( int y ){ // this.y = y + main.getHeight( null ) / 2; this.y = y; fireUpdate(); } public void setX( int x ){ this.x = x; fireUpdate(); } private void fireUpdate(){ for ( Iterator it = listeners.iterator(); it.hasNext(); ){ Lambda1 proc = (Lambda1) it.next(); proc.invoke_( this ); } } public void addListener( Lambda1 proc ){ if ( ! listeners.contains( proc ) ){ listeners.add( proc ); } } public void removeListener( Lambda1 proc ){ listeners.remove( proc ); } public int getWidth(){ return main.getWidth( null ); } public int getX1(){ return getX() - main.getWidth( null ) / 2; } public int getY1(){ return getY() - main.getHeight( null ); } public int getX2(){ return getX() + main.getWidth( null ) / 2; } public int getY2(){ return getY(); } public void setSelected( boolean s ){ selected = s; } protected void render( Image look, Graphics2D g, boolean highlight ){ // g.drawImage( main, startX + x, y, null ); // int mx = startX + x - main.getWidth( null ) / 2; // int mx = startX + x + main.getWidth( null ) / 2; int mx = x + look.getWidth( null ) / 2; int my = y - look.getHeight( null ); g.drawImage( look, new AffineTransform( -1, 0, 0, 1, mx, my ), null ); if ( selected ){ g.setColor( new Color( 0x66, 0xff, 0x77 ) ); } else if ( highlight ){ // g.setColor( new Color( 0x66, 0xff, 0x22 ) ); g.setColor( new Color( 0xff, 0x44, 0x33 ) ); } else { g.setColor( new Color( 64, 64, 255 ) ); } g.drawRect( getX1(), getY1(), look.getWidth( null ), look.getHeight( null ) ); g.setColor( new Color( 255, 255, 255 ) ); g.fillOval( x, y, 5, 5 ); } public void render( Graphics2D g, boolean highlight ){ render( getMain(), g, highlight ); } private static BufferedImage loadImage( String file, Thing t ) throws LoadException { if ( images.get( file ) != null ){ return (BufferedImage) images.get( file ); } images.put( file, t.readIdleImage( file ) ); return loadImage( file, t ); } protected abstract BufferedImage readIdleImage( String file ) throws LoadException; protected abstract String getType(); public abstract Token toToken(); public boolean equals( Object t ){ return this == t; } public int hashCode(){ return toToken().toString().hashCode(); } }
package course.labs.todomanager; import java.util.Calendar; import java.util.Date; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.TimePickerDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.TimePicker; import course.labs.todomanager.ToDoItem.Priority; import course.labs.todomanager.ToDoItem.Status; public class AddToDoActivity extends Activity { // 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000 private static final int SEVEN_DAYS = 604800000; private static final String TAG = "Lab-UserInterface"; private static String timeString; private static String dateString; private static TextView dateView; private static TextView timeView; private Date mDate; private RadioGroup mPriorityRadioGroup; private RadioGroup mStatusRadioGroup; private EditText mTitleText; private RadioButton mDefaultStatusButton; private RadioButton mDefaultPriorityButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_todo); mTitleText = (EditText) findViewById(R.id.title); mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone); mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority); mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup); mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup); dateView = (TextView) findViewById(R.id.date); timeView = (TextView) findViewById(R.id.time); // Set the default date and time setDefaultDateTime(); // OnClickListener for the Date button, calls showDatePickerDialog() to // show the Date dialog final Button datePickerButton = (Button) findViewById(R.id.date_picker_button); datePickerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); // OnClickListener for the Time button, calls showTimePickerDialog() to // show the Time Dialog final Button timePickerButton = (Button) findViewById(R.id.time_picker_button); timePickerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showTimePickerDialog(); } }); // OnClickListener for the Cancel Button, final Button cancelButton = (Button) findViewById(R.id.cancelButton); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO - Indicate result and finish } }); // TODO - Set up OnClickListener for the Reset Button final Button resetButton = (Button) findViewById(R.id.resetButton); resetButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO - Reset data to default values // reset date and time setDefaultDateTime(); } }); // Set up OnClickListener for the Submit Button final Button submitButton = (Button) findViewById(R.id.submitButton); submitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // gather ToDoItem data // TODO - Get the current Priority Priority priority = null; // TODO - Get the current Status Status status = null; // TODO - Get the current ToDoItem Title String titleString = null; // Construct the Date string String fullDate = dateString + " " + timeString; // Package ToDoItem data into an Intent Intent data = new Intent(); ToDoItem.packageIntent(data, titleString, priority, status, fullDate); // TODO - return data Intent and finish } }); } // Do not modify below this point. private void setDefaultDateTime() { // Default is current time + 7 days mDate = new Date(); mDate = new Date(mDate.getTime() + SEVEN_DAYS); Calendar c = Calendar.getInstance(); c.setTime(mDate); setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); dateView.setText(dateString); setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.MILLISECOND)); timeView.setText(timeString); } private static void setDateString(int year, int monthOfYear, int dayOfMonth) { // Increment monthOfYear for Calendar/Date -> Time Format setting monthOfYear++; String mon = "" + monthOfYear; String day = "" + dayOfMonth; if (monthOfYear < 10) mon = "0" + monthOfYear; if (dayOfMonth < 10) day = "0" + dayOfMonth; dateString = year + "-" + mon + "-" + day; } private static void setTimeString(int hourOfDay, int minute, int mili) { String hour = "" + hourOfDay; String min = "" + minute; if (hourOfDay < 10) hour = "0" + hourOfDay; if (minute < 10) min = "0" + minute; timeString = hour + ":" + min + ":00"; } private Priority getPriority() { switch (mPriorityRadioGroup.getCheckedRadioButtonId()) { case R.id.lowPriority: { return Priority.LOW; } case R.id.highPriority: { return Priority.HIGH; } default: { return Priority.MED; } } } private Status getStatus() { switch (mStatusRadioGroup.getCheckedRadioButtonId()) { case R.id.statusDone: { return Status.DONE; } default: { return Status.NOTDONE; } } } private String getToDoTitle() { return mTitleText.getText().toString(); } // DialogFragment used to pick a ToDoItem deadline date public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDateString(year, monthOfYear, dayOfMonth); dateView.setText(dateString); } } // DialogFragment used to pick a ToDoItem deadline time public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); // Create a new instance of TimePickerDialog and return return new TimePickerDialog(getActivity(), this, hour, minute, true); } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { setTimeString(hourOfDay, minute, 0); timeView.setText(timeString); } } private void showDatePickerDialog() { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getFragmentManager(), "datePicker"); } private void showTimePickerDialog() { DialogFragment newFragment = new TimePickerFragment(); newFragment.show(getFragmentManager(), "timePicker"); } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block; import alluxio.ClientContext; import alluxio.conf.ServerConfiguration; import alluxio.Constants; import alluxio.conf.PropertyKey; import alluxio.RuntimeConstants; import alluxio.Server; import alluxio.Sessions; import alluxio.StorageTierAssoc; import alluxio.exception.BlockAlreadyExistsException; import alluxio.exception.BlockDoesNotExistException; import alluxio.exception.ExceptionMessage; import alluxio.exception.InvalidWorkerStateException; import alluxio.exception.WorkerOutOfSpaceException; import alluxio.grpc.GrpcService; import alluxio.grpc.ServiceType; import alluxio.heartbeat.HeartbeatContext; import alluxio.heartbeat.HeartbeatExecutor; import alluxio.heartbeat.HeartbeatThread; import alluxio.master.MasterClientContext; import alluxio.metrics.MetricInfo; import alluxio.metrics.MetricKey; import alluxio.metrics.MetricsSystem; import alluxio.proto.dataserver.Protocol; import alluxio.retry.RetryUtils; import alluxio.security.user.ServerUserState; import alluxio.underfs.UfsManager; import alluxio.util.executor.ExecutorServiceFactories; import alluxio.wire.FileInfo; import alluxio.wire.WorkerNetAddress; import alluxio.worker.AbstractWorker; import alluxio.worker.SessionCleaner; import alluxio.worker.block.io.BlockReader; import alluxio.worker.block.io.BlockWriter; import alluxio.worker.block.meta.BlockMeta; import alluxio.worker.block.meta.TempBlockMeta; import alluxio.worker.file.FileSystemMasterClient; import com.google.common.base.Preconditions; import com.google.common.io.Closer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.ThreadSafe; /** * The class is responsible for managing all top level components of the Block Worker. * * This includes: * * Periodic Threads: {@link BlockMasterSync} (Worker to Master continuous communication) * * Logic: {@link DefaultBlockWorker} (Logic for all block related storage operations) */ @NotThreadSafe // TODO(jiri): make thread-safe (c.f. ALLUXIO-1624) public final class DefaultBlockWorker extends AbstractWorker implements BlockWorker { private static final Logger LOG = LoggerFactory.getLogger(DefaultBlockWorker.class); /** Runnable responsible for heartbeating and registration with master. */ private BlockMasterSync mBlockMasterSync; /** Runnable responsible for fetching pinlist from master. */ private PinListSync mPinListSync; /** Runnable responsible for clean up potential zombie sessions. */ private SessionCleaner mSessionCleaner; /** Used to close resources during stop. */ private Closer mResourceCloser; /** * Block master clients. commitBlock is the only reason to keep a pool of block master clients * on each worker. We should either improve our RPC model in the master or get rid of the * necessity to call commitBlock in the workers. */ private final BlockMasterClientPool mBlockMasterClientPool; /** Client for all file system master communication. */ private final FileSystemMasterClient mFileSystemMasterClient; /** Block store delta reporter for master heartbeat. */ private BlockHeartbeatReporter mHeartbeatReporter; /** Metrics reporter that listens on block events and increases metrics counters. */ private BlockMetricsReporter mMetricsReporter; /** Checker for storage paths. **/ private StorageChecker mStorageChecker; /** Session metadata, used to keep track of session heartbeats. */ private Sessions mSessions; /** Block Store manager. */ private BlockStore mBlockStore; private WorkerNetAddress mAddress; /** The under file system block store. */ private final UnderFileSystemBlockStore mUnderFileSystemBlockStore; /** * The worker ID for this worker. This is initialized in {@link #start(WorkerNetAddress)} and may * be updated by the block sync thread if the master requests re-registration. */ private AtomicReference<Long> mWorkerId; private final UfsManager mUfsManager; /** * Constructs a default block worker. * * @param ufsManager ufs manager */ DefaultBlockWorker(UfsManager ufsManager) { this(new BlockMasterClientPool(), new FileSystemMasterClient(MasterClientContext .newBuilder(ClientContext.create(ServerConfiguration.global())).build()), new Sessions(), new TieredBlockStore(), ufsManager); } /** * Constructs a default block worker. * * @param blockMasterClientPool a client pool for talking to the block master * @param fileSystemMasterClient a client for talking to the file system master * @param sessions an object for tracking and cleaning up client sessions * @param blockStore an Alluxio block store * @param ufsManager ufs manager */ DefaultBlockWorker(BlockMasterClientPool blockMasterClientPool, FileSystemMasterClient fileSystemMasterClient, Sessions sessions, BlockStore blockStore, UfsManager ufsManager) { super(ExecutorServiceFactories.fixedThreadPool("block-worker-executor", 5)); mResourceCloser = Closer.create(); mBlockMasterClientPool = mResourceCloser.register(blockMasterClientPool); mFileSystemMasterClient = mResourceCloser.register(fileSystemMasterClient); mHeartbeatReporter = new BlockHeartbeatReporter(); mMetricsReporter = new BlockMetricsReporter(); mSessions = sessions; mBlockStore = mResourceCloser.register(blockStore); mWorkerId = new AtomicReference<>(-1L); mBlockStore.registerBlockStoreEventListener(mHeartbeatReporter); mBlockStore.registerBlockStoreEventListener(mMetricsReporter); mUfsManager = ufsManager; mUnderFileSystemBlockStore = new UnderFileSystemBlockStore(mBlockStore, ufsManager); Metrics.registerGauges(this); } @Override public Set<Class<? extends Server>> getDependencies() { return new HashSet<>(); } @Override public String getName() { return Constants.BLOCK_WORKER_NAME; } @Override public BlockStore getBlockStore() { return mBlockStore; } @Override public Map<ServiceType, GrpcService> getServices() { return Collections.emptyMap(); } @Override public AtomicReference<Long> getWorkerId() { return mWorkerId; } /** * Runs the block worker. The thread must be called after all services (e.g., web, dataserver) * started. * * BlockWorker doesn't support being restarted! */ @Override public void start(WorkerNetAddress address) throws IOException { super.start(address); mAddress = address; // Acquire worker Id. BlockMasterClient blockMasterClient = mBlockMasterClientPool.acquire(); try { RetryUtils.retry("create worker id", () -> mWorkerId.set(blockMasterClient.getId(address)), RetryUtils.defaultWorkerMasterClientRetry(ServerConfiguration .getDuration(PropertyKey.WORKER_MASTER_CONNECT_RETRY_TIMEOUT))); } catch (Exception e) { throw new RuntimeException("Failed to create a worker id from block master: " + e.getMessage()); } finally { mBlockMasterClientPool.release(blockMasterClient); } Preconditions.checkNotNull(mWorkerId, "mWorkerId"); Preconditions.checkNotNull(mAddress, "mAddress"); // Setup BlockMasterSync mBlockMasterSync = mResourceCloser .register(new BlockMasterSync(this, mWorkerId, mAddress, mBlockMasterClientPool)); getExecutorService() .submit(new HeartbeatThread(HeartbeatContext.WORKER_BLOCK_SYNC, mBlockMasterSync, (int) ServerConfiguration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_INTERVAL_MS), ServerConfiguration.global(), ServerUserState.global())); // Setup PinListSyncer mPinListSync = mResourceCloser.register(new PinListSync(this, mFileSystemMasterClient)); getExecutorService() .submit(new HeartbeatThread(HeartbeatContext.WORKER_PIN_LIST_SYNC, mPinListSync, (int) ServerConfiguration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_INTERVAL_MS), ServerConfiguration.global(), ServerUserState.global())); // Setup session cleaner mSessionCleaner = mResourceCloser .register(new SessionCleaner(mSessions, mBlockStore, mUnderFileSystemBlockStore)); getExecutorService().submit(mSessionCleaner); // Setup storage checker if (ServerConfiguration.getBoolean(PropertyKey.WORKER_STORAGE_CHECKER_ENABLED)) { mStorageChecker = mResourceCloser.register(new StorageChecker()); getExecutorService() .submit(new HeartbeatThread(HeartbeatContext.WORKER_STORAGE_HEALTH, mStorageChecker, (int) ServerConfiguration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_INTERVAL_MS), ServerConfiguration.global(), ServerUserState.global())); } } /** * Stops the block worker. This method should only be called to terminate the worker. * * BlockWorker doesn't support being restarted! */ @Override public void stop() throws IOException { // Stop the base. (closes executors.) // This is intentionally called first in order to send interrupt signals to heartbeat threads. // Otherwise, if the heartbeat threads are not interrupted then the shutdown can hang. super.stop(); // Stop heart-beat executors and clients. mResourceCloser.close(); } @Override public void abortBlock(long sessionId, long blockId) throws BlockAlreadyExistsException, BlockDoesNotExistException, InvalidWorkerStateException, IOException { mBlockStore.abortBlock(sessionId, blockId); } @Override public void accessBlock(long sessionId, long blockId) throws BlockDoesNotExistException { mBlockStore.accessBlock(sessionId, blockId); } @Override public void commitBlock(long sessionId, long blockId, boolean pinOnCreate) throws BlockAlreadyExistsException, BlockDoesNotExistException, InvalidWorkerStateException, IOException, WorkerOutOfSpaceException { long lockId = -1; try { lockId = mBlockStore.commitBlockLocked(sessionId, blockId, pinOnCreate); } catch (BlockAlreadyExistsException e) { LOG.debug("Block {} has been in block store, this could be a retry due to master-side RPC " + "failure, therefore ignore the exception", blockId, e); } // TODO(calvin): Reconsider how to do this without heavy locking. // Block successfully committed, update master with new block metadata if (lockId == -1) { lockId = mBlockStore.lockBlock(sessionId, blockId); } BlockMasterClient blockMasterClient = mBlockMasterClientPool.acquire(); try { BlockMeta meta = mBlockStore.getBlockMeta(sessionId, blockId, lockId); BlockStoreLocation loc = meta.getBlockLocation(); String mediumType = loc.mediumType(); Long length = meta.getBlockSize(); BlockStoreMeta storeMeta = mBlockStore.getBlockStoreMeta(); Long bytesUsedOnTier = storeMeta.getUsedBytesOnTiers().get(loc.tierAlias()); blockMasterClient.commitBlock(mWorkerId.get(), bytesUsedOnTier, loc.tierAlias(), mediumType, blockId, length); } catch (Exception e) { throw new IOException(ExceptionMessage.FAILED_COMMIT_BLOCK_TO_MASTER.getMessage(blockId), e); } finally { mBlockMasterClientPool.release(blockMasterClient); mBlockStore.unlockBlock(lockId); } } @Override public void commitBlockInUfs(long blockId, long length) throws IOException { BlockMasterClient blockMasterClient = mBlockMasterClientPool.acquire(); try { blockMasterClient.commitBlockInUfs(blockId, length); } catch (Exception e) { throw new IOException(ExceptionMessage.FAILED_COMMIT_BLOCK_TO_MASTER.getMessage(blockId), e); } finally { mBlockMasterClientPool.release(blockMasterClient); } } @Override public String createBlock(long sessionId, long blockId, String tierAlias, String medium, long initialBytes) throws BlockAlreadyExistsException, WorkerOutOfSpaceException, IOException { BlockStoreLocation loc; if (medium.isEmpty()) { loc = BlockStoreLocation.anyDirInTier(tierAlias); } else { loc = BlockStoreLocation.anyDirInAnyTierWithMedium(medium); } TempBlockMeta createdBlock; try { createdBlock = mBlockStore.createBlock(sessionId, blockId, AllocateOptions.forCreate(initialBytes, loc)); } catch (WorkerOutOfSpaceException e) { LOG.error( "Failed to create block. SessionId: {}, BlockId: {}, " + "TierAlias:{}, Medium:{}, InitialBytes:{}, Error:{}", sessionId, blockId, tierAlias, medium, initialBytes, e); InetSocketAddress address = InetSocketAddress.createUnresolved(mAddress.getHost(), mAddress.getRpcPort()); throw new WorkerOutOfSpaceException(ExceptionMessage.CANNOT_REQUEST_SPACE .getMessageWithUrl(RuntimeConstants.ALLUXIO_DEBUG_DOCS_URL, address, blockId), e); } return createdBlock.getPath(); } @Override public void createBlockRemote(long sessionId, long blockId, String tierAlias, String medium, long initialBytes) throws BlockAlreadyExistsException, WorkerOutOfSpaceException, IOException { BlockStoreLocation loc; if (medium.isEmpty()) { loc = BlockStoreLocation.anyDirInTier(tierAlias); } else { loc = BlockStoreLocation.anyDirInAnyTierWithMedium(medium); } mBlockStore.createBlock(sessionId, blockId, AllocateOptions.forCreate(initialBytes, loc)); } @Override public void freeSpace(long sessionId, long availableBytes, String tierAlias) throws WorkerOutOfSpaceException, BlockDoesNotExistException, IOException, BlockAlreadyExistsException, InvalidWorkerStateException { BlockStoreLocation location = BlockStoreLocation.anyDirInTier(tierAlias); mBlockStore.freeSpace(sessionId, availableBytes, availableBytes, location); } @Override public BlockWriter getTempBlockWriterRemote(long sessionId, long blockId) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, IOException { return mBlockStore.getBlockWriter(sessionId, blockId); } @Override public BlockHeartbeatReport getReport() { return mHeartbeatReporter.generateReport(); } @Override public BlockStoreMeta getStoreMeta() { return mBlockStore.getBlockStoreMeta(); } @Override public BlockStoreMeta getStoreMetaFull() { return mBlockStore.getBlockStoreMetaFull(); } @Override public BlockMeta getVolatileBlockMeta(long blockId) throws BlockDoesNotExistException { return mBlockStore.getVolatileBlockMeta(blockId); } @Override public BlockMeta getBlockMeta(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException { return mBlockStore.getBlockMeta(sessionId, blockId, lockId); } @Override public boolean hasBlockMeta(long blockId) { return mBlockStore.hasBlockMeta(blockId); } @Override public long lockBlock(long sessionId, long blockId) throws BlockDoesNotExistException { return mBlockStore.lockBlock(sessionId, blockId); } @Override public long lockBlockNoException(long sessionId, long blockId) { return mBlockStore.lockBlockNoException(sessionId, blockId); } @Override public void moveBlock(long sessionId, long blockId, String tierAlias) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, WorkerOutOfSpaceException, IOException { // TODO(calvin): Move this logic into BlockStore#moveBlockInternal if possible // Because the move operation is expensive, we first check if the operation is necessary BlockStoreLocation dst = BlockStoreLocation.anyDirInTier(tierAlias); long lockId = mBlockStore.lockBlock(sessionId, blockId); try { BlockMeta meta = mBlockStore.getBlockMeta(sessionId, blockId, lockId); if (meta.getBlockLocation().belongsTo(dst)) { return; } } finally { mBlockStore.unlockBlock(lockId); } // Execute the block move if necessary mBlockStore.moveBlock(sessionId, blockId, AllocateOptions.forMove(dst)); } @Override public void moveBlockToMedium(long sessionId, long blockId, String mediumType) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, WorkerOutOfSpaceException, IOException { BlockStoreLocation dst = BlockStoreLocation.anyDirInAnyTierWithMedium(mediumType); long lockId = mBlockStore.lockBlock(sessionId, blockId); try { BlockMeta meta = mBlockStore.getBlockMeta(sessionId, blockId, lockId); if (meta.getBlockLocation().belongsTo(dst)) { return; } } finally { mBlockStore.unlockBlock(lockId); } // Execute the block move if necessary mBlockStore.moveBlock(sessionId, blockId, AllocateOptions.forMove(dst)); } @Override public String readBlock(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException { BlockMeta meta = mBlockStore.getBlockMeta(sessionId, blockId, lockId); return meta.getPath(); } @Override public BlockReader readBlockRemote(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException, IOException { return mBlockStore.getBlockReader(sessionId, blockId, lockId); } @Override public BlockReader readUfsBlock(long sessionId, long blockId, long offset, boolean positionShort) throws BlockDoesNotExistException, IOException { return mUnderFileSystemBlockStore.getBlockReader(sessionId, blockId, offset, positionShort); } @Override public void removeBlock(long sessionId, long blockId) throws InvalidWorkerStateException, BlockDoesNotExistException, IOException { mBlockStore.removeBlock(sessionId, blockId); } @Override public void requestSpace(long sessionId, long blockId, long additionalBytes) throws BlockDoesNotExistException, WorkerOutOfSpaceException, IOException { mBlockStore.requestSpace(sessionId, blockId, additionalBytes); } @Override public void unlockBlock(long lockId) throws BlockDoesNotExistException { mBlockStore.unlockBlock(lockId); } @Override // TODO(calvin): Remove when lock and reads are separate operations. public boolean unlockBlock(long sessionId, long blockId) { return mBlockStore.unlockBlock(sessionId, blockId); } @Override public void sessionHeartbeat(long sessionId) { mSessions.sessionHeartbeat(sessionId); } @Override public void updatePinList(Set<Long> pinnedInodes) { mBlockStore.updatePinnedInodes(pinnedInodes); } @Override public FileInfo getFileInfo(long fileId) throws IOException { return mFileSystemMasterClient.getFileInfo(fileId); } @Override public boolean openUfsBlock(long sessionId, long blockId, Protocol.OpenUfsBlockOptions options) throws BlockAlreadyExistsException { if (!options.hasUfsPath() && options.hasBlockInUfsTier() && options.getBlockInUfsTier()) { // This is a fallback UFS block read. Reset the UFS block path according to the UfsBlock flag. UfsManager.UfsClient ufsClient; try { ufsClient = mUfsManager.get(options.getMountId()); } catch (alluxio.exception.status.NotFoundException | alluxio.exception.status.UnavailableException e) { LOG.warn("Can not open UFS block: mount id {} not found {}", options.getMountId(), e.toString()); return false; } options = options.toBuilder().setUfsPath( alluxio.worker.BlockUtils.getUfsBlockPath(ufsClient, blockId)).build(); } return mUnderFileSystemBlockStore.acquireAccess(sessionId, blockId, options); } @Override public void closeUfsBlock(long sessionId, long blockId) throws BlockAlreadyExistsException, IOException, WorkerOutOfSpaceException { try { mUnderFileSystemBlockStore.closeReaderOrWriter(sessionId, blockId); if (mBlockStore.getTempBlockMeta(sessionId, blockId) != null) { try { commitBlock(sessionId, blockId, false); } catch (BlockDoesNotExistException e) { // This can only happen if the session is expired. Ignore this exception if that happens. LOG.warn("Block {} does not exist while being committed.", blockId); } catch (InvalidWorkerStateException e) { // This can happen if there are multiple sessions writing to the same block. // BlockStore#getTempBlockMeta does not check whether the temp block belongs to // the sessionId. LOG.debug("Invalid worker state while committing block.", e); } } } finally { mUnderFileSystemBlockStore.releaseAccess(sessionId, blockId); } } @Override public void clearMetrics() { // TODO(lu) Create a metrics worker and move this method to metrics worker MetricsSystem.resetAllMetrics(); } @Override public void cleanupSession(long sessionId) { mBlockStore.cleanupSession(sessionId); mUnderFileSystemBlockStore.cleanupSession(sessionId); } /** * This class contains some metrics related to the block worker. * This class is public because the metric names are referenced in * {@link alluxio.web.WebInterfaceAbstractMetricsServlet}. */ @ThreadSafe public static final class Metrics { /** * Registers metric gauges. * * @param blockWorker the block worker handle */ public static void registerGauges(final BlockWorker blockWorker) { MetricsSystem.registerGaugeIfAbsent( MetricsSystem.getMetricName(MetricKey.WORKER_CAPACITY_TOTAL.getName()), () -> blockWorker.getStoreMeta().getCapacityBytes()); MetricsSystem.registerGaugeIfAbsent( MetricsSystem.getMetricName(MetricKey.WORKER_CAPACITY_USED.getName()), () -> blockWorker.getStoreMeta().getUsedBytes()); MetricsSystem.registerGaugeIfAbsent( MetricsSystem.getMetricName(MetricKey.WORKER_CAPACITY_FREE.getName()), () -> blockWorker.getStoreMeta().getCapacityBytes() - blockWorker.getStoreMeta() .getUsedBytes()); StorageTierAssoc assoc = blockWorker.getStoreMeta().getStorageTierAssoc(); for (int i = 0; i < assoc.size(); i++) { String tier = assoc.getAlias(i); // TODO(lu) Add template to dynamically generate MetricKey MetricsSystem.registerGaugeIfAbsent(MetricsSystem.getMetricName( MetricKey.WORKER_CAPACITY_TOTAL.getName() + MetricInfo.TIER + tier), () -> blockWorker.getStoreMeta().getCapacityBytesOnTiers().getOrDefault(tier, 0L)); MetricsSystem.registerGaugeIfAbsent(MetricsSystem.getMetricName( MetricKey.WORKER_CAPACITY_USED.getName() + MetricInfo.TIER + tier), () -> blockWorker.getStoreMeta().getUsedBytesOnTiers().getOrDefault(tier, 0L)); MetricsSystem.registerGaugeIfAbsent(MetricsSystem.getMetricName( MetricKey.WORKER_CAPACITY_FREE.getName() + MetricInfo.TIER + tier), () -> blockWorker.getStoreMeta().getCapacityBytesOnTiers().getOrDefault(tier, 0L) - blockWorker.getStoreMeta().getUsedBytesOnTiers().getOrDefault(tier, 0L)); } MetricsSystem.registerGaugeIfAbsent(MetricsSystem.getMetricName( MetricKey.WORKER_BLOCKS_CACHED.getName()), () -> blockWorker.getStoreMetaFull().getNumberOfBlocks()); } private Metrics() {} // prevent instantiation } /** * StorageChecker periodically checks the health of each storage path and report missing blocks to * {@link BlockWorker}. */ @NotThreadSafe public final class StorageChecker implements HeartbeatExecutor { @Override public void heartbeat() { try { mBlockStore.checkStorage(); } catch (Exception e) { LOG.warn("Failed to check storage: {}", e.toString()); LOG.debug("Exception: ", e); } } @Override public void close() { // Nothing to clean up } } }
/** * 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.ipc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import junit.framework.TestCase; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.BlockingQueue; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.conf.Configuration; import org.mockito.Matchers; import static org.apache.hadoop.ipc.FairCallQueue.IPC_CALLQUEUE_PRIORITY_LEVELS_KEY; public class TestFairCallQueue extends TestCase { private FairCallQueue<Schedulable> fcq; private Schedulable mockCall(String id) { Schedulable mockCall = mock(Schedulable.class); UserGroupInformation ugi = mock(UserGroupInformation.class); when(ugi.getUserName()).thenReturn(id); when(mockCall.getUserGroupInformation()).thenReturn(ugi); return mockCall; } // A scheduler which always schedules into priority zero private RpcScheduler alwaysZeroScheduler; { RpcScheduler sched = mock(RpcScheduler.class); when(sched.getPriorityLevel(Matchers.<Schedulable>any())).thenReturn(0); // always queue 0 alwaysZeroScheduler = sched; } public void setUp() { Configuration conf = new Configuration(); conf.setInt("ns." + IPC_CALLQUEUE_PRIORITY_LEVELS_KEY, 2); fcq = new FairCallQueue<Schedulable>(5, "ns", conf); } // // Ensure that FairCallQueue properly implements BlockingQueue // public void testPollReturnsNullWhenEmpty() { assertNull(fcq.poll()); } public void testPollReturnsTopCallWhenNotEmpty() { Schedulable call = mockCall("c"); assertTrue(fcq.offer(call)); assertEquals(call, fcq.poll()); // Poll took it out so the fcq is empty assertEquals(0, fcq.size()); } public void testOfferSucceeds() { fcq.setScheduler(alwaysZeroScheduler); for (int i = 0; i < 5; i++) { // We can fit 10 calls assertTrue(fcq.offer(mockCall("c"))); } assertEquals(5, fcq.size()); } public void testOfferFailsWhenFull() { fcq.setScheduler(alwaysZeroScheduler); for (int i = 0; i < 5; i++) { assertTrue(fcq.offer(mockCall("c"))); } assertFalse(fcq.offer(mockCall("c"))); // It's full assertEquals(5, fcq.size()); } public void testOfferSucceedsWhenScheduledLowPriority() { // Scheduler will schedule into queue 0 x 5, then queue 1 RpcScheduler sched = mock(RpcScheduler.class); when(sched.getPriorityLevel(Matchers.<Schedulable>any())).thenReturn(0, 0, 0, 0, 0, 1, 0); fcq.setScheduler(sched); for (int i = 0; i < 5; i++) { assertTrue(fcq.offer(mockCall("c"))); } assertTrue(fcq.offer(mockCall("c"))); assertEquals(6, fcq.size()); } public void testPeekNullWhenEmpty() { assertNull(fcq.peek()); } public void testPeekNonDestructive() { Schedulable call = mockCall("c"); assertTrue(fcq.offer(call)); assertEquals(call, fcq.peek()); assertEquals(call, fcq.peek()); // Non-destructive assertEquals(1, fcq.size()); } public void testPeekPointsAtHead() { Schedulable call = mockCall("c"); Schedulable next = mockCall("b"); fcq.offer(call); fcq.offer(next); assertEquals(call, fcq.peek()); // Peek points at the head } public void testPollTimeout() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); assertNull(fcq.poll(10, TimeUnit.MILLISECONDS)); } public void testPollSuccess() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); Schedulable call = mockCall("c"); assertTrue(fcq.offer(call)); assertEquals(call, fcq.poll(10, TimeUnit.MILLISECONDS)); assertEquals(0, fcq.size()); } public void testOfferTimeout() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); for (int i = 0; i < 5; i++) { assertTrue(fcq.offer(mockCall("c"), 10, TimeUnit.MILLISECONDS)); } assertFalse(fcq.offer(mockCall("e"), 10, TimeUnit.MILLISECONDS)); // It's full assertEquals(5, fcq.size()); } public void testDrainTo() { Configuration conf = new Configuration(); conf.setInt("ns." + IPC_CALLQUEUE_PRIORITY_LEVELS_KEY, 2); FairCallQueue<Schedulable> fcq2 = new FairCallQueue<Schedulable>(10, "ns", conf); fcq.setScheduler(alwaysZeroScheduler); fcq2.setScheduler(alwaysZeroScheduler); // Start with 3 in fcq, to be drained for (int i = 0; i < 3; i++) { fcq.offer(mockCall("c")); } fcq.drainTo(fcq2); assertEquals(0, fcq.size()); assertEquals(3, fcq2.size()); } public void testDrainToWithLimit() { Configuration conf = new Configuration(); conf.setInt("ns." + IPC_CALLQUEUE_PRIORITY_LEVELS_KEY, 2); FairCallQueue<Schedulable> fcq2 = new FairCallQueue<Schedulable>(10, "ns", conf); fcq.setScheduler(alwaysZeroScheduler); fcq2.setScheduler(alwaysZeroScheduler); // Start with 3 in fcq, to be drained for (int i = 0; i < 3; i++) { fcq.offer(mockCall("c")); } fcq.drainTo(fcq2, 2); assertEquals(1, fcq.size()); assertEquals(2, fcq2.size()); } public void testInitialRemainingCapacity() { assertEquals(10, fcq.remainingCapacity()); } public void testFirstQueueFullRemainingCapacity() { fcq.setScheduler(alwaysZeroScheduler); while (fcq.offer(mockCall("c"))) ; // Queue 0 will fill up first, then queue 1 assertEquals(5, fcq.remainingCapacity()); } public void testAllQueuesFullRemainingCapacity() { RpcScheduler sched = mock(RpcScheduler.class); when(sched.getPriorityLevel(Matchers.<Schedulable>any())).thenReturn(0, 0, 0, 0, 0, 1, 1, 1, 1, 1); fcq.setScheduler(sched); while (fcq.offer(mockCall("c"))) ; assertEquals(0, fcq.remainingCapacity()); assertEquals(10, fcq.size()); } public void testQueuesPartialFilledRemainingCapacity() { RpcScheduler sched = mock(RpcScheduler.class); when(sched.getPriorityLevel(Matchers.<Schedulable>any())).thenReturn(0, 1, 0, 1, 0); fcq.setScheduler(sched); for (int i = 0; i < 5; i++) { fcq.offer(mockCall("c")); } assertEquals(5, fcq.remainingCapacity()); assertEquals(5, fcq.size()); } /** * Putter produces FakeCalls */ public class Putter implements Runnable { private final BlockingQueue<Schedulable> cq; public final String tag; public volatile int callsAdded = 0; // How many calls we added, accurate unless interrupted private final int maxCalls; private final CountDownLatch latch; public Putter(BlockingQueue<Schedulable> aCq, int maxCalls, String tag, CountDownLatch latch) { this.maxCalls = maxCalls; this.cq = aCq; this.tag = tag; this.latch = latch; } private String getTag() { if (this.tag != null) return this.tag; return ""; } @Override public void run() { try { // Fill up to max (which is infinite if maxCalls < 0) while (callsAdded < maxCalls || maxCalls < 0) { cq.put(mockCall(getTag())); callsAdded++; latch.countDown(); } } catch (InterruptedException e) { return; } } } /** * Taker consumes FakeCalls */ public class Taker implements Runnable { private final BlockingQueue<Schedulable> cq; public final String tag; // if >= 0 means we will only take the matching tag, and put back // anything else public volatile int callsTaken = 0; // total calls taken, accurate if we aren't interrupted public volatile Schedulable lastResult = null; // the last thing we took private final int maxCalls; // maximum calls to take private final CountDownLatch latch; private IdentityProvider uip; public Taker(BlockingQueue<Schedulable> aCq, int maxCalls, String tag, CountDownLatch latch) { this.maxCalls = maxCalls; this.cq = aCq; this.tag = tag; this.uip = new UserIdentityProvider(); this.latch = latch; } @Override public void run() { try { // Take while we don't exceed maxCalls, or if maxCalls is undefined (< 0) while (callsTaken < maxCalls || maxCalls < 0) { Schedulable res = cq.take(); String identity = uip.makeIdentity(res); if (tag != null && this.tag.equals(identity)) { // This call does not match our tag, we should put it back and try again cq.put(res); } else { callsTaken++; latch.countDown(); lastResult = res; } } } catch (InterruptedException e) { return; } } } // Assert we can take exactly the numberOfTakes public void assertCanTake(BlockingQueue<Schedulable> cq, int numberOfTakes, int takeAttempts) throws InterruptedException { CountDownLatch latch = new CountDownLatch(numberOfTakes); Taker taker = new Taker(cq, takeAttempts, "default", latch); Thread t = new Thread(taker); t.start(); latch.await(); assertEquals(numberOfTakes, taker.callsTaken); t.interrupt(); } // Assert we can put exactly the numberOfPuts public void assertCanPut(BlockingQueue<Schedulable> cq, int numberOfPuts, int putAttempts) throws InterruptedException { CountDownLatch latch = new CountDownLatch(numberOfPuts); Putter putter = new Putter(cq, putAttempts, null, latch); Thread t = new Thread(putter); t.start(); latch.await(); assertEquals(numberOfPuts, putter.callsAdded); t.interrupt(); } // Make sure put will overflow into lower queues when the top is full public void testPutOverflows() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); // We can fit more than 5, even though the scheduler suggests the top queue assertCanPut(fcq, 8, 8); assertEquals(8, fcq.size()); } public void testPutBlocksWhenAllFull() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); assertCanPut(fcq, 10, 10); // Fill up assertEquals(10, fcq.size()); // Put more which causes overflow assertCanPut(fcq, 0, 1); // Will block } public void testTakeBlocksWhenEmpty() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); assertCanTake(fcq, 0, 1); } public void testTakeRemovesCall() throws InterruptedException { fcq.setScheduler(alwaysZeroScheduler); Schedulable call = mockCall("c"); fcq.offer(call); assertEquals(call, fcq.take()); assertEquals(0, fcq.size()); } public void testTakeTriesNextQueue() throws InterruptedException { // Make a FCQ filled with calls in q 1 but empty in q 0 RpcScheduler q1Scheduler = mock(RpcScheduler.class); when(q1Scheduler.getPriorityLevel(Matchers.<Schedulable>any())).thenReturn(1); fcq.setScheduler(q1Scheduler); // A mux which only draws from q 0 RpcMultiplexer q0mux = mock(RpcMultiplexer.class); when(q0mux.getAndAdvanceCurrentIndex()).thenReturn(0); fcq.setMultiplexer(q0mux); Schedulable call = mockCall("c"); fcq.put(call); // Take from q1 even though mux said q0, since q0 empty assertEquals(call, fcq.take()); assertEquals(0, fcq.size()); } }
/** * 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.mapred; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.text.NumberFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.SecretKey; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem.Statistics; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.io.serializer.Deserializer; import org.apache.hadoop.io.serializer.SerializationFactory; import org.apache.hadoop.mapred.IFile.Writer; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.util.Progress; import org.apache.hadoop.util.Progressable; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.ResourceCalculatorPlugin; import org.apache.hadoop.util.ResourceCalculatorPlugin.ProcResourceValues; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.fs.FSDataInputStream; /** * Base class for tasks. * * This is NOT a public interface. */ abstract public class Task implements Writable, Configurable { private static final Log LOG = LogFactory.getLog(Task.class); public static final String MR_COMBINE_RECORDS_BEFORE_PROGRESS = "mapred.combine.recordsBeforeProgress"; public static final long DEFAULT_MR_COMBINE_RECORDS_BEFORE_PROGRESS = 10000; // Counters used by Task subclasses public static enum Counter { MAP_INPUT_RECORDS, MAP_OUTPUT_RECORDS, MAP_SKIPPED_RECORDS, MAP_INPUT_BYTES, MAP_OUTPUT_BYTES, MAP_OUTPUT_MATERIALIZED_BYTES, COMBINE_INPUT_RECORDS, COMBINE_OUTPUT_RECORDS, REDUCE_INPUT_GROUPS, REDUCE_SHUFFLE_BYTES, REDUCE_INPUT_RECORDS, REDUCE_OUTPUT_RECORDS, REDUCE_SKIPPED_GROUPS, REDUCE_SKIPPED_RECORDS, SPILLED_RECORDS, SPLIT_RAW_BYTES, CPU_MILLISECONDS, PHYSICAL_MEMORY_BYTES, VIRTUAL_MEMORY_BYTES, COMMITTED_HEAP_BYTES } /** * Counters to measure the usage of the different file systems. * Always return the String array with two elements. First one is the name of * BYTES_READ counter and second one is of the BYTES_WRITTEN counter. */ protected static String[] getFileSystemCounterNames(String uriScheme) { String scheme = uriScheme.toUpperCase(); return new String[]{scheme+"_BYTES_READ", scheme+"_BYTES_WRITTEN"}; } /** * Name of the FileSystem counters' group */ protected static final String FILESYSTEM_COUNTER_GROUP = "FileSystemCounters"; /////////////////////////////////////////////////////////// // Helper methods to construct task-output paths /////////////////////////////////////////////////////////// /** Construct output file names so that, when an output directory listing is * sorted lexicographically, positions correspond to output partitions.*/ private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); static { NUMBER_FORMAT.setMinimumIntegerDigits(5); NUMBER_FORMAT.setGroupingUsed(false); } static synchronized String getOutputName(int partition) { return "part-" + NUMBER_FORMAT.format(partition); } //////////////////////////////////////////// // Fields //////////////////////////////////////////// private String jobFile; // job configuration file private String user; // user running the job private TaskAttemptID taskId; // unique, includes job id private int partition; // id within job TaskStatus taskStatus; // current status of the task protected JobStatus.State jobRunStateForCleanup; protected boolean jobCleanup = false; protected boolean jobSetup = false; protected boolean taskCleanup = false; //skip ranges based on failed ranges from previous attempts private SortedRanges skipRanges = new SortedRanges(); private boolean skipping = false; private boolean writeSkipRecs = true; //currently processing record start index private volatile long currentRecStartIndex; private Iterator<Long> currentRecIndexIterator = skipRanges.skipRangeIterator(); private ResourceCalculatorPlugin resourceCalculator = null; private long initCpuCumulativeTime = 0; protected JobConf conf; protected MapOutputFile mapOutputFile = new MapOutputFile(); protected LocalDirAllocator lDirAlloc; private final static int MAX_RETRIES = 10; protected JobContext jobContext; protected TaskAttemptContext taskContext; protected org.apache.hadoop.mapreduce.OutputFormat<?,?> outputFormat; protected org.apache.hadoop.mapreduce.OutputCommitter committer; protected final Counters.Counter spilledRecordsCounter; private int numSlotsRequired; private String pidFile = ""; protected TaskUmbilicalProtocol umbilical; protected SecretKey tokenSecret; protected JvmContext jvmContext; //////////////////////////////////////////// // Constructors //////////////////////////////////////////// public Task() { taskStatus = TaskStatus.createTaskStatus(isMapTask()); taskId = new TaskAttemptID(); spilledRecordsCounter = counters.findCounter(Counter.SPILLED_RECORDS); } public Task(String jobFile, TaskAttemptID taskId, int partition, int numSlotsRequired) { this.jobFile = jobFile; this.taskId = taskId; this.partition = partition; this.numSlotsRequired = numSlotsRequired; this.taskStatus = TaskStatus.createTaskStatus(isMapTask(), this.taskId, 0.0f, numSlotsRequired, TaskStatus.State.UNASSIGNED, "", "", "", isMapTask() ? TaskStatus.Phase.MAP : TaskStatus.Phase.SHUFFLE, counters); spilledRecordsCounter = counters.findCounter(Counter.SPILLED_RECORDS); } //////////////////////////////////////////// // Accessors //////////////////////////////////////////// public void setJobFile(String jobFile) { this.jobFile = jobFile; } public String getJobFile() { return jobFile; } public TaskAttemptID getTaskID() { return taskId; } public int getNumSlotsRequired() { return numSlotsRequired; } Counters getCounters() { return counters; } /** * Get the job name for this task. * @return the job name */ public JobID getJobID() { return taskId.getJobID(); } /** * Set the job token secret * @param tokenSecret the secret */ public void setJobTokenSecret(SecretKey tokenSecret) { this.tokenSecret = tokenSecret; } /** * Get the job token secret * @return the token secret */ public SecretKey getJobTokenSecret() { return this.tokenSecret; } /** * Set the task JvmContext * @param jvmContext */ public void setJvmContext(JvmContext jvmContext) { this.jvmContext = jvmContext; } /** * Gets the task JvmContext * @return the jvm context */ public JvmContext getJvmContext() { return this.jvmContext; } /** * Get the index of this task within the job. * @return the integer part of the task id */ public int getPartition() { return partition; } /** * Return current phase of the task. * needs to be synchronized as communication thread sends the phase every second * @return the curent phase of the task */ public synchronized TaskStatus.Phase getPhase(){ return this.taskStatus.getPhase(); } /** * Set current phase of the task. * @param phase task phase */ protected synchronized void setPhase(TaskStatus.Phase phase){ this.taskStatus.setPhase(phase); } /** * Get whether to write skip records. */ protected boolean toWriteSkipRecs() { return writeSkipRecs; } /** * Set whether to write skip records. */ protected void setWriteSkipRecs(boolean writeSkipRecs) { this.writeSkipRecs = writeSkipRecs; } /** * Report a fatal error to the parent (task) tracker. */ protected void reportFatalError(TaskAttemptID id, Throwable throwable, String logMsg) { LOG.fatal(logMsg); Throwable tCause = throwable.getCause(); String cause = tCause == null ? StringUtils.stringifyException(throwable) : StringUtils.stringifyException(tCause); try { umbilical.fatalError(id, cause, jvmContext); } catch (IOException ioe) { LOG.fatal("Failed to contact the tasktracker", ioe); System.exit(-1); } } /** * Get skipRanges. */ public SortedRanges getSkipRanges() { return skipRanges; } /** * Set skipRanges. */ public void setSkipRanges(SortedRanges skipRanges) { this.skipRanges = skipRanges; } /** * Is Task in skipping mode. */ public boolean isSkipping() { return skipping; } /** * Sets whether to run Task in skipping mode. * @param skipping */ public void setSkipping(boolean skipping) { this.skipping = skipping; } /** * Return current state of the task. * needs to be synchronized as communication thread * sends the state every second * @return */ synchronized TaskStatus.State getState(){ return this.taskStatus.getRunState(); } /** * Set current state of the task. * @param state */ synchronized void setState(TaskStatus.State state){ this.taskStatus.setRunState(state); } void setTaskCleanupTask() { taskCleanup = true; } boolean isTaskCleanupTask() { return taskCleanup; } boolean isJobCleanupTask() { return jobCleanup; } boolean isJobAbortTask() { // the task is an abort task if its marked for cleanup and the final // expected state is either failed or killed. return isJobCleanupTask() && (jobRunStateForCleanup == JobStatus.State.KILLED || jobRunStateForCleanup == JobStatus.State.FAILED); } boolean isJobSetupTask() { return jobSetup; } void setJobSetupTask() { jobSetup = true; } void setJobCleanupTask() { jobCleanup = true; } /** * Sets the task to do job abort in the cleanup. * @param status the final runstate of the job */ void setJobCleanupTaskState(JobStatus.State status) { jobRunStateForCleanup = status; } boolean isMapOrReduce() { return !jobSetup && !jobCleanup && !taskCleanup; } void setUser(String user) { this.user = user; } /** * Get the name of the user running the job/task. TaskTracker needs task's * user name even before it's JobConf is localized. So we explicitly serialize * the user name. * * @return user */ public String getUser() { return user; } //////////////////////////////////////////// // Writable methods //////////////////////////////////////////// public void write(DataOutput out) throws IOException { Text.writeString(out, jobFile); taskId.write(out); out.writeInt(partition); out.writeInt(numSlotsRequired); taskStatus.write(out); skipRanges.write(out); out.writeBoolean(skipping); out.writeBoolean(jobCleanup); if (jobCleanup) { WritableUtils.writeEnum(out, jobRunStateForCleanup); } out.writeBoolean(jobSetup); out.writeBoolean(writeSkipRecs); out.writeBoolean(taskCleanup); Text.writeString(out, user); } public void readFields(DataInput in) throws IOException { jobFile = Text.readString(in); taskId = TaskAttemptID.read(in); partition = in.readInt(); numSlotsRequired = in.readInt(); taskStatus.readFields(in); skipRanges.readFields(in); currentRecIndexIterator = skipRanges.skipRangeIterator(); currentRecStartIndex = currentRecIndexIterator.next(); skipping = in.readBoolean(); jobCleanup = in.readBoolean(); if (jobCleanup) { jobRunStateForCleanup = WritableUtils.readEnum(in, JobStatus.State.class); } jobSetup = in.readBoolean(); writeSkipRecs = in.readBoolean(); taskCleanup = in.readBoolean(); if (taskCleanup) { setPhase(TaskStatus.Phase.CLEANUP); } user = Text.readString(in); } @Override public String toString() { return taskId.toString(); } /** * Localize the given JobConf to be specific for this task. */ public void localizeConfiguration(JobConf conf) throws IOException { conf.set("mapred.tip.id", taskId.getTaskID().toString()); conf.set("mapred.task.id", taskId.toString()); conf.setBoolean("mapred.task.is.map", isMapTask()); conf.setInt("mapred.task.partition", partition); conf.set("mapred.job.id", taskId.getJobID().toString()); } /** Run this task as a part of the named job. This method is executed in the * child process and is what invokes user-supplied map, reduce, etc. methods. * @param umbilical for progress reports */ public abstract void run(JobConf job, TaskUmbilicalProtocol umbilical) throws IOException, ClassNotFoundException, InterruptedException; /** Return an approprate thread runner for this task. * @param tip TODO*/ public abstract TaskRunner createRunner(TaskTracker tracker, TaskTracker.TaskInProgress tip, TaskTracker.RunningJob rjob ) throws IOException; /** The number of milliseconds between progress reports. */ public static final int PROGRESS_INTERVAL = 3000; private transient Progress taskProgress = new Progress(); // Current counters private transient Counters counters = new Counters(); /* flag to track whether task is done */ private AtomicBoolean taskDone = new AtomicBoolean(false); public abstract boolean isMapTask(); public Progress getProgress() { return taskProgress; } public void initialize(JobConf job, JobID id, Reporter reporter, boolean useNewApi) throws IOException, ClassNotFoundException, InterruptedException { jobContext = new JobContext(job, id, reporter); taskContext = new TaskAttemptContext(job, taskId, reporter); if (getState() == TaskStatus.State.UNASSIGNED) { setState(TaskStatus.State.RUNNING); } if (useNewApi) { if (LOG.isDebugEnabled()) { LOG.debug("using new api for output committer"); } outputFormat = ReflectionUtils.newInstance(taskContext.getOutputFormatClass(), job); committer = outputFormat.getOutputCommitter(taskContext); } else { committer = conf.getOutputCommitter(); } Path outputPath = FileOutputFormat.getOutputPath(conf); if (outputPath != null) { if ((committer instanceof FileOutputCommitter)) { FileOutputFormat.setWorkOutputPath(conf, ((FileOutputCommitter)committer).getTempTaskOutputPath(taskContext)); } else { FileOutputFormat.setWorkOutputPath(conf, outputPath); } } committer.setupTask(taskContext); Class<? extends ResourceCalculatorPlugin> clazz = conf.getClass(TaskTracker.TT_RESOURCE_CALCULATOR_PLUGIN, null, ResourceCalculatorPlugin.class); resourceCalculator = ResourceCalculatorPlugin .getResourceCalculatorPlugin(clazz, conf); LOG.info(" Using ResourceCalculatorPlugin : " + resourceCalculator); if (resourceCalculator != null) { initCpuCumulativeTime = resourceCalculator.getProcResourceValues().getCumulativeCpuTime(); } } protected class TaskReporter extends org.apache.hadoop.mapreduce.StatusReporter implements Runnable, Reporter { private TaskUmbilicalProtocol umbilical; private InputSplit split = null; private Progress taskProgress; private JvmContext jvmContext; private Thread pingThread = null; private static final int PROGRESS_STATUS_LEN_LIMIT = 512; private boolean done = true; private Object lock = new Object(); /** * flag that indicates whether progress update needs to be sent to parent. * If true, it has been set. If false, it has been reset. * Using AtomicBoolean since we need an atomic read & reset method. */ private AtomicBoolean progressFlag = new AtomicBoolean(false); TaskReporter(Progress taskProgress, TaskUmbilicalProtocol umbilical, JvmContext jvmContext) { this.umbilical = umbilical; this.taskProgress = taskProgress; this.jvmContext = jvmContext; } // getters and setters for flag void setProgressFlag() { progressFlag.set(true); } boolean resetProgressFlag() { return progressFlag.getAndSet(false); } public void setStatus(String status) { //Check to see if the status string // is too long and just concatenate it // to progress limit characters. if (status.length() > PROGRESS_STATUS_LEN_LIMIT) { status = status.substring(0, PROGRESS_STATUS_LEN_LIMIT); } taskProgress.setStatus(status); // indicate that progress update needs to be sent setProgressFlag(); } public void setProgress(float progress) { taskProgress.set(progress); // indicate that progress update needs to be sent setProgressFlag(); } public void progress() { // indicate that progress update needs to be sent setProgressFlag(); } public Counters.Counter getCounter(String group, String name) { Counters.Counter counter = null; if (counters != null) { counter = counters.findCounter(group, name); } return counter; } public Counters.Counter getCounter(Enum<?> name) { return counters == null ? null : counters.findCounter(name); } public void incrCounter(Enum key, long amount) { if (counters != null) { counters.incrCounter(key, amount); } setProgressFlag(); } public void incrCounter(String group, String counter, long amount) { if (counters != null) { counters.incrCounter(group, counter, amount); } if(skipping && SkipBadRecords.COUNTER_GROUP.equals(group) && ( SkipBadRecords.COUNTER_MAP_PROCESSED_RECORDS.equals(counter) || SkipBadRecords.COUNTER_REDUCE_PROCESSED_GROUPS.equals(counter))) { //if application reports the processed records, move the //currentRecStartIndex to the next. //currentRecStartIndex is the start index which has not yet been //finished and is still in task's stomach. for(int i=0;i<amount;i++) { currentRecStartIndex = currentRecIndexIterator.next(); } } setProgressFlag(); } public void setInputSplit(InputSplit split) { this.split = split; } public InputSplit getInputSplit() throws UnsupportedOperationException { if (split == null) { throw new UnsupportedOperationException("Input only available on map"); } else { return split; } } /** * The communication thread handles communication with the parent (Task Tracker). * It sends progress updates if progress has been made or if the task needs to * let the parent know that it's alive. It also pings the parent to see if it's alive. */ public void run() { final int MAX_RETRIES = 3; int remainingRetries = MAX_RETRIES; // get current flag value and reset it as well boolean sendProgress = resetProgressFlag(); while (!taskDone.get()) { try { boolean taskFound = true; // whether TT knows about this task // sleep for a bit try { synchronized(lock) { done = false; lock.wait(PROGRESS_INTERVAL); if (taskDone.get()) { done = true; lock.notify(); return; } } } catch (InterruptedException e) { if (LOG.isDebugEnabled()) { LOG.debug(getTaskID() + " Progress/ping thread exiting " + "since it got interrupted"); } break; } if (sendProgress) { // we need to send progress update updateCounters(); taskStatus.statusUpdate(taskProgress.get(), taskProgress.toString(), counters); taskFound = umbilical.statusUpdate(taskId, taskStatus, jvmContext); taskStatus.clearStatus(); } else { // send ping taskFound = umbilical.ping(taskId, jvmContext); } // if Task Tracker is not aware of our task ID (probably because it died and // came back up), kill ourselves if (!taskFound) { LOG.warn("Parent died. Exiting "+taskId); resetDoneFlag(); System.exit(66); } sendProgress = resetProgressFlag(); remainingRetries = MAX_RETRIES; } catch (Throwable t) { LOG.info("Communication exception: " + StringUtils.stringifyException(t)); remainingRetries -=1; if (remainingRetries == 0) { ReflectionUtils.logThreadInfo(LOG, "Communication exception", 0); LOG.warn("Last retry, killing "+taskId); resetDoneFlag(); System.exit(65); } } } //Notify that we are done with the work resetDoneFlag(); } void resetDoneFlag() { synchronized(lock) { done = true; lock.notify(); } } public void startCommunicationThread() { if (pingThread == null) { pingThread = new Thread(this, "communication thread"); pingThread.setDaemon(true); pingThread.start(); } } public void stopCommunicationThread() throws InterruptedException { // Updating resources specified in ResourceCalculatorPlugin if (pingThread != null) { synchronized(lock) { lock.notify(); // wake up the wait in the while loop while(!done) { lock.wait(); } } pingThread.interrupt(); pingThread.join(); } } } /** * Reports the next executing record range to TaskTracker. * * @param umbilical * @param nextRecIndex the record index which would be fed next. * @throws IOException */ protected void reportNextRecordRange(final TaskUmbilicalProtocol umbilical, long nextRecIndex) throws IOException{ //currentRecStartIndex is the start index which has not yet been finished //and is still in task's stomach. long len = nextRecIndex - currentRecStartIndex +1; SortedRanges.Range range = new SortedRanges.Range(currentRecStartIndex, len); taskStatus.setNextRecordRange(range); if (LOG.isDebugEnabled()) { LOG.debug("sending reportNextRecordRange " + range); } umbilical.reportNextRecordRange(taskId, range, jvmContext); } /** * An updater that tracks the last number reported for a given file * system and only creates the counters when they are needed. */ class FileSystemStatisticUpdater { private long prevReadBytes = 0; private long prevWriteBytes = 0; private FileSystem.Statistics stats; private Counters.Counter readCounter = null; private Counters.Counter writeCounter = null; private String[] counterNames; FileSystemStatisticUpdater(String uriScheme, FileSystem.Statistics stats) { this.stats = stats; this.counterNames = getFileSystemCounterNames(uriScheme); } void updateCounters() { long newReadBytes = stats.getBytesRead(); long newWriteBytes = stats.getBytesWritten(); if (prevReadBytes != newReadBytes) { if (readCounter == null) { readCounter = counters.findCounter(FILESYSTEM_COUNTER_GROUP, counterNames[0]); } readCounter.increment(newReadBytes - prevReadBytes); prevReadBytes = newReadBytes; } if (prevWriteBytes != newWriteBytes) { if (writeCounter == null) { writeCounter = counters.findCounter(FILESYSTEM_COUNTER_GROUP, counterNames[1]); } writeCounter.increment(newWriteBytes - prevWriteBytes); prevWriteBytes = newWriteBytes; } } } /** * A Map where Key-> URIScheme and value->FileSystemStatisticUpdater */ private Map<String, FileSystemStatisticUpdater> statisticUpdaters = new HashMap<String, FileSystemStatisticUpdater>(); /** * Update resource information counters */ void updateResourceCounters() { // Update generic resource counters updateHeapUsageCounter(); if (resourceCalculator == null) { return; } ProcResourceValues res = resourceCalculator.getProcResourceValues(); long cpuTime = res.getCumulativeCpuTime(); long pMem = res.getPhysicalMemorySize(); long vMem = res.getVirtualMemorySize(); // Remove the CPU time consumed previously by JVM reuse cpuTime -= initCpuCumulativeTime; counters.findCounter(Counter.CPU_MILLISECONDS).setValue(cpuTime); counters.findCounter(Counter.PHYSICAL_MEMORY_BYTES).setValue(pMem); counters.findCounter(Counter.VIRTUAL_MEMORY_BYTES).setValue(vMem); } private synchronized void updateCounters() { for(Statistics stat: FileSystem.getAllStatistics()) { String uriScheme = stat.getScheme(); FileSystemStatisticUpdater updater = statisticUpdaters.get(uriScheme); if(updater==null) {//new FileSystem has been found in the cache updater = new FileSystemStatisticUpdater(uriScheme, stat); statisticUpdaters.put(uriScheme, updater); } updater.updateCounters(); } // TODO Should CPU related counters be update only once i.e in the end updateResourceCounters(); } /** * Updates the {@link TaskCounter#COMMITTED_HEAP_BYTES} counter to reflect the * current total committed heap space usage of this JVM. */ @SuppressWarnings("deprecation") private void updateHeapUsageCounter() { long currentHeapUsage = Runtime.getRuntime().totalMemory(); counters.findCounter(Counter.COMMITTED_HEAP_BYTES) .setValue(currentHeapUsage); } public void done(TaskUmbilicalProtocol umbilical, TaskReporter reporter ) throws IOException, InterruptedException { LOG.info("Task:" + taskId + " is done." + " And is in the process of commiting"); updateCounters(); boolean commitRequired = isCommitRequired(); if (commitRequired) { int retries = MAX_RETRIES; setState(TaskStatus.State.COMMIT_PENDING); // say the task tracker that task is commit pending while (true) { try { umbilical.commitPending(taskId, taskStatus, jvmContext); break; } catch (InterruptedException ie) { // ignore } catch (IOException ie) { LOG.warn("Failure sending commit pending: " + StringUtils.stringifyException(ie)); if (--retries == 0) { System.exit(67); } } } //wait for commit approval and commit commit(umbilical, reporter, committer); } taskDone.set(true); reporter.stopCommunicationThread(); sendLastUpdate(umbilical); //signal the tasktracker that we are done sendDone(umbilical); } /** * Checks if this task has anything to commit, depending on the * type of task, as well as on whether the {@link OutputCommitter} * has anything to commit. * * @return true if the task has to commit * @throws IOException */ boolean isCommitRequired() throws IOException { boolean commitRequired = false; if (isMapOrReduce()) { commitRequired = committer.needsTaskCommit(taskContext); } return commitRequired; } protected void statusUpdate(TaskUmbilicalProtocol umbilical) throws IOException { int retries = MAX_RETRIES; while (true) { try { if (!umbilical.statusUpdate(getTaskID(), taskStatus, jvmContext)) { LOG.warn("Parent died. Exiting "+taskId); System.exit(66); } taskStatus.clearStatus(); return; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // interrupt ourself } catch (IOException ie) { LOG.warn("Failure sending status update: " + StringUtils.stringifyException(ie)); if (--retries == 0) { throw ie; } } } } /** * Sends last status update before sending umbilical.done(); */ private void sendLastUpdate(TaskUmbilicalProtocol umbilical) throws IOException { taskStatus.setOutputSize(calculateOutputSize()); // send a final status report taskStatus.statusUpdate(taskProgress.get(), taskProgress.toString(), counters); statusUpdate(umbilical); } /** * Calculates the size of output for this task. * * @return -1 if it can't be found. */ private long calculateOutputSize() throws IOException { if (!isMapOrReduce()) { return -1; } if (isMapTask() && conf.getNumReduceTasks() > 0) { try { Path mapOutput = mapOutputFile.getOutputFile(); FileSystem localFS = FileSystem.getLocal(conf); return localFS.getFileStatus(mapOutput).getLen(); } catch (IOException e) { LOG.warn ("Could not find output size " , e); } } return -1; } private void sendDone(TaskUmbilicalProtocol umbilical) throws IOException { int retries = MAX_RETRIES; while (true) { try { umbilical.done(getTaskID(), jvmContext); LOG.info("Task '" + taskId + "' done."); return; } catch (IOException ie) { LOG.warn("Failure signalling completion: " + StringUtils.stringifyException(ie)); if (--retries == 0) { throw ie; } } } } private void commit(TaskUmbilicalProtocol umbilical, TaskReporter reporter, org.apache.hadoop.mapreduce.OutputCommitter committer ) throws IOException { int retries = MAX_RETRIES; while (true) { try { while (!umbilical.canCommit(taskId, jvmContext)) { try { Thread.sleep(1000); } catch(InterruptedException ie) { //ignore } reporter.setProgressFlag(); } break; } catch (IOException ie) { LOG.warn("Failure asking whether task can commit: " + StringUtils.stringifyException(ie)); if (--retries == 0) { //if it couldn't query successfully then delete the output discardOutput(taskContext); System.exit(68); } } } // task can Commit now try { LOG.info("Task " + taskId + " is allowed to commit now"); committer.commitTask(taskContext); return; } catch (IOException iee) { LOG.warn("Failure committing: " + StringUtils.stringifyException(iee)); //if it couldn't commit a successfully then delete the output discardOutput(taskContext); throw iee; } } private void discardOutput(TaskAttemptContext taskContext) { try { committer.abortTask(taskContext); } catch (IOException ioe) { LOG.warn("Failure cleaning up: " + StringUtils.stringifyException(ioe)); } } protected void runTaskCleanupTask(TaskUmbilicalProtocol umbilical, TaskReporter reporter) throws IOException, InterruptedException { taskCleanup(umbilical); done(umbilical, reporter); } void taskCleanup(TaskUmbilicalProtocol umbilical) throws IOException { // set phase for this task setPhase(TaskStatus.Phase.CLEANUP); getProgress().setStatus("cleanup"); statusUpdate(umbilical); LOG.info("Runnning cleanup for the task"); // do the cleanup committer.abortTask(taskContext); } protected void runJobCleanupTask(TaskUmbilicalProtocol umbilical, TaskReporter reporter ) throws IOException, InterruptedException { // set phase for this task setPhase(TaskStatus.Phase.CLEANUP); getProgress().setStatus("cleanup"); statusUpdate(umbilical); // do the cleanup LOG.info("Cleaning up job"); if (jobRunStateForCleanup == JobStatus.State.FAILED || jobRunStateForCleanup == JobStatus.State.KILLED) { LOG.info("Aborting job with runstate : " + jobRunStateForCleanup); committer.abortJob(jobContext, jobRunStateForCleanup); } else if (jobRunStateForCleanup == JobStatus.State.SUCCEEDED){ LOG.info("Committing job"); committer.commitJob(jobContext); } else { throw new IOException("Invalid state of the job for cleanup. State found " + jobRunStateForCleanup + " expecting " + JobStatus.State.SUCCEEDED + ", " + JobStatus.State.FAILED + " or " + JobStatus.State.KILLED); } // delete the staging area for the job JobConf conf = new JobConf(jobContext.getConfiguration()); if (!supportIsolationRunner(conf)) { String jobTempDir = conf.get("mapreduce.job.dir"); Path jobTempDirPath = new Path(jobTempDir); FileSystem fs = jobTempDirPath.getFileSystem(conf); fs.delete(jobTempDirPath, true); } done(umbilical, reporter); } protected boolean supportIsolationRunner(JobConf conf) { return (conf.getKeepTaskFilesPattern() != null || conf .getKeepFailedTaskFiles()); } protected void runJobSetupTask(TaskUmbilicalProtocol umbilical, TaskReporter reporter ) throws IOException, InterruptedException { // do the setup getProgress().setStatus("setup"); committer.setupJob(jobContext); done(umbilical, reporter); } /** * Gets a handle to the Statistics instance based on the scheme associated * with path. * * @param path * the path. * @return a Statistics instance, or null if none is found for the scheme. */ protected static Statistics getFsStatistics(Path path, Configuration conf) throws IOException { Statistics matchedStats = null; path = path.getFileSystem(conf).makeQualified(path); for (Statistics stats : FileSystem.getAllStatistics()) { if (stats.getScheme().equals(path.toUri().getScheme())) { matchedStats = stats; break; } } return matchedStats; } public void setConf(Configuration conf) { if (conf instanceof JobConf) { this.conf = (JobConf) conf; } else { this.conf = new JobConf(conf); } this.mapOutputFile.setConf(this.conf); this.lDirAlloc = new LocalDirAllocator("mapred.local.dir"); // add the static resolutions (this is required for the junit to // work on testcases that simulate multiple nodes on a single physical // node. String hostToResolved[] = conf.getStrings("hadoop.net.static.resolutions"); if (hostToResolved != null) { for (String str : hostToResolved) { String name = str.substring(0, str.indexOf('=')); String resolvedName = str.substring(str.indexOf('=') + 1); NetUtils.addStaticResolution(name, resolvedName); } } } public Configuration getConf() { return this.conf; } /** * OutputCollector for the combiner. */ protected static class CombineOutputCollector<K extends Object, V extends Object> implements OutputCollector<K, V> { private Writer<K, V> writer; private Counters.Counter outCounter; private Progressable progressable; private long progressBar; public CombineOutputCollector(Counters.Counter outCounter, Progressable progressable, Configuration conf) { this.outCounter = outCounter; this.progressable=progressable; progressBar = conf.getLong(MR_COMBINE_RECORDS_BEFORE_PROGRESS, DEFAULT_MR_COMBINE_RECORDS_BEFORE_PROGRESS); } public synchronized void setWriter(Writer<K, V> writer) { this.writer = writer; } public synchronized void collect(K key, V value) throws IOException { outCounter.increment(1); writer.append(key, value); if ((outCounter.getValue() % progressBar) == 0) { progressable.progress(); } } } /** Iterates values while keys match in sorted input. */ static class ValuesIterator<KEY,VALUE> implements Iterator<VALUE> { protected RawKeyValueIterator in; //input iterator private KEY key; // current key private KEY nextKey; private VALUE value; // current value private boolean hasNext; // more w/ this key private boolean more; // more in file private RawComparator<KEY> comparator; protected Progressable reporter; private Deserializer<KEY> keyDeserializer; private Deserializer<VALUE> valDeserializer; private DataInputBuffer keyIn = new DataInputBuffer(); private DataInputBuffer valueIn = new DataInputBuffer(); public ValuesIterator (RawKeyValueIterator in, RawComparator<KEY> comparator, Class<KEY> keyClass, Class<VALUE> valClass, Configuration conf, Progressable reporter) throws IOException { this.in = in; this.comparator = comparator; this.reporter = reporter; SerializationFactory serializationFactory = new SerializationFactory(conf); this.keyDeserializer = serializationFactory.getDeserializer(keyClass); this.keyDeserializer.open(keyIn); this.valDeserializer = serializationFactory.getDeserializer(valClass); this.valDeserializer.open(this.valueIn); readNextKey(); key = nextKey; nextKey = null; // force new instance creation hasNext = more; } RawKeyValueIterator getRawIterator() { return in; } /// Iterator methods public boolean hasNext() { return hasNext; } private int ctr = 0; public VALUE next() { if (!hasNext) { throw new NoSuchElementException("iterate past last value"); } try { readNextValue(); readNextKey(); } catch (IOException ie) { throw new RuntimeException("problem advancing post rec#"+ctr, ie); } reporter.progress(); return value; } public void remove() { throw new RuntimeException("not implemented"); } /// Auxiliary methods /** Start processing next unique key. */ void nextKey() throws IOException { // read until we find a new key while (hasNext) { readNextKey(); } ++ctr; // move the next key to the current one KEY tmpKey = key; key = nextKey; nextKey = tmpKey; hasNext = more; } /** True iff more keys remain. */ boolean more() { return more; } /** The current key. */ KEY getKey() { return key; } /** * read the next key */ private void readNextKey() throws IOException { more = in.next(); if (more) { DataInputBuffer nextKeyBytes = in.getKey(); keyIn.reset(nextKeyBytes.getData(), nextKeyBytes.getPosition(), nextKeyBytes.getLength()); nextKey = keyDeserializer.deserialize(nextKey); hasNext = key != null && (comparator.compare(key, nextKey) == 0); } else { hasNext = false; } } /** * Read the next value * @throws IOException */ private void readNextValue() throws IOException { DataInputBuffer nextValueBytes = in.getValue(); valueIn.reset(nextValueBytes.getData(), nextValueBytes.getPosition(), nextValueBytes.getLength()); value = valDeserializer.deserialize(value); } } protected static class CombineValuesIterator<KEY,VALUE> extends ValuesIterator<KEY,VALUE> { private final Counters.Counter combineInputCounter; public CombineValuesIterator(RawKeyValueIterator in, RawComparator<KEY> comparator, Class<KEY> keyClass, Class<VALUE> valClass, Configuration conf, Reporter reporter, Counters.Counter combineInputCounter) throws IOException { super(in, comparator, keyClass, valClass, conf, reporter); this.combineInputCounter = combineInputCounter; } public VALUE next() { combineInputCounter.increment(1); return super.next(); } } private static final Constructor<org.apache.hadoop.mapreduce.Reducer.Context> contextConstructor; static { try { contextConstructor = org.apache.hadoop.mapreduce.Reducer.Context.class.getConstructor (new Class[]{org.apache.hadoop.mapreduce.Reducer.class, Configuration.class, org.apache.hadoop.mapreduce.TaskAttemptID.class, RawKeyValueIterator.class, org.apache.hadoop.mapreduce.Counter.class, org.apache.hadoop.mapreduce.Counter.class, org.apache.hadoop.mapreduce.RecordWriter.class, org.apache.hadoop.mapreduce.OutputCommitter.class, org.apache.hadoop.mapreduce.StatusReporter.class, RawComparator.class, Class.class, Class.class}); } catch (NoSuchMethodException nme) { throw new IllegalArgumentException("Can't find constructor"); } } @SuppressWarnings("unchecked") protected static <INKEY,INVALUE,OUTKEY,OUTVALUE> org.apache.hadoop.mapreduce.Reducer<INKEY,INVALUE,OUTKEY,OUTVALUE>.Context createReduceContext(org.apache.hadoop.mapreduce.Reducer <INKEY,INVALUE,OUTKEY,OUTVALUE> reducer, Configuration job, org.apache.hadoop.mapreduce.TaskAttemptID taskId, RawKeyValueIterator rIter, org.apache.hadoop.mapreduce.Counter inputKeyCounter, org.apache.hadoop.mapreduce.Counter inputValueCounter, org.apache.hadoop.mapreduce.RecordWriter<OUTKEY,OUTVALUE> output, org.apache.hadoop.mapreduce.OutputCommitter committer, org.apache.hadoop.mapreduce.StatusReporter reporter, RawComparator<INKEY> comparator, Class<INKEY> keyClass, Class<INVALUE> valueClass ) throws IOException, ClassNotFoundException { try { return contextConstructor.newInstance(reducer, job, taskId, rIter, inputKeyCounter, inputValueCounter, output, committer, reporter, comparator, keyClass, valueClass); } catch (InstantiationException e) { throw new IOException("Can't create Context", e); } catch (InvocationTargetException e) { throw new IOException("Can't invoke Context constructor", e); } catch (IllegalAccessException e) { throw new IOException("Can't invoke Context constructor", e); } } protected static abstract class CombinerRunner<K,V> { protected final Counters.Counter inputCounter; protected final JobConf job; protected final TaskReporter reporter; CombinerRunner(Counters.Counter inputCounter, JobConf job, TaskReporter reporter) { this.inputCounter = inputCounter; this.job = job; this.reporter = reporter; } /** * Run the combiner over a set of inputs. * @param iterator the key/value pairs to use as input * @param collector the output collector */ abstract void combine(RawKeyValueIterator iterator, OutputCollector<K,V> collector ) throws IOException, InterruptedException, ClassNotFoundException; @SuppressWarnings("unchecked") static <K,V> CombinerRunner<K,V> create(JobConf job, TaskAttemptID taskId, Counters.Counter inputCounter, TaskReporter reporter, org.apache.hadoop.mapreduce.OutputCommitter committer ) throws ClassNotFoundException { Class<? extends Reducer<K,V,K,V>> cls = (Class<? extends Reducer<K,V,K,V>>) job.getCombinerClass(); if (cls != null) { return new OldCombinerRunner(cls, job, inputCounter, reporter); } // make a task context so we can get the classes org.apache.hadoop.mapreduce.TaskAttemptContext taskContext = new org.apache.hadoop.mapreduce.TaskAttemptContext(job, taskId); Class<? extends org.apache.hadoop.mapreduce.Reducer<K,V,K,V>> newcls = (Class<? extends org.apache.hadoop.mapreduce.Reducer<K,V,K,V>>) taskContext.getCombinerClass(); if (newcls != null) { return new NewCombinerRunner<K,V>(newcls, job, taskId, taskContext, inputCounter, reporter, committer); } return null; } } protected static class OldCombinerRunner<K,V> extends CombinerRunner<K,V> { private final Class<? extends Reducer<K,V,K,V>> combinerClass; private final Class<K> keyClass; private final Class<V> valueClass; private final RawComparator<K> comparator; @SuppressWarnings("unchecked") protected OldCombinerRunner(Class<? extends Reducer<K,V,K,V>> cls, JobConf conf, Counters.Counter inputCounter, TaskReporter reporter) { super(inputCounter, conf, reporter); combinerClass = cls; keyClass = (Class<K>) job.getMapOutputKeyClass(); valueClass = (Class<V>) job.getMapOutputValueClass(); comparator = (RawComparator<K>) job.getOutputKeyComparator(); } @SuppressWarnings("unchecked") protected void combine(RawKeyValueIterator kvIter, OutputCollector<K,V> combineCollector ) throws IOException { Reducer<K,V,K,V> combiner = ReflectionUtils.newInstance(combinerClass, job); try { CombineValuesIterator<K,V> values = new CombineValuesIterator<K,V>(kvIter, comparator, keyClass, valueClass, job, Reporter.NULL, inputCounter); while (values.more()) { combiner.reduce(values.getKey(), values, combineCollector, Reporter.NULL); values.nextKey(); } } finally { combiner.close(); } } } protected static class NewCombinerRunner<K, V> extends CombinerRunner<K,V> { private final Class<? extends org.apache.hadoop.mapreduce.Reducer<K,V,K,V>> reducerClass; private final org.apache.hadoop.mapreduce.TaskAttemptID taskId; private final RawComparator<K> comparator; private final Class<K> keyClass; private final Class<V> valueClass; private final org.apache.hadoop.mapreduce.OutputCommitter committer; @SuppressWarnings("unchecked") NewCombinerRunner(Class reducerClass, JobConf job, org.apache.hadoop.mapreduce.TaskAttemptID taskId, org.apache.hadoop.mapreduce.TaskAttemptContext context, Counters.Counter inputCounter, TaskReporter reporter, org.apache.hadoop.mapreduce.OutputCommitter committer) { super(inputCounter, job, reporter); this.reducerClass = reducerClass; this.taskId = taskId; keyClass = (Class<K>) context.getMapOutputKeyClass(); valueClass = (Class<V>) context.getMapOutputValueClass(); comparator = (RawComparator<K>) context.getSortComparator(); this.committer = committer; } private static class OutputConverter<K,V> extends org.apache.hadoop.mapreduce.RecordWriter<K,V> { OutputCollector<K,V> output; OutputConverter(OutputCollector<K,V> output) { this.output = output; } @Override public void close(org.apache.hadoop.mapreduce.TaskAttemptContext context){ } @Override public void write(K key, V value ) throws IOException, InterruptedException { output.collect(key,value); } } @SuppressWarnings("unchecked") @Override void combine(RawKeyValueIterator iterator, OutputCollector<K,V> collector ) throws IOException, InterruptedException, ClassNotFoundException { // make a reducer org.apache.hadoop.mapreduce.Reducer<K,V,K,V> reducer = (org.apache.hadoop.mapreduce.Reducer<K,V,K,V>) ReflectionUtils.newInstance(reducerClass, job); org.apache.hadoop.mapreduce.Reducer.Context reducerContext = createReduceContext(reducer, job, taskId, iterator, null, inputCounter, new OutputConverter(collector), committer, reporter, comparator, keyClass, valueClass); reducer.run(reducerContext); } } }
package stroom.proxy.app.guice; import stroom.collection.mock.MockCollectionModule; import stroom.db.util.DbModule; import stroom.dictionary.impl.DictionaryModule; import stroom.dictionary.impl.DictionaryStore; import stroom.docstore.api.DocumentResourceHelper; import stroom.docstore.api.Serialiser2Factory; import stroom.docstore.api.StoreFactory; import stroom.docstore.impl.DocumentResourceHelperImpl; import stroom.docstore.impl.Persistence; import stroom.docstore.impl.Serialiser2FactoryImpl; import stroom.docstore.impl.StoreFactoryImpl; import stroom.docstore.impl.fs.FSPersistence; import stroom.dropwizard.common.LogLevelInspector; import stroom.dropwizard.common.PermissionExceptionMapper; import stroom.dropwizard.common.TokenExceptionMapper; import stroom.importexport.api.ImportExportActionHandler; import stroom.legacy.impex_6_1.LegacyImpexModule; import stroom.proxy.app.Config; import stroom.proxy.app.ContentSyncService; import stroom.proxy.app.ProxyConfigHealthCheck; import stroom.proxy.app.ProxyConfigHolder; import stroom.proxy.app.ProxyLifecycle; import stroom.proxy.app.RequestAuthenticatorImpl; import stroom.proxy.app.RestClientConfig; import stroom.proxy.app.RestClientConfigConverter; import stroom.proxy.app.forwarder.ForwarderDestinationsImpl; import stroom.proxy.app.handler.ProxyRequestHandler; import stroom.proxy.app.handler.RemoteFeedStatusService; import stroom.proxy.app.servlet.ProxySecurityFilter; import stroom.proxy.app.servlet.ProxyStatusServlet; import stroom.proxy.app.servlet.ProxyWelcomeServlet; import stroom.proxy.repo.ErrorReceiver; import stroom.proxy.repo.ErrorReceiverImpl; import stroom.proxy.repo.ForwarderDestinations; import stroom.proxy.repo.ProgressLog; import stroom.proxy.repo.ProgressLogImpl; import stroom.proxy.repo.ProxyRepoDbModule; import stroom.proxy.repo.RepoDbDirProvider; import stroom.proxy.repo.RepoDbDirProviderImpl; import stroom.proxy.repo.RepoDirProvider; import stroom.proxy.repo.RepoDirProviderImpl; import stroom.proxy.repo.Sender; import stroom.proxy.repo.SenderImpl; import stroom.receive.common.DataReceiptPolicyAttributeMapFilterFactory; import stroom.receive.common.DebugServlet; import stroom.receive.common.FeedStatusResourceImpl; import stroom.receive.common.FeedStatusService; import stroom.receive.common.ReceiveDataServlet; import stroom.receive.common.RemoteFeedModule; import stroom.receive.common.RequestHandler; import stroom.receive.rules.impl.DataReceiptPolicyAttributeMapFilterFactoryImpl; import stroom.receive.rules.impl.ReceiveDataRuleSetResourceImpl; import stroom.receive.rules.impl.ReceiveDataRuleSetService; import stroom.receive.rules.impl.ReceiveDataRuleSetServiceImpl; import stroom.security.api.RequestAuthenticator; import stroom.security.api.SecurityContext; import stroom.security.mock.MockSecurityContext; import stroom.task.impl.TaskContextModule; import stroom.util.BuildInfoModule; import stroom.util.entityevent.EntityEventBus; import stroom.util.guice.FilterBinder; import stroom.util.guice.FilterInfo; import stroom.util.guice.GuiceUtil; import stroom.util.guice.HasHealthCheckBinder; import stroom.util.guice.RestResourcesBinder; import stroom.util.guice.ServletBinder; import stroom.util.io.PathCreator; import stroom.util.shared.BuildInfo; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.client.JerseyClientConfiguration; import io.dropwizard.client.ssl.TlsConfiguration; import io.dropwizard.lifecycle.Managed; import io.dropwizard.setup.Environment; import org.glassfish.jersey.logging.LoggingFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.file.Path; import java.util.Optional; import javax.inject.Provider; import javax.ws.rs.client.Client; import javax.ws.rs.ext.ExceptionMapper; public class ProxyModule extends AbstractModule { private static final Logger LOGGER = LoggerFactory.getLogger(ProxyModule.class); // This name is used by dropwizard metrics private static final String PROXY_JERSEY_CLIENT_NAME = "stroom-proxy_jersey_client"; private static final String PROXY_JERSEY_CLIENT_USER_AGENT_PREFIX = "stroom-proxy/"; private final Config configuration; private final Environment environment; private final ProxyConfigHolder proxyConfigHolder; public ProxyModule(final Config configuration, final Environment environment, final Path configFile) { this.configuration = configuration; this.environment = environment; proxyConfigHolder = new ProxyConfigHolder( configuration.getProxyConfig(), configFile); } @Override protected void configure() { bind(Config.class).toInstance(configuration); bind(Environment.class).toInstance(environment); install(new ProxyConfigModule(proxyConfigHolder)); install(new DbModule()); install(new ProxyRepoDbModule()); install(new MockCollectionModule()); install(new DictionaryModule()); // Allow discovery of feed status from other proxies. install(new RemoteFeedModule()); install(new TaskContextModule()); install(new LegacyImpexModule()); install(new BuildInfoModule()); bind(DataReceiptPolicyAttributeMapFilterFactory.class).to(DataReceiptPolicyAttributeMapFilterFactoryImpl.class); bind(DocumentResourceHelper.class).to(DocumentResourceHelperImpl.class); bind(ErrorReceiver.class).to(ErrorReceiverImpl.class); bind(FeedStatusService.class).to(RemoteFeedStatusService.class); bind(RequestAuthenticator.class).to(RequestAuthenticatorImpl.class).asEagerSingleton(); bind(ReceiveDataRuleSetService.class).to(ReceiveDataRuleSetServiceImpl.class); bind(RequestHandler.class).to(ProxyRequestHandler.class); bind(SecurityContext.class).to(MockSecurityContext.class); bind(Serialiser2Factory.class).to(Serialiser2FactoryImpl.class); bind(StoreFactory.class).to(StoreFactoryImpl.class); bind(ForwarderDestinations.class).to(ForwarderDestinationsImpl.class); bind(Sender.class).to(SenderImpl.class); bind(ProgressLog.class).to(ProgressLogImpl.class); bind(RepoDirProvider.class).to(RepoDirProviderImpl.class); bind(RepoDbDirProvider.class).to(RepoDbDirProviderImpl.class); HasHealthCheckBinder.create(binder()) .bind(ContentSyncService.class) .bind(FeedStatusResourceImpl.class) .bind(ForwarderDestinationsImpl.class) .bind(LogLevelInspector.class) .bind(ProxyConfigHealthCheck.class) .bind(RemoteFeedStatusService.class); FilterBinder.create(binder()) .bind(new FilterInfo(ProxySecurityFilter.class.getSimpleName(), "/*"), ProxySecurityFilter.class); ServletBinder.create(binder()) .bind(DebugServlet.class) .bind(ProxyStatusServlet.class) .bind(ProxyWelcomeServlet.class) .bind(ReceiveDataServlet.class); RestResourcesBinder.create(binder()) .bind(ReceiveDataRuleSetResourceImpl.class) .bind(FeedStatusResourceImpl.class); GuiceUtil.buildMultiBinder(binder(), Managed.class) .addBinding(ContentSyncService.class) .addBinding(ProxyLifecycle.class); GuiceUtil.buildMultiBinder(binder(), ExceptionMapper.class) .addBinding(PermissionExceptionMapper.class) .addBinding(TokenExceptionMapper.class); GuiceUtil.buildMultiBinder(binder(), ImportExportActionHandler.class) .addBinding(ReceiveDataRuleSetService.class) .addBinding(DictionaryStore.class); } @Provides @Singleton Persistence providePersistence(final PathCreator pathCreator) { final String path = configuration.getProxyConfig().getContentDir(); return new FSPersistence(pathCreator.toAppPath(path)); } @Provides @Singleton Client provideJerseyClient(final RestClientConfig restClientConfig, final Environment environment, final Provider<BuildInfo> buildInfoProvider, final PathCreator pathCreator, final RestClientConfigConverter restClientConfigConverter) { // RestClientConfig is really just a copy of JerseyClientConfiguration // so do the conversion final JerseyClientConfiguration jerseyClientConfiguration = restClientConfigConverter.convert( restClientConfig); // If the userAgent has not been explicitly set in the config then set it based // on the build version if (jerseyClientConfiguration.getUserAgent().isEmpty()) { final String userAgent = PROXY_JERSEY_CLIENT_USER_AGENT_PREFIX + buildInfoProvider.get().getBuildVersion(); LOGGER.info("Setting rest client user agent string to [{}]", userAgent); jerseyClientConfiguration.setUserAgent(Optional.of(userAgent)); } // Mutating the TLS config is not ideal but I'm not sure there is another way. // We need to allow for relative paths (relative to proxy home), '~', and other system // props in the path. Therefore if path creator produces a different path to what was // configured then update the config object. final TlsConfiguration tlsConfiguration = jerseyClientConfiguration.getTlsConfiguration(); if (tlsConfiguration != null) { if (tlsConfiguration.getKeyStorePath() != null) { final File modifiedKeyStorePath = pathCreator.toAppPath(tlsConfiguration.getKeyStorePath().getPath()) .toFile(); if (!modifiedKeyStorePath.getPath().equals(tlsConfiguration.getKeyStorePath().getPath())) { LOGGER.info("Updating rest client key store path from {} to {}", tlsConfiguration.getKeyStorePath(), modifiedKeyStorePath); tlsConfiguration.setKeyStorePath(modifiedKeyStorePath); } } if (tlsConfiguration.getTrustStorePath() != null) { final File modifiedTrustStorePath = pathCreator.toAppPath( tlsConfiguration.getTrustStorePath().getPath()).toFile(); if (!modifiedTrustStorePath.getPath().equals(tlsConfiguration.getTrustStorePath().getPath())) { LOGGER.info("Updating rest client trust store path from {} to {}", tlsConfiguration.getTrustStorePath(), modifiedTrustStorePath); tlsConfiguration.setTrustStorePath(modifiedTrustStorePath); } } } LOGGER.info("Creating jersey rest client {}", PROXY_JERSEY_CLIENT_NAME); return new JerseyClientBuilder(environment) .using(jerseyClientConfiguration) .build(PROXY_JERSEY_CLIENT_NAME) .register(LoggingFeature.class); } @Provides EntityEventBus entityEventBus() { return event -> { }; } }
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.ap.util; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.SimpleAnnotationValueVisitor6; import javax.lang.model.util.Types; /** * A helper class providing some useful methods to work with types * from the JSR-269-API. * * @author Gunnar Morling */ public class AnnotationApiHelper { private Elements elementUtils; private Types typeUtils; private final Map<Class<?>, TypeMirror> primitiveMirrors; public AnnotationApiHelper(Elements elementUtils, Types typeUtils) { this.elementUtils = elementUtils; this.typeUtils = typeUtils; Map<Class<?>, TypeMirror> tempPrimitiveMirrors = CollectionHelper.newHashMap(); tempPrimitiveMirrors.put( Boolean.TYPE, typeUtils.getPrimitiveType( TypeKind.BOOLEAN ) ); tempPrimitiveMirrors.put( Character.TYPE, typeUtils.getPrimitiveType( TypeKind.CHAR ) ); tempPrimitiveMirrors.put( Byte.TYPE, typeUtils.getPrimitiveType( TypeKind.BYTE ) ); tempPrimitiveMirrors.put( Short.TYPE, typeUtils.getPrimitiveType( TypeKind.SHORT ) ); tempPrimitiveMirrors.put( Integer.TYPE, typeUtils.getPrimitiveType( TypeKind.INT ) ); tempPrimitiveMirrors.put( Long.TYPE, typeUtils.getPrimitiveType( TypeKind.LONG ) ); tempPrimitiveMirrors.put( Float.TYPE, typeUtils.getPrimitiveType( TypeKind.FLOAT ) ); tempPrimitiveMirrors.put( Double.TYPE, typeUtils.getPrimitiveType( TypeKind.DOUBLE ) ); primitiveMirrors = Collections.unmodifiableMap( tempPrimitiveMirrors ); } /** * Returns a list containing those annotation mirrors from the input list, * which are of type <code>annotationType</code>. The input collection * remains untouched. * * @param annotationMirrors A list of annotation mirrors. * @param annotationType The type to be compared against. * * @return A list with those annotation mirrors from the input list, which * are of type <code>annotationType</code>. May be empty but never * null. */ public List<AnnotationMirror> filterByType(List<? extends AnnotationMirror> annotationMirrors, TypeMirror annotationType) { List<AnnotationMirror> theValue = CollectionHelper.newArrayList(); if ( annotationMirrors == null || annotationType == null ) { return theValue; } for ( AnnotationMirror oneAnnotationMirror : annotationMirrors ) { if ( typeUtils.isSameType( oneAnnotationMirror.getAnnotationType(), annotationType ) ) { theValue.add( oneAnnotationMirror ); } } return theValue; } /** * Returns that mirror from the given list of annotation mirrors that * represents the annotation type specified by the given class. * * @param annotationMirrors A list of annotation mirrors. * @param annotationClazz The class of the annotation of interest. * * @return The mirror from the given list that represents the specified * annotation or null, if the given list doesn't contain such a * mirror. */ public AnnotationMirror getMirror(List<? extends AnnotationMirror> annotationMirrors, Class<? extends Annotation> annotationClazz) { return getMirror( annotationMirrors, annotationClazz.getCanonicalName() ); } /** * Returns that mirror from the given list of annotation mirrors that * represents the annotation type specified by the given class. * * @param annotationMirrors A list of annotation mirrors. * @param annotationTypeName The FQN of the annotation of interest. * * @return The mirror from the given list that represents the specified * annotation or null, if the given list doesn't contain such a * mirror. */ public AnnotationMirror getMirror(List<? extends AnnotationMirror> annotationMirrors, String annotationTypeName) { if ( annotationMirrors == null || annotationTypeName == null ) { return null; } TypeElement typeElement = elementUtils.getTypeElement( annotationTypeName ); if ( typeElement == null ) { return null; } for ( AnnotationMirror oneAnnotationMirror : annotationMirrors ) { if ( typeUtils.isSameType( oneAnnotationMirror.getAnnotationType(), typeElement.asType() ) ) { return oneAnnotationMirror; } } return null; } /** * Returns a TypeMirror for the given class. * * @param clazz The class of interest. * * @return A TypeMirror for the given class. */ public TypeMirror getMirrorForType(Class<?> clazz) { if ( clazz.isArray() ) { return typeUtils.getArrayType( getMirrorForNonArrayType( clazz.getComponentType() ) ); } else { return getMirrorForNonArrayType( clazz ); } } private TypeMirror getMirrorForNonArrayType(Class<?> clazz) { TypeMirror theValue = null; if ( clazz.isPrimitive() ) { theValue = primitiveMirrors.get( clazz ); } else { theValue = getDeclaredTypeByName( clazz.getCanonicalName() ); } if ( theValue != null ) { return theValue; } else { throw new AssertionError( "Couldn't find a type mirror for class " + clazz ); } } /** * Returns the {@link DeclaredType} for the given class name. * * @param className A fully qualified class name, e.g. "java.lang.String". * * @return A {@link DeclaredType} representing the type with the given name, * or null, if no such type exists. */ public DeclaredType getDeclaredTypeByName(String className) { TypeElement typeElement = elementUtils.getTypeElement( className ); return typeElement != null ? typeUtils.getDeclaredType( typeElement ) : null; } /** * Returns the annotation value of the given annotation mirror with the * given name. * * @param annotationMirror An annotation mirror. * @param name The name of the annotation value of interest. * * @return The annotation value with the given name or null, if one of the * input values is null or if no value with the given name exists * within the given annotation mirror. */ public AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String name) { if ( annotationMirror == null || name == null ) { return null; } Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror.getElementValues(); for ( Entry<? extends ExecutableElement, ? extends AnnotationValue> oneElementValue : elementValues.entrySet() ) { if ( oneElementValue.getKey().getSimpleName().contentEquals( name ) ) { return oneElementValue.getValue(); } } return null; } /** * Returns the given annotation mirror's array-typed annotation value with * the given name. * * @param annotationMirror An annotation mirror. * @param name The name of the annotation value of interest. * * @return The annotation value with the given name or an empty list, if no * such value exists within the given annotation mirror or such a * value exists but is not an array-typed one. */ public List<? extends AnnotationValue> getAnnotationArrayValue(AnnotationMirror annotationMirror, String name) { AnnotationValue annotationValue = getAnnotationValue( annotationMirror, name ); if ( annotationValue == null ) { return Collections.<AnnotationValue>emptyList(); } List<? extends AnnotationValue> theValue = annotationValue.accept( new SimpleAnnotationValueVisitor6<List<? extends AnnotationValue>, Void>() { @Override public List<? extends AnnotationValue> visitArray(List<? extends AnnotationValue> values, Void p) { return values; } }, null ); return theValue != null ? theValue : Collections .<AnnotationValue>emptyList(); } /** * <p> * Returns a set containing the "lowest" type per hierarchy contained in the * input set. The following examples shall demonstrate the behavior. * </p> * <ul> * <li> * Input: <code>String</code>; Output: <code>String</code></li> * <li> * Input: <code>Object</code>, <code>String</code>; Output: * <code>String</code></li> * <li> * Input: <code>Object</code>, <code>Collection</code>, <code>List</code>; * Output: <code>List</code></li> * <li> * Input: <code>Collection</code>, <code>Set</code>, <code>List</code>; * Output: <code>List</code>, <code>Set</code></li> * </ul> * * @param types A set of type mirrors. * * @return A set with the lowest types per hierarchy or null, if the input * set was null. */ public Set<TypeMirror> keepLowestTypePerHierarchy(Set<TypeMirror> types) { if ( types == null ) { return null; } Set<TypeMirror> theValue = CollectionHelper.newHashSet(); for ( TypeMirror typeMirror1 : types ) { boolean foundSubType = false; for ( TypeMirror typeMirror2 : types ) { if ( !typeUtils.isSameType( typeMirror2, typeMirror1 ) && typeUtils.isAssignable( typeMirror2, typeMirror1 ) ) { foundSubType = true; continue; } } if ( !foundSubType ) { theValue.add( typeMirror1 ); } } return theValue; } }
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.RosterPacket; import org.jivesoftware.smack.util.StringUtils; /** * Represents a user's roster, which is the collection of users a person receives * presence updates for. Roster items are categorized into groups for easier management.<p> * <p/> * Others users may attempt to subscribe to this user using a subscription request. Three * modes are supported for handling these requests: <ul> * <li>{@link SubscriptionMode#accept_all accept_all} -- accept all subscription requests.</li> * <li>{@link SubscriptionMode#reject_all reject_all} -- reject all subscription requests.</li> * <li>{@link SubscriptionMode#manual manual} -- manually process all subscription requests.</li> * </ul> * * @author Matt Tucker * @see Connection#getRoster() */ public class Roster { /** * The default subscription processing mode to use when a Roster is created. By default * all subscription requests are automatically accepted. */ private static SubscriptionMode defaultSubscriptionMode = SubscriptionMode.accept_all; private RosterStorage persistentStorage; private Connection connection; private final Map<String, RosterGroup> groups; private final Map<String,RosterEntry> entries; private final List<RosterEntry> unfiledEntries; private final List<RosterListener> rosterListeners; private Map<String, Map<String, Presence>> presenceMap; // The roster is marked as initialized when at least a single roster packet // has been recieved and processed. boolean rosterInitialized = false; private PresencePacketListener presencePacketListener; private SubscriptionMode subscriptionMode = getDefaultSubscriptionMode(); private String requestPacketId; /** * Returns the default subscription processing mode to use when a new Roster is created. The * subscription processing mode dictates what action Smack will take when subscription * requests from other users are made. The default subscription mode * is {@link SubscriptionMode#accept_all}. * * @return the default subscription mode to use for new Rosters */ public static SubscriptionMode getDefaultSubscriptionMode() { return defaultSubscriptionMode; } /** * Sets the default subscription processing mode to use when a new Roster is created. The * subscription processing mode dictates what action Smack will take when subscription * requests from other users are made. The default subscription mode * is {@link SubscriptionMode#accept_all}. * * @param subscriptionMode the default subscription mode to use for new Rosters. */ public static void setDefaultSubscriptionMode(SubscriptionMode subscriptionMode) { defaultSubscriptionMode = subscriptionMode; } Roster(final Connection connection, RosterStorage persistentStorage){ this(connection); this.persistentStorage = persistentStorage; } /** * Creates a new roster. * * @param connection an XMPP connection. */ Roster(final Connection connection) { this.connection = connection; //Disable roster versioning if server doesn't offer support for it if(!connection.getConfiguration().isRosterVersioningAvailable()){ persistentStorage=null; } groups = new ConcurrentHashMap<String, RosterGroup>(); unfiledEntries = new CopyOnWriteArrayList<RosterEntry>(); entries = new ConcurrentHashMap<String,RosterEntry>(); rosterListeners = new CopyOnWriteArrayList<RosterListener>(); presenceMap = new ConcurrentHashMap<String, Map<String, Presence>>(); // Listen for any roster packets. PacketFilter rosterFilter = new PacketTypeFilter(RosterPacket.class); connection.addPacketListener(new RosterPacketListener(), rosterFilter); // Listen for any presence packets. PacketFilter presenceFilter = new PacketTypeFilter(Presence.class); presencePacketListener = new PresencePacketListener(); connection.addPacketListener(presencePacketListener, presenceFilter); // Listen for connection events connection.addConnectionListener(new ConnectionListener() { public void connectionClosed() { // Changes the presence available contacts to unavailable setOfflinePresences(); } public void connectionClosedOnError(Exception e) { // Changes the presence available contacts to unavailable setOfflinePresences(); } public void reconnectingIn(int seconds) { // Ignore } public void reconnectionFailed(Exception e) { // Ignore } public void reconnectionSuccessful() { // Ignore } }); } /** * Returns the subscription processing mode, which dictates what action * Smack will take when subscription requests from other users are made. * The default subscription mode is {@link SubscriptionMode#accept_all}.<p> * <p/> * If using the manual mode, a PacketListener should be registered that * listens for Presence packets that have a type of * {@link org.jivesoftware.smack.packet.Presence.Type#subscribe}. * * @return the subscription mode. */ public SubscriptionMode getSubscriptionMode() { return subscriptionMode; } /** * Sets the subscription processing mode, which dictates what action * Smack will take when subscription requests from other users are made. * The default subscription mode is {@link SubscriptionMode#accept_all}.<p> * <p/> * If using the manual mode, a PacketListener should be registered that * listens for Presence packets that have a type of * {@link org.jivesoftware.smack.packet.Presence.Type#subscribe}. * * @param subscriptionMode the subscription mode. */ public void setSubscriptionMode(SubscriptionMode subscriptionMode) { this.subscriptionMode = subscriptionMode; } /** * Reloads the entire roster from the server. This is an asynchronous operation, * which means the method will return immediately, and the roster will be * reloaded at a later point when the server responds to the reload request. */ public void reload() { RosterPacket packet = new RosterPacket(); if(persistentStorage!=null){ packet.setVersion(persistentStorage.getRosterVersion()); } requestPacketId = packet.getPacketID(); PacketFilter idFilter = new PacketIDFilter(requestPacketId); connection.addPacketListener(new RosterResultListener(), idFilter); connection.sendPacket(packet); } /** * Adds a listener to this roster. The listener will be fired anytime one or more * changes to the roster are pushed from the server. * * @param rosterListener a roster listener. */ public void addRosterListener(RosterListener rosterListener) { if (!rosterListeners.contains(rosterListener)) { rosterListeners.add(rosterListener); } } /** * Removes a listener from this roster. The listener will be fired anytime one or more * changes to the roster are pushed from the server. * * @param rosterListener a roster listener. */ public void removeRosterListener(RosterListener rosterListener) { rosterListeners.remove(rosterListener); } /** * Creates a new group.<p> * <p/> * Note: you must add at least one entry to the group for the group to be kept * after a logout/login. This is due to the way that XMPP stores group information. * * @param name the name of the group. * @return a new group. */ public RosterGroup createGroup(String name) { if (groups.containsKey(name)) { throw new IllegalArgumentException("Group with name " + name + " alread exists."); } RosterGroup group = new RosterGroup(name, connection); groups.put(name, group); return group; } /** * Creates a new roster entry and presence subscription. The server will asynchronously * update the roster with the subscription status. * * @param user the user. (e.g. johndoe@jabber.org) * @param name the nickname of the user. * @param groups the list of group names the entry will belong to, or <tt>null</tt> if the * the roster entry won't belong to a group. * @throws XMPPException if an XMPP exception occurs. */ public void createEntry(String user, String name, String[] groups) throws XMPPException { // Create and send roster entry creation packet. RosterPacket rosterPacket = new RosterPacket(); rosterPacket.setType(IQ.Type.SET); RosterPacket.Item item = new RosterPacket.Item(user, name); if (groups != null) { for (String group : groups) { if (group != null && group.trim().length() > 0) { item.addGroupName(group); } } } rosterPacket.addRosterItem(item); // Wait up to a certain number of seconds for a reply from the server. PacketCollector collector = connection.createPacketCollector( new PacketIDFilter(rosterPacket.getPacketID())); connection.sendPacket(rosterPacket); IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (response == null) { throw new XMPPException("No response from the server."); } // If the server replied with an error, throw an exception. else if (response.getType() == IQ.Type.ERROR) { throw new XMPPException(response.getError()); } // Create a presence subscription packet and send. Presence presencePacket = new Presence(Presence.Type.subscribe); presencePacket.setTo(user); connection.sendPacket(presencePacket); } private void insertRosterItems(List<RosterPacket.Item> items){ Collection<String> addedEntries = new ArrayList<String>(); Collection<String> updatedEntries = new ArrayList<String>(); Collection<String> deletedEntries = new ArrayList<String>(); Iterator<RosterPacket.Item> iter = items.iterator(); while(iter.hasNext()){ insertRosterItem(iter.next(), addedEntries,updatedEntries,deletedEntries); } fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries); } private void insertRosterItem(RosterPacket.Item item, Collection<String> addedEntries, Collection<String> updatedEntries, Collection<String> deletedEntries){ RosterEntry entry = new RosterEntry(item.getUser(), item.getName(), item.getItemType(), item.getItemStatus(), this, connection); // If the packet is of the type REMOVE then remove the entry if (RosterPacket.ItemType.remove.equals(item.getItemType())) { // Remove the entry from the entry list. if (entries.containsKey(item.getUser())) { entries.remove(item.getUser()); } // Remove the entry from the unfiled entry list. if (unfiledEntries.contains(entry)) { unfiledEntries.remove(entry); } // Removing the user from the roster, so remove any presence information // about them. String key = StringUtils.parseName(item.getUser()) + "@" + StringUtils.parseServer(item.getUser()); presenceMap.remove(key); // Keep note that an entry has been removed if(deletedEntries!=null){ deletedEntries.add(item.getUser()); } } else { // Make sure the entry is in the entry list. if (!entries.containsKey(item.getUser())) { entries.put(item.getUser(), entry); // Keep note that an entry has been added if(addedEntries!=null){ addedEntries.add(item.getUser()); } } else { // If the entry was in then list then update its state with the new values entries.put(item.getUser(), entry); // Keep note that an entry has been updated if(updatedEntries!=null){ updatedEntries.add(item.getUser()); } } // If the roster entry belongs to any groups, remove it from the // list of unfiled entries. if (!item.getGroupNames().isEmpty()) { unfiledEntries.remove(entry); } // Otherwise add it to the list of unfiled entries. else { if (!unfiledEntries.contains(entry)) { unfiledEntries.add(entry); } } } // Find the list of groups that the user currently belongs to. List<String> currentGroupNames = new ArrayList<String>(); for (RosterGroup group: getGroups()) { if (group.contains(entry)) { currentGroupNames.add(group.getName()); } } // If the packet is not of the type REMOVE then add the entry to the groups if (!RosterPacket.ItemType.remove.equals(item.getItemType())) { // Create the new list of groups the user belongs to. List<String> newGroupNames = new ArrayList<String>(); for (String groupName : item.getGroupNames()) { // Add the group name to the list. newGroupNames.add(groupName); // Add the entry to the group. RosterGroup group = getGroup(groupName); if (group == null) { group = createGroup(groupName); groups.put(groupName, group); } // Add the entry. group.addEntryLocal(entry); } // We have the list of old and new group names. We now need to // remove the entry from the all the groups it may no longer belong // to. We do this by subracting the new group set from the old. for (String newGroupName : newGroupNames) { currentGroupNames.remove(newGroupName); } } // Loop through any groups that remain and remove the entries. // This is neccessary for the case of remote entry removals. for (String groupName : currentGroupNames) { RosterGroup group = getGroup(groupName); group.removeEntryLocal(entry); if (group.getEntryCount() == 0) { groups.remove(groupName); } } // Remove all the groups with no entries. We have to do this because // RosterGroup.removeEntry removes the entry immediately (locally) and the // group could remain empty. // TODO Check the performance/logic for rosters with large number of groups for (RosterGroup group : getGroups()) { if (group.getEntryCount() == 0) { groups.remove(group.getName()); } } } /** * Removes a roster entry from the roster. The roster entry will also be removed from the * unfiled entries or from any roster group where it could belong and will no longer be part * of the roster. Note that this is an asynchronous call -- Smack must wait for the server * to send an updated subscription status. * * @param entry a roster entry. * @throws XMPPException if an XMPP error occurs. */ public void removeEntry(RosterEntry entry) throws XMPPException { // Only remove the entry if it's in the entry list. // The actual removal logic takes place in RosterPacketListenerprocess>>Packet(Packet) if (!entries.containsKey(entry.getUser())) { return; } RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.SET); RosterPacket.Item item = RosterEntry.toRosterItem(entry); // Set the item type as REMOVE so that the server will delete the entry item.setItemType(RosterPacket.ItemType.remove); packet.addRosterItem(item); PacketCollector collector = connection.createPacketCollector( new PacketIDFilter(packet.getPacketID())); connection.sendPacket(packet); IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (response == null) { throw new XMPPException("No response from the server."); } // If the server replied with an error, throw an exception. else if (response.getType() == IQ.Type.ERROR) { throw new XMPPException(response.getError()); } } /** * Returns a count of the entries in the roster. * * @return the number of entries in the roster. */ public int getEntryCount() { return getEntries().size(); } /** * Returns an unmodifiable collection of all entries in the roster, including entries * that don't belong to any groups. * * @return all entries in the roster. */ public Collection<RosterEntry> getEntries() { Set<RosterEntry> allEntries = new HashSet<RosterEntry>(); // Loop through all roster groups and add their entries to the answer for (RosterGroup rosterGroup : getGroups()) { allEntries.addAll(rosterGroup.getEntries()); } // Add the roster unfiled entries to the answer allEntries.addAll(unfiledEntries); return Collections.unmodifiableCollection(allEntries); } /** * Returns a count of the unfiled entries in the roster. An unfiled entry is * an entry that doesn't belong to any groups. * * @return the number of unfiled entries in the roster. */ public int getUnfiledEntryCount() { return unfiledEntries.size(); } /** * Returns an unmodifiable collection for the unfiled roster entries. An unfiled entry is * an entry that doesn't belong to any groups. * * @return the unfiled roster entries. */ public Collection<RosterEntry> getUnfiledEntries() { return Collections.unmodifiableList(unfiledEntries); } /** * Returns the roster entry associated with the given XMPP address or * <tt>null</tt> if the user is not an entry in the roster. * * @param user the XMPP address of the user (eg "jsmith@example.com"). The address could be * in any valid format (e.g. "domain/resource", "user@domain" or "user@domain/resource"). * @return the roster entry or <tt>null</tt> if it does not exist. */ public RosterEntry getEntry(String user) { if (user == null) { return null; } return entries.get(user.toLowerCase()); } /** * Returns true if the specified XMPP address is an entry in the roster. * * @param user the XMPP address of the user (eg "jsmith@example.com"). The * address could be in any valid format (e.g. "domain/resource", * "user@domain" or "user@domain/resource"). * @return true if the XMPP address is an entry in the roster. */ public boolean contains(String user) { return getEntry(user) != null; } /** * Returns the roster group with the specified name, or <tt>null</tt> if the * group doesn't exist. * * @param name the name of the group. * @return the roster group with the specified name. */ public RosterGroup getGroup(String name) { return groups.get(name); } /** * Returns the number of the groups in the roster. * * @return the number of groups in the roster. */ public int getGroupCount() { return groups.size(); } /** * Returns an unmodiable collections of all the roster groups. * * @return an iterator for all roster groups. */ public Collection<RosterGroup> getGroups() { return Collections.unmodifiableCollection(groups.values()); } /** * Returns the presence info for a particular user. If the user is offline, or * if no presence data is available (such as when you are not subscribed to the * user's presence updates), unavailable presence will be returned.<p> * <p/> * If the user has several presences (one for each resource), then the presence with * highest priority will be returned. If multiple presences have the same priority, * the one with the "most available" presence mode will be returned. In order, * that's {@link org.jivesoftware.smack.packet.Presence.Mode#chat free to chat}, * {@link org.jivesoftware.smack.packet.Presence.Mode#available available}, * {@link org.jivesoftware.smack.packet.Presence.Mode#away away}, * {@link org.jivesoftware.smack.packet.Presence.Mode#xa extended away}, and * {@link org.jivesoftware.smack.packet.Presence.Mode#dnd do not disturb}.<p> * <p/> * Note that presence information is received asynchronously. So, just after logging * in to the server, presence values for users in the roster may be unavailable * even if they are actually online. In other words, the value returned by this * method should only be treated as a snapshot in time, and may not accurately reflect * other user's presence instant by instant. If you need to track presence over time, * such as when showing a visual representation of the roster, consider using a * {@link RosterListener}. * * @param user an XMPP ID. The address could be in any valid format (e.g. * "domain/resource", "user@domain" or "user@domain/resource"). Any resource * information that's part of the ID will be discarded. * @return the user's current presence, or unavailable presence if the user is offline * or if no presence information is available.. */ public Presence getPresence(String user) { String key = getPresenceMapKey(StringUtils.parseBareAddress(user)); Map<String, Presence> userPresences = presenceMap.get(key); if (userPresences == null) { Presence presence = new Presence(Presence.Type.unavailable); presence.setFrom(user); return presence; } else { // Find the resource with the highest priority // Might be changed to use the resource with the highest availability instead. Presence presence = null; for (String resource : userPresences.keySet()) { Presence p = userPresences.get(resource); if (!p.isAvailable()) { continue; } // Chose presence with highest priority first. if (presence == null || p.getPriority() > presence.getPriority()) { presence = p; } // If equal priority, choose "most available" by the mode value. else if (p.getPriority() == presence.getPriority()) { Presence.Mode pMode = p.getMode(); // Default to presence mode of available. if (pMode == null) { pMode = Presence.Mode.available; } Presence.Mode presenceMode = presence.getMode(); // Default to presence mode of available. if (presenceMode == null) { presenceMode = Presence.Mode.available; } if (pMode.compareTo(presenceMode) < 0) { presence = p; } } } if (presence == null) { presence = new Presence(Presence.Type.unavailable); presence.setFrom(user); return presence; } else { return presence; } } } /** * Returns the presence info for a particular user's resource, or unavailable presence * if the user is offline or if no presence information is available, such as * when you are not subscribed to the user's presence updates. * * @param userWithResource a fully qualified XMPP ID including a resource (user@domain/resource). * @return the user's current presence, or unavailable presence if the user is offline * or if no presence information is available. */ public Presence getPresenceResource(String userWithResource) { String key = getPresenceMapKey(userWithResource); String resource = StringUtils.parseResource(userWithResource); Map<String, Presence> userPresences = presenceMap.get(key); if (userPresences == null) { Presence presence = new Presence(Presence.Type.unavailable); presence.setFrom(userWithResource); return presence; } else { Presence presence = userPresences.get(resource); if (presence == null) { presence = new Presence(Presence.Type.unavailable); presence.setFrom(userWithResource); return presence; } else { return presence; } } } /** * Returns an iterator (of Presence objects) for all of a user's current presences * or an unavailable presence if the user is unavailable (offline) or if no presence * information is available, such as when you are not subscribed to the user's presence * updates. * * @param user a XMPP ID, e.g. jdoe@example.com. * @return an iterator (of Presence objects) for all the user's current presences, * or an unavailable presence if the user is offline or if no presence information * is available. */ public Iterator<Presence> getPresences(String user) { String key = getPresenceMapKey(user); Map<String, Presence> userPresences = presenceMap.get(key); if (userPresences == null) { Presence presence = new Presence(Presence.Type.unavailable); presence.setFrom(user); return Arrays.asList(presence).iterator(); } else { Collection<Presence> answer = new ArrayList<Presence>(); for (Presence presence : userPresences.values()) { if (presence.isAvailable()) { answer.add(presence); } } if (!answer.isEmpty()) { return answer.iterator(); } else { Presence presence = new Presence(Presence.Type.unavailable); presence.setFrom(user); return Arrays.asList(presence).iterator(); } } } /** * Cleans up all resources used by the roster. */ void cleanup() { rosterListeners.clear(); } /** * Returns the key to use in the presenceMap for a fully qualified XMPP ID. * The roster can contain any valid address format such us "domain/resource", * "user@domain" or "user@domain/resource". If the roster contains an entry * associated with the fully qualified XMPP ID then use the fully qualified XMPP * ID as the key in presenceMap, otherwise use the bare address. Note: When the * key in presenceMap is a fully qualified XMPP ID, the userPresences is useless * since it will always contain one entry for the user. * * @param user the bare or fully qualified XMPP ID, e.g. jdoe@example.com or * jdoe@example.com/Work. * @return the key to use in the presenceMap for the fully qualified XMPP ID. */ private String getPresenceMapKey(String user) { if (user == null) { return null; } String key = user; if (!contains(user)) { key = StringUtils.parseBareAddress(user); } return key.toLowerCase(); } /** * Changes the presence of available contacts offline by simulating an unavailable * presence sent from the server. After a disconnection, every Presence is set * to offline. */ private void setOfflinePresences() { Presence packetUnavailable; for (String user : presenceMap.keySet()) { Map<String, Presence> resources = presenceMap.get(user); if (resources != null) { for (String resource : resources.keySet()) { packetUnavailable = new Presence(Presence.Type.unavailable); packetUnavailable.setFrom(user + "/" + resource); presencePacketListener.processPacket(packetUnavailable); } } } } /** * Fires roster changed event to roster listeners indicating that the * specified collections of contacts have been added, updated or deleted * from the roster. * * @param addedEntries the collection of address of the added contacts. * @param updatedEntries the collection of address of the updated contacts. * @param deletedEntries the collection of address of the deleted contacts. */ private void fireRosterChangedEvent(Collection<String> addedEntries, Collection<String> updatedEntries, Collection<String> deletedEntries) { for (RosterListener listener : rosterListeners) { if (!addedEntries.isEmpty()) { listener.entriesAdded(addedEntries); } if (!updatedEntries.isEmpty()) { listener.entriesUpdated(updatedEntries); } if (!deletedEntries.isEmpty()) { listener.entriesDeleted(deletedEntries); } } } /** * Fires roster presence changed event to roster listeners. * * @param presence the presence change. */ private void fireRosterPresenceEvent(Presence presence) { for (RosterListener listener : rosterListeners) { listener.presenceChanged(presence); } } /** * An enumeration for the subscription mode options. */ public enum SubscriptionMode { /** * Automatically accept all subscription and unsubscription requests. This is * the default mode and is suitable for simple client. More complex client will * likely wish to handle subscription requests manually. */ accept_all, /** * Automatically reject all subscription requests. */ reject_all, /** * Subscription requests are ignored, which means they must be manually * processed by registering a listener for presence packets and then looking * for any presence requests that have the type Presence.Type.SUBSCRIBE or * Presence.Type.UNSUBSCRIBE. */ manual } /** * Listens for all presence packets and processes them. */ private class PresencePacketListener implements PacketListener { public void processPacket(Packet packet) { Presence presence = (Presence) packet; String from = presence.getFrom(); String key = getPresenceMapKey(from); // If an "available" presence, add it to the presence map. Each presence // map will hold for a particular user a map with the presence // packets saved for each resource. if (presence.getType() == Presence.Type.available) { Map<String, Presence> userPresences; // Get the user presence map if (presenceMap.get(key) == null) { userPresences = new ConcurrentHashMap<String, Presence>(); presenceMap.put(key, userPresences); } else { userPresences = presenceMap.get(key); } // See if an offline presence was being stored in the map. If so, remove // it since we now have an online presence. userPresences.remove(""); // Add the new presence, using the resources as a key. userPresences.put(StringUtils.parseResource(from), presence); // If the user is in the roster, fire an event. RosterEntry entry = entries.get(key); if (entry != null) { fireRosterPresenceEvent(presence); } } // If an "unavailable" packet. else if (presence.getType() == Presence.Type.unavailable) { // If no resource, this is likely an offline presence as part of // a roster presence flood. In that case, we store it. if ("".equals(StringUtils.parseResource(from))) { Map<String, Presence> userPresences; // Get the user presence map if (presenceMap.get(key) == null) { userPresences = new ConcurrentHashMap<String, Presence>(); presenceMap.put(key, userPresences); } else { userPresences = presenceMap.get(key); } userPresences.put("", presence); } // Otherwise, this is a normal offline presence. else if (presenceMap.get(key) != null) { Map<String, Presence> userPresences = presenceMap.get(key); // Store the offline presence, as it may include extra information // such as the user being on vacation. userPresences.put(StringUtils.parseResource(from), presence); } // If the user is in the roster, fire an event. RosterEntry entry = entries.get(key); if (entry != null) { fireRosterPresenceEvent(presence); } } else if (presence.getType() == Presence.Type.subscribe) { if (subscriptionMode == SubscriptionMode.accept_all) { // Accept all subscription requests. Presence response = new Presence(Presence.Type.subscribed); response.setTo(presence.getFrom()); connection.sendPacket(response); } else if (subscriptionMode == SubscriptionMode.reject_all) { // Reject all subscription requests. Presence response = new Presence(Presence.Type.unsubscribed); response.setTo(presence.getFrom()); connection.sendPacket(response); } // Otherwise, in manual mode so ignore. } else if (presence.getType() == Presence.Type.unsubscribe) { if (subscriptionMode != SubscriptionMode.manual) { // Acknowledge and accept unsubscription notification so that the // server will stop sending notifications saying that the contact // has unsubscribed to our presence. Presence response = new Presence(Presence.Type.unsubscribed); response.setTo(presence.getFrom()); connection.sendPacket(response); } // Otherwise, in manual mode so ignore. } // Error presence packets from a bare JID mean we invalidate all existing // presence info for the user. else if (presence.getType() == Presence.Type.error && "".equals(StringUtils.parseResource(from))) { Map<String, Presence> userPresences; if (!presenceMap.containsKey(key)) { userPresences = new ConcurrentHashMap<String, Presence>(); presenceMap.put(key, userPresences); } else { userPresences = presenceMap.get(key); // Any other presence data is invalidated by the error packet. userPresences.clear(); } // Set the new presence using the empty resource as a key. userPresences.put("", presence); // If the user is in the roster, fire an event. RosterEntry entry = entries.get(key); if (entry != null) { fireRosterPresenceEvent(presence); } } } } /** * Listen for empty IQ results which indicate that the client has already a current * roster version * @author Till Klocke * */ private class RosterResultListener implements PacketListener{ public void processPacket(Packet packet) { if(packet instanceof IQ){ IQ result = (IQ)packet; if(result.getType().equals(IQ.Type.RESULT) && result.getExtensions().isEmpty()){ Collection<String> addedEntries = new ArrayList<String>(); Collection<String> updatedEntries = new ArrayList<String>(); Collection<String> deletedEntries = new ArrayList<String>(); if(persistentStorage!=null){ for(RosterPacket.Item item : persistentStorage.getEntries()){ insertRosterItem(item,addedEntries,updatedEntries,deletedEntries); } synchronized (Roster.this) { rosterInitialized = true; Roster.this.notifyAll(); } fireRosterChangedEvent(addedEntries,updatedEntries,deletedEntries); } } } connection.removePacketListener(this); } } /** * Listens for all roster packets and processes them. */ private class RosterPacketListener implements PacketListener { public void processPacket(Packet packet) { // Keep a registry of the entries that were added, deleted or updated. An event // will be fired for each affected entry Collection<String> addedEntries = new ArrayList<String>(); Collection<String> updatedEntries = new ArrayList<String>(); Collection<String> deletedEntries = new ArrayList<String>(); String version=null; RosterPacket rosterPacket = (RosterPacket) packet; List<RosterPacket.Item> rosterItems = new ArrayList<RosterPacket.Item>(); for(RosterPacket.Item item : rosterPacket.getRosterItems()){ rosterItems.add(item); } //Here we check if the server send a versioned roster, if not we do not use //the roster storage to store entries and work like in the old times if(rosterPacket.getVersion()==null){ persistentStorage=null; } else{ version = rosterPacket.getVersion(); } if(persistentStorage!=null && !rosterInitialized){ for(RosterPacket.Item item : persistentStorage.getEntries()){ rosterItems.add(item); } } for (RosterPacket.Item item : rosterItems) { insertRosterItem(item,addedEntries,updatedEntries,deletedEntries); } if(persistentStorage!=null){ for (RosterPacket.Item i : rosterPacket.getRosterItems()){ if(i.getItemType().equals(RosterPacket.ItemType.remove)){ persistentStorage.removeEntry(i.getUser()); } else{ persistentStorage.addEntry(i, version); } } } // Mark the roster as initialized. synchronized (Roster.this) { rosterInitialized = true; Roster.this.notifyAll(); } // Fire event for roster listeners. fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries); } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Renan Tomazoni Pinzon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.rpinzon.misc.connectivity; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class used to access a FTP server. * * @author Renan Tomazoni Pinzon */ public final class ClientFTP { private static final Logger LOG = LoggerFactory.getLogger(ClientFTP.class); private final String hostname; private final int port; private final String username; private final String password; private final FTPClient client; /** * Default constructor. * * @param hostname the hostname of the FTP server * @param port the port that will be used in connection * @param connectTimeout the connection timeout * @param timeout the read timeout * @param username the username to authenticate * @param password the password of the user */ public ClientFTP(String hostname, int port, int connectTimeout, int timeout, String username, String password) { validate(hostname, port, connectTimeout, timeout, username, password); this.hostname = hostname; this.port = port; this.username = username; this.password = password; this.client = buildFTPClient(connectTimeout, timeout); } /** * Validate required fields to access the FTP server. * * @param hostname the hostname of the FTP server * @param port the port that will be used in connection * @param connectTimeout the connection timeout * @param timeout the read timeout * @param username the username to authenticate * @param password the password of the user */ private static void validate(String hostname, int port, int connectTimeout, int timeout, String username, String password) { Validate.notBlank(hostname, "The hostname cannot be null or blank"); Validate.isTrue(port > 0, "The number of the port must be greater than zero"); Validate.isTrue(connectTimeout > 0, "The connection timeout must be greater than zero"); Validate.isTrue(timeout >= 0, "The read timeout must be greater or equal than zero"); Validate.notBlank(username, "The username cannot be null or blank"); Validate.notBlank(password, "The password cannot be null or blank"); } /** * Retrieves the content for the given path from FTP server. * * @param remotePath the full path of the file to retrieve * @return the stream of the content * @throws Exception if an error occurs while attempting to retrieve the * content */ public InputStream retrieve(String remotePath) throws Exception { try { connect(); client.setFileType(FTP.BINARY_FILE_TYPE); InputStream content = null; if (exists(remotePath)) { content = client.retrieveFileStream(remotePath); if (!client.completePendingCommand()) { client.logout(); throw new Exception("Content could not be retrieve from FTP server"); } } return content; } catch (SocketException e) { LOG.error("Error while attempting to connect to FTP server", e); throw new Exception(e); } catch (IOException e) { LOG.error("Error retrieving content from FTP server", e); throw new Exception(e); } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { LOG.error("Error disconnecting from FTP server", e); } } } } /** * Stores the given content to the FTP server storing it in the given remote * path if there is no file with the same name in there when the 'overwrite' * attribute is false. In case of 'overwrite' is true if a file already * exists it will be with this content. * * @param content the content to be sent to FTP server * @param remotePath the remote path with the name of the file * @param overwrite if must overwrite when a file already exists with the * same name * @throws Exception if an error occurs while attempting to connect or store * the content to FTP server */ public void store(InputStream content, String remotePath, boolean overwrite) throws Exception { try { connect(); /* * remove the file name and the prefix from the path and change it * to Unix separator */ String path = FilenameUtils.separatorsToUnix(FilenameUtils.getPath(remotePath)); // for each directory create and change to it String[] dirs = StringUtils.split(path, '/'); for (String dir : dirs) { /* * tries to change to the directory and if it is not possible * create it */ if (!client.changeWorkingDirectory(dir)) { // tries to create the directory boolean created = client.makeDirectory(dir); /* * if the directory was not created OR the directory was * created and it is not possible to change to the directory * then it is an error and the content will not be sent to * FTP server */ if (!created || !client.changeWorkingDirectory(dir)) { client.logout(); String message = String.format("Directory does not exists or the user does not have permission. remotePath [%s] - username [%s] - response [%s]", remotePath, username, client.getReplyString()); throw new Exception(message); } } } String filename = FilenameUtils.getName(remotePath); if (!overwrite && client.listFiles(filename).length > 0) { client.logout(); String message = String.format("There is a file with the same name into the FTP server. remotePath [%s]", remotePath); throw new Exception(message); } // effectively store the file into the FTP server client.storeFile(filename, content); } catch (SocketException e) { LOG.error("Error while attempting to connect to FTP server", e); throw new Exception(e); } catch (IOException e) { LOG.error("Error sending content to FTP server", e); throw new Exception(e); } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { LOG.error("Error disconnecting from FTP server", e); } } } } /** * Builds the FTP client defining connection and read timeout. * * @param connectTimeout connection timeout * @param timeout read timeout * @return an instance of the client to access the FTP server */ private FTPClient buildFTPClient(int connectTimeout, int timeout) { FTPClient client = new FTPClient(); client.setConnectTimeout(connectTimeout); client.setDataTimeout(timeout); return client; } /** * Attempts to connect to the FTP server. * * @throws SocketException if an error occurs while attempting to establish * connection with the server * @throws IOException if an error occurs while attempting to authenticate * in the server * @throws Exception if the connection was established but the response was * not positive or if the authentication failed due to invalid username or * password */ private void connect() throws SocketException, IOException, Exception { client.connect(hostname, port); // verify if the reply code is success if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { String message = String.format("Connection refused by the FTP server. hostname [%s] - port [%d] ", hostname, port); throw new Exception(message); } // verify if the user has permission to connect to the server if (!client.login(username, password)) { client.logout(); throw new Exception("Invalid username or password"); } } /** * Checks whether the file exists or not on FTP server. * * @param remotePath the full path of the file * @return true if it exists * @throws IOException if an error occurs while trying to check if the file * exists */ private boolean exists(String remotePath) throws IOException { return client.listFiles(remotePath).length > 0; } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.toolbar; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.Toast; import org.chromium.chrome.R; import org.chromium.chrome.browser.Tab; import org.chromium.chrome.browser.appmenu.AppMenuButtonHelper; import org.chromium.chrome.browser.compositor.Invalidator; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.omnibox.LocationBar; import org.chromium.chrome.browser.util.ViewUtils; import org.chromium.chrome.browser.widget.TintedImageButton; import org.chromium.chrome.browser.widget.ToolbarProgressBar; import org.chromium.ui.UiUtils; /** * Layout class that contains the base shared logic for manipulating the toolbar component. For * interaction that are not from Views inside Toolbar hierarchy all interactions should be done * through {@link Toolbar} rather than using this class directly. */ abstract class ToolbarLayout extends FrameLayout implements Toolbar { protected static final int BACKGROUND_TRANSITION_DURATION_MS = 400; private Invalidator mInvalidator; private final int[] mTempPosition = new int[2]; /** * The ImageButton view that represents the menu button. */ protected TintedImageButton mMenuButton; private AppMenuButtonHelper mAppMenuButtonHelper; private ToolbarDataProvider mToolbarDataProvider; private ToolbarTabController mToolbarTabController; private ToolbarProgressBar mProgressBar; private boolean mNativeLibraryReady; private boolean mUrlHasFocus; private long mFirstDrawTimeMs; protected final int mToolbarHeightWithoutShadow; private boolean mFindInPageToolbarShowing; /** * Basic constructor for {@link ToolbarLayout}. */ public ToolbarLayout(Context context, AttributeSet attrs) { super(context, attrs); mToolbarHeightWithoutShadow = getResources().getDimensionPixelOffset( getToolbarHeightWithoutShadowResId()); } @Override protected void onFinishInflate() { super.onFinishInflate(); mProgressBar = (ToolbarProgressBar) findViewById(R.id.progress); if (mProgressBar != null) { removeView(mProgressBar); getFrameLayoutParams(mProgressBar).topMargin = mToolbarHeightWithoutShadow - getFrameLayoutParams(mProgressBar).height; } mMenuButton = (TintedImageButton) findViewById(R.id.menu_button); // Initialize the provider to an empty version to avoid null checking everywhere. mToolbarDataProvider = new ToolbarDataProvider() { @Override public boolean isIncognito() { return false; } @Override public Tab getTab() { return null; } @Override public String getText() { return null; } @Override public boolean wouldReplaceURL() { return false; } @Override public NewTabPage getNewTabPageForCurrentTab() { return null; } @Override public String getCorpusChipText() { return null; } @Override public int getPrimaryColor() { return 0; } @Override public boolean isUsingBrandColor() { return false; } }; } /** * Quick getter for LayoutParams for a View inside a FrameLayout. * @param view {@link View} to fetch the layout params for. * @return {@link LayoutParams} the given {@link View} is currently using. */ protected FrameLayout.LayoutParams getFrameLayoutParams(View view) { return ((FrameLayout.LayoutParams) view.getLayoutParams()); } /** * @return The resource id to be used while getting the toolbar height with no shadow. */ protected int getToolbarHeightWithoutShadowResId() { return R.dimen.toolbar_height_no_shadow; } /** * Initialize the external dependencies required for view interaction. * @param toolbarDataProvider The provider for toolbar data. * @param tabController The controller that handles interactions with the tab. * @param appMenuButtonHelper The helper for managing menu button interactions. */ public void initialize(ToolbarDataProvider toolbarDataProvider, ToolbarTabController tabController, AppMenuButtonHelper appMenuButtonHelper) { mToolbarDataProvider = toolbarDataProvider; mToolbarTabController = tabController; mMenuButton.setOnTouchListener(new OnTouchListener() { @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { return mAppMenuButtonHelper.onTouch(v, event); } }); mAppMenuButtonHelper = appMenuButtonHelper; } /** * This function handles native dependent initialization for this class */ public void onNativeLibraryReady() { mNativeLibraryReady = true; } /** * @return The menu button view. */ protected View getMenuButton() { return mMenuButton; } /** * @return The {@link ProgressBar} this layout uses. */ ToolbarProgressBar getProgressBar() { return mProgressBar; } @Override public void getPositionRelativeToContainer(View containerView, int[] position) { ViewUtils.getRelativeDrawPosition(containerView, this, position); } /** * @return The helper for menu button UI interactions. */ protected AppMenuButtonHelper getMenuButtonHelper() { return mAppMenuButtonHelper; } /** * @return Whether or not the native library is loaded and ready. */ protected boolean isNativeLibraryReady() { return mNativeLibraryReady; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); recordFirstDrawTime(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mProgressBar != null) { ViewGroup controlContainer = (ViewGroup) getRootView().findViewById(R.id.control_container); int progressBarPosition = UiUtils.insertAfter( controlContainer, mProgressBar, (View) getParent()); assert progressBarPosition >= 0; } } /** * Shows the content description toast for items on the toolbar. * @param view The view to anchor the toast. * @param stringResId The resource id for the string in the toast. * @return Whether a toast has been shown successfully. */ protected boolean showAccessibilityToast(View view, int stringResId) { if (stringResId == 0) return false; final int screenWidth = getResources().getDisplayMetrics().widthPixels; final int[] screenPos = new int[2]; view.getLocationOnScreen(screenPos); final int width = view.getWidth(); Toast toast = Toast.makeText( getContext(), getResources().getString(stringResId), Toast.LENGTH_SHORT); toast.setGravity( Gravity.TOP | Gravity.END, screenWidth - screenPos[0] - width / 2, getHeight()); toast.show(); return true; } /** * @return The provider for toolbar related data. */ protected ToolbarDataProvider getToolbarDataProvider() { return mToolbarDataProvider; } /** * Sets the {@link Invalidator} that will be called when the toolbar attempts to invalidate the * drawing surface. This will give the object that registers as the host for the * {@link Invalidator} a chance to defer the actual invalidate to sync drawing. * @param invalidator An {@link Invalidator} instance. */ public void setPaintInvalidator(Invalidator invalidator) { mInvalidator = invalidator; } /** * Triggers a paint but allows the {@link Invalidator} set by * {@link #setPaintInvalidator(Invalidator)} to decide when to actually invalidate. * @param client A {@link Invalidator.Client} instance that wants to be invalidated. */ protected void triggerPaintInvalidate(Invalidator.Client client) { if (mInvalidator == null) { client.doInvalidate(); } else { mInvalidator.invalidate(client); } } /** * Gives inheriting classes the chance to respond to * {@link org.chromium.chrome.browser.widget.findinpage.FindToolbar} state changes. * @param showing Whether or not the {@code FindToolbar} will be showing. */ protected void handleFindToolbarStateChange(boolean showing) { mFindInPageToolbarShowing = showing; } /** * Sets the OnClickListener that will be notified when the TabSwitcher button is pressed. * @param listener The callback that will be notified when the TabSwitcher button is pressed. */ public void setOnTabSwitcherClickHandler(OnClickListener listener) { } /** * Sets the OnClickListener that will be notified when the New Tab button is pressed. * @param listener The callback that will be notified when the New Tab button is pressed. */ public void setOnNewTabClickHandler(OnClickListener listener) { } /** * Sets the OnClickListener that will be notified when the bookmark button is pressed. * @param listener The callback that will be notified when the bookmark button is pressed. */ public void setBookmarkClickHandler(OnClickListener listener) { } /** * Sets the OnClickListener to notify when the close button is pressed in a custom tab. * @param listener The callback that will be notified when the close button is pressed. */ public void setCustomTabCloseClickHandler(OnClickListener listener) { } /** * Gives inheriting classes the chance to update the visibility of the * back button. * @param canGoBack Whether or not the current tab has any history to go back to. */ protected void updateBackButtonVisibility(boolean canGoBack) { } /** * Gives inheriting classes the chance to update the visibility of the * forward button. * @param canGoForward Whether or not the current tab has any history to go forward to. */ protected void updateForwardButtonVisibility(boolean canGoForward) { } /** * Gives inheriting classes the chance to update the visibility of the * reload button. * @param isReloading Whether or not the current tab is loading. */ protected void updateReloadButtonVisibility(boolean isReloading) { } /** * Gives inheriting classes the chance to update the visual status of the * bookmark button. * @param isBookmarked Whether or not the current tab is already bookmarked. * @param editingAllowed Whether or not bookmarks can be modified (added, edited, or removed). */ protected void updateBookmarkButton(boolean isBookmarked, boolean editingAllowed) { } /** * Gives inheriting classes the chance to respond to accessibility state changes. * @param enabled Whether or not accessibility is enabled. */ protected void onAccessibilityStatusChanged(boolean enabled) { } /** * Gives inheriting classes the chance to do the necessary UI operations after Chrome is * restored to a previously saved state. */ protected void onStateRestored() { } /** * Gives inheriting classes the chance to update home button UI if home button preference is * changed. * @param homeButtonEnabled Whether or not home button is enabled in preference. */ protected void onHomeButtonUpdate(boolean homeButtonEnabled) { } /** * Triggered when the current tab or model has changed. * <p> * As there are cases where you can select a model with no tabs (i.e. having incognito * tabs but no normal tabs will still allow you to select the normal model), this should * not guarantee that the model's current tab is non-null. */ protected void onTabOrModelChanged() { NewTabPage ntp = getToolbarDataProvider().getNewTabPageForCurrentTab(); if (ntp != null) getLocationBar().onTabLoadingNTP(ntp); getLocationBar().updateMicButtonState(); } /** * For extending classes to override and carry out the changes related with the primary color * for the current tab changing. */ protected void onPrimaryColorChanged() { } /** * Sets the icon resource that the close button in the toolbar (if any) should show. */ public void setCloseButtonImageResource(int iconRes) { } /** * Adds a custom action button to the {@link ToolbarLayout} if it is supported. * @param buttonSource The {@link Bitmap} resource to use as the source for the button. * @param listener The {@link OnClickListener} to use for clicks to the button. */ public void addCustomActionButton(Drawable drawable, OnClickListener listener) { } /** * Triggered when the content view for the specified tab has changed. */ protected void onTabContentViewChanged() { NewTabPage ntp = getToolbarDataProvider().getNewTabPageForCurrentTab(); if (ntp != null) getLocationBar().onTabLoadingNTP(ntp); } @Override public boolean isReadyForTextureCapture() { return true; } /** * @param attached Whether or not the web content is attached to the view heirarchy. */ protected void setContentAttached(boolean attached) { } /** * Gives inheriting classes the chance to show or hide the TabSwitcher mode of this toolbar. * @param inTabSwitcherMode Whether or not TabSwitcher mode should be shown or hidden. * @param showToolbar Whether or not to show the normal toolbar while animating. * @param delayAnimation Whether or not to delay the animation until after the transition has * finished (which can be detected by a call to * {@link #onTabSwitcherTransitionFinished()}). */ protected void setTabSwitcherMode( boolean inTabSwitcherMode, boolean showToolbar, boolean delayAnimation) { } /** * Gives inheriting classes the chance to update their state when the TabSwitcher transition has * finished. */ protected void onTabSwitcherTransitionFinished() { } /** * Gives inheriting classes the chance to update themselves based on the * number of tabs in the current TabModel. * @param numberOfTabs The number of tabs in the current model. */ protected void updateTabCountVisuals(int numberOfTabs) { } /** * Gives inheriting classes the chance to update themselves based on default search engine * changes. */ protected void onDefaultSearchEngineChanged() { } @Override public void getLocationBarContentRect(Rect outRect) { View container = getLocationBar().getContainerView(); outRect.set(container.getPaddingLeft(), container.getPaddingTop(), container.getWidth() - container.getPaddingRight(), container.getHeight() - container.getPaddingBottom()); ViewUtils.getRelativeDrawPosition( this, getLocationBar().getContainerView(), mTempPosition); outRect.offset(mTempPosition[0], mTempPosition[1]); } @Override public void setTextureCaptureMode(boolean textureMode) { } @Override public boolean shouldIgnoreSwipeGesture() { return mUrlHasFocus || (mAppMenuButtonHelper != null && mAppMenuButtonHelper.isAppMenuActive()) || mFindInPageToolbarShowing; } /** * @return Whether or not the url bar has focus. */ protected boolean urlHasFocus() { return mUrlHasFocus; } /** * Triggered when the URL input field has gained or lost focus. * @param hasFocus Whether the URL field has gained focus. */ protected void onUrlFocusChange(boolean hasFocus) { mUrlHasFocus = hasFocus; } protected boolean shouldShowMenuButton() { return true; } /** * Keeps track of the first time the toolbar is drawn. */ private void recordFirstDrawTime() { if (mFirstDrawTimeMs == 0) mFirstDrawTimeMs = SystemClock.elapsedRealtime(); } /** * Returns the elapsed realtime in ms of the time at which first draw for the toolbar occurred. */ public long getFirstDrawTime() { return mFirstDrawTimeMs; } /** * Notified when a navigation to a different page has occurred. */ protected void onNavigatedToDifferentPage() { } /** * Starts load progress. */ protected void startLoadProgress() { if (mProgressBar != null) { mProgressBar.start(); } } /** * Sets load progress. * @param progress The load progress between 0 and 1. */ protected void setLoadProgress(float progress) { if (mProgressBar != null) { mProgressBar.setProgress(progress); } } /** * Finishes load progress. * @param delayed Whether hiding progress bar should be delayed to give enough time for user to * recognize the last state. */ protected void finishLoadProgress(boolean delayed) { if (mProgressBar != null) { mProgressBar.finish(delayed); } } /** * Finish any toolbar animations. */ public void finishAnimations() { } /** * @return The current View showing in the Tab. */ protected View getCurrentTabView() { Tab tab = mToolbarDataProvider.getTab(); if (tab != null) { return tab.getView(); } return null; } /** * @return Whether or not the toolbar is incognito. */ protected boolean isIncognito() { return mToolbarDataProvider.isIncognito(); } /** * @return {@link LocationBar} object this {@link ToolbarLayout} contains. */ public abstract LocationBar getLocationBar(); /** * Navigates the current Tab back. * @return Whether or not the current Tab did go back. */ protected boolean back() { getLocationBar().hideSuggestions(); return mToolbarTabController != null ? mToolbarTabController.back() : false; } /** * Navigates the current Tab forward. * @return Whether or not the current Tab did go forward. */ protected boolean forward() { getLocationBar().hideSuggestions(); return mToolbarTabController != null ? mToolbarTabController.forward() : false; } /** * If the page is currently loading, this will trigger the tab to stop. If the page is fully * loaded, this will trigger a refresh. * * <p>The buttons of the toolbar will be updated as a result of making this call. */ protected void stopOrReloadCurrentTab() { getLocationBar().hideSuggestions(); if (mToolbarTabController != null) mToolbarTabController.stopOrReloadCurrentTab(); } /** * Opens hompage in the current tab. */ protected void openHomepage() { getLocationBar().hideSuggestions(); if (mToolbarTabController != null) mToolbarTabController.openHomepage(); } }
/* * Copyright 2002-2019 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.handler.invocation.reactive; import java.lang.reflect.Method; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException; import org.springframework.messaging.handler.invocation.ResolvableMethod; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; /** * Unit tests for {@link InvocableHandlerMethod}. * * @author Rossen Stoyanchev * @author Juergen Hoeller */ public class InvocableHandlerMethodTests { private final Message<?> message = mock(Message.class); private final List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(); @Test public void resolveArg() { this.resolvers.add(new StubArgumentResolver(99)); this.resolvers.add(new StubArgumentResolver("value")); Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method); assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); assertThat(value).isEqualTo("99-value"); assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("intArg"); assertThat(getStubResolver(1).getResolvedParameters().get(0).getParameterName()).isEqualTo("stringArg"); } @Test public void resolveNoArgValue() { this.resolvers.add(new StubArgumentResolver(Integer.class)); this.resolvers.add(new StubArgumentResolver(String.class)); Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method); assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); assertThat(value).isEqualTo("null-null"); } @Test public void cannotResolveArg() { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); assertThatExceptionOfType(MethodArgumentResolutionException.class).isThrownBy(() -> invokeAndBlock(new Handler(), method)) .withMessageContaining("Could not resolve parameter [0]"); } @Test public void resolveProvidedArg() { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method, 99, "value"); assertThat(value).isNotNull(); assertThat(value.getClass()).isEqualTo(String.class); assertThat(value).isEqualTo("99-value"); } @Test public void resolveProvidedArgFirst() { this.resolvers.add(new StubArgumentResolver(1)); this.resolvers.add(new StubArgumentResolver("value1")); Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method, 2, "value2"); assertThat(value).isEqualTo("2-value2"); } @Test public void exceptionInResolvingArg() { this.resolvers.add(new InvocableHandlerMethodTests.ExceptionRaisingArgumentResolver()); Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); assertThatIllegalArgumentException().isThrownBy(() -> invokeAndBlock(new Handler(), method)); } @Test public void illegalArgumentException() { this.resolvers.add(new StubArgumentResolver(Integer.class, "__not_an_int__")); this.resolvers.add(new StubArgumentResolver("value")); Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); assertThatIllegalStateException().isThrownBy(() -> invokeAndBlock(new Handler(), method)) .withCauseInstanceOf(IllegalArgumentException.class) .withMessageContaining("Endpoint [") .withMessageContaining("Method [") .withMessageContaining("with argument values:") .withMessageContaining("[0] [type=java.lang.String] [value=__not_an_int__]") .withMessageContaining("[1] [type=java.lang.String] [value=value"); } @Test public void invocationTargetException() { Method method = ResolvableMethod.on(Handler.class).argTypes(Throwable.class).resolveMethod(); Throwable expected = new Throwable("error"); Mono<Object> result = invoke(new Handler(), method, expected); StepVerifier.create(result).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(); } @Test public void voidMethod() { this.resolvers.add(new StubArgumentResolver(double.class, 5.25)); Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0.0d)).method(); Handler handler = new Handler(); Object value = invokeAndBlock(handler, method); assertThat(value).isNull(); assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); assertThat(handler.getResult()).isEqualTo("5.25"); assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("amount"); } @Test public void voidMonoMethod() { Method method = ResolvableMethod.on(Handler.class).mockCall(Handler::handleAsync).method(); Handler handler = new Handler(); Object value = invokeAndBlock(handler, method); assertThat(value).isNull(); assertThat(handler.getResult()).isEqualTo("success"); } @Nullable private Object invokeAndBlock(Object handler, Method method, Object... providedArgs) { return invoke(handler, method, providedArgs).block(Duration.ofSeconds(5)); } private Mono<Object> invoke(Object handler, Method method, Object... providedArgs) { InvocableHandlerMethod handlerMethod = new InvocableHandlerMethod(handler, method); handlerMethod.setArgumentResolvers(this.resolvers); return handlerMethod.invoke(this.message, providedArgs); } private StubArgumentResolver getStubResolver(int index) { return (StubArgumentResolver) this.resolvers.get(index); } @SuppressWarnings({"unused", "UnusedReturnValue", "SameParameterValue"}) private static class Handler { private AtomicReference<String> result = new AtomicReference<>(); public Handler() { } public String getResult() { return this.result.get(); } String handle(Integer intArg, String stringArg) { return intArg + "-" + stringArg; } void handle(double amount) { this.result.set(String.valueOf(amount)); } void handleWithException(Throwable ex) throws Throwable { throw ex; } Mono<Void> handleAsync() { return Mono.delay(Duration.ofMillis(100)).thenEmpty(Mono.defer(() -> { this.result.set("success"); return Mono.empty(); })); } } private static class ExceptionRaisingArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return true; } @Override public Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) { return Mono.error(new IllegalArgumentException("oops, can't read")); } } }
package water.api; import java.lang.reflect.Constructor; import java.util.Arrays; import hex.Model; import hex.grid.Grid; import water.DKV; import water.Iced; import water.Job; import water.Key; import water.Keyed; import water.Value; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Frame; import water.fvec.Vec; import water.util.KeyedVoid; import water.util.ReflectionUtils; /** * <p> * Base Schema Class for Keys. Note that Key schemas are generally typed by the type of * object they point to (e.g., the front something like a Key<Frame>). * <p> * The type parameters are a bit subtle, because we have several schemas that map to Key, * by type. We want to be parameterized by the type of Keyed that we point to, but the * Iced type we pass up to Schema must be Iced, so that a lookup for a Schema for Key<T> * doesn't get an arbitrary subclass of KeyV1. */ public class KeyV3<I extends Iced, S extends KeyV3<I, S, K>, K extends Keyed> extends Schema<I, S> { @API(help="Name (string representation) for this Key.", direction = API.Direction.INOUT) public String name; @API(help="Name (string representation) for the type of Keyed this Key points to.", direction = API.Direction.INOUT) public String type; @API(help="URL for the resource that this Key points to, if one exists.", direction = API.Direction.INOUT) public String URL; public KeyV3() { // NOTE: this is a bit of a hack; without this we won't have the type parameter. // We'll be able to remove this once we have proper typed Key subclasses, like FrameKey. get__meta().setSchema_type("Key<" + getKeyedClassType() + ">"); } // need versioned public KeyV3(Key key) { this(); if (null != key) { Class clz = getKeyedClass(); Value v = DKV.get(key); if (null != v) { // Type checking of value from DKV if (Job.class.isAssignableFrom(clz) && !v.isJob()) throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Job; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Job; found a: " + v.theFreezableClass() + " (" + clz + ")"); else if (Frame.class.isAssignableFrom(clz) && !v.isFrame() && !v.isVec()) // NOTE: we currently allow Vecs to be fetched via the /Frames endpoint, so this constraint is relaxed accordingly. Note this means that if the user gets hold of a (hidden) Vec key and passes it to some other endpoint they will get an ugly error instead of an H2OIllegalArgumentException. throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Frame; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Frame; found a: " + v.theFreezableClass() + " (" + clz + ")"); else if (Model.class.isAssignableFrom(clz) && !v.isModel()) throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Model; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Model; found a: " + v.theFreezableClass() + " (" + clz + ")"); else if (Vec.class.isAssignableFrom(clz) && !v.isVec()) throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Vec; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Vec; found a: " + v.theFreezableClass() + " (" + clz + ")"); } this.fillFromImpl(key); } } public static KeyV3 make(Class<? extends KeyV3> clz, Key key) { KeyV3 result = null; try { Constructor c = clz.getConstructor(Key.class); result = (KeyV3)c.newInstance(key); } catch (Exception e) { throw new H2OIllegalArgumentException("Caught exception trying to instantiate KeyV1 for class: " + clz.toString() + ": " + e + "; cause: " + e.getCause() + " " + Arrays.toString(e.getCause().getStackTrace())); } return result; } /** TODO: figure out the right KeyV1 class from the Key, so the type is set properly. */ public static KeyV3 make(Key key) { return make(KeyV3.class, key); } /** Factory method which returns the correct KeyV1 for the given Keyed class (e.g., for Frame.class). */ public static KeyV3 forKeyedClass(Class<? extends Keyed> keyed_class, Key key) { if (Job.class.isAssignableFrom(keyed_class)) return KeyV3.make(JobKeyV3.class, key); else if (Frame.class.isAssignableFrom(keyed_class)) return KeyV3.make(FrameKeyV3.class, key); else if (Model.class.isAssignableFrom(keyed_class)) return KeyV3.make(ModelKeyV3.class, key); else if (Vec.class.isAssignableFrom(keyed_class)) return KeyV3.make(VecKeyV3.class, key); else if (Grid.class.isAssignableFrom(keyed_class)) return KeyV3.make(GridKeyV3.class, key); else if (KeyedVoid.class.isAssignableFrom(keyed_class)) return KeyV3.make(KeyedVoidV3.class, key); else return KeyV3.make(KeyV3.class, key); } public static class JobKeyV3 extends KeyV3<Iced, JobKeyV3, Job> { public JobKeyV3() {} public JobKeyV3(Key<Job> key) { super(key); } } public static class FrameKeyV3 extends KeyV3<Iced, FrameKeyV3, Frame> { public FrameKeyV3() {} public FrameKeyV3(Key<Frame> key) { super(key); } } public static class ModelKeyV3 extends KeyV3<Iced, ModelKeyV3, Model> { public ModelKeyV3() {} public ModelKeyV3(Key<? extends Model> key) { super(key); } } public static class VecKeyV3 extends KeyV3<Iced, VecKeyV3, Vec> { public VecKeyV3() { } public VecKeyV3(Key<Vec> key) { super(key); } } public static class GridKeyV3 extends KeyV3<Iced, GridKeyV3, Grid> { public GridKeyV3() { } public GridKeyV3(Key<Grid> key) { super(key); } } public static class KeyedVoidV3 extends KeyV3<Iced, KeyedVoidV3, KeyedVoid> { public KeyedVoidV3() { } public KeyedVoidV3(Key<KeyedVoid> key) { super(key); } } @Override public S fillFromImpl(Iced i) { if (! (i instanceof Key)) throw new H2OIllegalArgumentException("fillFromImpl", "key", i); Key key = (Key)i; if (null == key) return (S)this; this.name = key.toString(); // Our type is generally determined by our type parameter, but some APIs use raw untyped KeyV1s to return multiple types. this.type = "Key<" + this.getKeyedClassType() + ">"; if ("Keyed".equals(this.type)) { // get the actual type, if the key points to a value in the DKV String vc = key.valueClassSimple(); if (null != vc) { this.type = "Key<" + vc + ">"; } } Class<? extends Keyed> keyed_class = this.getKeyedClass(); // TODO: this is kinda hackey; the handlers should register the types they can fetch. if (Job.class.isAssignableFrom(keyed_class)) this.URL = "/" + Schema.getHighestSupportedVersion() + "/Jobs/" + key.toString(); else if (Frame.class.isAssignableFrom(keyed_class)) this.URL = "/" + Schema.getHighestSupportedVersion() + "/Frames/" + key.toString(); else if (Model.class.isAssignableFrom(keyed_class)) this.URL = "/" + Schema.getHighestSupportedVersion() + "/Models/" + key.toString(); else if (Vec.class.isAssignableFrom(keyed_class)) this.URL = null; else this.URL = null; return (S)this; } public static Class<? extends Keyed> getKeyedClass(Class<? extends KeyV3> clz) { // (Only) if we're a subclass of KeyV1 the Keyed class is type parameter 2. if (clz == KeyV3.class) return Keyed.class; return (Class<? extends Keyed>) ReflectionUtils.findActualClassParameter(clz, 2); } public Class<? extends Keyed> getKeyedClass() { return getKeyedClass(this.getClass()); } public static String getKeyedClassType(Class<? extends KeyV3> clz) { Class<? extends Keyed> keyed_class = getKeyedClass(clz); return keyed_class.getSimpleName(); } public String getKeyedClassType() { return getKeyedClassType(this.getClass()); } public Key<K> key() { if (null == name) return null; return Key.make(this.name); } @Override public I createImpl() { return (I)Key.make(this.name); } @Override public String toString() { return type + " " + name; } }
package org.hl7.v3; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; @XmlRegistry public class ObjectFactory { private static final QName _ClinicalDocument_QNAME = new QName("urn:hl7-org:v3", "ClinicalDocument"); private static final QName _ENSuffix_QNAME = new QName("urn:hl7-org:v3", "suffix"); private static final QName _ENDelimiter_QNAME = new QName("urn:hl7-org:v3", "delimiter"); private static final QName _ENValidTime_QNAME = new QName("urn:hl7-org:v3", "validTime"); private static final QName _ENPrefix_QNAME = new QName("urn:hl7-org:v3", "prefix"); private static final QName _ENFamily_QNAME = new QName("urn:hl7-org:v3", "family"); private static final QName _ENGiven_QNAME = new QName("urn:hl7-org:v3", "given"); private static final QName _StrucDocItemTable_QNAME = new QName("urn:hl7-org:v3", "table"); private static final QName _StrucDocItemList_QNAME = new QName("urn:hl7-org:v3", "list"); private static final QName _StrucDocItemCaption_QNAME = new QName("urn:hl7-org:v3", "caption"); private static final QName _StrucDocItemRenderMultiMedia_QNAME = new QName("urn:hl7-org:v3", "renderMultiMedia"); private static final QName _StrucDocItemBr_QNAME = new QName("urn:hl7-org:v3", "br"); private static final QName _StrucDocItemLinkHtml_QNAME = new QName("urn:hl7-org:v3", "linkHtml"); private static final QName _StrucDocItemSup_QNAME = new QName("urn:hl7-org:v3", "sup"); private static final QName _StrucDocItemSub_QNAME = new QName("urn:hl7-org:v3", "sub"); private static final QName _StrucDocItemContent_QNAME = new QName("urn:hl7-org:v3", "content"); private static final QName _StrucDocItemFootnoteRef_QNAME = new QName("urn:hl7-org:v3", "footnoteRef"); private static final QName _StrucDocItemFootnote_QNAME = new QName("urn:hl7-org:v3", "footnote"); private static final QName _StrucDocItemParagraph_QNAME = new QName("urn:hl7-org:v3", "paragraph"); private static final QName _IVLINTHigh_QNAME = new QName("urn:hl7-org:v3", "high"); private static final QName _IVLINTLow_QNAME = new QName("urn:hl7-org:v3", "low"); private static final QName _IVLINTCenter_QNAME = new QName("urn:hl7-org:v3", "center"); private static final QName _IVLINTWidth_QNAME = new QName("urn:hl7-org:v3", "width"); private static final QName _ADDeliveryModeIdentifier_QNAME = new QName("urn:hl7-org:v3", "deliveryModeIdentifier"); private static final QName _ADHouseNumber_QNAME = new QName("urn:hl7-org:v3", "houseNumber"); private static final QName _ADState_QNAME = new QName("urn:hl7-org:v3", "state"); private static final QName _ADCity_QNAME = new QName("urn:hl7-org:v3", "city"); private static final QName _ADAdditionalLocator_QNAME = new QName("urn:hl7-org:v3", "additionalLocator"); private static final QName _ADStreetAddressLine_QNAME = new QName("urn:hl7-org:v3", "streetAddressLine"); private static final QName _ADDeliveryInstallationArea_QNAME = new QName("urn:hl7-org:v3", "deliveryInstallationArea"); private static final QName _ADStreetNameType_QNAME = new QName("urn:hl7-org:v3", "streetNameType"); private static final QName _ADDeliveryInstallationQualifier_QNAME = new QName("urn:hl7-org:v3", "deliveryInstallationQualifier"); private static final QName _ADDirection_QNAME = new QName("urn:hl7-org:v3", "direction"); private static final QName _ADCensusTract_QNAME = new QName("urn:hl7-org:v3", "censusTract"); private static final QName _ADUnitID_QNAME = new QName("urn:hl7-org:v3", "unitID"); private static final QName _ADPostalCode_QNAME = new QName("urn:hl7-org:v3", "postalCode"); private static final QName _ADStreetName_QNAME = new QName("urn:hl7-org:v3", "streetName"); private static final QName _ADDeliveryInstallationType_QNAME = new QName("urn:hl7-org:v3", "deliveryInstallationType"); private static final QName _ADStreetNameBase_QNAME = new QName("urn:hl7-org:v3", "streetNameBase"); private static final QName _ADDeliveryMode_QNAME = new QName("urn:hl7-org:v3", "deliveryMode"); private static final QName _ADPostBox_QNAME = new QName("urn:hl7-org:v3", "postBox"); private static final QName _ADCountry_QNAME = new QName("urn:hl7-org:v3", "country"); private static final QName _ADDeliveryAddressLine_QNAME = new QName("urn:hl7-org:v3", "deliveryAddressLine"); private static final QName _ADUseablePeriod_QNAME = new QName("urn:hl7-org:v3", "useablePeriod"); private static final QName _ADCareOf_QNAME = new QName("urn:hl7-org:v3", "careOf"); private static final QName _ADUnitType_QNAME = new QName("urn:hl7-org:v3", "unitType"); private static final QName _ADPrecinct_QNAME = new QName("urn:hl7-org:v3", "precinct"); private static final QName _ADHouseNumberNumeric_QNAME = new QName("urn:hl7-org:v3", "houseNumberNumeric"); private static final QName _ADBuildingNumberSuffix_QNAME = new QName("urn:hl7-org:v3", "buildingNumberSuffix"); private static final QName _ADCounty_QNAME = new QName("urn:hl7-org:v3", "county"); public POCDMT000040ClinicalDocument createPOCDMT000040ClinicalDocument() { return new POCDMT000040ClinicalDocument(); } public POCDMT000040Specimen createPOCDMT000040Specimen() { return new POCDMT000040Specimen(); } public POCDMT000040RegionOfInterestValue createPOCDMT000040RegionOfInterestValue() { return new POCDMT000040RegionOfInterestValue(); } public BXITIVLPQ createBXITIVLPQ() { return new BXITIVLPQ(); } public ED createED() { return new ED(); } public StrucDocBr createStrucDocBr() { return new StrucDocBr(); } public POCDMT000040ReferenceRange createPOCDMT000040ReferenceRange() { return new POCDMT000040ReferenceRange(); } public POCDMT000040CustodianOrganization createPOCDMT000040CustodianOrganization() { return new POCDMT000040CustodianOrganization(); } public POCDMT000040ExternalDocument createPOCDMT000040ExternalDocument() { return new POCDMT000040ExternalDocument(); } public POCDMT000040Product createPOCDMT000040Product() { return new POCDMT000040Product(); } public POCDMT000040ExternalProcedure createPOCDMT000040ExternalProcedure() { return new POCDMT000040ExternalProcedure(); } public AdxpDeliveryMode createAdxpDeliveryMode() { return new AdxpDeliveryMode(); } public EN createEN() { return new EN(); } public ANYNonNull createANYNonNull() { return new ANYNonNull(); } public StrucDocTitleFootnote createStrucDocTitleFootnote() { return new StrucDocTitleFootnote(); } public SXCMPQ createSXCMPQ() { return new SXCMPQ(); } public StrucDocColgroup createStrucDocColgroup() { return new StrucDocColgroup(); } public POCDMT000040AssociatedEntity createPOCDMT000040AssociatedEntity() { return new POCDMT000040AssociatedEntity(); } public POCDMT000040MaintainedEntity createPOCDMT000040MaintainedEntity() { return new POCDMT000040MaintainedEntity(); } public AdxpDeliveryInstallationType createAdxpDeliveryInstallationType() { return new AdxpDeliveryInstallationType(); } public AdxpDelimiter createAdxpDelimiter() { return new AdxpDelimiter(); } public INT createINT() { return new INT(); } public EIVLTS createEIVLTS() { return new EIVLTS(); } public POCDMT000040RecordTarget createPOCDMT000040RecordTarget() { return new POCDMT000040RecordTarget(); } public POCDMT000040ExternalObservation createPOCDMT000040ExternalObservation() { return new POCDMT000040ExternalObservation(); } public POCDMT000040Device createPOCDMT000040Device() { return new POCDMT000040Device(); } public UVPTS createUVPTS() { return new UVPTS(); } public POCDMT000040SubstanceAdministration createPOCDMT000040SubstanceAdministration() { return new POCDMT000040SubstanceAdministration(); } public POCDMT000040Custodian createPOCDMT000040Custodian() { return new POCDMT000040Custodian(); } public POCDMT000040Component1 createPOCDMT000040Component1() { return new POCDMT000040Component1(); } public POCDMT000040Component2 createPOCDMT000040Component2() { return new POCDMT000040Component2(); } public POCDMT000040Component3 createPOCDMT000040Component3() { return new POCDMT000040Component3(); } public POCDMT000040Component4 createPOCDMT000040Component4() { return new POCDMT000040Component4(); } public POCDMT000040Component5 createPOCDMT000040Component5() { return new POCDMT000040Component5(); } public AdxpPrecinct createAdxpPrecinct() { return new AdxpPrecinct(); } public POCDMT000040Consent createPOCDMT000040Consent() { return new POCDMT000040Consent(); } public POCDMT000040ParticipantRole createPOCDMT000040ParticipantRole() { return new POCDMT000040ParticipantRole(); } public POCDMT000040Reference createPOCDMT000040Reference() { return new POCDMT000040Reference(); } public POCDMT000040Participant1 createPOCDMT000040Participant1() { return new POCDMT000040Participant1(); } public POCDMT000040Participant2 createPOCDMT000040Participant2() { return new POCDMT000040Participant2(); } public POCDMT000040Author createPOCDMT000040Author() { return new POCDMT000040Author(); } public POCDMT000040Subject createPOCDMT000040Subject() { return new POCDMT000040Subject(); } public AD createAD() { return new AD(); } public AdxpStreetAddressLine createAdxpStreetAddressLine() { return new AdxpStreetAddressLine(); } public StrucDocFootnoteRef createStrucDocFootnoteRef() { return new StrucDocFootnoteRef(); } public POCDMT000040RelatedDocument createPOCDMT000040RelatedDocument() { return new POCDMT000040RelatedDocument(); } public SXCMMO createSXCMMO() { return new SXCMMO(); } public BN createBN() { return new BN(); } public BL createBL() { return new BL(); } public CV createCV() { return new CV(); } public EnDelimiter createEnDelimiter() { return new EnDelimiter(); } public CS createCS() { return new CS(); } public SLISTPQ createSLISTPQ() { return new SLISTPQ(); } public StrucDocParagraph createStrucDocParagraph() { return new StrucDocParagraph(); } public CE createCE() { return new CE(); } public CD createCD() { return new CD(); } public AdxpUnitType createAdxpUnitType() { return new AdxpUnitType(); } public CR createCR() { return new CR(); } public POCDMT000040AuthoringDevice createPOCDMT000040AuthoringDevice() { return new POCDMT000040AuthoringDevice(); } public CO createCO() { return new CO(); } public IVLPPDTS createIVLPPDTS() { return new IVLPPDTS(); } public AdxpCountry createAdxpCountry() { return new AdxpCountry(); } public AdxpHouseNumberNumeric createAdxpHouseNumberNumeric() { return new AdxpHouseNumberNumeric(); } public POCDMT000040Authorization createPOCDMT000040Authorization() { return new POCDMT000040Authorization(); } public StrucDocTable createStrucDocTable() { return new StrucDocTable(); } public IVXBREAL createIVXBREAL() { return new IVXBREAL(); } public POCDMT000040InFulfillmentOf createPOCDMT000040InFulfillmentOf() { return new POCDMT000040InFulfillmentOf(); } public POCDMT000040ManufacturedProduct createPOCDMT000040ManufacturedProduct() { return new POCDMT000040ManufacturedProduct(); } public AdxpUnitID createAdxpUnitID() { return new AdxpUnitID(); } public AdxpCareOf createAdxpCareOf() { return new AdxpCareOf(); } public POCDMT000040Observation createPOCDMT000040Observation() { return new POCDMT000040Observation(); } public POCDMT000040SpecimenRole createPOCDMT000040SpecimenRole() { return new POCDMT000040SpecimenRole(); } public StrucDocFootnote createStrucDocFootnote() { return new StrucDocFootnote(); } public EnPrefix createEnPrefix() { return new EnPrefix(); } public POCDMT000040Consumable createPOCDMT000040Consumable() { return new POCDMT000040Consumable(); } public POCDMT000040Organization createPOCDMT000040Organization() { return new POCDMT000040Organization(); } public MO createMO() { return new MO(); } public POCDMT000040Birthplace createPOCDMT000040Birthplace() { return new POCDMT000040Birthplace(); } public IVXBTS createIVXBTS() { return new IVXBTS(); } public ON createON() { return new ON(); } public PPDPQ createPPDPQ() { return new PPDPQ(); } public TEL createTEL() { return new TEL(); } public POCDMT000040ObservationMedia createPOCDMT000040ObservationMedia() { return new POCDMT000040ObservationMedia(); } public RTOPQPQ createRTOPQPQ() { return new RTOPQPQ(); } public PN createPN() { return new PN(); } public EnSuffix createEnSuffix() { return new EnSuffix(); } public AdxpDeliveryInstallationQualifier createAdxpDeliveryInstallationQualifier() { return new AdxpDeliveryInstallationQualifier(); } public AdxpCounty createAdxpCounty() { return new AdxpCounty(); } public POCDMT000040Material createPOCDMT000040Material() { return new POCDMT000040Material(); } public POCDMT000040Place createPOCDMT000040Place() { return new POCDMT000040Place(); } public POCDMT000040NonXMLBody createPOCDMT000040NonXMLBody() { return new POCDMT000040NonXMLBody(); } public StrucDocList createStrucDocList() { return new StrucDocList(); } public IVLPPDPQ createIVLPPDPQ() { return new IVLPPDPQ(); } public HXITPQ createHXITPQ() { return new HXITPQ(); } public StrucDocThead createStrucDocThead() { return new StrucDocThead(); } public AdxpHouseNumber createAdxpHouseNumber() { return new AdxpHouseNumber(); } public StrucDocTfoot createStrucDocTfoot() { return new StrucDocTfoot(); } public EIVLPPDTS createEIVLPPDTS() { return new EIVLPPDTS(); } public II createII() { return new II(); } public StrucDocCol createStrucDocCol() { return new StrucDocCol(); } public IVLINT createIVLINT() { return new IVLINT(); } public IVXBPQ createIVXBPQ() { return new IVXBPQ(); } public SXCMTS createSXCMTS() { return new SXCMTS(); } public POCDMT000040RegionOfInterest createPOCDMT000040RegionOfInterest() { return new POCDMT000040RegionOfInterest(); } public EnGiven createEnGiven() { return new EnGiven(); } public POCDMT000040AssignedCustodian createPOCDMT000040AssignedCustodian() { return new POCDMT000040AssignedCustodian(); } public POCDMT000040Entry createPOCDMT000040Entry() { return new POCDMT000040Entry(); } public StrucDocTitle createStrucDocTitle() { return new StrucDocTitle(); } public IVXBMO createIVXBMO() { return new IVXBMO(); } public POCDMT000040ParentDocument createPOCDMT000040ParentDocument() { return new POCDMT000040ParentDocument(); } public POCDMT000040RelatedSubject createPOCDMT000040RelatedSubject() { return new POCDMT000040RelatedSubject(); } public POCDMT000040StructuredBody createPOCDMT000040StructuredBody() { return new POCDMT000040StructuredBody(); } public POCDMT000040Performer1 createPOCDMT000040Performer1() { return new POCDMT000040Performer1(); } public POCDMT000040InfrastructureRootTypeId createPOCDMT000040InfrastructureRootTypeId() { return new POCDMT000040InfrastructureRootTypeId(); } public StrucDocContent createStrucDocContent() { return new StrucDocContent(); } public POCDMT000040Performer2 createPOCDMT000040Performer2() { return new POCDMT000040Performer2(); } public POCDMT000040AssignedAuthor createPOCDMT000040AssignedAuthor() { return new POCDMT000040AssignedAuthor(); } public POCDMT000040EncompassingEncounter createPOCDMT000040EncompassingEncounter() { return new POCDMT000040EncompassingEncounter(); } public StrucDocTr createStrucDocTr() { return new StrucDocTr(); } public POCDMT000040RelatedEntity createPOCDMT000040RelatedEntity() { return new POCDMT000040RelatedEntity(); } public POCDMT000040Order createPOCDMT000040Order() { return new POCDMT000040Order(); } public StrucDocTd createStrucDocTd() { return new StrucDocTd(); } public AdxpBuildingNumberSuffix createAdxpBuildingNumberSuffix() { return new AdxpBuildingNumberSuffix(); } public StrucDocTh createStrucDocTh() { return new StrucDocTh(); } public IVXBPPDTS createIVXBPPDTS() { return new IVXBPPDTS(); } public IVLTS createIVLTS() { return new IVLTS(); } public SXPRTS createSXPRTS() { return new SXPRTS(); } public PIVLTS createPIVLTS() { return new PIVLTS(); } public POCDMT000040Entity createPOCDMT000040Entity() { return new POCDMT000040Entity(); } public POCDMT000040Procedure createPOCDMT000040Procedure() { return new POCDMT000040Procedure(); } public POCDMT000040PlayingEntity createPOCDMT000040PlayingEntity() { return new POCDMT000040PlayingEntity(); } public POCDMT000040ExternalAct createPOCDMT000040ExternalAct() { return new POCDMT000040ExternalAct(); } public IVLPQ createIVLPQ() { return new IVLPQ(); } public StrucDocTbody createStrucDocTbody() { return new StrucDocTbody(); } public AdxpCensusTract createAdxpCensusTract() { return new AdxpCensusTract(); } public POCDMT000040ServiceEvent createPOCDMT000040ServiceEvent() { return new POCDMT000040ServiceEvent(); } public REAL createREAL() { return new REAL(); } public POCDMT000040Organizer createPOCDMT000040Organizer() { return new POCDMT000040Organizer(); } public PIVLPPDTS createPIVLPPDTS() { return new PIVLPPDTS(); } public POCDMT000040SubjectPerson createPOCDMT000040SubjectPerson() { return new POCDMT000040SubjectPerson(); } public ENXP createENXP() { return new ENXP(); } public IVLREAL createIVLREAL() { return new IVLREAL(); } public SXCMPPDTS createSXCMPPDTS() { return new SXCMPPDTS(); } public POCDMT000040LanguageCommunication createPOCDMT000040LanguageCommunication() { return new POCDMT000040LanguageCommunication(); } public POCDMT000040HealthCareFacility createPOCDMT000040HealthCareFacility() { return new POCDMT000040HealthCareFacility(); } public IVXBPPDPQ createIVXBPPDPQ() { return new IVXBPPDPQ(); } public AdxpDeliveryAddressLine createAdxpDeliveryAddressLine() { return new AdxpDeliveryAddressLine(); } public StrucDocCaption createStrucDocCaption() { return new StrucDocCaption(); } public PQ createPQ() { return new PQ(); } public AdxpDeliveryModeIdentifier createAdxpDeliveryModeIdentifier() { return new AdxpDeliveryModeIdentifier(); } public StrucDocItem createStrucDocItem() { return new StrucDocItem(); } public POCDMT000040InformationRecipient createPOCDMT000040InformationRecipient() { return new POCDMT000040InformationRecipient(); } public TN createTN() { return new TN(); } public TS createTS() { return new TS(); } public POCDMT000040LabeledDrug createPOCDMT000040LabeledDrug() { return new POCDMT000040LabeledDrug(); } public POCDMT000040Section createPOCDMT000040Section() { return new POCDMT000040Section(); } public ST createST() { return new ST(); } public AdxpStreetName createAdxpStreetName() { return new AdxpStreetName(); } public AdxpStreetNameType createAdxpStreetNameType() { return new AdxpStreetNameType(); } public AdxpDirection createAdxpDirection() { return new AdxpDirection(); } public SC createSC() { return new SC(); } public PPDTS createPPDTS() { return new PPDTS(); } public POCDMT000040EncounterParticipant createPOCDMT000040EncounterParticipant() { return new POCDMT000040EncounterParticipant(); } public IVLMO createIVLMO() { return new IVLMO(); } public POCDMT000040Criterion createPOCDMT000040Criterion() { return new POCDMT000040Criterion(); } public POCDMT000040IntendedRecipient createPOCDMT000040IntendedRecipient() { return new POCDMT000040IntendedRecipient(); } public StrucDocRenderMultiMedia createStrucDocRenderMultiMedia() { return new StrucDocRenderMultiMedia(); } public AdxpState createAdxpState() { return new AdxpState(); } public AdxpCity createAdxpCity() { return new AdxpCity(); } public RTOMOPQ createRTOMOPQ() { return new RTOMOPQ(); } public POCDMT000040PatientRole createPOCDMT000040PatientRole() { return new POCDMT000040PatientRole(); } public SXCMPPDPQ createSXCMPPDPQ() { return new SXCMPPDPQ(); } public RTOQTYQTY createRTOQTYQTY() { return new RTOQTYQTY(); } public POCDMT000040Authenticator createPOCDMT000040Authenticator() { return new POCDMT000040Authenticator(); } public POCDMT000040Encounter createPOCDMT000040Encounter() { return new POCDMT000040Encounter(); } public IVXBINT createIVXBINT() { return new IVXBINT(); } public POCDMT000040LegalAuthenticator createPOCDMT000040LegalAuthenticator() { return new POCDMT000040LegalAuthenticator(); } public POCDMT000040ObservationRange createPOCDMT000040ObservationRange() { return new POCDMT000040ObservationRange(); } public StrucDocSub createStrucDocSub() { return new StrucDocSub(); } public AdxpPostalCode createAdxpPostalCode() { return new AdxpPostalCode(); } public SXCMREAL createSXCMREAL() { return new SXCMREAL(); } public POCDMT000040Patient createPOCDMT000040Patient() { return new POCDMT000040Patient(); } public StrucDocSup createStrucDocSup() { return new StrucDocSup(); } public SLISTTS createSLISTTS() { return new SLISTTS(); } public BXITCD createBXITCD() { return new BXITCD(); } public GLISTTS createGLISTTS() { return new GLISTTS(); } public POCDMT000040ResponsibleParty createPOCDMT000040ResponsibleParty() { return new POCDMT000040ResponsibleParty(); } public PQR createPQR() { return new PQR(); } public POCDMT000040Guardian createPOCDMT000040Guardian() { return new POCDMT000040Guardian(); } public EIVLEvent createEIVLEvent() { return new EIVLEvent(); } public StrucDocLinkHtml createStrucDocLinkHtml() { return new StrucDocLinkHtml(); } public POCDMT000040Informant12 createPOCDMT000040Informant12() { return new POCDMT000040Informant12(); } public SXCMCD createSXCMCD() { return new SXCMCD(); } public POCDMT000040AssignedEntity createPOCDMT000040AssignedEntity() { return new POCDMT000040AssignedEntity(); } public AdxpStreetNameBase createAdxpStreetNameBase() { return new AdxpStreetNameBase(); } public Thumbnail createThumbnail() { return new Thumbnail(); } public POCDMT000040Act createPOCDMT000040Act() { return new POCDMT000040Act(); } public StrucDocTitleContent createStrucDocTitleContent() { return new StrucDocTitleContent(); } public POCDMT000040DocumentationOf createPOCDMT000040DocumentationOf() { return new POCDMT000040DocumentationOf(); } public SXCMINT createSXCMINT() { return new SXCMINT(); } public AdxpAdditionalLocator createAdxpAdditionalLocator() { return new AdxpAdditionalLocator(); } public RTO createRTO() { return new RTO(); } public HXITCE createHXITCE() { return new HXITCE(); } public GLISTPQ createGLISTPQ() { return new GLISTPQ(); } public POCDMT000040DataEnterer createPOCDMT000040DataEnterer() { return new POCDMT000040DataEnterer(); } public POCDMT000040OrganizationPartOf createPOCDMT000040OrganizationPartOf() { return new POCDMT000040OrganizationPartOf(); } public POCDMT000040Precondition createPOCDMT000040Precondition() { return new POCDMT000040Precondition(); } public StrucDocText createStrucDocText() { return new StrucDocText(); } public AdxpPostBox createAdxpPostBox() { return new AdxpPostBox(); } public ADXP createADXP() { return new ADXP(); } public POCDMT000040Supply createPOCDMT000040Supply() { return new POCDMT000040Supply(); } public POCDMT000040EntryRelationship createPOCDMT000040EntryRelationship() { return new POCDMT000040EntryRelationship(); } public AdxpDeliveryInstallationArea createAdxpDeliveryInstallationArea() { return new AdxpDeliveryInstallationArea(); } public POCDMT000040Location createPOCDMT000040Location() { return new POCDMT000040Location(); } public POCDMT000040Person createPOCDMT000040Person() { return new POCDMT000040Person(); } public EnFamily createEnFamily() { return new EnFamily(); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="ClinicalDocument") public JAXBElement<POCDMT000040ClinicalDocument> createClinicalDocument(POCDMT000040ClinicalDocument value) { return new JAXBElement(_ClinicalDocument_QNAME, POCDMT000040ClinicalDocument.class, null, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="suffix", scope=EN.class) public JAXBElement<EnSuffix> createENSuffix(EnSuffix value) { return new JAXBElement(_ENSuffix_QNAME, EnSuffix.class, EN.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="delimiter", scope=EN.class) public JAXBElement<EnDelimiter> createENDelimiter(EnDelimiter value) { return new JAXBElement(_ENDelimiter_QNAME, EnDelimiter.class, EN.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="validTime", scope=EN.class) public JAXBElement<IVLTS> createENValidTime(IVLTS value) { return new JAXBElement(_ENValidTime_QNAME, IVLTS.class, EN.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="prefix", scope=EN.class) public JAXBElement<EnPrefix> createENPrefix(EnPrefix value) { return new JAXBElement(_ENPrefix_QNAME, EnPrefix.class, EN.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="family", scope=EN.class) public JAXBElement<EnFamily> createENFamily(EnFamily value) { return new JAXBElement(_ENFamily_QNAME, EnFamily.class, EN.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="given", scope=EN.class) public JAXBElement<EnGiven> createENGiven(EnGiven value) { return new JAXBElement(_ENGiven_QNAME, EnGiven.class, EN.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="table", scope=StrucDocItem.class) public JAXBElement<StrucDocTable> createStrucDocItemTable(StrucDocTable value) { return new JAXBElement(_StrucDocItemTable_QNAME, StrucDocTable.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="list", scope=StrucDocItem.class) public JAXBElement<StrucDocList> createStrucDocItemList(StrucDocList value) { return new JAXBElement(_StrucDocItemList_QNAME, StrucDocList.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="caption", scope=StrucDocItem.class) public JAXBElement<StrucDocCaption> createStrucDocItemCaption(StrucDocCaption value) { return new JAXBElement(_StrucDocItemCaption_QNAME, StrucDocCaption.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocItem.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocItemRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocItem.class) public JAXBElement<StrucDocBr> createStrucDocItemBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocItem.class) public JAXBElement<StrucDocLinkHtml> createStrucDocItemLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocItem.class) public JAXBElement<StrucDocSup> createStrucDocItemSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocItem.class) public JAXBElement<StrucDocSub> createStrucDocItemSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocItem.class) public JAXBElement<StrucDocContent> createStrucDocItemContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocItem.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocItemFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocItem.class) public JAXBElement<StrucDocFootnote> createStrucDocItemFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="paragraph", scope=StrucDocItem.class) public JAXBElement<StrucDocParagraph> createStrucDocItemParagraph(StrucDocParagraph value) { return new JAXBElement(_StrucDocItemParagraph_QNAME, StrucDocParagraph.class, StrucDocItem.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocContent.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocContentRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocContent.class) public JAXBElement<StrucDocBr> createStrucDocContentBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocContent.class) public JAXBElement<StrucDocLinkHtml> createStrucDocContentLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocContent.class) public JAXBElement<StrucDocSup> createStrucDocContentSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocContent.class) public JAXBElement<StrucDocSub> createStrucDocContentSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocContent.class) public JAXBElement<StrucDocContent> createStrucDocContentContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocContent.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocContentFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocContent.class) public JAXBElement<StrucDocFootnote> createStrucDocContentFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLINT.class) public JAXBElement<IVXBINT> createIVLINTHigh(IVXBINT value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBINT.class, IVLINT.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLINT.class) public JAXBElement<IVXBINT> createIVLINTLow(IVXBINT value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBINT.class, IVLINT.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLINT.class) public JAXBElement<INT> createIVLINTCenter(INT value) { return new JAXBElement(_IVLINTCenter_QNAME, INT.class, IVLINT.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLINT.class) public JAXBElement<INT> createIVLINTWidth(INT value) { return new JAXBElement(_IVLINTWidth_QNAME, INT.class, IVLINT.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLPPDPQ.class) public JAXBElement<IVXBPPDPQ> createIVLPPDPQHigh(IVXBPPDPQ value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBPPDPQ.class, IVLPPDPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLPPDPQ.class) public JAXBElement<IVXBPPDPQ> createIVLPPDPQLow(IVXBPPDPQ value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBPPDPQ.class, IVLPPDPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLPPDPQ.class) public JAXBElement<PPDPQ> createIVLPPDPQCenter(PPDPQ value) { return new JAXBElement(_IVLINTCenter_QNAME, PPDPQ.class, IVLPPDPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLPPDPQ.class) public JAXBElement<PPDPQ> createIVLPPDPQWidth(PPDPQ value) { return new JAXBElement(_IVLINTWidth_QNAME, PPDPQ.class, IVLPPDPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="list", scope=StrucDocTd.class) public JAXBElement<StrucDocList> createStrucDocTdList(StrucDocList value) { return new JAXBElement(_StrucDocItemList_QNAME, StrucDocList.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocTd.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocTdRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocTd.class) public JAXBElement<StrucDocBr> createStrucDocTdBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocTd.class) public JAXBElement<StrucDocLinkHtml> createStrucDocTdLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocTd.class) public JAXBElement<StrucDocSup> createStrucDocTdSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocTd.class) public JAXBElement<StrucDocSub> createStrucDocTdSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocTd.class) public JAXBElement<StrucDocContent> createStrucDocTdContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocTd.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocTdFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocTd.class) public JAXBElement<StrucDocFootnote> createStrucDocTdFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="paragraph", scope=StrucDocTd.class) public JAXBElement<StrucDocParagraph> createStrucDocTdParagraph(StrucDocParagraph value) { return new JAXBElement(_StrucDocItemParagraph_QNAME, StrucDocParagraph.class, StrucDocTd.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocTitle.class) public JAXBElement<StrucDocBr> createStrucDocTitleBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocTitle.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocTitle.class) public JAXBElement<StrucDocSup> createStrucDocTitleSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocTitle.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocTitle.class) public JAXBElement<StrucDocSub> createStrucDocTitleSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocTitle.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocTitle.class) public JAXBElement<StrucDocTitleContent> createStrucDocTitleContent(StrucDocTitleContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocTitleContent.class, StrucDocTitle.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocTitle.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocTitleFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocTitle.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocTitle.class) public JAXBElement<StrucDocTitleFootnote> createStrucDocTitleFootnote(StrucDocTitleFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocTitleFootnote.class, StrucDocTitle.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="table", scope=StrucDocText.class) public JAXBElement<StrucDocTable> createStrucDocTextTable(StrucDocTable value) { return new JAXBElement(_StrucDocItemTable_QNAME, StrucDocTable.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="list", scope=StrucDocText.class) public JAXBElement<StrucDocList> createStrucDocTextList(StrucDocList value) { return new JAXBElement(_StrucDocItemList_QNAME, StrucDocList.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocText.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocTextRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocText.class) public JAXBElement<StrucDocBr> createStrucDocTextBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocText.class) public JAXBElement<StrucDocLinkHtml> createStrucDocTextLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocText.class) public JAXBElement<StrucDocSup> createStrucDocTextSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocText.class) public JAXBElement<StrucDocSub> createStrucDocTextSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocText.class) public JAXBElement<StrucDocContent> createStrucDocTextContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocText.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocTextFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocText.class) public JAXBElement<StrucDocFootnote> createStrucDocTextFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="paragraph", scope=StrucDocText.class) public JAXBElement<StrucDocParagraph> createStrucDocTextParagraph(StrucDocParagraph value) { return new JAXBElement(_StrucDocItemParagraph_QNAME, StrucDocParagraph.class, StrucDocText.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocTh.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocThRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocTh.class) public JAXBElement<StrucDocBr> createStrucDocThBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocTh.class) public JAXBElement<StrucDocLinkHtml> createStrucDocThLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocTh.class) public JAXBElement<StrucDocSup> createStrucDocThSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocTh.class) public JAXBElement<StrucDocSub> createStrucDocThSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocTh.class) public JAXBElement<StrucDocContent> createStrucDocThContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocTh.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocThFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocTh.class) public JAXBElement<StrucDocFootnote> createStrucDocThFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocTh.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="caption", scope=StrucDocParagraph.class) public JAXBElement<StrucDocCaption> createStrucDocParagraphCaption(StrucDocCaption value) { return new JAXBElement(_StrucDocItemCaption_QNAME, StrucDocCaption.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocParagraph.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocParagraphRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocParagraph.class) public JAXBElement<StrucDocBr> createStrucDocParagraphBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocParagraph.class) public JAXBElement<StrucDocLinkHtml> createStrucDocParagraphLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocParagraph.class) public JAXBElement<StrucDocSup> createStrucDocParagraphSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocParagraph.class) public JAXBElement<StrucDocSub> createStrucDocParagraphSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocParagraph.class) public JAXBElement<StrucDocContent> createStrucDocParagraphContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocParagraph.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocParagraphFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocParagraph.class) public JAXBElement<StrucDocFootnote> createStrucDocParagraphFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocParagraph.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocLinkHtml.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocLinkHtmlFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocLinkHtml.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocLinkHtml.class) public JAXBElement<StrucDocFootnote> createStrucDocLinkHtmlFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocLinkHtml.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocTitleContent.class) public JAXBElement<StrucDocBr> createStrucDocTitleContentBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocTitleContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocTitleContent.class) public JAXBElement<StrucDocSup> createStrucDocTitleContentSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocTitleContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocTitleContent.class) public JAXBElement<StrucDocSub> createStrucDocTitleContentSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocTitleContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocTitleContent.class) public JAXBElement<StrucDocTitleContent> createStrucDocTitleContentContent(StrucDocTitleContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocTitleContent.class, StrucDocTitleContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocTitleContent.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocTitleContentFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocTitleContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocTitleContent.class) public JAXBElement<StrucDocTitleFootnote> createStrucDocTitleContentFootnote(StrucDocTitleFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocTitleFootnote.class, StrucDocTitleContent.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocCaption.class) public JAXBElement<StrucDocLinkHtml> createStrucDocCaptionLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocCaption.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocCaption.class) public JAXBElement<StrucDocSup> createStrucDocCaptionSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocCaption.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocCaption.class) public JAXBElement<StrucDocSub> createStrucDocCaptionSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocCaption.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnoteRef", scope=StrucDocCaption.class) public JAXBElement<StrucDocFootnoteRef> createStrucDocCaptionFootnoteRef(StrucDocFootnoteRef value) { return new JAXBElement(_StrucDocItemFootnoteRef_QNAME, StrucDocFootnoteRef.class, StrucDocCaption.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="footnote", scope=StrucDocCaption.class) public JAXBElement<StrucDocFootnote> createStrucDocCaptionFootnote(StrucDocFootnote value) { return new JAXBElement(_StrucDocItemFootnote_QNAME, StrucDocFootnote.class, StrucDocCaption.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLTS.class) public JAXBElement<IVXBTS> createIVLTSHigh(IVXBTS value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBTS.class, IVLTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLTS.class) public JAXBElement<IVXBTS> createIVLTSLow(IVXBTS value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBTS.class, IVLTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLTS.class) public JAXBElement<TS> createIVLTSCenter(TS value) { return new JAXBElement(_IVLINTCenter_QNAME, TS.class, IVLTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLTS.class) public JAXBElement<PQ> createIVLTSWidth(PQ value) { return new JAXBElement(_IVLINTWidth_QNAME, PQ.class, IVLTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocTitleFootnote.class) public JAXBElement<StrucDocBr> createStrucDocTitleFootnoteBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocTitleFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocTitleFootnote.class) public JAXBElement<StrucDocSup> createStrucDocTitleFootnoteSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocTitleFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocTitleFootnote.class) public JAXBElement<StrucDocSub> createStrucDocTitleFootnoteSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocTitleFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocTitleFootnote.class) public JAXBElement<StrucDocTitleContent> createStrucDocTitleFootnoteContent(StrucDocTitleContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocTitleContent.class, StrucDocTitleFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="deliveryModeIdentifier", scope=AD.class) public JAXBElement<AdxpDeliveryModeIdentifier> createADDeliveryModeIdentifier(AdxpDeliveryModeIdentifier value) { return new JAXBElement(_ADDeliveryModeIdentifier_QNAME, AdxpDeliveryModeIdentifier.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="houseNumber", scope=AD.class) public JAXBElement<AdxpHouseNumber> createADHouseNumber(AdxpHouseNumber value) { return new JAXBElement(_ADHouseNumber_QNAME, AdxpHouseNumber.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="state", scope=AD.class) public JAXBElement<AdxpState> createADState(AdxpState value) { return new JAXBElement(_ADState_QNAME, AdxpState.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="city", scope=AD.class) public JAXBElement<AdxpCity> createADCity(AdxpCity value) { return new JAXBElement(_ADCity_QNAME, AdxpCity.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="additionalLocator", scope=AD.class) public JAXBElement<AdxpAdditionalLocator> createADAdditionalLocator(AdxpAdditionalLocator value) { return new JAXBElement(_ADAdditionalLocator_QNAME, AdxpAdditionalLocator.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="streetAddressLine", scope=AD.class) public JAXBElement<AdxpStreetAddressLine> createADStreetAddressLine(AdxpStreetAddressLine value) { return new JAXBElement(_ADStreetAddressLine_QNAME, AdxpStreetAddressLine.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="deliveryInstallationArea", scope=AD.class) public JAXBElement<AdxpDeliveryInstallationArea> createADDeliveryInstallationArea(AdxpDeliveryInstallationArea value) { return new JAXBElement(_ADDeliveryInstallationArea_QNAME, AdxpDeliveryInstallationArea.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="streetNameType", scope=AD.class) public JAXBElement<AdxpStreetNameType> createADStreetNameType(AdxpStreetNameType value) { return new JAXBElement(_ADStreetNameType_QNAME, AdxpStreetNameType.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="deliveryInstallationQualifier", scope=AD.class) public JAXBElement<AdxpDeliveryInstallationQualifier> createADDeliveryInstallationQualifier(AdxpDeliveryInstallationQualifier value) { return new JAXBElement(_ADDeliveryInstallationQualifier_QNAME, AdxpDeliveryInstallationQualifier.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="direction", scope=AD.class) public JAXBElement<AdxpDirection> createADDirection(AdxpDirection value) { return new JAXBElement(_ADDirection_QNAME, AdxpDirection.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="censusTract", scope=AD.class) public JAXBElement<AdxpCensusTract> createADCensusTract(AdxpCensusTract value) { return new JAXBElement(_ADCensusTract_QNAME, AdxpCensusTract.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="unitID", scope=AD.class) public JAXBElement<AdxpUnitID> createADUnitID(AdxpUnitID value) { return new JAXBElement(_ADUnitID_QNAME, AdxpUnitID.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="postalCode", scope=AD.class) public JAXBElement<AdxpPostalCode> createADPostalCode(AdxpPostalCode value) { return new JAXBElement(_ADPostalCode_QNAME, AdxpPostalCode.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="streetName", scope=AD.class) public JAXBElement<AdxpStreetName> createADStreetName(AdxpStreetName value) { return new JAXBElement(_ADStreetName_QNAME, AdxpStreetName.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="deliveryInstallationType", scope=AD.class) public JAXBElement<AdxpDeliveryInstallationType> createADDeliveryInstallationType(AdxpDeliveryInstallationType value) { return new JAXBElement(_ADDeliveryInstallationType_QNAME, AdxpDeliveryInstallationType.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="streetNameBase", scope=AD.class) public JAXBElement<AdxpStreetNameBase> createADStreetNameBase(AdxpStreetNameBase value) { return new JAXBElement(_ADStreetNameBase_QNAME, AdxpStreetNameBase.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="deliveryMode", scope=AD.class) public JAXBElement<AdxpDeliveryMode> createADDeliveryMode(AdxpDeliveryMode value) { return new JAXBElement(_ADDeliveryMode_QNAME, AdxpDeliveryMode.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="postBox", scope=AD.class) public JAXBElement<AdxpPostBox> createADPostBox(AdxpPostBox value) { return new JAXBElement(_ADPostBox_QNAME, AdxpPostBox.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="country", scope=AD.class) public JAXBElement<AdxpCountry> createADCountry(AdxpCountry value) { return new JAXBElement(_ADCountry_QNAME, AdxpCountry.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="deliveryAddressLine", scope=AD.class) public JAXBElement<AdxpDeliveryAddressLine> createADDeliveryAddressLine(AdxpDeliveryAddressLine value) { return new JAXBElement(_ADDeliveryAddressLine_QNAME, AdxpDeliveryAddressLine.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="useablePeriod", scope=AD.class) public JAXBElement<SXCMTS> createADUseablePeriod(SXCMTS value) { return new JAXBElement(_ADUseablePeriod_QNAME, SXCMTS.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="careOf", scope=AD.class) public JAXBElement<AdxpCareOf> createADCareOf(AdxpCareOf value) { return new JAXBElement(_ADCareOf_QNAME, AdxpCareOf.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="unitType", scope=AD.class) public JAXBElement<AdxpUnitType> createADUnitType(AdxpUnitType value) { return new JAXBElement(_ADUnitType_QNAME, AdxpUnitType.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="precinct", scope=AD.class) public JAXBElement<AdxpPrecinct> createADPrecinct(AdxpPrecinct value) { return new JAXBElement(_ADPrecinct_QNAME, AdxpPrecinct.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="delimiter", scope=AD.class) public JAXBElement<AdxpDelimiter> createADDelimiter(AdxpDelimiter value) { return new JAXBElement(_ENDelimiter_QNAME, AdxpDelimiter.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="houseNumberNumeric", scope=AD.class) public JAXBElement<AdxpHouseNumberNumeric> createADHouseNumberNumeric(AdxpHouseNumberNumeric value) { return new JAXBElement(_ADHouseNumberNumeric_QNAME, AdxpHouseNumberNumeric.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="buildingNumberSuffix", scope=AD.class) public JAXBElement<AdxpBuildingNumberSuffix> createADBuildingNumberSuffix(AdxpBuildingNumberSuffix value) { return new JAXBElement(_ADBuildingNumberSuffix_QNAME, AdxpBuildingNumberSuffix.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="county", scope=AD.class) public JAXBElement<AdxpCounty> createADCounty(AdxpCounty value) { return new JAXBElement(_ADCounty_QNAME, AdxpCounty.class, AD.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLREAL.class) public JAXBElement<IVXBREAL> createIVLREALHigh(IVXBREAL value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBREAL.class, IVLREAL.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLREAL.class) public JAXBElement<IVXBREAL> createIVLREALLow(IVXBREAL value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBREAL.class, IVLREAL.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLREAL.class) public JAXBElement<REAL> createIVLREALCenter(REAL value) { return new JAXBElement(_IVLINTCenter_QNAME, REAL.class, IVLREAL.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLREAL.class) public JAXBElement<REAL> createIVLREALWidth(REAL value) { return new JAXBElement(_IVLINTWidth_QNAME, REAL.class, IVLREAL.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLPQ.class) public JAXBElement<IVXBPQ> createIVLPQHigh(IVXBPQ value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBPQ.class, IVLPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLPQ.class) public JAXBElement<IVXBPQ> createIVLPQLow(IVXBPQ value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBPQ.class, IVLPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLPQ.class) public JAXBElement<PQ> createIVLPQCenter(PQ value) { return new JAXBElement(_IVLINTCenter_QNAME, PQ.class, IVLPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLPQ.class) public JAXBElement<PQ> createIVLPQWidth(PQ value) { return new JAXBElement(_IVLINTWidth_QNAME, PQ.class, IVLPQ.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="table", scope=StrucDocFootnote.class) public JAXBElement<StrucDocTable> createStrucDocFootnoteTable(StrucDocTable value) { return new JAXBElement(_StrucDocItemTable_QNAME, StrucDocTable.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="list", scope=StrucDocFootnote.class) public JAXBElement<StrucDocList> createStrucDocFootnoteList(StrucDocList value) { return new JAXBElement(_StrucDocItemList_QNAME, StrucDocList.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="renderMultiMedia", scope=StrucDocFootnote.class) public JAXBElement<StrucDocRenderMultiMedia> createStrucDocFootnoteRenderMultiMedia(StrucDocRenderMultiMedia value) { return new JAXBElement(_StrucDocItemRenderMultiMedia_QNAME, StrucDocRenderMultiMedia.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="br", scope=StrucDocFootnote.class) public JAXBElement<StrucDocBr> createStrucDocFootnoteBr(StrucDocBr value) { return new JAXBElement(_StrucDocItemBr_QNAME, StrucDocBr.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="linkHtml", scope=StrucDocFootnote.class) public JAXBElement<StrucDocLinkHtml> createStrucDocFootnoteLinkHtml(StrucDocLinkHtml value) { return new JAXBElement(_StrucDocItemLinkHtml_QNAME, StrucDocLinkHtml.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sup", scope=StrucDocFootnote.class) public JAXBElement<StrucDocSup> createStrucDocFootnoteSup(StrucDocSup value) { return new JAXBElement(_StrucDocItemSup_QNAME, StrucDocSup.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="sub", scope=StrucDocFootnote.class) public JAXBElement<StrucDocSub> createStrucDocFootnoteSub(StrucDocSub value) { return new JAXBElement(_StrucDocItemSub_QNAME, StrucDocSub.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="content", scope=StrucDocFootnote.class) public JAXBElement<StrucDocContent> createStrucDocFootnoteContent(StrucDocContent value) { return new JAXBElement(_StrucDocItemContent_QNAME, StrucDocContent.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="paragraph", scope=StrucDocFootnote.class) public JAXBElement<StrucDocParagraph> createStrucDocFootnoteParagraph(StrucDocParagraph value) { return new JAXBElement(_StrucDocItemParagraph_QNAME, StrucDocParagraph.class, StrucDocFootnote.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLPPDTS.class) public JAXBElement<IVXBPPDTS> createIVLPPDTSHigh(IVXBPPDTS value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBPPDTS.class, IVLPPDTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLPPDTS.class) public JAXBElement<IVXBPPDTS> createIVLPPDTSLow(IVXBPPDTS value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBPPDTS.class, IVLPPDTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLPPDTS.class) public JAXBElement<PPDTS> createIVLPPDTSCenter(PPDTS value) { return new JAXBElement(_IVLINTCenter_QNAME, PPDTS.class, IVLPPDTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLPPDTS.class) public JAXBElement<PPDPQ> createIVLPPDTSWidth(PPDPQ value) { return new JAXBElement(_IVLINTWidth_QNAME, PPDPQ.class, IVLPPDTS.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="high", scope=IVLMO.class) public JAXBElement<IVXBMO> createIVLMOHigh(IVXBMO value) { return new JAXBElement(_IVLINTHigh_QNAME, IVXBMO.class, IVLMO.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="low", scope=IVLMO.class) public JAXBElement<IVXBMO> createIVLMOLow(IVXBMO value) { return new JAXBElement(_IVLINTLow_QNAME, IVXBMO.class, IVLMO.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="center", scope=IVLMO.class) public JAXBElement<MO> createIVLMOCenter(MO value) { return new JAXBElement(_IVLINTCenter_QNAME, MO.class, IVLMO.class, value); } @XmlElementDecl(namespace="urn:hl7-org:v3", name="width", scope=IVLMO.class) public JAXBElement<MO> createIVLMOWidth(MO value) { return new JAXBElement(_IVLINTWidth_QNAME, MO.class, IVLMO.class, value); } }
/* * 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.openapi.ui; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.impl.MouseGestureManager; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.openapi.wm.impl.IdeMenuBar; import com.intellij.ui.BalloonLayout; import com.intellij.ui.FocusTrackback; import com.intellij.util.ImageLoader; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.Map; public class FrameWrapper implements Disposable, DataProvider { private String myDimensionKey = null; private JComponent myComponent = null; private JComponent myPreferedFocus = null; private String myTitle = ""; private Image myImage = ImageLoader.loadFromResource(ApplicationInfoImpl.getShadowInstance().getIconUrl()); private boolean myCloseOnEsc = false; private Window myFrame; private final Map<String, Object> myDatas = new HashMap<String, Object>(); private Project myProject; private final ProjectManagerListener myProjectListener = new MyProjectManagerListener(); private FocusTrackback myFocusTrackback; private FocusWatcher myFocusWatcher; private ActionCallback myFocusedCallback; private boolean myDisposed; protected StatusBar myStatusBar; private boolean myShown; private boolean myIsDialog; public FrameWrapper(Project project) { this(project, null); } public FrameWrapper(Project project, @Nullable @NonNls String dimensionServiceKey) { this(project, dimensionServiceKey, false); } public FrameWrapper(Project project, @Nullable @NonNls String dimensionServiceKey, boolean isDialog) { myProject = project; myDimensionKey = dimensionServiceKey; myIsDialog = isDialog; } public void setDimensionKey(String dimensionKey) { myDimensionKey = dimensionKey; } public void setData(String dataId, Object data) { myDatas.put(dataId, data); } public void setProject(@NotNull final Project project) { myProject = project; setData(CommonDataKeys.PROJECT.getName(), project); ProjectManager.getInstance().addProjectManagerListener(project, myProjectListener); Disposer.register(this, new Disposable() { @Override public void dispose() { ProjectManager.getInstance().removeProjectManagerListener(project, myProjectListener); } }); } public void show() { show(true); } public void show(boolean restoreBounds) { myFocusedCallback = new ActionCallback(); if (myProject != null) { IdeFocusManager.getInstance(myProject).typeAheadUntil(myFocusedCallback); } final Window frame = getFrame(); if (myStatusBar != null) { myStatusBar.install((IdeFrame)frame); } myFocusTrackback = new FocusTrackback(this, IdeFocusManager.findInstance().getFocusOwner(), true); if (frame instanceof JFrame) { ((JFrame)frame).setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } else { ((JDialog)frame).setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } final WindowAdapter focusListener = new WindowAdapter() { public void windowOpened(WindowEvent e) { IdeFocusManager fm = IdeFocusManager.getInstance(myProject); JComponent toFocus = myPreferedFocus; if (toFocus == null) { toFocus = fm.getFocusTargetFor(myComponent); } if (toFocus != null) { fm.requestFocus(toFocus, true).notify(myFocusedCallback); } else { myFocusedCallback.setRejected(); } } }; frame.addWindowListener(focusListener); Disposer.register(this, new Disposable() { @Override public void dispose() { frame.removeWindowListener(focusListener); } }); if (myCloseOnEsc) addCloseOnEsc((RootPaneContainer)frame); ((RootPaneContainer)frame).getContentPane().add(myComponent, BorderLayout.CENTER); if (frame instanceof JFrame) { ((JFrame)frame).setTitle(myTitle); } else { ((JDialog)frame).setTitle(myTitle); } frame.setIconImage(myImage); if (restoreBounds) { loadFrameState(); } myFocusWatcher = new FocusWatcher() { protected void focusLostImpl(final FocusEvent e) { myFocusTrackback.consume(); } }; myFocusWatcher.install(myComponent); myShown = true; frame.setVisible(true); } public void close() { Disposer.dispose(this); } public void dispose() { if (isDisposed()) return; Window frame = getFrame(); final JRootPane rootPane = ((RootPaneContainer)frame).getRootPane(); if (rootPane != null) { DialogWrapper.unregisterKeyboardActions(rootPane); } frame.setVisible(false); frame.dispose(); if (frame instanceof JFrame) { FocusTrackback.release((JFrame)frame); } if (myStatusBar != null) { Disposer.dispose(myStatusBar); myStatusBar = null; } myDisposed = true; } public boolean isDisposed() { return myDisposed; } private void addCloseOnEsc(final RootPaneContainer frame) { frame.getRootPane().registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager(); MenuElement[] selectedPath = menuSelectionManager.getSelectedPath(); if (selectedPath.length > 0) { // hide popup menu if any menuSelectionManager.clearSelectedPath(); } else { close(); } } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW ); } public Window getFrame() { assert !myDisposed : "Already disposed!"; if (myFrame == null) { final IdeFrame parent = WindowManager.getInstance().getIdeFrame(myProject); myFrame = myIsDialog ? createJDialog(parent) : createJFrame(parent); } return myFrame; } protected JFrame createJFrame(IdeFrame parent) { return new MyJFrame(parent) { @Override public IdeRootPaneNorthExtension getNorthExtension(String key) { return FrameWrapper.this.getNorthExtension(key); } }; } protected JDialog createJDialog(IdeFrame parent) { return new MyJDialog(parent); } protected IdeRootPaneNorthExtension getNorthExtension(String key) { return null; } @Override public Object getData(@NonNls String dataId) { return null; } public void setComponent(JComponent component) { myComponent = component; } public void setPreferredFocusedComponent(JComponent preferedFocus) { myPreferedFocus = preferedFocus; } public void closeOnEsc() { myCloseOnEsc = true; } public void setImage(Image image) { myImage = image; } protected void loadFrameState() { final Window frame = getFrame(); final Point location; final Dimension size; final int extendedState; DimensionService dimensionService = DimensionService.getInstance(); if (myDimensionKey == null || dimensionService == null) { location = null; size = null; extendedState = -1; } else { location = dimensionService.getLocation(myDimensionKey); size = dimensionService.getSize(myDimensionKey); extendedState = dimensionService.getExtendedState(myDimensionKey); } if (size != null && location != null) { frame.setLocation(location); frame.setSize(size); ((RootPaneContainer)frame).getRootPane().revalidate(); } else { final IdeFrame ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(myProject); if (ideFrame != null) { frame.pack(); frame.setBounds(ideFrame.suggestChildFrameBounds()); } } if (extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) { ((JFrame)frame).setExtendedState(extendedState); } } private static void saveFrameState(String dimensionKey, Component frame) { DimensionService dimensionService = DimensionService.getInstance(); if (dimensionKey == null || dimensionService == null) return; dimensionService.setLocation(dimensionKey, frame.getLocation()); dimensionService.setSize(dimensionKey, frame.getSize()); if (frame instanceof JFrame) { dimensionService.setExtendedState(dimensionKey, ((JFrame)frame).getExtendedState()); } } public void setTitle(String title) { myTitle = title; } public void addDisposable(Disposable disposable) { Disposer.register(this, disposable); } protected void setStatusBar(StatusBar statusBar) { if (myStatusBar != null) { Disposer.dispose(myStatusBar); } myStatusBar = statusBar; } private class MyJFrame extends JFrame implements DataProvider, IdeFrame.Child { private boolean myDisposing; private final IdeFrame myParent; private String myFrameTitle; private String myFileTitle; private File myFile; private MyJFrame(IdeFrame parent) throws HeadlessException { myParent = parent; setGlassPane(new IdeGlassPaneImpl(getRootPane())); if (SystemInfo.isMac) { setJMenuBar(new IdeMenuBar(ActionManagerEx.getInstanceEx(), DataManager.getInstance())); } MouseGestureManager.getInstance().add(this); setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt()); } @Override public JComponent getComponent() { return getRootPane(); } @Override public StatusBar getStatusBar() { return myStatusBar != null ? myStatusBar : myParent.getStatusBar(); } @Override public Rectangle suggestChildFrameBounds() { return myParent.suggestChildFrameBounds(); } @Override public Project getProject() { return myParent.getProject(); } @Override public void setFrameTitle(String title) { myFrameTitle = title; updateTitle(); } @Override public void setFileTitle(String fileTitle, File ioFile) { myFileTitle = fileTitle; myFile = ioFile; updateTitle(); } @Override public IdeRootPaneNorthExtension getNorthExtension(String key) { return null; } @Override public BalloonLayout getBalloonLayout() { return null; } private void updateTitle() { IdeFrameImpl.updateTitle(this, myFrameTitle, myFileTitle, myFile); } @Override public IdeFrame getParentFrame() { return myParent; } public void dispose() { if (myDisposing) return; myDisposing = true; MouseGestureManager.getInstance().remove(this); if (myShown) { saveFrameState(myDimensionKey, this); } Disposer.dispose(FrameWrapper.this); myDatas.clear(); myProject = null; myPreferedFocus = null; if (myFocusTrackback != null) { myFocusTrackback.restoreFocus(); } if (myComponent != null && myFocusWatcher != null) { myFocusWatcher.deinstall(myComponent); } myFocusWatcher = null; myFocusedCallback = null; super.dispose(); } public Object getData(String dataId) { if (IdeFrame.KEY.getName().equals(dataId)) { return this; } Object data = FrameWrapper.this.getData(dataId); return data != null ? data : myDatas.get(dataId); } @Override public void paint(Graphics g) { UIUtil.applyRenderingHints(g); super.paint(g); } } private class MyJDialog extends JDialog implements DataProvider, IdeFrame.Child { private boolean myDisposing; private final IdeFrame myParent; private MyJDialog(IdeFrame parent) throws HeadlessException { super((JFrame)parent); myParent = parent; setGlassPane(new IdeGlassPaneImpl(getRootPane())); getRootPane().putClientProperty("Window.style", "small"); setBackground(UIUtil.getPanelBackground()); MouseGestureManager.getInstance().add(this); setFocusTraversalPolicy(new LayoutFocusTraversalPolicyExt()); } @Override public JComponent getComponent() { return getRootPane(); } @Override public StatusBar getStatusBar() { return null; } @Nullable @Override public BalloonLayout getBalloonLayout() { return null; } @Override public Rectangle suggestChildFrameBounds() { return myParent.suggestChildFrameBounds(); } @Override public Project getProject() { return myParent.getProject(); } @Override public void setFrameTitle(String title) { setTitle(title); } @Override public void setFileTitle(String fileTitle, File ioFile) { setTitle(fileTitle); } @Override public IdeRootPaneNorthExtension getNorthExtension(String key) { return null; } @Override public IdeFrame getParentFrame() { return myParent; } public void dispose() { if (myDisposing) return; myDisposing = true; MouseGestureManager.getInstance().remove(this); if (myShown) { saveFrameState(myDimensionKey, this); } Disposer.dispose(FrameWrapper.this); myDatas.clear(); myProject = null; myPreferedFocus = null; if (myFocusTrackback != null) { myFocusTrackback.restoreFocus(); } if (myComponent != null && myFocusWatcher != null) { myFocusWatcher.deinstall(myComponent); } myFocusWatcher = null; myFocusedCallback = null; super.dispose(); } public Object getData(String dataId) { if (IdeFrame.KEY.getName().equals(dataId)) { return this; } Object data = FrameWrapper.this.getData(dataId); return data != null ? data : myDatas.get(dataId); } @Override public void paint(Graphics g) { UIUtil.applyRenderingHints(g); super.paint(g); } } public void setLocation(Point location) { getFrame().setLocation(location); } public void setSize(Dimension size) { getFrame().setSize(size); } private class MyProjectManagerListener extends ProjectManagerAdapter { public void projectClosing(Project project) { if (project == myProject) { close(); } } } }
// Copyright 2007, 2008, 2012 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.internal.renderers; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.commons.util.CollectionFactory; import org.apache.tapestry5.http.TapestryHttpSymbolConstants; import org.apache.tapestry5.http.services.Context; import org.apache.tapestry5.http.services.Request; import org.apache.tapestry5.ioc.annotations.Primary; import org.apache.tapestry5.ioc.annotations.Symbol; import org.apache.tapestry5.ioc.internal.util.InternalUtils; import org.apache.tapestry5.services.ObjectRenderer; import java.util.List; public class RequestRenderer implements ObjectRenderer<Request> { private final Context context; private final String contextPath; private final ObjectRenderer masterObjectRenderer; public RequestRenderer(@Primary ObjectRenderer masterObjectRenderer, Context context, @Symbol(TapestryHttpSymbolConstants.CONTEXT_PATH) String contextPath) { this.masterObjectRenderer = masterObjectRenderer; this.context = context; this.contextPath = contextPath; } public void render(Request request, MarkupWriter writer) { coreProperties(request, writer); parameters(request, writer); headers(request, writer); attributes(request, writer); context(writer); } private void coreProperties(Request request, MarkupWriter writer) { writer.element("dl", "class", "dl-horizontal"); dt(writer, "Context Path"); writer.element("dd"); if (contextPath.equals("")) { writer.element("em"); writer.write("none (deployed as root)"); writer.end(); } else { writer.write(contextPath); } writer.end(); // dd dt(writer, "Path", request.getPath()); dt(writer, "Locale", request.getLocale().toString()); dt(writer, "Server Name", request.getServerName()); List<String> flags = CollectionFactory.newList(); if (request.isSecure()) { flags.add("secure"); } if (request.isXHR()) { flags.add("XHR"); } if (request.isRequestedSessionIdValid()) { flags.add("requested session id valid"); } if (request.isSessionInvalidated()) { flags.add("session invalidated"); } if (!flags.isEmpty()) { dt(writer, "Flags", InternalUtils.join(flags)); } dt(writer, "Ports (local/server)", String.format("%d / %d", request.getLocalPort(), request.getServerPort())); dt(writer, "Method", request.getMethod()); writer.end(); } private void context(MarkupWriter writer) { List<String> attributeNames = context.getAttributeNames(); if (attributeNames.isEmpty()) return; section(writer, "Context Attributes"); writer.element("dl"); for (String name : attributeNames) { dt(writer, name); writer.element("dd"); masterObjectRenderer.render(context.getAttribute(name), writer); writer.end(); // dd } writer.end(); // dl } private void parameters(Request request, MarkupWriter writer) { List<String> parameterNames = request.getParameterNames(); if (parameterNames.isEmpty()) return; section(writer, "Query Parameters"); writer.element("dl"); for (String name : parameterNames) { String[] values = request.getParameters(name); dt(writer, name); writer.element("dd"); if (values.length > 1) { writer.element("ul"); for (String value : values) { writer.element("li"); writer.write(value); writer.end(); } writer.end(); // ul } else { writer.write(values[0]); } writer.end(); // dd } writer.end(); // dl } private void dt(MarkupWriter writer, String name, String value) { if (value != null) { dt(writer, name); dd(writer, value); } } private void dt(MarkupWriter writer, String name) { writer.element("dt"); writer.write(name); writer.end(); } private void dd(MarkupWriter writer, String name) { writer.element("dd"); writer.write(name); writer.end(); } private void section(MarkupWriter writer, String name) { writer.element("h3"); writer.write(name); writer.end(); } private void headers(Request request, MarkupWriter writer) { section(writer, "Headers"); writer.element("dl", "class", "dl-horizontal"); for (String name : request.getHeaderNames()) { dt(writer, name, request.getHeader(name)); } writer.end(); // dl } private void attributes(Request request, MarkupWriter writer) { List<String> attributeNames = request.getAttributeNames(); if (attributeNames.isEmpty()) { return; } section(writer, "Attributes"); writer.element("dl"); for (String name : attributeNames) { dt(writer, name, String.valueOf(request.getAttribute(name))); } writer.end(); // dl } }
/* * Copyright 2008 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.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.javascript.jscomp.CodingConvention.SubclassRelationship; import com.google.javascript.jscomp.ReferenceCollectingCallback.Behavior; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.jstype.JSType; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Using the infrastructure provided by VariableReferencePass, identify variables that are used only * once and in a way that is safe to move, and then inline them. * * <p>This pass has two "modes." One mode only inlines variables declared as constants, for legacy * compiler clients. The second mode inlines any variable that we can provably inline. Note that the * second mode is a superset of the first mode. We only support the first mode for * backwards-compatibility with compiler clients that don't want --inline_variables. * * <p>The approach of this pass is similar to {@link CrossChunkCodeMotion} * * @author kushal@google.com (Kushal Dave) * @author nicksantos@google.com (Nick Santos) */ class InlineVariables implements CompilerPass { private final AbstractCompiler compiler; enum Mode { // Only inline things explicitly marked as constant. CONSTANTS_ONLY(Var::isDeclaredOrInferredConst), // Locals only LOCALS_ONLY(Var::isLocal), ALL(Predicates.alwaysTrue()); @SuppressWarnings("ImmutableEnumChecker") private final Predicate<Var> varPredicate; private Mode(Predicate<Var> varPredicate) { this.varPredicate = varPredicate; } } private final Mode mode; // Inlines all strings, even if they increase the size of the gzipped binary. private final boolean inlineAllStrings; InlineVariables( AbstractCompiler compiler, Mode mode, boolean inlineAllStrings) { this.compiler = compiler; this.mode = mode; this.inlineAllStrings = inlineAllStrings; } @Override public void process(Node externs, Node root) { ReferenceCollectingCallback callback = new ReferenceCollectingCallback( compiler, new InliningBehavior(), new SyntacticScopeCreator(compiler), mode.varPredicate); callback.process(externs, root); } private static class AliasCandidate { private final Var alias; private final ReferenceCollection refInfo; AliasCandidate(Var alias, ReferenceCollection refInfo) { this.alias = alias; this.refInfo = refInfo; } } /** * Builds up information about nodes in each scope. When exiting the * scope, inspects all variables in that scope, and inlines any * that we can. */ private class InliningBehavior implements Behavior { /** * A list of variables that should not be inlined, because their * reference information is out of sync with the state of the AST. */ private final Set<Var> staleVars = new HashSet<>(); /** * Stored possible aliases of variables that never change, with * all the reference info about those variables. Hashed by the NAME * node of the variable being aliased. */ final Map<Node, AliasCandidate> aliasCandidates = new HashMap<>(); @Override public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) { collectAliasCandidates(t, referenceMap); doInlinesForScope(t, referenceMap); } /** * If any of the variables are well-defined and alias other variables, * mark them as aliasing candidates. */ private void collectAliasCandidates(NodeTraversal t, ReferenceMap referenceMap) { if (mode != Mode.CONSTANTS_ONLY) { for (Var v : t.getScope().getVarIterable()) { ReferenceCollection referenceInfo = referenceMap.getReferences(v); // NOTE(nicksantos): Don't handle variables that are never used. // The tests are much easier to write if you don't, and there's // another pass that handles unused variables much more elegantly. if (referenceInfo != null && referenceInfo.references.size() >= 2 && referenceInfo.isWellDefined() && referenceInfo.isAssignedOnceInLifetime()) { Reference init = referenceInfo.getInitializingReference(); Node value = init.getAssignedValue(); if (value != null && value.isName() && !value.getString().equals(v.getName())) { aliasCandidates.put(value, new AliasCandidate(v, referenceInfo)); } } } } } /** * For all variables in this scope, see if they are only used once. * If it looks safe to do so, inline them. */ private void doInlinesForScope(NodeTraversal t, ReferenceMap referenceMap) { boolean maybeModifiedArguments = maybeEscapedOrModifiedArguments(t.getScope(), referenceMap); for (Var v : t.getScope().getVarIterable()) { ReferenceCollection referenceInfo = referenceMap.getReferences(v); // referenceInfo will be null if we're in constants-only mode // and the variable is not a constant. if (referenceInfo == null || isVarInlineForbidden(v)) { // Never try to inline exported variables or variables that // were not collected or variables that have already been inlined. continue; } else if (isInlineableDeclaredConstant(v, referenceInfo)) { Reference init = referenceInfo.getInitializingReferenceForConstants(); Node value = init.getAssignedValue(); inlineDeclaredConstant(v, value, referenceInfo.references); staleVars.add(v); } else if (mode == Mode.CONSTANTS_ONLY) { // If we're in constants-only mode, don't run more aggressive // inlining heuristics. See InlineConstantsTest. continue; } else { inlineNonConstants(v, referenceInfo, maybeModifiedArguments); } } } private boolean maybeEscapedOrModifiedArguments(Scope scope, ReferenceMap referenceMap) { if (scope.isFunctionScope() && !scope.getRootNode().isArrowFunction()) { Var arguments = scope.getArgumentsVar(); ReferenceCollection refs = referenceMap.getReferences(arguments); if (refs != null && !refs.references.isEmpty()) { for (Reference ref : refs.references) { Node refNode = ref.getNode(); Node refParent = ref.getParent(); // Any reference that is not a read of the arguments property // consider a escape of the arguments object. if (!(NodeUtil.isGet(refParent) && refNode == ref.getParent().getFirstChild() && !NodeUtil.isLValue(refParent))) { return true; } } } } return false; } private void inlineNonConstants( Var v, ReferenceCollection referenceInfo, boolean maybeModifiedArguments) { int refCount = referenceInfo.references.size(); Reference declaration = referenceInfo.references.get(0); Reference init = referenceInfo.getInitializingReference(); int firstRefAfterInit = (declaration == init) ? 2 : 3; if (refCount > 1 && isImmutableAndWellDefinedVariable(v, referenceInfo)) { // if the variable is referenced more than once, we can only // inline it if it's immutable and never defined before referenced. Node value; if (init != null) { value = init.getAssignedValue(); } else { // Create a new node for variable that is never initialized. Node srcLocation = declaration.getNode(); value = NodeUtil.newUndefinedNode(srcLocation); } checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } else if (refCount == firstRefAfterInit) { // The variable likely only read once, try some more // complex inlining heuristics. Reference reference = referenceInfo.references.get(firstRefAfterInit - 1); if (canInline(declaration, init, reference)) { inline(v, declaration, init, reference); staleVars.add(v); } } else if (declaration != init && refCount == 2) { if (isValidDeclaration(declaration) && isValidInitialization(init)) { // The only reference is the initialization, remove the assignment and // the variable declaration. Node value = init.getAssignedValue(); checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } } // If this variable was not inlined normally, check if we can // inline an alias of it. (If the variable was inlined, then the // reference data is out of sync. We're better off just waiting for // the next pass.) if (!maybeModifiedArguments && !staleVars.contains(v) && referenceInfo.isWellDefined() && referenceInfo.isAssignedOnceInLifetime()) { List<Reference> refs = referenceInfo.references; for (int i = 1 /* start from a read */; i < refs.size(); i++) { Node nameNode = refs.get(i).getNode(); if (aliasCandidates.containsKey(nameNode)) { AliasCandidate candidate = aliasCandidates.get(nameNode); if (!staleVars.contains(candidate.alias) && !isVarInlineForbidden(candidate.alias)) { Reference aliasInit; aliasInit = candidate.refInfo.getInitializingReference(); Node value = aliasInit.getAssignedValue(); checkNotNull(value); inlineWellDefinedVariable(candidate.alias, value, candidate.refInfo.references); staleVars.add(candidate.alias); } } } } } /** * If there are any variable references in the given node tree, blacklist * them to prevent the pass from trying to inline the variable. */ private void blacklistVarReferencesInTree(Node root, Scope scope) { for (Node c = root.getFirstChild(); c != null; c = c.getNext()) { blacklistVarReferencesInTree(c, scope); } if (root.isName()) { staleVars.add(scope.getVar(root.getString())); } } /** * Whether the given variable is forbidden from being inlined. */ private boolean isVarInlineForbidden(Var var) { // A variable may not be inlined if: // 1) The variable is exported, // 2) A reference to the variable has been inlined. We're downstream // of the mechanism that creates variable references, so we don't // have a good way to update the reference. Just punt on it. // 3) Don't inline the special property rename functions. return var.isExtern() || compiler.getCodingConvention().isExported(var.name) || compiler .getCodingConvention() .isPropertyRenameFunction(var.nameNode.getOriginalQualifiedName()) || staleVars.contains(var) || hasNoInlineAnnotation(var); } /** * Do the actual work of inlining a single declaration into a single * reference. */ private void inline(Var v, Reference decl, Reference init, Reference ref) { Node value = init.getAssignedValue(); checkState(value != null); // Check for function declarations before the value is moved in the AST. boolean isFunctionDeclaration = NodeUtil.isFunctionDeclaration(value); if (isFunctionDeclaration) { // In addition to changing the containing scope, inlining function declarations also changes // the function name scope from the containing scope to the inner scope. compiler.reportChangeToChangeScope(value); compiler.reportChangeToEnclosingScope(value.getParent()); } inlineValue(v, ref, value.detach()); if (decl != init) { Node expressRoot = init.getGrandparent(); checkState(expressRoot.isExprResult()); NodeUtil.removeChild(expressRoot.getParent(), expressRoot); } // Function declarations have already been removed. if (!isFunctionDeclaration) { removeDeclaration(decl); } } /** * Inline an immutable variable into all of its references. */ private void inlineWellDefinedVariable(Var v, Node value, List<Reference> refSet) { Reference decl = refSet.get(0); for (int i = 1; i < refSet.size(); i++) { Node clonedValue = value.cloneTree(); NodeUtil.markNewScopesChanged(clonedValue, compiler); inlineValue(v, refSet.get(i), clonedValue); } removeDeclaration(decl); } /** * Inline a declared constant. */ private void inlineDeclaredConstant(Var v, Node value, List<Reference> refSet) { // Replace the references with the constant value Reference decl = null; for (Reference r : refSet) { if (r.getNode() == v.getNameNode()) { decl = r; } else { Node clonedValue = value.cloneTree(); NodeUtil.markNewScopesChanged(clonedValue, compiler); inlineValue(v, r, clonedValue); } } removeDeclaration(decl); } /** * Remove the given VAR declaration. */ private void removeDeclaration(Reference decl) { Node varNode = decl.getParent(); checkState(NodeUtil.isNameDeclaration(varNode), varNode); Node grandparent = decl.getGrandparent(); compiler.reportChangeToEnclosingScope(decl.getNode()); varNode.removeChild(decl.getNode()); // Remove var node if empty if (!varNode.hasChildren()) { NodeUtil.removeChild(grandparent, varNode); } } /** * Replace the given reference with the given value node. * * @param v The variable that's referenced. * @param ref The reference to replace. * @param value The node tree to replace it with. This tree should be safe * to re-parent. */ private void inlineValue(Var v, Reference ref, Node value) { compiler.reportChangeToEnclosingScope(ref.getNode()); if (ref.isSimpleAssignmentToName()) { // This is the initial assignment. replaceChildPreserveCast(ref.getGrandparent(), ref.getParent(), value); } else { replaceChildPreserveCast(ref.getParent(), ref.getNode(), value); } blacklistVarReferencesInTree(value, v.scope); } private void replaceChildPreserveCast(Node parent, Node child, Node replacement) { JSType typeBeforeCast = child.getJSTypeBeforeCast(); if (typeBeforeCast != null) { replacement.setJSTypeBeforeCast(typeBeforeCast); replacement.setJSType(child.getJSType()); } parent.replaceChild(child, replacement); NodeUtil.markFunctionsDeleted(child, compiler); } /** Determines whether the given variable is declared as a constant and may be inlined. */ private boolean isInlineableDeclaredConstant(Var var, ReferenceCollection refInfo) { if (!Mode.CONSTANTS_ONLY.varPredicate.apply(var)) { return false; } if (!refInfo.isAssignedOnceInLifetime()) { return false; } Reference init = refInfo.getInitializingReferenceForConstants(); if (init == null) { return false; } Node value = init.getAssignedValue(); if (value == null) { // This constant is either externally defined or initialized indirectly // (e.g. in an function expression used to hide // temporary variables), so the constant is ineligible for inlining. return false; } // Is the constant's value immutable? if (!NodeUtil.isImmutableValue(value)) { return false; } // Determine if we should really inline a String or not. return !value.isString() || isStringWorthInlining(var, refInfo.references); } /** * Compute whether the given string is worth inlining. */ private boolean isStringWorthInlining(Var var, List<Reference> refs) { if (!inlineAllStrings && !var.isDefine()) { int len = var.getInitialValue().getString().length() + "''".length(); // if not inlined: var xx="value"; .. xx .. xx .. // The 4 bytes per reference is just a heuristic: // 2 bytes per var name plus maybe 2 bytes if we don't inline, e.g. // in the case of "foo " + CONST + " bar" int noInlineBytes = "var xx=;".length() + len + 4 * (refs.size() - 1); // if inlined: // I'm going to assume that half of the quotes will be eliminated // thanks to constant folding, therefore I subtract 1 (2/2=1) from // the string length. int inlineBytes = (len - 1) * (refs.size() - 1); // Not inlining if doing so uses more bytes, or this constant is being // defined. return noInlineBytes >= inlineBytes; } return true; } /** * @return true if the provided reference and declaration can be safely * inlined according to our criteria */ private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } // If the value is read more than once, skip it. // VAR declarations and EXPR_RESULT don't need the value, but other // ASSIGN expressions parents do. if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } // Be very conservative and do not cross control structures or scope boundaries if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } // Do not inline into a call node. This would change // the context in which it was being called. For example, // var a = b.c; // a(); // should not be inlined, because it calls a in the context of b // rather than the context of the window. // var a = b.c; // f(a) // is OK. Node value = initialization.getAssignedValue(); checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); // Bug 2388531: Don't inline subclass definitions into class defining // calls as this confused class removing logic. SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } // issue 668: Don't inline singleton getter methods // calls as this confused class removing logic. if (convention.getSingletonGetterClassName(callNode) != null) { return false; } } } if (initialization.getScope() != declaration.getScope() || !initialization.getScope().contains(reference.getScope())) { return false; } return canMoveAggressively(value) || canMoveModerately(initialization, reference); } /** * If the value is a literal, we can cross more boundaries to inline it. */ private boolean canMoveAggressively(Node value) { // Function expressions and other mutable objects can move within // the same basic block. return NodeUtil.isLiteralValue(value, true) || value.isFunction(); } /** * If the value of a variable is not constant, then it may read or modify * state. Therefore it cannot be moved past anything else that may modify * the value being read or read values that are modified. */ private boolean canMoveModerately( Reference initialization, Reference reference) { // Check if declaration can be inlined without passing // any side-effect causing nodes. Iterator<Node> it; if (NodeUtil.isNameDeclaration(initialization.getParent())) { it = NodeIterators.LocalVarMotion.forVar( compiler, initialization.getNode(), // NAME initialization.getParent(), // VAR/LET/CONST initialization.getGrandparent()); // VAR/LET/CONST container } else if (initialization.getParent().isAssign()) { checkState(initialization.getGrandparent().isExprResult()); it = NodeIterators.LocalVarMotion.forAssign( compiler, initialization.getNode(), // NAME initialization.getParent(), // ASSIGN initialization.getGrandparent(), // EXPR_RESULT initialization.getGrandparent().getParent()); // EXPR container } else { throw new IllegalStateException("Unexpected initialization parent\n" + initialization.getParent().toStringTree()); } Node targetName = reference.getNode(); while (it.hasNext()) { Node curNode = it.next(); if (curNode == targetName) { return true; } } return false; } /** * @return true if the reference is a normal VAR or FUNCTION declaration. */ private boolean isValidDeclaration(Reference declaration) { return (NodeUtil.isNameDeclaration(declaration.getParent()) && !NodeUtil.isLoopStructure(declaration.getGrandparent())) || NodeUtil.isFunctionDeclaration(declaration.getParent()); } /** * @return Whether there is a initial value. */ private boolean isValidInitialization(Reference initialization) { if (initialization == null) { return false; } else if (initialization.isDeclaration()) { // The reference is a FUNCTION declaration or normal VAR declaration // with a value. if (!NodeUtil.isFunctionDeclaration(initialization.getParent()) && initialization.getNode().getFirstChild() == null) { return false; } } else { Node parent = initialization.getParent(); checkState(parent.isAssign() && parent.getFirstChild() == initialization.getNode()); } Node n = initialization.getAssignedValue(); if (n.isFunction()) { return compiler.getCodingConvention().isInlinableFunction(n); } return true; } /** * @return true if the reference is a candidate for inlining */ private boolean isValidReference(Reference reference) { return !reference.isDeclaration() && !reference.isLvalue(); } /** * Determines whether the reference collection describes a variable that * is initialized to an immutable value, never modified, and defined before * every reference. */ private boolean isImmutableAndWellDefinedVariable(Var v, ReferenceCollection refInfo) { List<Reference> refSet = refInfo.references; int startingReadRef = 1; Reference refDecl = refSet.get(0); if (!isValidDeclaration(refDecl)) { return false; } boolean isNeverAssigned = refInfo.isNeverAssigned(); // For values that are never assigned, only the references need to be // checked. if (!isNeverAssigned) { Reference refInit = refInfo.getInitializingReference(); if (!isValidInitialization(refInit)) { return false; } if (refDecl != refInit) { checkState(refInit == refSet.get(1)); startingReadRef = 2; } if (!refInfo.isWellDefined()) { return false; } Node value = refInit.getAssignedValue(); checkNotNull(value); boolean isImmutableValueWorthInlining = NodeUtil.isImmutableValue(value) && (!value.isString() || isStringWorthInlining(v, refInfo.references)); boolean isInlinableThisAlias = value.isThis() && !refInfo.isEscaped(); if (!isImmutableValueWorthInlining && !isInlinableThisAlias) { return false; } } for (int i = startingReadRef; i < refSet.size(); i++) { Reference ref = refSet.get(i); if (!isValidReference(ref)) { return false; } } return true; } } private static boolean hasNoInlineAnnotation(Var var) { JSDocInfo jsDocInfo = var.getJSDocInfo(); return jsDocInfo != null && jsDocInfo.isNoInline(); } }
/* Derby - Class com.pivotal.gemfirexd.internal.impl.services.cache.ClockPolicy 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. */ /* * Changes for GemFireXD distributed data platform (some marked by "GemStone changes") * * Portions Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.pivotal.gemfirexd.internal.impl.services.cache; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.services.cache.Cacheable; import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager; /** * Implementation of a replacement policy which uses the clock algorithm. All * the cache entries are stored in a circular buffer, called the clock. There * is also a clock hand which points to one of the entries in the clock. Each * time an entry is accessed, it is marked as recently used. If a new entry is * inserted into the cache and the cache is full, the clock hand is moved until * it is over a not recently used entry, and that entry is evicted to make * space for the new entry. Each time the clock hand sweeps over a recently * used entry, it is marked as not recently used, and it will be a candidate * for removal the next time the clock hand sweeps over it, unless it has been * marked as recently used in the meantime. * * <p> * * To allow concurrent access from multiple threads, the methods in this class * need to synchronize on a number of different objects: * * <ul> * * <li><code>CacheEntry</code> objects must be locked before they can be * used</li> * * <li>accesses to the clock structure (circular buffer + clock hand) should be * synchronized on the <code>ArrayList</code> representing the circular * buffer</li> * * <li>accesses to individual <code>Holder</code> objects in the clock * structure should be protected by synchronizing on the holder</li> * * </ul> * * To avoid deadlocks, we need to ensure that all threads obtain * synchronization locks in the same order. <code>CacheEntry</code>'s class * javadoc dictates the order when locking <code>CacheEntry</code> * objects. Additionally, we require that no thread should obtain any other * synchronization locks while it is holding a synchronization lock on the * clock structure or on a <code>Holder</code> object. The threads are however * allowed to obtain synchronization locks on the clock structure or on a * holder while they are locking one or more <code>CacheEntry</code> objects. */ final class ClockPolicy implements ReplacementPolicy { /** * The minimum number of items to check before we decide to give up * looking for evictable entries when rotating the clock. */ private static final int MIN_ITEMS_TO_CHECK = 20; /** * How large part of the clock to look at before giving up in * {@code rotateClock()}. */ private static final float MAX_ROTATION = 0.2f; /** * How large part of the clock to look at before giving up finding * an evictable entry in {@code shrinkMe()}. */ private static final float PART_OF_CLOCK_FOR_SHRINK = 0.1f; /** The cache manager for which this replacement policy is used. */ private final ConcurrentCache cacheManager; /** * The maximum size of the cache. When this size is exceeded, entries must * be evicted before new ones are inserted. */ private final int maxSize; /** * The circular clock buffer which holds all the entries in the * cache. Accesses to <code>clock</code> and <code>hand</code> must be * synchronized on <code>clock</code>. */ private final ArrayList<Holder> clock; /** The current position of the clock hand. */ private int hand; /** * The number of free entries. This is the number of objects that have been * removed from the cache and whose entries are free to be reused without * eviction. */ private final AtomicInteger freeEntries = new AtomicInteger(); /** * Tells whether there currently is a thread in the {@code doShrink()} * method. If this variable is {@code true} a call to {@code doShrink()} * will be a no-op. */ private final AtomicBoolean isShrinking = new AtomicBoolean(); /** * Create a new <code>ClockPolicy</code> instance. * * @param cacheManager the cache manager that requests this policy * @param initialSize the initial capacity of the cache * @param maxSize the maximum size of the cache */ ClockPolicy(ConcurrentCache cacheManager, int initialSize, int maxSize) { this.cacheManager = cacheManager; this.maxSize = maxSize; clock = new ArrayList<Holder>(initialSize); } /** * Insert an entry into the cache. If the maximum size is exceeded, evict a * <em>not recently used</em> object from the cache. If there are no * entries available for reuse, increase the size of the cache. * * @param entry the entry to insert (must be locked) * @exception StandardException if an error occurs when inserting the entry */ public void insertEntry(CacheEntry entry) throws StandardException { final int size; synchronized (clock) { size = clock.size(); if (size < maxSize) { if (freeEntries.get() == 0) { // We have not reached the maximum size yet, and there's no // free entry to reuse. Make room by growing. clock.add(new Holder(entry)); return; } } } if (size > maxSize) { // Maximum size is exceeded. Shrink the clock in the background // cleaner, if we have one; otherwise, shrink it in the current // thread. BackgroundCleaner cleaner = cacheManager.getBackgroundCleaner(); if (cleaner != null) { cleaner.scheduleShrink(); } else { doShrink(); } } // Rotate the clock hand (look at up to 20% of the cache) and try to // find free space for the entry. Only allow evictions if the cache // has reached its maximum size. Otherwise, we only look for invalid // entries and rather grow the cache than evict valid entries. Holder h = rotateClock(entry, size >= maxSize); if (h == null) { // didn't find a victim, so we need to grow synchronized (clock) { clock.add(new Holder(entry)); } } } /** * Holder class which represents an entry in the cache. It maintains a * <code>recentlyUsed</code> required by the clock algorithm. The class * also implements the <code>Callback</code> interface, so that * <code>ConcurrentCache</code> can notify the clock policy about events * relevant to the clock algorithm. */ private class Holder implements Callback { /** * Flag indicating whether or not this entry has been accessed * recently. Should only be accessed/modified when the current thread * has locked the <code>CacheEntry</code> object stored in the * <code>entry</code> field. */ boolean recentlyUsed; /** * Reference to the <code>CacheEntry</code> object held by this * object. The reference should only be accessed when the thread owns * the monitor on this holder. A thread is only allowed to change the * reference if it also has locked the entry that the reference points * to (if the reference is non-null). This ensures that no other thread * can disassociate a holder from its entry while the entry is locked, * even though the monitor on the holder has been released. */ private CacheEntry entry; /** * Cacheable object from a removed object. If this object is non-null, * <code>entry</code> must be <code>null</code> (which means that the * holder is not associated with any object in the cache). */ private Cacheable freedCacheable; /** * Flag which tells whether this holder has been evicted from the * clock. If it has been evicted, it can't be reused when a new entry * is inserted. Only the owner of this holder's monitor is allowed to * access this variable. */ private boolean evicted; Holder(CacheEntry e) { entry = e; e.setCallback(this); } /** * Mark this entry as recently used. Caller must have locked * <code>entry</code>. */ public void access() { recentlyUsed = true; } /** * Mark this object as free and reusable. Caller must have locked * <code>entry</code>. */ public synchronized void free() { freedCacheable = entry.getCacheable(); entry = null; recentlyUsed = false; // let others know that a free entry is available int free = freeEntries.incrementAndGet(); if (SanityManager.DEBUG) { // GemStone changes BEGIN if (free <= 0) // GemStone changes END SanityManager.ASSERT( free > 0, "freeEntries should be greater than 0, but is " + free); } } /** * Associate this holder with the specified entry if the holder is free * (that is, not associated with any other entry). * * @param e the entry to associate the holder with (it must be locked * by the current thread) * @return <code>true</code> if the holder has been associated with the * specified entry, <code>false</code> if someone else has taken it or * the holder has been evicted from the clock */ synchronized boolean takeIfFree(CacheEntry e) { if (entry == null && !evicted) { // the holder is free - take it! int free = freeEntries.decrementAndGet(); if (SanityManager.DEBUG) { // GemStone changes BEGIN if (free < 0) // GemStone changes END SanityManager.ASSERT( free >= 0, "freeEntries is negative: " + free); } e.setCacheable(freedCacheable); e.setCallback(this); entry = e; freedCacheable = null; return true; } // someone else has taken it return false; } /** * Returns the entry that is currently associated with this holder. * * @return the associated entry */ synchronized CacheEntry getEntry() { return entry; } /** * Switch which entry the holder is associated with. Will be called * when we evict an entry to make room for a new one. When this method * is called, the current thread must have locked both the entry that * is evicted and the entry that is inserted. * * @param e the entry to associate this holder with */ synchronized void switchEntry(CacheEntry e) { e.setCallback(this); e.setCacheable(entry.getCacheable()); entry = e; } /** * Evict this holder from the clock if it is not associated with an * entry. * * @return <code>true</code> if the holder was successfully evicted, * <code>false</code> otherwise */ synchronized boolean evictIfFree() { if (entry == null && !evicted) { int free = freeEntries.decrementAndGet(); if (SanityManager.DEBUG) { // GemStone changes BEGIN if (free < 0) // GemStone changes END SanityManager.ASSERT( free >= 0, "freeEntries is negative: " + free); } evicted = true; return true; } return false; } /** * Mark this holder as evicted from the clock, effectively preventing * reuse of the holder. Calling thread must have locked the holder's * entry. */ synchronized void setEvicted() { if (SanityManager.DEBUG) { SanityManager.ASSERT(!evicted, "Already evicted"); } evicted = true; entry = null; } /** * Check whether this holder has been evicted from the clock. * * @return <code>true</code> if it has been evicted, <code>false</code> * otherwise */ synchronized boolean isEvicted() { return evicted; } } /** * Get the holder under the clock hand, and move the hand to the next * holder. * * @return the holder under the clock hand, or {@code null} if the clock is * empty */ private Holder moveHand() { synchronized (clock) { if (clock.isEmpty()) { return null; } if (hand >= clock.size()) { hand = 0; } return clock.get(hand++); } } /** * Rotate the clock in order to find a free space for a new entry. If * <code>allowEvictions</code> is <code>true</code>, an not recently used * object might be evicted to make room for the new entry. Otherwise, only * unused entries are searched for. When evictions are allowed, entries are * marked as not recently used when the clock hand sweeps over them. The * search stops when a reusable entry is found, or when more than a certain * percentage of the entries have been visited. If there are * free (unused) entries, the search will continue until a reusable entry * is found, regardless of how many entries that need to be checked. * * @param entry the entry to insert * @param allowEvictions tells whether evictions are allowed (normally * <code>true</code> if the cache is full and <code>false</code> otherwise) * @return a holder that we can reuse, or <code>null</code> if we didn't * find one */ private Holder rotateClock(CacheEntry entry, boolean allowEvictions) throws StandardException { // Calculate how many items we need to check before we give up // finding an evictable one. If we don't allow evictions, none should // be checked (however, we may search for unused entries in the loop // below). int itemsToCheck = 0; if (allowEvictions) { synchronized (clock) { itemsToCheck = Math.max(MIN_ITEMS_TO_CHECK, (int) (clock.size() * MAX_ROTATION)); } } // Check up to itemsToCheck entries before giving up, but don't give up // if we know there are unused entries. while (itemsToCheck-- > 0 || freeEntries.get() > 0) { final Holder h = moveHand(); if (h == null) { // There are no elements in the clock, hence there is no // reusable entry. return null; } final CacheEntry e = h.getEntry(); if (e == null) { if (h.takeIfFree(entry)) { return h; } // Someone else grabbed this entry between the calls to // getEntry() and takeIfFree(). Just move on to the next entry. continue; } if (!allowEvictions) { // Evictions are not allowed, so we can't reuse this entry. continue; } // This variable will hold a dirty cacheable that should be cleaned // after the try/finally block. final Cacheable dirty; e.lock(); try { if (!isEvictable(e, h, true)) { continue; } // The entry is not in use, and has not been used for at least // one round on the clock. See if it needs to be cleaned. Cacheable c = e.getCacheable(); if (!c.isDirty()) { // GemStone changes BEGIN // synchronize against shrinkMe() on holder since entry // is going to be switched and entry lock is not enough // (see UseCase8's support issue #6131) synchronized (h) { // Not in use and not dirty. Take over the holder. h.switchEntry(entry); cacheManager.evictEntry(c.getIdentity()); // clear the identity of this Cacheable c.clearIdentity(); } /* (original code) // Not in use and not dirty. Take over the holder. h.switchEntry(entry); cacheManager.evictEntry(c.getIdentity()); */ // GemStone changes END return h; } // Ask the background cleaner to clean the entry. BackgroundCleaner cleaner = cacheManager.getBackgroundCleaner(); if (cleaner != null && cleaner.scheduleClean(e)) { // Successfully scheduled the clean operation. We can't // evict it until the clean operation has finished. Since // we'd like to be as responsive as possible, move on to // the next entry instead of waiting for the clean // operation to finish. continue; } // There is no background cleaner, or the background cleaner // has no free capacity. Let's clean the object ourselves. // First, mark the entry as kept to prevent eviction until // we have cleaned it, but don't mark it as accessed (recently // used). e.keep(false); dirty = c; } finally { e.unlock(); } // Clean the entry and unkeep it. cacheManager.cleanAndUnkeepEntry(e, dirty); // If no one has touched the entry while we were cleaning it, we // could reuse it at this point. The old buffer manager (Clock) // would however under high load normally move on to the next // entry in the clock instead of reusing the one it recently // cleaned. Some of the performance tests performed as part of // DERBY-2911 indicated that not reusing the entry that was just // cleaned made the replacement algorithm more efficient. For now // we try to stay as close to the old buffer manager as possible // and don't reuse the entry immediately. } return null; } /** * Check if an entry can be evicted. Only entries that still are present in * the cache, are not kept and not recently used, can be evicted. This * method does not check whether the {@code Cacheable} contained in the * entry is dirty, so it may be necessary to clean it before an eviction * can take place even if the method returns {@code true}. The caller must * hold the lock on the entry before calling this method. * * @param e the entry to check * @param h the holder which holds the entry * @param clearRecentlyUsedFlag tells whether or not the recently used flag * should be cleared on the entry ({@code true} only when called as part of * a normal clock rotation) * @return whether or not this entry can be evicted (provided that its * {@code Cacheable} is cleaned first) */ private boolean isEvictable(CacheEntry e, Holder h, boolean clearRecentlyUsedFlag) { if (h.getEntry() != e) { // Someone else evicted this entry before we obtained the // lock, so we can't evict it. return false; } if (e.isKept()) { // The entry is in use and cannot be evicted. return false; } if (SanityManager.DEBUG) { // At this point the entry must be valid. If it's not, it's either // removed (in which case getEntry() != e and we shouldn't get // here), or it is setting its identity (in which case it is kept // and we shouldn't get here). SanityManager.ASSERT(e.isValid(), "Holder contains invalid entry"); SanityManager.ASSERT(!h.isEvicted(), "Holder is evicted"); } if (h.recentlyUsed) { // The object has been used recently, so it cannot be evicted. if (clearRecentlyUsedFlag) { h.recentlyUsed = false; } return false; } return true; } /** * Remove the holder at the given clock position. * * @param pos position of the holder * @param h the holder to remove */ private void removeHolder(int pos, Holder h) { synchronized (clock) { Holder removed = clock.remove(pos); if (SanityManager.DEBUG) { SanityManager.ASSERT(removed == h, "Wrong Holder removed"); } } } /** * Try to shrink the clock if it's larger than its maximum size. */ public void doShrink() { // If we're already performing a shrink, ignore this request. We'll get // a new call later by someone else if the current shrink operation is // not enough. If we manage to change isShrinking atomically from false // to true, no one else is currently inside shrinkMe(), and others will // be blocked from entering it until we reset isShrinking to false. if (isShrinking.compareAndSet(false, true)) { try { shrinkMe(); } finally { // allow others to call shrinkMe() isShrinking.set(false); } } } /** * Perform the shrinking of the clock. This method should only be called * by a single thread at a time. */ private void shrinkMe() { if (SanityManager.DEBUG) { SanityManager.ASSERT(isShrinking.get(), "Called shrinkMe() without ensuring exclusive access"); } // Max number of candidates to look at (always at least 1). int maxLooks = Math.max(1, (int) (maxSize * PART_OF_CLOCK_FOR_SHRINK)); // Since we don't scan the entire cache, start at the clock hand so // that we don't always scan the first 10% of the cache. int pos; synchronized (clock) { pos = hand; } while (maxLooks-- > 0) { final Holder h; final int size; // Fetch the next holder from the clock. synchronized (clock) { size = clock.size(); if (pos >= size) { pos = 0; } h = clock.get(pos); } // The index of the holder we're looking at. Since no one else than // us can remove elements from the clock while we're in this // method, and new elements will be added at the end of the list, // the index for a holder does not change until we remove it. final int index = pos; // Let pos point at the index of the holder we'll look at in the // next iteration. pos++; // No need to shrink if the size isn't greater than maxSize. if (size <= maxSize) { break; } final CacheEntry e = h.getEntry(); if (e == null) { // The holder does not hold an entry. Try to remove it. if (h.evictIfFree()) { removeHolder(index, h); // move position back because of the removal so that we // don't skip one clock element pos = index; } // Either the holder was evicted, or someone else took it // before we could evict it. In either case, we should move on // to the next holder. continue; } e.lock(); try { if (!isEvictable(e, h, false)) { continue; } final Cacheable c = e.getCacheable(); if (c.isDirty()) { // Don't evict dirty entries. continue; } // GemStone changes BEGIN // synchronize against rotateClock() on holder since entry // is going to be switched by it and entry lock is not enough // (see UseCase8's support issue #6131) synchronized (h) { // mark as evicted to prevent reuse h.setEvicted(); // remove from cache manager cacheManager.evictEntry(c.getIdentity()); // remove from clock removeHolder(index, h); // clear the identity of this Cacheable c.clearIdentity(); } /* (original code) // mark as evicted to prevent reuse h.setEvicted(); // remove from cache manager cacheManager.evictEntry(c.getIdentity()); // remove from clock removeHolder(index, h); */ // GemStone changes END // move position back because of the removal so that we don't // skip one clock element pos = index; } finally { e.unlock(); } } } }
/** * Copyright (c) 2009--2010, Stephan Preibisch & Stephan Saalfeld * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials * provided with the distribution. Neither the name of the Fiji project 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. * * @author Stephan Preibisch & Stephan Saalfeld */ package mpicbg.imglib.container.cell; import java.util.ArrayList; import mpicbg.imglib.container.ContainerFactory; import mpicbg.imglib.container.DirectAccessContainerImpl; import mpicbg.imglib.container.basictypecontainer.array.ArrayDataAccess; import mpicbg.imglib.cursor.Cursor; import mpicbg.imglib.cursor.array.ArrayLocalizableByDimCursor; import mpicbg.imglib.cursor.array.ArrayLocalizableCursor; import mpicbg.imglib.cursor.cell.CellCursor; import mpicbg.imglib.cursor.cell.CellLocalizableByDimCursor; import mpicbg.imglib.cursor.cell.CellLocalizableByDimOutOfBoundsCursor; import mpicbg.imglib.cursor.cell.CellLocalizableCursor; import mpicbg.imglib.cursor.cell.CellLocalizablePlaneCursor; import mpicbg.imglib.image.Image; import mpicbg.imglib.outofbounds.OutOfBoundsStrategyFactory; import mpicbg.imglib.type.Type; import mpicbg.imglib.type.label.FakeType; public class CellContainer<T extends Type<T>, A extends ArrayDataAccess<A>> extends DirectAccessContainerImpl<T, A> { final protected ArrayList<Cell<T,A>> data; final protected int[] numCellsDim, cellSize; final protected int numCells; public CellContainer( final ContainerFactory factory, final A creator, final int[] dim, final int[] cellSize, final int entitiesPerPixel ) { super(factory, dim, entitiesPerPixel); // check that cellsize is not bigger than the image for ( int d = 0; d < getNumDimensions(); d++ ) if ( cellSize[ d ] > dim[ d ] ) cellSize[ d ] = dim[ d ]; this.cellSize = cellSize; numCellsDim = new int[ getNumDimensions() ]; int tmp = 1; for ( int d = 0; d < getNumDimensions(); d++ ) { numCellsDim[ d ] = ( dim[ d ] - 1) / cellSize[ d ] + 1; tmp *= numCellsDim[ d ]; } numCells = tmp; data = createCellArray( numCells ); // Here we "misuse" an ArrayLocalizableCursor to iterate over cells, // it always gives us the location of the current cell we are instantiating. final ArrayLocalizableCursor<FakeType> cursor = ArrayLocalizableCursor.createLinearCursor( numCellsDim ); for ( int c = 0; c < numCells; c++ ) { cursor.fwd(); final int[] finalSize = new int[ getNumDimensions() ]; final int[] finalOffset = new int[ getNumDimensions() ]; for ( int d = 0; d < getNumDimensions(); d++ ) { finalSize[ d ] = cellSize[ d ]; // the last cell in each dimension might have another size if ( cursor.getPosition( d ) == numCellsDim[ d ] - 1 ) if ( dim[ d ] % cellSize[ d ] != 0 ) finalSize[ d ] = dim[ d ] % cellSize[ d ]; finalOffset[ d ] = cursor.getPosition( d ) * cellSize[ d ]; } data.add( createCellInstance( creator, c, finalSize, finalOffset, entitiesPerPixel ) ); } cursor.close(); } @Override public A update( final Cursor<?> c ) { return data.get( c.getStorageIndex() ).getData(); } public ArrayList<Cell<T, A>> createCellArray( final int numCells ) { return new ArrayList<Cell<T, A>>( numCells ); } public Cell<T, A> createCellInstance( final A creator, final int cellId, final int[] dim, final int offset[], final int entitiesPerPixel ) { return new Cell<T,A>( creator, cellId, dim, offset, entitiesPerPixel ); } public Cell<T, A> getCell( final int cellId ) { return data.get( cellId ); } public int getCellIndex( final ArrayLocalizableByDimCursor<FakeType> cursor, final int[] cellPos ) { cursor.setPosition( cellPos ); return cursor.getArrayIndex(); } // many cursors using the same cursor for getting their position public int getCellIndex( final ArrayLocalizableByDimCursor<FakeType> cursor, final int cellPos, final int dim ) { cursor.setPosition( cellPos, dim ); return cursor.getArrayIndex(); } public int[] getCellPosition( final int[] position ) { final int[] cellPos = new int[ position.length ]; for ( int d = 0; d < numDimensions; d++ ) cellPos[ d ] = position[ d ] / cellSize[ d ]; return cellPos; } public void getCellPosition( final int[] position, final int[] cellPos ) { for ( int d = 0; d < numDimensions; d++ ) cellPos[ d ] = position[ d ] / cellSize[ d ]; } public int getCellPosition( final int position, final int dim ) { return position / cellSize[ dim ]; } public int getCellIndexFromImageCoordinates( final ArrayLocalizableByDimCursor<FakeType> cursor, final int[] position ) { return getCellIndex( cursor, getCellPosition( position ) ); } public int getNumCells( final int dim ) { if ( dim < numDimensions ) return numCellsDim[ dim ]; else return 1; } public int getNumCells() { return numCells; } public int[] getNumCellsDim() { return numCellsDim.clone(); } public int getCellSize( final int dim ) { return cellSize[ dim ]; } public int[] getCellSize() { return cellSize.clone(); } @Override public void close() { for ( final Cell<T, A> e : data ) e.close(); } @Override public CellCursor<T> createCursor( final Image<T> image ) { // create a Cursor using a Type that is linked to the container CellCursor<T> c = new CellCursor<T>( this, image, linkedType.duplicateTypeOnSameDirectAccessContainer() ); return c; } @Override public CellLocalizableCursor<T> createLocalizableCursor( final Image<T> image ) { // create a Cursor using a Type that is linked to the container CellLocalizableCursor<T> c = new CellLocalizableCursor<T>( this, image, linkedType.duplicateTypeOnSameDirectAccessContainer() ); return c; } @Override public CellLocalizablePlaneCursor<T> createLocalizablePlaneCursor( final Image<T> image ) { // create a Cursor using a Type that is linked to the container CellLocalizablePlaneCursor<T> c = new CellLocalizablePlaneCursor<T>( this, image, linkedType.duplicateTypeOnSameDirectAccessContainer() ); return c; } @Override public CellLocalizableByDimCursor<T> createLocalizableByDimCursor( final Image<T> image ) { // create a Cursor using a Type that is linked to the container CellLocalizableByDimCursor<T> c = new CellLocalizableByDimCursor<T>( this, image, linkedType.duplicateTypeOnSameDirectAccessContainer() ); return c; } @Override public CellLocalizableByDimCursor<T> createLocalizableByDimCursor( final Image<T> image, final OutOfBoundsStrategyFactory<T> outOfBoundsFactory ) { // create a Cursor using a Type that is linked to the container CellLocalizableByDimOutOfBoundsCursor<T> c = new CellLocalizableByDimOutOfBoundsCursor<T>( this, image, linkedType.duplicateTypeOnSameDirectAccessContainer(), outOfBoundsFactory ); return c; } }
package crazypants.enderio.conduit.gui.item; import java.awt.Color; import java.awt.Rectangle; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import org.lwjgl.opengl.GL11; import crazypants.enderio.conduit.ConnectionMode; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.gui.BaseSettingsPanel; import crazypants.enderio.conduit.gui.FilterChangeListener; import crazypants.enderio.conduit.gui.GuiExternalConnection; import crazypants.enderio.conduit.item.IItemConduit; import crazypants.enderio.conduit.item.filter.ExistingItemFilter; import crazypants.enderio.conduit.item.filter.IItemFilter; import crazypants.enderio.conduit.item.filter.ItemFilter; import crazypants.enderio.conduit.item.filter.ModItemFilter; import crazypants.enderio.conduit.item.filter.PowerItemFilter; import crazypants.enderio.conduit.packet.PacketExtractMode; import crazypants.enderio.conduit.packet.PacketItemConduitFilter; import crazypants.enderio.gui.ColorButton; import crazypants.enderio.gui.IconButtonEIO; import crazypants.enderio.gui.IconEIO; import crazypants.enderio.gui.RedstoneModeButton; import crazypants.enderio.gui.ToggleButtonEIO; import crazypants.enderio.machine.IRedstoneModeControlable; import crazypants.enderio.machine.RedstoneControlMode; import crazypants.enderio.network.PacketHandler; import crazypants.gui.GuiToolTip; import crazypants.render.ColorUtil; import crazypants.render.RenderUtil; import crazypants.util.DyeColor; import crazypants.util.Lang; public class ItemSettings extends BaseSettingsPanel { private static final int NEXT_FILTER_ID = 98932; private static final int ID_REDSTONE_BUTTON = 12614; private static final int ID_COLOR_BUTTON = 179816; private static final int ID_LOOP = 22; private static final int ID_ROUND_ROBIN = 24; private static final int ID_PRIORITY_UP = 25; private static final int ID_PRIORITY_DOWN = 26; private static final int ID_CHANNEL = 23; private IItemConduit itemConduit; private String inputHeading; private String outputHeading; private final IconButtonEIO nextFilterB; private final ToggleButtonEIO loopB; private final ToggleButtonEIO roundRobinB; private final IconButtonEIO priUpB; private final IconButtonEIO priDownB; private final RedstoneModeButton rsB; private final ColorButton colorB; private ColorButton channelB; boolean inOutShowIn = false; private IItemFilter activeFilter; private int priLeft; private int priWidth = 32; private final GuiToolTip priorityTooltip; private final GuiToolTip speedUpgradeTooltip; private final GuiToolTip filterUpgradeTooltip; private IItemFilterGui filterGui; public ItemSettings(final GuiExternalConnection gui, IConduit con) { super(IconEIO.WRENCH_OVERLAY_ITEM, Lang.localize("itemItemConduit.name"), gui, con); itemConduit = (IItemConduit) con; inputHeading = Lang.localize("gui.conduit.item.extractionFilter"); outputHeading = Lang.localize("gui.conduit.item.insertionFilter"); int x = 52; int y = customTop; nextFilterB = new IconButtonEIO(gui, NEXT_FILTER_ID, x, y, IconEIO.RIGHT_ARROW); nextFilterB.setSize(8, 16); x = 66; channelB = new ColorButton(gui, ID_CHANNEL, x, y); channelB.setColorIndex(0); channelB.setToolTipHeading(Lang.localize("gui.conduit.item.channel")); filterUpgradeTooltip = new GuiToolTip(new Rectangle(x - 21 - 18 * 2, customTop + 3 + 16, 18, 18), Lang.localize("gui.conduit.item.filterupgrade")); speedUpgradeTooltip = new GuiToolTip(new Rectangle(x - 21 - 18, customTop + 3 + 16, 18, 18), Lang.localize("gui.conduit.item.speedupgrade"), Lang.localize("gui.conduit.item.speedupgrade2")); x += channelB.getWidth() + 4; priLeft = x - 8; rsB = new RedstoneModeButton(gui, ID_REDSTONE_BUTTON, x, y, new IRedstoneModeControlable() { @Override public void setRedstoneControlMode(RedstoneControlMode mode) { RedstoneControlMode curMode = getRedstoneControlMode(); itemConduit.setExtractionRedstoneMode(mode, gui.getDir()); if(curMode != mode) { PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(itemConduit, gui.getDir())); } } @Override public RedstoneControlMode getRedstoneControlMode() { return itemConduit.getExtractionRedstoneMode(gui.getDir()); } }); x += rsB.getWidth() + 4; colorB = new ColorButton(gui, ID_COLOR_BUTTON, x, y); colorB.setColorIndex(itemConduit.getExtractionSignalColor(gui.getDir()).ordinal()); colorB.setToolTipHeading(Lang.localize("gui.conduit.item.sigCol")); x += 4 + colorB.getWidth(); roundRobinB = new ToggleButtonEIO(gui, ID_ROUND_ROBIN, x, y, IconEIO.ROUND_ROBIN_OFF, IconEIO.ROUND_ROBIN); roundRobinB.setSelectedToolTip(Lang.localize("gui.conduit.item.roundRobinEnabled")); roundRobinB.setUnselectedToolTip(Lang.localize("gui.conduit.item.roundRobinDisabled")); roundRobinB.setPaintSelectedBorder(false); x += 4 + roundRobinB.getWidth(); loopB = new ToggleButtonEIO(gui, ID_LOOP, x, y, IconEIO.LOOP_OFF, IconEIO.LOOP); loopB.setSelectedToolTip(Lang.localize("gui.conduit.item.selfFeedEnabled")); loopB.setUnselectedToolTip(Lang.localize("gui.conduit.item.selfFeedDisabled")); loopB.setPaintSelectedBorder(false); priorityTooltip = new GuiToolTip(new Rectangle(priLeft + 9, y, priWidth, 16), Lang.localize("gui.conduit.item.priority")); x = priLeft + priWidth + 9; priUpB = new IconButtonEIO(gui, ID_PRIORITY_UP, x, y, IconEIO.ADD_BUT); priUpB.setSize(8, 8); y += 8; priDownB = new IconButtonEIO(gui, ID_PRIORITY_DOWN, x, y, IconEIO.MINUS_BUT); priDownB.setSize(8, 8); gui.getContainer().addFilterListener(new FilterChangeListener() { @Override public void onFilterChanged() { filtersChanged(); } }); } private String getHeading() { ConnectionMode mode = con.getConnectionMode(gui.getDir()); if(mode == ConnectionMode.DISABLED) { return ""; } if(mode == ConnectionMode.OUTPUT) { return outputHeading; } if(mode == ConnectionMode.INPUT || inOutShowIn) { return inputHeading; } return outputHeading; } @Override protected void initCustomOptions() { updateGuiVisibility(); } private void updateGuiVisibility() { deactivate(); createFilterGUI(); updateButtons(); } private void createFilterGUI() { boolean showInput = false; boolean showOutput = false; ConnectionMode mode = con.getConnectionMode(gui.getDir()); if(mode == ConnectionMode.INPUT) { showInput = true; } else if(mode == ConnectionMode.OUTPUT) { showOutput = true; } else if(mode == ConnectionMode.IN_OUT) { nextFilterB.onGuiInit(); showInput = inOutShowIn; showOutput = !inOutShowIn; } if(!showInput && !showOutput) { filterGui = null; activeFilter = null; } else if(showInput) { activeFilter = itemConduit.getInputFilter(gui.getDir()); gui.getContainer().setInventorySlotsVisible(true); gui.getContainer().setInputSlotsVisible(true); gui.getContainer().setOutputSlotsVisible(false); if(activeFilter != null) { filterGui = getFilterGui(activeFilter, true); } } else if(showOutput) { activeFilter = itemConduit.getOutputFilter(gui.getDir()); gui.getContainer().setInputSlotsVisible(false); gui.getContainer().setOutputSlotsVisible(true); gui.getContainer().setInventorySlotsVisible(true); if(activeFilter != null) { filterGui = getFilterGui(activeFilter, false); } } } private void filtersChanged() { deactiveFilterGUI(); createFilterGUI(); if(filterGui != null) { filterGui.updateButtons(); } } private IItemFilterGui getFilterGui(IItemFilter filter, boolean isInput) { //TODO: move to a factory if(filter instanceof ItemFilter) { ItemConduitFilterContainer cont = new ItemConduitFilterContainer(itemConduit, gui.getDir(), isInput); BasicItemFilterGui basicItemFilterGui = new BasicItemFilterGui(gui, cont, !isInput); basicItemFilterGui.createFilterSlots(); return basicItemFilterGui; } else if(filter instanceof ExistingItemFilter) { return new ExistingItemFilterGui(gui, itemConduit, isInput); } else if(filter instanceof ModItemFilter) { return new ModItemFilterGui(gui, itemConduit, isInput); } else if(filter instanceof PowerItemFilter) { return new PowerItemFilterGui(gui, itemConduit, isInput); } return null; } private void updateButtons() { ConnectionMode mode = con.getConnectionMode(gui.getDir()); if(mode == ConnectionMode.DISABLED) { return; } boolean outputActive = (mode == ConnectionMode.IN_OUT && !inOutShowIn) || (mode == ConnectionMode.OUTPUT); if(!outputActive) { rsB.onGuiInit(); rsB.setMode(itemConduit.getExtractionRedstoneMode(gui.getDir())); colorB.onGuiInit(); colorB.setColorIndex(itemConduit.getExtractionSignalColor(gui.getDir()).ordinal()); } gui.addToolTip(filterUpgradeTooltip); if(mode == ConnectionMode.IN_OUT && !outputActive) { loopB.onGuiInit(); loopB.setSelected(itemConduit.isSelfFeedEnabled(gui.getDir())); } if((mode == ConnectionMode.IN_OUT && !outputActive) || mode == ConnectionMode.INPUT) { roundRobinB.onGuiInit(); roundRobinB.setSelected(itemConduit.isRoundRobinEnabled(gui.getDir())); gui.addToolTip(speedUpgradeTooltip); } if((mode == ConnectionMode.IN_OUT && outputActive) || mode == ConnectionMode.OUTPUT) { priUpB.onGuiInit(); priDownB.onGuiInit(); gui.addToolTip(priorityTooltip); } int chanCol; if(!outputActive) { chanCol = itemConduit.getInputColor(gui.getDir()).ordinal(); } else { chanCol = itemConduit.getOutputColor(gui.getDir()).ordinal(); } channelB.onGuiInit(); channelB.setColorIndex(chanCol); if(filterGui != null) { filterGui.updateButtons(); } } @Override public void actionPerformed(GuiButton guiButton) { super.actionPerformed(guiButton); if(guiButton.id == NEXT_FILTER_ID) { inOutShowIn = !inOutShowIn; updateGuiVisibility(); } else if(guiButton.id == ID_COLOR_BUTTON) { itemConduit.setExtractionSignalColor(gui.getDir(), DyeColor.values()[colorB.getColorIndex()]); PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(itemConduit, gui.getDir())); } else if(guiButton.id == ID_LOOP) { itemConduit.setSelfFeedEnabled(gui.getDir(), !itemConduit.isSelfFeedEnabled(gui.getDir())); sendFilterChange(); } else if(guiButton.id == ID_ROUND_ROBIN) { itemConduit.setRoundRobinEnabled(gui.getDir(), !itemConduit.isRoundRobinEnabled(gui.getDir())); sendFilterChange(); } else if(guiButton.id == ID_PRIORITY_UP) { itemConduit.setOutputPriority(gui.getDir(), itemConduit.getOutputPriority(gui.getDir()) + 1); sendFilterChange(); } else if(guiButton.id == ID_PRIORITY_DOWN) { itemConduit.setOutputPriority(gui.getDir(), itemConduit.getOutputPriority(gui.getDir()) - 1); sendFilterChange(); } else if(guiButton.id == ID_CHANNEL) { DyeColor col = DyeColor.values()[channelB.getColorIndex()]; if(isInputVisible()) { itemConduit.setInputColor(gui.getDir(), col); } else { itemConduit.setOutputColor(gui.getDir(), col); } sendFilterChange(); } if(filterGui != null) { filterGui.actionPerformed(guiButton); } } private void sendFilterChange() { PacketHandler.INSTANCE.sendToServer(new PacketItemConduitFilter(itemConduit, gui.getDir())); } @Override public void mouseClicked(int x, int y, int par3) { super.mouseClicked(x, y, par3); if(filterGui != null) { filterGui.mouseClicked(x, y, par3); } } private boolean isInputVisible() { ConnectionMode mode = con.getConnectionMode(gui.getDir()); return (mode == ConnectionMode.IN_OUT && inOutShowIn) || (mode == ConnectionMode.INPUT); } @Override protected void connectionModeChanged(ConnectionMode conectionMode) { super.connectionModeChanged(conectionMode); updateGuiVisibility(); } @Override protected void renderCustomOptions(int top, float par1, int par2, int par3) { ConnectionMode mode = con.getConnectionMode(gui.getDir()); if(mode == ConnectionMode.DISABLED) { return; } RenderUtil.bindTexture("enderio:textures/gui/itemFilter.png"); gui.drawTexturedModalRect(gui.getGuiLeft(), gui.getGuiTop() + 55, 0, 55, gui.getXSize(), 145); FontRenderer fr = gui.getFontRenderer(); String heading = getHeading(); int x = 0; int rgb = ColorUtil.getRGB(Color.darkGray); fr.drawString(heading, left + x, top, rgb); boolean outputActive = (mode == ConnectionMode.IN_OUT && !inOutShowIn) || (mode == ConnectionMode.OUTPUT); if(outputActive) { GL11.glColor3f(1, 1, 1); IconEIO.BUTTON_DOWN.renderIcon(left + priLeft, top - 5, priWidth, 16, 0, true); String str = itemConduit.getOutputPriority(gui.getDir()) + ""; int sw = fr.getStringWidth(str); fr.drawString(str, left + priLeft + priWidth - sw - gap, top, ColorUtil.getRGB(Color.black)); } else { //draw speed upgrade slot GL11.glColor3f(1, 1, 1); RenderUtil.bindTexture("enderio:textures/gui/itemFilter.png"); gui.drawTexturedModalRect(gui.getGuiLeft() + 9 + 18, gui.getGuiTop() + 46, 94, 238, 18, 18); } //filter upgrade slot GL11.glColor3f(1, 1, 1); RenderUtil.bindTexture("enderio:textures/gui/itemFilter.png"); gui.drawTexturedModalRect(gui.getGuiLeft() + 9, gui.getGuiTop() + 46, 94, 220, 18, 18); if(filterGui != null) { filterGui.renderCustomOptions(top, par1, par2, par3); } } @Override public void deactivate() { gui.getContainer().setInventorySlotsVisible(false); gui.getContainer().setInputSlotsVisible(false); gui.getContainer().setOutputSlotsVisible(false); rsB.detach(); colorB.detach(); roundRobinB.detach(); loopB.detach(); nextFilterB.detach(); priUpB.detach(); priDownB.detach(); gui.removeToolTip(priorityTooltip); gui.removeToolTip(speedUpgradeTooltip); gui.removeToolTip(filterUpgradeTooltip); channelB.detach(); deactiveFilterGUI(); } private void deactiveFilterGUI() { if(filterGui != null) { filterGui.deactivate(); filterGui = null; } gui.getGhostSlots().clear(); } }
package com.myreader.view.epubview; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MotionEvent; import android.view.View; import android.webkit.WebView; import com.myreader.ui.activity.ReadEPubActivity; import com.myreader.ui.fragment.EPubReaderFragment; /** * @author yuyh. * @date 2016/12/13. */ public class ObservableWebView extends WebView { private ReaderCallback mActivityCallback; private EPubReaderFragment fragment; private float MOVE_THRESHOLD_DP; private boolean mMoveOccured = false; private float mDownPosX; private float mDownPosY; private ScrollListener mScrollListener; private SizeChangedListener mSizeChangedListener; public interface ScrollListener { void onScrollChange(int percent); } public interface SizeChangedListener { void onSizeChanged(int height); } public ObservableWebView(Context context) { this(context, null); } public ObservableWebView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ObservableWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); MOVE_THRESHOLD_DP = 20 * getResources().getDisplayMetrics().density; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public ObservableWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public void setScrollListener(ScrollListener listener) { mScrollListener = listener; } public void setSizeChangedListener(SizeChangedListener listener) { mSizeChangedListener = listener; } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { mActivityCallback = (ReadEPubActivity) getContext(); mActivityCallback.hideToolBarIfVisible(); if (mScrollListener != null) mScrollListener.onScrollChange(t); super.onScrollChanged(l, t, oldl, oldt); } @Override protected void onSizeChanged(int w, int h, int ow, int oh) { super.onSizeChanged(w, h, ow, oh); if (mSizeChangedListener != null) { mSizeChangedListener.onSizeChanged(h); } } public int getContentHeightVal() { int height = (int) Math.floor(this.getContentHeight() * this.getScale()); return height; } public int getWebviewHeight() { return this.getMeasuredHeight(); } @Override public ActionMode startActionMode(ActionMode.Callback callback, int type) { return this.dummyActionMode(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if (mActivityCallback == null) mActivityCallback = (ReadEPubActivity) getContext(); final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: mMoveOccured = false; mDownPosX = event.getX(); mDownPosY = event.getY(); fragment.removeCallback(); break; case MotionEvent.ACTION_UP: if (!mMoveOccured) { mActivityCallback.toggleToolBarVisible(); } fragment.startCallback(); break; case MotionEvent.ACTION_MOVE: if (Math.abs(event.getX() - mDownPosX) > MOVE_THRESHOLD_DP || Math.abs(event.getY() - mDownPosY) > MOVE_THRESHOLD_DP) { mMoveOccured = true; fragment.fadeInSeekbarIfInvisible(); } break; } return super.dispatchTouchEvent(event); } @Override public ActionMode startActionMode(ActionMode.Callback callback) { return this.dummyActionMode(); } public ActionMode dummyActionMode() { return new ActionMode() { @Override public void setTitle(CharSequence title) { } @Override public void setTitle(int resId) { } @Override public void setSubtitle(CharSequence subtitle) { } @Override public void setSubtitle(int resId) { } @Override public void setCustomView(View view) { } @Override public void invalidate() { } @Override public void finish() { } @Override public Menu getMenu() { return null; } @Override public CharSequence getTitle() { return null; } @Override public CharSequence getSubtitle() { return null; } @Override public View getCustomView() { return null; } @Override public MenuInflater getMenuInflater() { return null; } }; } public void setFragment(EPubReaderFragment fragment) { this.fragment = fragment; } }
/* * Copyright 2018-2020 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 * * 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.cloud.spring.autoconfigure.pubsub.health; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.api.gax.core.CredentialsProvider; import com.google.api.gax.grpc.GrpcStatusCode; import com.google.api.gax.rpc.ApiException; import com.google.auth.Credentials; import com.google.cloud.spring.autoconfigure.pubsub.GcpPubSubAutoConfiguration; import com.google.cloud.spring.core.GcpProjectIdProvider; import com.google.cloud.spring.pubsub.core.PubSubTemplate; import com.google.cloud.spring.pubsub.support.AcknowledgeablePubsubMessage; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.actuate.health.CompositeHealthContributor; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.util.concurrent.ListenableFuture; /** Tests for Pub/Sub Health Indicator autoconfiguration. */ class PubSubHealthIndicatorAutoConfigurationTests { private static final Pattern UUID_PATTERN = Pattern.compile("spring-cloud-gcp-healthcheck-[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}"); private ApplicationContextRunner baseContextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( PubSubHealthIndicatorAutoConfiguration.class, GcpPubSubAutoConfiguration.class)) .withBean(GcpProjectIdProvider.class, () -> () -> "fake project") .withBean(CredentialsProvider.class, () -> () -> mock(Credentials.class)); @SuppressWarnings("unchecked") @Test void healthIndicatorPresent_defaults() throws Exception { PubSubTemplate mockPubSubTemplate = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); when(future.get(anyLong(), any())).thenReturn(Collections.emptyList()); when(mockPubSubTemplate.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); this.baseContextRunner .withBean("pubSubTemplate", PubSubTemplate.class, () -> mockPubSubTemplate) .run( ctx -> { PubSubHealthIndicator healthIndicator = ctx.getBean(PubSubHealthIndicator.class); assertThat(healthIndicator).isNotNull(); assertThat(healthIndicator.getSubscription()).matches(UUID_PATTERN); assertThat(healthIndicator.getTimeoutMillis()).isEqualTo(2000); assertThat(healthIndicator.isAcknowledgeMessages()).isFalse(); assertThat(healthIndicator.isSpecifiedSubscription()).isFalse(); verify(mockPubSubTemplate).pullAsync(healthIndicator.getSubscription(), 1, true); verify(future).get(healthIndicator.getTimeoutMillis(), TimeUnit.MILLISECONDS); }); } @SuppressWarnings("unchecked") @Test void healthIndicatorPresent_customConfig() throws Exception { PubSubTemplate mockPubSubTemplate = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); when(future.get(anyLong(), any())).thenReturn(Collections.emptyList()); when(mockPubSubTemplate.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); this.baseContextRunner .withBean("pubSubTemplate", PubSubTemplate.class, () -> mockPubSubTemplate) .withPropertyValues( "management.health.pubsub.enabled=true", "spring.cloud.gcp.pubsub.health.subscription=test", "spring.cloud.gcp.pubsub.health.timeout-millis=1500", "spring.cloud.gcp.pubsub.health.acknowledgeMessages=true") .run( ctx -> { PubSubHealthIndicator healthIndicator = ctx.getBean(PubSubHealthIndicator.class); assertThat(healthIndicator).isNotNull(); assertThat(healthIndicator.getSubscription()).isEqualTo("test"); assertThat(healthIndicator.getTimeoutMillis()).isEqualTo(1500); assertThat(healthIndicator.isAcknowledgeMessages()).isTrue(); assertThat(healthIndicator.isSpecifiedSubscription()).isTrue(); verify(mockPubSubTemplate).pullAsync(healthIndicator.getSubscription(), 1, true); verify(future).get(healthIndicator.getTimeoutMillis(), TimeUnit.MILLISECONDS); }); } @SuppressWarnings("unchecked") @Test void compositeHealthIndicatorPresentMultiplePubSubTemplate() throws Exception { PubSubTemplate mockPubSubTemplate1 = mock(PubSubTemplate.class); PubSubTemplate mockPubSubTemplate2 = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); when(future.get(anyLong(), any())).thenReturn(Collections.emptyList()); when(mockPubSubTemplate1.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); when(mockPubSubTemplate2.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); this.baseContextRunner .withBean("pubSubTemplate1", PubSubTemplate.class, () -> mockPubSubTemplate1) .withBean("pubSubTemplate2", PubSubTemplate.class, () -> mockPubSubTemplate2) .withPropertyValues( "management.health.pubsub.enabled=true", "spring.cloud.gcp.pubsub.health.subscription=test", "spring.cloud.gcp.pubsub.health.timeout-millis=1500", "spring.cloud.gcp.pubsub.health.acknowledgeMessages=true", "spring.cloud.gcp.pubsub.subscriber.executorThreads=4") .run( ctx -> { assertThatThrownBy(() -> ctx.getBean(PubSubHealthIndicator.class)) .isInstanceOf(NoSuchBeanDefinitionException.class); CompositeHealthContributor healthContributor = ctx.getBean("pubSubHealthContributor", CompositeHealthContributor.class); assertThat(healthContributor).isNotNull(); assertThat(healthContributor.stream()).hasSize(2); assertThat(healthContributor.stream().map(c -> c.getName())) .containsExactlyInAnyOrder("pubSubTemplate1", "pubSubTemplate2"); }); } @SuppressWarnings("unchecked") @Test void apiExceptionWhenValidating_userSubscriptionSpecified_healthAutoConfigurationFails() throws Exception { PubSubHealthIndicatorProperties properties = new PubSubHealthIndicatorProperties(); PubSubHealthIndicatorAutoConfiguration p = new PubSubHealthIndicatorAutoConfiguration(properties); properties.setSubscription("test"); PubSubTemplate mockPubSubTemplate = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); Exception e = new ApiException( new IllegalStateException("Illegal State"), GrpcStatusCode.of(io.grpc.Status.Code.NOT_FOUND), false); when(mockPubSubTemplate.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); doThrow(new ExecutionException(e)).when(future).get(anyLong(), any()); Map<String, PubSubTemplate> pubSubTemplates = Collections.singletonMap("pubSubTemplate", mockPubSubTemplate); assertThatThrownBy(() -> p.pubSubHealthContributor(pubSubTemplates)) .isInstanceOf(BeanInitializationException.class); } @SuppressWarnings("unchecked") @Test void apiExceptionWhenValidating_userSubscriptionNotSpecified_healthAutoConfigurationSucceeds() throws Exception { PubSubHealthIndicatorProperties properties = new PubSubHealthIndicatorProperties(); PubSubHealthIndicatorAutoConfiguration p = new PubSubHealthIndicatorAutoConfiguration(properties); PubSubTemplate mockPubSubTemplate = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); Exception e = new ApiException( new IllegalStateException("Illegal State"), GrpcStatusCode.of(io.grpc.Status.Code.NOT_FOUND), false); when(mockPubSubTemplate.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); doThrow(new ExecutionException(e)).when(future).get(anyLong(), any()); Map<String, PubSubTemplate> pubSubTemplates = Collections.singletonMap("pubSubTemplate", mockPubSubTemplate); assertThatCode(() -> p.pubSubHealthContributor(pubSubTemplates)).doesNotThrowAnyException(); } @SuppressWarnings("unchecked") @Test void runtimeExceptionWhenValidating_healthAutoConfigurationFails() throws Exception { PubSubHealthIndicatorProperties properties = new PubSubHealthIndicatorProperties(); PubSubHealthIndicatorAutoConfiguration p = new PubSubHealthIndicatorAutoConfiguration(properties); PubSubTemplate mockPubSubTemplate = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); Exception e = new RuntimeException("Runtime exception"); when(mockPubSubTemplate.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); doThrow(e).when(future).get(anyLong(), any()); Map<String, PubSubTemplate> pubSubTemplates = Collections.singletonMap("pubSubTemplate", mockPubSubTemplate); assertThatThrownBy(() -> p.pubSubHealthContributor(pubSubTemplates)) .isInstanceOf(BeanInitializationException.class); } @SuppressWarnings("unchecked") @Test void interruptedExceptionWhenValidating_healthAutoConfigurationFails() throws Exception { PubSubHealthIndicatorProperties properties = new PubSubHealthIndicatorProperties(); PubSubHealthIndicatorAutoConfiguration p = new PubSubHealthIndicatorAutoConfiguration(properties); PubSubTemplate mockPubSubTemplate = mock(PubSubTemplate.class); ListenableFuture<List<AcknowledgeablePubsubMessage>> future = mock(ListenableFuture.class); InterruptedException e = new InterruptedException("interrupted"); when(mockPubSubTemplate.pullAsync(anyString(), anyInt(), anyBoolean())).thenReturn(future); doThrow(e).when(future).get(anyLong(), any()); Map<String, PubSubTemplate> pubSubTemplates = Collections.singletonMap("pubSubTemplate", mockPubSubTemplate); assertThatThrownBy(() -> p.pubSubHealthContributor(pubSubTemplates)) .isInstanceOf(BeanInitializationException.class); } @Test void healthCheckConfigurationBacksOffWhenHealthIndicatorBeanPresent() { PubSubHealthIndicator userHealthIndicator = mock(PubSubHealthIndicator.class); this.baseContextRunner .withBean("pubSubTemplate1", PubSubTemplate.class, () -> mock(PubSubTemplate.class)) .withBean("pubSubTemplate2", PubSubTemplate.class, () -> mock(PubSubTemplate.class)) .withBean(PubSubHealthIndicator.class, () -> userHealthIndicator) .withPropertyValues("management.health.pubsub.enabled=true") .run( ctx -> { assertThat(ctx).doesNotHaveBean("pubSubHealthContributor"); assertThat(ctx).hasSingleBean(PubSubHealthIndicator.class); assertThat(ctx.getBean(PubSubHealthIndicator.class)).isEqualTo(userHealthIndicator); }); } @Test void healthIndicatorDisabledWhenPubSubTurnedOff() { this.baseContextRunner .withPropertyValues( "management.health.pubsub.enabled=true", "spring.cloud.gcp.pubsub.enabled=false") .run( ctx -> { assertThat(ctx.getBeansOfType(PubSubHealthIndicator.class)).isEmpty(); }); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.client.internal; import static org.apache.geode.internal.logging.LogWriterLevel.FINE; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.CancelCriterion; import org.apache.geode.LogWriter; import org.apache.geode.cache.client.NoAvailableServersException; import org.apache.geode.cache.client.ServerConnectivityException; import org.apache.geode.cache.client.ServerOperationException; import org.apache.geode.cache.client.internal.pooling.ConnectionManager; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.ServerLocation; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.ServerQueueStatus; import org.apache.geode.internal.logging.InternalLogWriter; import org.apache.geode.internal.logging.LocalLogWriter; import org.apache.geode.test.junit.categories.ClientServerTest; @Category({ClientServerTest.class}) public class OpExecutorImplJUnitTest { DummyManager manager; private LogWriter logger; private DummyEndpointManager endpointManager; private DummyQueueManager queueManager; private RegisterInterestTracker riTracker; protected int borrows; protected int returns; protected int invalidateConnections; protected int exchanges; protected int serverCrashes; protected int getPrimary; protected int getBackups; private CancelCriterion cancelCriterion; @Before public void setUp() { this.logger = new LocalLogWriter(FINE.intLevel(), System.out); this.endpointManager = new DummyEndpointManager(); this.queueManager = new DummyQueueManager(); this.manager = new DummyManager(); riTracker = new RegisterInterestTracker(); cancelCriterion = new CancelCriterion() { @Override public String cancelInProgress() { return null; } @Override public RuntimeException generateCancelledException(Throwable e) { return null; } }; } @Test public void testExecute() throws Exception { OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, null); Object result = exec.execute(new Op() { @Override public Object attempt(Connection cnx) throws Exception { return "hello"; } }); assertEquals("hello", result); assertEquals(1, borrows); assertEquals(1, returns); assertEquals(0, invalidateConnections); assertEquals(0, serverCrashes); reset(); try { result = exec.execute(new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new SocketTimeoutException(); } }); fail("Should have got an exception"); } catch (ServerConnectivityException expected) { // do nothing } assertEquals(1, borrows); assertEquals(3, exchanges); assertEquals(1, returns); assertEquals(4, invalidateConnections); assertEquals(0, serverCrashes); reset(); try { result = exec.execute(new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new ServerOperationException("Something didn't work"); } }); fail("Should have got an exception"); } catch (ServerOperationException expected) { // do nothing } assertEquals(1, borrows); assertEquals(1, returns); assertEquals(0, invalidateConnections); assertEquals(0, serverCrashes); reset(); try { result = exec.execute(new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new IOException("Something didn't work"); } }); fail("Should have got an exception"); } catch (ServerConnectivityException expected) { // do nothing } assertEquals(1, borrows); assertEquals(3, exchanges); assertEquals(1, returns); assertEquals(4, invalidateConnections); assertEquals(4, serverCrashes); } private void reset() { borrows = 0; returns = 0; invalidateConnections = 0; exchanges = 0; serverCrashes = 0; getPrimary = 0; getBackups = 0; } @Test public void testExecuteOncePerServer() throws Exception { OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, null); manager.numServers = 5; try { exec.execute(new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new IOException("Something didn't work"); } }); fail("Should have got an exception"); } catch (ServerConnectivityException expected) { // do nothing } assertEquals(1, borrows); assertEquals(4, exchanges); assertEquals(1, returns); assertEquals(6, invalidateConnections); assertEquals(6, serverCrashes); } @Test public void testRetryFailedServers() throws Exception { OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 10, 10, cancelCriterion, null); manager.numServers = 5; try { exec.execute(new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new IOException("Something didn't work"); } }); fail("Should have got an exception"); } catch (ServerConnectivityException expected) { // do nothing } assertEquals(1, borrows); assertEquals(10, exchanges); assertEquals(1, returns); assertEquals(11, invalidateConnections); assertEquals(11, serverCrashes); } @Test public void testExecuteOn() throws Exception { OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, null); ServerLocation server = new ServerLocation("localhost", -1); Object result = exec.executeOn(server, new Op() { @Override public Object attempt(Connection cnx) throws Exception { return "hello"; } }); assertEquals("hello", result); assertEquals(1, borrows); assertEquals(1, returns); assertEquals(0, invalidateConnections); assertEquals(0, serverCrashes); reset(); try { result = exec.executeOn(server, new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new SocketTimeoutException(); } }); fail("Should have got an exception"); } catch (ServerConnectivityException expected) { // do nothing } assertEquals(1, borrows); assertEquals(1, returns); assertEquals(1, invalidateConnections); assertEquals(0, serverCrashes); reset(); try { result = exec.executeOn(server, new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new ServerOperationException("Something didn't work"); } }); fail("Should have got an exception"); } catch (ServerOperationException expected) { // do nothing } assertEquals(1, borrows); assertEquals(1, returns); assertEquals(0, invalidateConnections); assertEquals(0, serverCrashes); reset(); { final String expectedEx = "java.lang.Exception"; final String addExpected = "<ExpectedException action=add>" + expectedEx + "</ExpectedException>"; final String removeExpected = "<ExpectedException action=remove>" + expectedEx + "</ExpectedException>"; logger.info(addExpected); try { result = exec.executeOn(server, new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new Exception("Something didn't work"); } }); fail("Should have got an exception"); } catch (ServerConnectivityException expected) { // do nothing } finally { logger.info(removeExpected); } } assertEquals(1, borrows); assertEquals(1, returns); assertEquals(1, invalidateConnections); assertEquals(1, serverCrashes); } @Test public void testExecuteOnAllQueueServers() { OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, null); exec.executeOnAllQueueServers(new Op() { @Override public Object attempt(Connection cnx) throws Exception { return "hello"; } }); assertEquals(0, invalidateConnections); assertEquals(0, serverCrashes); assertEquals(1, getPrimary); assertEquals(1, getBackups); reset(); queueManager.backups = 3; exec.executeOnAllQueueServers(new Op() { @Override public Object attempt(Connection cnx) throws Exception { throw new SocketTimeoutException(); } }); assertEquals(4, invalidateConnections); assertEquals(0, serverCrashes); assertEquals(1, getPrimary); assertEquals(1, getBackups); reset(); queueManager.backups = 3; Object result = exec.executeOnQueuesAndReturnPrimaryResult(new Op() { int i = 0; @Override public Object attempt(Connection cnx) throws Exception { i++; if (i < 15) { throw new IOException(); } return "hello"; } }); assertEquals("hello", result); assertEquals(14, serverCrashes); assertEquals(14, invalidateConnections); assertEquals(12, getPrimary); assertEquals(1, getBackups); } @Test public void executeWithServerAffinityDoesNotChangeInitialRetryCountOfZero() { OpExecutorImpl opExecutor = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.class)); Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.class); ServerLocation serverLocation = mock(ServerLocation.class); opExecutor.setAffinityRetryCount(0); opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp); assertEquals(0, opExecutor.getAffinityRetryCount()); } @Test public void executeWithServerAffinityWithNonZeroAffinityRetryCountWillNotSetToZero() { OpExecutorImpl opExecutor = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.class)); Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.class); ServerLocation serverLocation = mock(ServerLocation.class); opExecutor.setAffinityRetryCount(1); opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp); assertNotEquals(0, opExecutor.getAffinityRetryCount()); } @Test public void executeWithServerAffinityWithServerConnectivityExceptionIncrementsRetryCountAndResetsToZero() { OpExecutorImpl opExecutor = spy(new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.class))); Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.class); ServerLocation serverLocation = mock(ServerLocation.class); ServerConnectivityException serverConnectivityException = new ServerConnectivityException(); doThrow(serverConnectivityException).when(opExecutor).executeOnServer(serverLocation, txSynchronizationOp, true, false); opExecutor.setupServerAffinity(true); when(((AbstractOp) txSynchronizationOp).getMessage()).thenReturn(mock(Message.class)); opExecutor.setAffinityRetryCount(0); opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp); verify(opExecutor, times(1)).setAffinityRetryCount(1); assertEquals(0, opExecutor.getAffinityRetryCount()); } @Test public void executeWithServerAffinityAndRetryCountGreaterThansTxRetryAttemptThrowsServerConnectivityException() { OpExecutorImpl opExecutor = spy(new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.class))); Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.class); ServerLocation serverLocation = mock(ServerLocation.class); ServerConnectivityException serverConnectivityException = new ServerConnectivityException(); doThrow(serverConnectivityException).when(opExecutor).executeOnServer(serverLocation, txSynchronizationOp, true, false); opExecutor.setupServerAffinity(true); when(((AbstractOp) txSynchronizationOp).getMessage()).thenReturn(mock(Message.class)); opExecutor.setAffinityRetryCount(opExecutor.TX_RETRY_ATTEMPT + 1); assertThatThrownBy( () -> opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp)) .isSameAs(serverConnectivityException); } private class DummyManager implements ConnectionManager { protected int numServers = Integer.MAX_VALUE; private int currentServer = 0; public DummyManager() {} @Override public void emergencyClose() {} @Override public Connection borrowConnection(long aquireTimeout) { borrows++; return new DummyConnection(new ServerLocation("localhost", currentServer++ % numServers)); } @Override public Connection borrowConnection(ServerLocation server, boolean onlyUseExistingCnx) { borrows++; return new DummyConnection(server); } @Override public void close(boolean keepAlive) {} @Override public void returnConnection(Connection connection) { returns++; } @Override public void returnConnection(Connection connection, boolean accessed) { returns++; } @Override public void start(ScheduledExecutorService backgroundProcessor) {} @Override public Connection exchangeConnection(Connection conn, Set<ServerLocation> excludedServers) { if (excludedServers.size() >= numServers) { throw new NoAvailableServersException(); } exchanges++; return new DummyConnection(new ServerLocation("localhost", currentServer++ % numServers)); } @Override public int getConnectionCount() { return 0; } } private class DummyConnection implements Connection { private ServerLocation server; public DummyConnection(ServerLocation serverLocation) { this.server = serverLocation; } @Override public void close(boolean keepAlive) throws Exception {} @Override public void destroy() { invalidateConnections++; } @Override public boolean isDestroyed() { return false; } @Override public ByteBuffer getCommBuffer() { return null; } @Override public ServerLocation getServer() { return server; } @Override public Socket getSocket() { return null; } @Override public ConnectionStats getStats() { return null; } @Override public int getDistributedSystemId() { return 0; } @Override public Endpoint getEndpoint() { return new Endpoint(null, null, null, null, null); } @Override public ServerQueueStatus getQueueStatus() { return null; } @Override public Object execute(Op op) throws Exception { return op.attempt(this); } @Override public void emergencyClose() {} @Override public short getWanSiteVersion() { return -1; } @Override public void setWanSiteVersion(short wanSiteVersion) {} @Override public InputStream getInputStream() { return null; } @Override public OutputStream getOutputStream() { return null; } @Override public void setConnectionID(long id) {} @Override public long getConnectionID() { return 0; } } private class DummyEndpointManager implements EndpointManager { @Override public void addListener(EndpointListener listener) {} @Override public void close() {} @Override public Endpoint referenceEndpoint(ServerLocation server, DistributedMember memberId) { return null; } @Override public Map getEndpointMap() { return null; } @Override public void removeListener(EndpointListener listener) {} @Override public void serverCrashed(Endpoint endpoint) { serverCrashes++; } @Override public int getConnectedServerCount() { return 0; } @Override public Map getAllStats() { return null; } @Override public String getPoolName() { return null; } } private class DummyQueueManager implements QueueManager { int backups = 0; int currentServer = 0; @Override public QueueConnections getAllConnectionsNoWait() { return getAllConnections(); } @Override public void emergencyClose() {} @Override public QueueConnections getAllConnections() { return new QueueConnections() { @Override public List getBackups() { getBackups++; ArrayList result = new ArrayList(backups); for (int i = 0; i < backups; i++) { result.add(new DummyConnection(new ServerLocation("localhost", currentServer++))); } return result; } @Override public Connection getPrimary() { getPrimary++; return new DummyConnection(new ServerLocation("localhost", currentServer++)); } @Override public QueueConnectionImpl getConnection(Endpoint ep) { return null; } }; } @Override public void close(boolean keepAlive) {} @Override public void start(ScheduledExecutorService background) {} @Override public QueueState getState() { return null; } @Override public InternalPool getPool() { return null; } @Override public void readyForEvents(InternalDistributedSystem system) {} @Override public InternalLogWriter getSecurityLogger() { return null; } @Override public void checkEndpoint(ClientUpdater qc, Endpoint endpoint) {} } }
/* * 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.search; import com.carrotsearch.hppc.IntArrayList; import org.apache.lucene.search.Query; import org.apache.lucene.store.AlreadyClosedException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchTask; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.query.AbstractQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryRewriteContext; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.SearchPlugin; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.ShardFetchRequest; import org.elasticsearch.search.internal.AliasFilter; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.ShardSearchLocalRequest; import org.elasticsearch.test.ESSingleNodeTestCase; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import static java.util.Collections.singletonList; import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE; import static org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.DELETED; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; public class SearchServiceTests extends ESSingleNodeTestCase { @Override protected boolean resetNodeAfterTest() { return true; } @Override protected Collection<Class<? extends Plugin>> getPlugins() { return pluginList(FailOnRewriteQueryPlugin.class); } @Override protected Settings nodeSettings() { return Settings.builder().put("search.default_search_timeout", "5s").build(); } public void testClearOnClose() throws ExecutionException, InterruptedException { createIndex("index"); client().prepareIndex("index", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); SearchResponse searchResponse = client().prepareSearch("index").setSize(1).setScroll("1m").get(); assertThat(searchResponse.getScrollId(), is(notNullValue())); SearchService service = getInstanceFromNode(SearchService.class); assertEquals(1, service.getActiveContexts()); service.doClose(); // this kills the keep-alive reaper we have to reset the node after this test assertEquals(0, service.getActiveContexts()); } public void testClearOnStop() throws ExecutionException, InterruptedException { createIndex("index"); client().prepareIndex("index", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); SearchResponse searchResponse = client().prepareSearch("index").setSize(1).setScroll("1m").get(); assertThat(searchResponse.getScrollId(), is(notNullValue())); SearchService service = getInstanceFromNode(SearchService.class); assertEquals(1, service.getActiveContexts()); service.doStop(); assertEquals(0, service.getActiveContexts()); } public void testClearIndexDelete() throws ExecutionException, InterruptedException { createIndex("index"); client().prepareIndex("index", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); SearchResponse searchResponse = client().prepareSearch("index").setSize(1).setScroll("1m").get(); assertThat(searchResponse.getScrollId(), is(notNullValue())); SearchService service = getInstanceFromNode(SearchService.class); assertEquals(1, service.getActiveContexts()); assertAcked(client().admin().indices().prepareDelete("index")); assertEquals(0, service.getActiveContexts()); } public void testCloseSearchContextOnRewriteException() { createIndex("index"); client().prepareIndex("index", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); SearchService service = getInstanceFromNode(SearchService.class); IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); IndexShard indexShard = indexService.getShard(0); final int activeContexts = service.getActiveContexts(); final int activeRefs = indexShard.store().refCount(); expectThrows(SearchPhaseExecutionException.class, () -> client().prepareSearch("index").setQuery(new FailOnRewriteQueryBuilder()).get()); assertEquals(activeContexts, service.getActiveContexts()); assertEquals(activeRefs, indexShard.store().refCount()); } public void testSearchWhileIndexDeleted() throws IOException, InterruptedException { createIndex("index"); client().prepareIndex("index", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); SearchService service = getInstanceFromNode(SearchService.class); IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); IndexShard indexShard = indexService.getShard(0); AtomicBoolean running = new AtomicBoolean(true); CountDownLatch startGun = new CountDownLatch(1); Semaphore semaphore = new Semaphore(Integer.MAX_VALUE); final Thread thread = new Thread() { @Override public void run() { startGun.countDown(); while(running.get()) { service.afterIndexRemoved(indexService.index(), indexService.getIndexSettings(), DELETED); if (randomBoolean()) { // here we trigger some refreshes to ensure the IR go out of scope such that we hit ACE if we access a search // context in a non-sane way. try { semaphore.acquire(); } catch (InterruptedException e) { throw new AssertionError(e); } client().prepareIndex("index", "type").setSource("field", "value") .setRefreshPolicy(randomFrom(WriteRequest.RefreshPolicy.values())).execute(new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse indexResponse) { semaphore.release(); } @Override public void onFailure(Exception e) { semaphore.release(); } }); } } } }; thread.start(); startGun.await(); try { final int rounds = scaledRandomIntBetween(100, 10000); for (int i = 0; i < rounds; i++) { try { SearchPhaseResult searchPhaseResult = service.executeQueryPhase( new ShardSearchLocalRequest(indexShard.shardId(), 1, SearchType.DEFAULT, new SearchSourceBuilder(), new String[0], false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1.0f), new SearchTask(123L, "", "", "", null)); IntArrayList intCursors = new IntArrayList(1); intCursors.add(0); ShardFetchRequest req = new ShardFetchRequest(searchPhaseResult.getRequestId(), intCursors, null /* not a scroll */); service.executeFetchPhase(req, new SearchTask(123L, "", "", "", null)); } catch (AlreadyClosedException ex) { throw ex; } catch (IllegalStateException ex) { assertEquals("search context is already closed can't increment refCount current count [0]", ex.getMessage()); } catch (SearchContextMissingException ex) { // that's fine } } } finally { running.set(false); thread.join(); semaphore.acquire(Integer.MAX_VALUE); } } public void testTimeout() throws IOException { createIndex("index"); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); final SearchContext contextWithDefaultTimeout = service.createContext( new ShardSearchLocalRequest( indexShard.shardId(), 1, SearchType.DEFAULT, new SearchSourceBuilder(), new String[0], false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1.0f), null); try { // the search context should inherit the default timeout assertThat(contextWithDefaultTimeout.timeout(), equalTo(TimeValue.timeValueSeconds(5))); } finally { contextWithDefaultTimeout.decRef(); service.freeContext(contextWithDefaultTimeout.id()); } final long seconds = randomIntBetween(6, 10); final SearchContext context = service.createContext( new ShardSearchLocalRequest( indexShard.shardId(), 1, SearchType.DEFAULT, new SearchSourceBuilder().timeout(TimeValue.timeValueSeconds(seconds)), new String[0], false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1.0f), null); try { // the search context should inherit the query timeout assertThat(context.timeout(), equalTo(TimeValue.timeValueSeconds(seconds))); } finally { context.decRef(); service.freeContext(context.id()); } } public static class FailOnRewriteQueryPlugin extends Plugin implements SearchPlugin { @Override public List<QuerySpec<?>> getQueries() { return singletonList(new QuerySpec<>("fail_on_rewrite_query", FailOnRewriteQueryBuilder::new, parseContext -> { throw new UnsupportedOperationException("No query parser for this plugin"); })); } } public static class FailOnRewriteQueryBuilder extends AbstractQueryBuilder<FailOnRewriteQueryBuilder> { public FailOnRewriteQueryBuilder(StreamInput in) throws IOException { super(in); } public FailOnRewriteQueryBuilder() { } @Override protected QueryBuilder doRewrite(QueryRewriteContext queryShardContext) throws IOException { throw new IllegalStateException("Fail on rewrite phase"); } @Override protected void doWriteTo(StreamOutput out) throws IOException { } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { } @Override protected Query doToQuery(QueryShardContext context) throws IOException { return null; } @Override protected boolean doEquals(FailOnRewriteQueryBuilder other) { return false; } @Override protected int doHashCode() { return 0; } @Override public String getWriteableName() { return null; } } }
/* * Copyright 2015 - 2019 Michael Rapp * * 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 de.mrapp.android.validation.adapter; import android.content.Context; import android.content.res.ColorStateList; import android.database.DataSetObserver; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import de.mrapp.util.Condition; /** * A spinner adapter, which acts as a proxy for an other adapter in order to initially show a hint * instead of the adapter's first item. * * @author Michael Rapp * @since 1.0.0 */ public class ProxySpinnerAdapter implements SpinnerAdapter, ListAdapter { /** * The context, which is used by the adapter. */ private final Context context; /** * The adapter, which contains the actual items. */ private final SpinnerAdapter adapter; /** * The resource id if the layout, which should be used to display the hint. */ private final int hintViewId; /** * The hint, which is displayed initially. */ private final CharSequence hint; /** * The color of the hint, which is displayed initially. */ private final ColorStateList hintColor; /** * Inflates and returns the view, which is used to display the hint. * * @param parent * The parent view of the view, which should be inflated, as an instance of the class * {@link ViewGroup} or null, if no parent view is available * @return The view, which has been inflated, as an instance of the class {@link View} */ private View inflateHintView(@Nullable final ViewGroup parent) { TextView view = (TextView) LayoutInflater.from(context).inflate(hintViewId, parent, false); view.setText(hint); if (hintColor != null) { view.setTextColor(hintColor); } return view; } /** * Creates a new spinner adapter, which acts as a proxy for an other adapter in order to * initially show a hint instead of the adapter's first item. * * @param context * The context, which should be used by the adapter, as an instance of the class {@link * Context}. The context may not be null * @param adapter * The adapter, which contains the actual items, as an instance of the type {@link * SpinnerAdapter}. The adapter may not be null * @param hintViewId * The resource id of the layout, which should be used to display the hint, as an {@link * Integer} value. The resource id must corresponds to a valid layout resource * @param hint * The hint, which should be displayed initially, as an instance of the type {@link * CharSequence} or null, if no hint should be displayed * @param hintColor * The color of the hint, which should be displayed initially, as an instance of the * class {@link ColorStateList} or null, if the default color should be used */ public ProxySpinnerAdapter(@NonNull final Context context, @NonNull final SpinnerAdapter adapter, @LayoutRes final int hintViewId, @Nullable final CharSequence hint, @Nullable final ColorStateList hintColor) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(adapter, "The adapter may not be null"); this.context = context; this.adapter = adapter; this.hintViewId = hintViewId; this.hint = hint; this.hintColor = hintColor; } /** * Returns the adapter, which contains the actual items. * * @return The adapter, which contains the actual items, as an instance of the type {@link * SpinnerAdapter} */ public final SpinnerAdapter getAdapter() { return adapter; } @Override public final View getView(final int position, final View convertView, final ViewGroup parent) { if (position == 0) { return inflateHintView(parent); } return adapter.getView(position - 1, null, parent); } @Override public final View getDropDownView(final int position, final View convertView, final ViewGroup parent) { if (position == 0) { return new View(context); } return adapter.getDropDownView(position - 1, null, parent); } @Override public final int getCount() { return adapter.getCount() == 0 ? 0 : adapter.getCount() + 1; } @Override public final Object getItem(final int position) { return position == 0 ? null : adapter.getItem(position - 1); } @Override public final int getItemViewType(final int position) { return 0; } @Override public final int getViewTypeCount() { return 1; } @Override public final long getItemId(final int position) { return position > 0 ? adapter.getItemId(position - 1) : -1; } @Override public final boolean hasStableIds() { return adapter.hasStableIds(); } @Override public final boolean isEmpty() { return adapter.isEmpty(); } @Override public final void registerDataSetObserver(final DataSetObserver observer) { adapter.registerDataSetObserver(observer); } @Override public final void unregisterDataSetObserver(final DataSetObserver observer) { adapter.unregisterDataSetObserver(observer); } @Override public final boolean areAllItemsEnabled() { return false; } @Override public final boolean isEnabled(final int position) { return position > 0; } }
package com.planet_ink.coffee_mud.Races; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; 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.Libraries.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.*; import java.util.*; /* Copyright 2001-2022 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 Dwarf extends StdRace { @Override public String ID() { return "Dwarf"; } public Dwarf() { super(); super.naturalAbilImmunities.add("Disease_Syphilis"); } private final static String localizedStaticName = CMLib.lang().L("Dwarf"); @Override public String name() { return localizedStaticName; } @Override public int shortestMale() { return 52; } @Override public int shortestFemale() { return 48; } @Override public int heightVariance() { return 8; } @Override public int lightestWeight() { return 150; } @Override public int weightVariance() { return 100; } @Override public long forbiddenWornBits() { return 0; } private final static String localizedStaticRacialCat = CMLib.lang().L("Dwarf"); @Override public String racialCategory() { return localizedStaticRacialCat; } private final String[] culturalAbilityNames = { "Dwarven", "Mining" }; private final int[] culturalAbilityProficiencies = { 100, 50 }; @Override public String[] culturalAbilityNames() { return culturalAbilityNames; } @Override public int[] culturalAbilityProficiencies() { return culturalAbilityProficiencies; } private final String[] racialEffectNames = { "Skill_Stonecunning" }; private final int[] racialEffectLevels = { 1 }; private final String[] racialEffectParms = { "" }; @Override protected String[] racialEffectNames() { return racialEffectNames; } @Override protected int[] racialEffectLevels() { return racialEffectLevels; } @Override protected String[] racialEffectParms() { return racialEffectParms; } // an ey ea he ne ar ha to le fo no gi mo wa ta wi private static final int[] parts={0 ,2 ,2 ,1 ,1 ,2 ,2 ,1 ,2 ,2 ,1 ,0 ,1 ,1 ,0 ,0 }; @Override public int[] bodyMask() { return parts; } private final int[] agingChart = { 0, 1, 5, 40, 125, 188, 250, 270, 290 }; @Override public int[] getAgingChart() { return agingChart; } private static Vector<RawMaterial> resources = new Vector<RawMaterial>(); @Override public int availabilityCode() { return Area.THEME_FANTASY; } @Override public void affectPhyStats(final Physical affected, final PhyStats affectableStats) { super.affectPhyStats(affected,affectableStats); affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_SEE_INFRARED); } @Override public void affectCharStats(final MOB affectedMOB, final CharStats affectableStats) { super.affectCharStats(affectedMOB, affectableStats); affectableStats.adjStat(CharStats.STAT_CONSTITUTION,1); affectableStats.adjStat(CharStats.STAT_CHARISMA,-1); affectableStats.setStat(CharStats.STAT_SAVE_POISON,affectableStats.getStat(CharStats.STAT_SAVE_POISON)+10); } @Override public void unaffectCharStats(final MOB affectedMOB, final CharStats affectableStats) { super.unaffectCharStats(affectedMOB, affectableStats); affectableStats.adjStat(CharStats.STAT_CONSTITUTION,-1); affectableStats.adjStat(CharStats.STAT_CHARISMA,+1); affectableStats.setStat(CharStats.STAT_SAVE_POISON,affectableStats.getStat(CharStats.STAT_SAVE_POISON)-10); } @Override public List<Item> outfit(final MOB myChar) { if(outfitChoices==null) { // Have to, since it requires use of special constructor final Armor s1=CMClass.getArmor("GenShirt"); if(s1 == null) return new Vector<Item>(); outfitChoices=new Vector<Item>(); s1.setName(L("a grey work tunic")); s1.setDisplayText(L("a grey work tunic has been left here.")); s1.setDescription(L("There are lots of little loops and folks for hanging tools about it.")); s1.text(); outfitChoices.add(s1); final Armor s2=CMClass.getArmor("GenShoes"); s2.setName(L("a pair of hefty work boots")); s2.setDisplayText(L("some hefty work boots have been left here.")); s2.setDescription(L("Thick and well worn boots with very tough souls.")); s2.text(); outfitChoices.add(s2); final Armor p1=CMClass.getArmor("GenPants"); p1.setName(L("some hefty work pants")); p1.setDisplayText(L("some hefty work pants have been left here.")); p1.setDescription(L("There are lots of little loops and folks for hanging tools about it.")); p1.text(); outfitChoices.add(p1); final Armor s3=CMClass.getArmor("GenBelt"); outfitChoices.add(s3); } return outfitChoices; } @Override public Weapon myNaturalWeapon() { return funHumanoidWeapon(); } @Override public String healthText(final MOB viewer, final MOB mob) { final double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints())); if(pct<.10) return L("^r@x1^r is nearly dead!^N",mob.name(viewer)); else if(pct<.20) return L("^r@x1^r is covered in blood.^N",mob.name(viewer)); else if(pct<.30) return L("^r@x1^r is bleeding from cuts and gashes.^N",mob.name(viewer)); else if(pct<.40) return L("^y@x1^y has numerous wounds.^N",mob.name(viewer)); else if(pct<.50) return L("^y@x1^y has some wounds.^N",mob.name(viewer)); else if(pct<.60) return L("^p@x1^p has a few cuts.^N",mob.name(viewer)); else if(pct<.70) return L("^p@x1^p is cut.^N",mob.name(viewer)); else if(pct<.80) return L("^g@x1^g has some bruises.^N",mob.name(viewer)); else if(pct<.90) return L("^g@x1^g is very winded.^N",mob.name(viewer)); else if(pct<.99) return L("^g@x1^g is slightly winded.^N",mob.name(viewer)); else return L("^c@x1^c is in perfect health.^N",mob.name(viewer)); } @Override public List<RawMaterial> myResources() { synchronized(resources) { if(resources.size()==0) { resources.addElement(makeResource (L("a @x1 beard",name().toLowerCase()),RawMaterial.RESOURCE_FUR,L("@x1 beard",name().toLowerCase()))); resources.addElement(makeResource (L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD)); resources.addElement(makeResource (L("a pile of @x1 bones",name().toLowerCase()),RawMaterial.RESOURCE_BONE)); } } return resources; } }
/* * 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.search.aggregations; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorStreams; import org.elasticsearch.search.aggregations.support.AggregationPath; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * An internal implementation of {@link Aggregation}. Serves as a base class for all aggregation implementations. */ public abstract class InternalAggregation implements Aggregation, ToXContent, Streamable { /** * The aggregation type that holds all the string types that are associated with an aggregation: * <ul> * <li>name - used as the parser type</li> * <li>stream - used as the stream type</li> * </ul> */ public static class Type { private String name; private BytesReference stream; public Type(String name) { this(name, new BytesArray(name)); } public Type(String name, String stream) { this(name, new BytesArray(stream)); } public Type(String name, BytesReference stream) { this.name = name; this.stream = stream; } /** * @return The name of the type of aggregation. This is the key for parsing the aggregation from XContent and is the name of the * aggregation's builder when serialized. */ public String name() { return name; } /** * @return The name of the stream type (used for registering the aggregation stream * (see {@link AggregationStreams#registerStream(AggregationStreams.Stream, org.elasticsearch.common.bytes.BytesReference...)}). */ public BytesReference stream() { return stream; } @Override public String toString() { return name; } } public static class ReduceContext { private final BigArrays bigArrays; private final ScriptService scriptService; private final ClusterState clusterState; public ReduceContext(BigArrays bigArrays, ScriptService scriptService, ClusterState clusterState) { this.bigArrays = bigArrays; this.scriptService = scriptService; this.clusterState = clusterState; } public BigArrays bigArrays() { return bigArrays; } public ScriptService scriptService() { return scriptService; } public ClusterState clusterState() { return clusterState; } } protected String name; protected Map<String, Object> metaData; private List<PipelineAggregator> pipelineAggregators; /** Constructs an un initialized addAggregation (used for serialization) **/ protected InternalAggregation() {} /** * Constructs an get with a given name. * * @param name The name of the get. */ protected InternalAggregation(String name, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) { this.name = name; this.pipelineAggregators = pipelineAggregators; this.metaData = metaData; } @Override public String getName() { return name; } /** * @return The {@link Type} of this aggregation */ public abstract Type type(); /** * Reduces the given addAggregation to a single one and returns it. In <b>most</b> cases, the assumption will be the all given * addAggregation are of the same type (the same type as this aggregation). For best efficiency, when implementing, * try reusing an existing get instance (typically the first in the given list) to save on redundant object * construction. */ public final InternalAggregation reduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) { InternalAggregation aggResult = doReduce(aggregations, reduceContext); for (PipelineAggregator pipelineAggregator : pipelineAggregators) { aggResult = pipelineAggregator.reduce(aggResult, reduceContext); } return aggResult; } public abstract InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext); @Override public Object getProperty(String path) { AggregationPath aggPath = AggregationPath.parse(path); return getProperty(aggPath.getPathElementsAsStringList()); } public abstract Object getProperty(List<String> path); /** * Read a size under the assumption that a value of 0 means unlimited. */ protected static int readSize(StreamInput in) throws IOException { final int size = in.readVInt(); return size == 0 ? Integer.MAX_VALUE : size; } /** * Write a size under the assumption that a value of 0 means unlimited. */ protected static void writeSize(int size, StreamOutput out) throws IOException { if (size == Integer.MAX_VALUE) { size = 0; } out.writeVInt(size); } @Override public Map<String, Object> getMetaData() { return metaData; } public List<PipelineAggregator> pipelineAggregators() { return pipelineAggregators; } @Override public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); if (this.metaData != null) { builder.field(CommonFields.META); builder.map(this.metaData); } doXContentBody(builder, params); builder.endObject(); return builder; } public abstract XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException; @Override public final void writeTo(StreamOutput out) throws IOException { out.writeString(name); out.writeGenericValue(metaData); out.writeVInt(pipelineAggregators.size()); for (PipelineAggregator pipelineAggregator : pipelineAggregators) { out.writeBytesReference(pipelineAggregator.type().stream()); pipelineAggregator.writeTo(out); } doWriteTo(out); } protected abstract void doWriteTo(StreamOutput out) throws IOException; @Override public final void readFrom(StreamInput in) throws IOException { name = in.readString(); metaData = in.readMap(); int size = in.readVInt(); if (size == 0) { pipelineAggregators = Collections.emptyList(); } else { pipelineAggregators = new ArrayList<>(size); for (int i = 0; i < size; i++) { BytesReference type = in.readBytesReference(); PipelineAggregator pipelineAggregator = PipelineAggregatorStreams.stream(type).readResult(in); pipelineAggregators.add(pipelineAggregator); } } doReadFrom(in); } protected abstract void doReadFrom(StreamInput in) throws IOException; /** * Common xcontent fields that are shared among addAggregation */ public static final class CommonFields { public static final String META = "meta"; public static final String BUCKETS = "buckets"; public static final String VALUE = "value"; public static final String VALUES = "values"; public static final String VALUE_AS_STRING = "value_as_string"; public static final String DOC_COUNT = "doc_count"; public static final String KEY = "key"; public static final String KEY_AS_STRING = "key_as_string"; public static final String FROM = "from"; public static final String FROM_AS_STRING = "from_as_string"; public static final String TO = "to"; public static final String TO_AS_STRING = "to_as_string"; } }