gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * 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.tika.example; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.tika.Tika; import org.apache.tika.exception.TikaException; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.serialization.JsonMetadataList; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.EmptyParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.parser.RecursiveParserWrapper; import org.apache.tika.sax.BasicContentHandlerFactory; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.sax.ContentHandlerFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class ParsingExample { /** * Example of how to use Tika's parseToString method to parse the content of a file, * and return any text found. * <p> * Note: Tika.parseToString() will extract content from the outer container * document and any embedded/attached documents. * * @return The content of a file. */ public String parseToStringExample() throws IOException, SAXException, TikaException { Tika tika = new Tika(); try (InputStream stream = ParsingExample.class.getResourceAsStream("test.doc")) { return tika.parseToString(stream); } } /** * Example of how to use Tika to parse a file when you do not know its file type * ahead of time. * <p> * AutoDetectParser attempts to discover the file's type automatically, then call * the exact Parser built for that file type. * <p> * The stream to be parsed by the Parser. In this case, we get a file from the * resources folder of this project. * <p> * Handlers are used to get the exact information you want out of the host of * information gathered by Parsers. The body content handler, intuitively, extracts * everything that would go between HTML body tags. * <p> * The Metadata object will be filled by the Parser with Metadata discovered about * the file being parsed. * <p> * Note: This example will extract content from the outer document and all * embedded documents. However, if you choose to use a {@link ParseContext}, * make sure to set a {@link Parser} or else embedded content will not be * parsed. * * @return The content of a file. */ public String parseExample() throws IOException, SAXException, TikaException { AutoDetectParser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); try (InputStream stream = ParsingExample.class.getResourceAsStream("test.doc")) { parser.parse(stream, handler, metadata); return handler.toString(); } } /** * If you don't want content from embedded documents, send in * a {@link org.apache.tika.parser.ParseContext} that does contains a * {@link EmptyParser}. * * @return The content of a file. */ public String parseNoEmbeddedExample() throws IOException, SAXException, TikaException { AutoDetectParser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); ParseContext parseContext = new ParseContext(); parseContext.set(Parser.class, new EmptyParser()); try (InputStream stream = ParsingExample.class.getResourceAsStream("test_recursive_embedded.docx")) { parser.parse(stream, handler, metadata, parseContext); return handler.toString(); } } /** * This example shows how to extract content from the outer document and all * embedded documents. The key is to specify a {@link Parser} in the {@link ParseContext}. * * @return content, including from embedded documents * @throws IOException * @throws SAXException * @throws TikaException */ public String parseEmbeddedExample() throws IOException, SAXException, TikaException { AutoDetectParser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); ParseContext context = new ParseContext(); context.set(Parser.class, parser); try (InputStream stream = ParsingExample.class.getResourceAsStream("test_recursive_embedded.docx")) { parser.parse(stream, handler, metadata, context); return handler.toString(); } } /** * For documents that may contain embedded documents, it might be helpful * to create list of metadata objects, one for the container document and * one for each embedded document. This allows easy access to both the * extracted content and the metadata of each embedded document. * Note that many document formats can contain embedded documents, * including traditional container formats -- zip, tar and others -- but also * common office document formats including: MSWord, MSExcel, * MSPowerPoint, RTF, PDF, MSG and several others. * <p> * The "content" format is determined by the ContentHandlerFactory, and * the content is stored in {@link org.apache.tika.parser.RecursiveParserWrapper#TIKA_CONTENT} * <p> * The drawback to the RecursiveParserWrapper is that it caches metadata and contents * in memory. This should not be used on files whose contents are too big to be handled * in memory. * * @return a list of metadata object, one each for the container file and each embedded file * @throws IOException * @throws SAXException * @throws TikaException */ public List<Metadata> recursiveParserWrapperExample() throws IOException, SAXException, TikaException { Parser p = new AutoDetectParser(); ContentHandlerFactory factory = new BasicContentHandlerFactory( BasicContentHandlerFactory.HANDLER_TYPE.HTML, -1); RecursiveParserWrapper wrapper = new RecursiveParserWrapper(p, factory); Metadata metadata = new Metadata(); metadata.set(Metadata.RESOURCE_NAME_KEY, "test_recursive_embedded.docx"); ParseContext context = new ParseContext(); try (InputStream stream = ParsingExample.class.getResourceAsStream("test_recursive_embedded.docx")) { wrapper.parse(stream, new DefaultHandler(), metadata, context); } return wrapper.getMetadata(); } /** * We include a simple JSON serializer for a list of metadata with * {@link org.apache.tika.metadata.serialization.JsonMetadataList}. * That class also includes a deserializer to convert from JSON * back to a List<Metadata>. * <p> * This functionality is also available in tika-app's GUI, and * with the -J option on tika-app's commandline. For tika-server * users, there is the "rmeta" service that will return this format. * * @return a JSON representation of a list of Metadata objects * @throws IOException * @throws SAXException * @throws TikaException */ public String serializedRecursiveParserWrapperExample() throws IOException, SAXException, TikaException { List<Metadata> metadataList = recursiveParserWrapperExample(); StringWriter writer = new StringWriter(); JsonMetadataList.toJson(metadataList, writer); return writer.toString(); } /** * @param outputPath -- output directory to place files * @return list of files created * @throws IOException * @throws SAXException * @throws TikaException */ public List<Path> extractEmbeddedDocumentsExample(Path outputPath) throws IOException, SAXException, TikaException { ExtractEmbeddedFiles ex = new ExtractEmbeddedFiles(); List<Path> ret = new ArrayList<>(); try (TikaInputStream stream = TikaInputStream.get( ParsingExample.class.getResourceAsStream("test_recursive_embedded.docx"))) { ex.extract(stream, outputPath); try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(outputPath)) { for (Path entry : dirStream) { ret.add(entry); } } } return ret; } }
package alien4cloud.orchestrators.locations.services; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import javax.inject.Inject; import alien4cloud.component.repository.exception.ToscaTypeAlreadyDefinedInOtherCSAR; import org.alien4cloud.tosca.catalog.index.ArchiveIndexer; import org.alien4cloud.tosca.catalog.index.CsarService; import org.alien4cloud.tosca.model.CSARDependency; import org.alien4cloud.tosca.model.Csar; import org.alien4cloud.tosca.model.types.AbstractToscaType; import org.alien4cloud.tosca.model.types.NodeType; import org.apache.commons.collections4.CollectionUtils; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import alien4cloud.component.repository.exception.CSARUsedInActiveDeployment; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.events.LocationArchiveDeleteRequested; import alien4cloud.events.LocationTypeIndexed; import alien4cloud.exception.AlreadyExistException; import alien4cloud.model.common.Tag; import alien4cloud.model.common.Usage; import alien4cloud.model.components.CSARSource; import alien4cloud.model.orchestrators.Orchestrator; import alien4cloud.model.orchestrators.locations.Location; import alien4cloud.orchestrators.plugin.ILocationConfiguratorPlugin; import alien4cloud.orchestrators.plugin.IOrchestratorPlugin; import alien4cloud.orchestrators.plugin.IOrchestratorPluginFactory; import alien4cloud.orchestrators.plugin.model.PluginArchive; import alien4cloud.orchestrators.services.OrchestratorService; import alien4cloud.paas.OrchestratorPluginService; import alien4cloud.paas.exception.OrchestratorDisabledException; import alien4cloud.tosca.model.ArchiveRoot; import alien4cloud.tosca.parser.ParsingError; import lombok.extern.slf4j.Slf4j; /** * Manage the indexing of TOSCA archives. */ @Slf4j @Component @SuppressWarnings("rawtypes") public class PluginArchiveIndexer { @Inject private OrchestratorService orchestratorService; @Inject private OrchestratorPluginService orchestratorPluginService; @Inject private CsarService csarService; @Inject private ArchiveIndexer archiveIndexer; @Resource(name = "alien-es-dao") private IGenericSearchDAO alienDAO; @Inject private ApplicationContext applicationContext; /** * Ensure that location archives are indexed. * * @param orchestrator the orchestrator for which to index archives. * @param location The location of the orchestrator for which to index archives. */ public Set<CSARDependency> indexLocationArchives(Orchestrator orchestrator, Location location) { IOrchestratorPlugin orchestratorInstance = (IOrchestratorPlugin) orchestratorPluginService.getOrFail(orchestrator.getId()); ILocationConfiguratorPlugin configuratorPlugin = orchestratorInstance.getConfigurator(location.getInfrastructureType()); // ensure that the plugin archives for this location are imported in the catalog List<PluginArchive> pluginArchives = configuratorPlugin.pluginArchives(); Set<CSARDependency> dependencies = Sets.newHashSet(); if (pluginArchives == null) { return dependencies; } // index archive here if not already indexed for (PluginArchive pluginArchive : pluginArchives) { ArchiveRoot archive = pluginArchive.getArchive(); Csar csar = csarService.get(archive.getArchive().getName(), archive.getArchive().getVersion()); String lastParsedHash = null; if (csar == null) { // index the required archive indexArchive(pluginArchive, orchestrator, location); lastParsedHash = archive.getArchive().getHash(); } else { lastParsedHash = csar.getHash(); } if (archive.getArchive().getDependencies() != null) { dependencies.addAll(archive.getArchive().getDependencies()); } dependencies.add(new CSARDependency(archive.getArchive().getName(), archive.getArchive().getVersion(), lastParsedHash)); } return dependencies; } /** * Index archives defined at the orchestrator level by a plugin. * * @param orchestratorFactory The orchestrator factory. * @param orchestratorInstance The instance of the orchestrator (created by the factory). */ public void indexOrchestratorArchives(IOrchestratorPluginFactory<IOrchestratorPlugin<?>, ?> orchestratorFactory, IOrchestratorPlugin<Object> orchestratorInstance) { for (PluginArchive pluginArchive : orchestratorInstance.pluginArchives()) { try { archiveIndexer.importArchive(pluginArchive.getArchive(), CSARSource.ORCHESTRATOR, pluginArchive.getArchiveFilePath(), Lists.<ParsingError> newArrayList()); publishLocationTypeIndexedEvent(pluginArchive.getArchive().getNodeTypes().values(), orchestratorFactory, null); } catch (AlreadyExistException e) { log.debug("Skipping orchestrator archive import as the released version already exists in the repository. " + e.getMessage()); } catch (CSARUsedInActiveDeployment e) { log.debug("Skipping orchestrator archive import as it is used in an active deployment. " + e.getMessage()); } catch (ToscaTypeAlreadyDefinedInOtherCSAR e) { log.debug("Skipping orchestrator archive import, it's archive contain's a tosca type already defined in an other archive." + e.getMessage()); } } } private void indexArchive(PluginArchive pluginArchive, Orchestrator orchestrator, Location location) { ArchiveRoot archive = pluginArchive.getArchive(); // inject a specific tag to allow components catalog filtering search injectWorkSpace(archive.getNodeTypes().values(), orchestrator, location); injectWorkSpace(archive.getArtifactTypes().values(), orchestrator, location); injectWorkSpace(archive.getCapabilityTypes().values(), orchestrator, location); injectWorkSpace(archive.getRelationshipTypes().values(), orchestrator, location); List<ParsingError> parsingErrors = Lists.newArrayList(); // index the archive in alien catalog try { archiveIndexer.importArchive(archive, CSARSource.ORCHESTRATOR, pluginArchive.getArchiveFilePath(), parsingErrors); } catch (AlreadyExistException e) { log.debug("Skipping location archive import as the released version already exists in the repository."); } catch (CSARUsedInActiveDeployment e) { log.debug("Skipping orchestrator archive import as it is used in an active deployment. " + e.getMessage()); } catch (ToscaTypeAlreadyDefinedInOtherCSAR e) { log.debug("Skipping orchestrator archive import, it's archive contain's a tosca type already defined in an other archive." + e.getMessage()); } // Publish event to allow plugins to post-process elements (portability plugin for example). publishLocationTypeIndexedEvent(archive.getNodeTypes().values(), orchestrator, location); } private void publishLocationTypeIndexedEvent(Collection<NodeType> collection, Orchestrator orchestrator, Location location) { IOrchestratorPluginFactory orchestratorFactory = orchestratorService.getPluginFactory(orchestrator); publishLocationTypeIndexedEvent(collection, orchestratorFactory, location); } private void publishLocationTypeIndexedEvent(Collection<NodeType> collection, IOrchestratorPluginFactory orchestratorFactory, Location location) { if (CollectionUtils.isNotEmpty(collection)) { for (NodeType nodeType : collection) { LocationTypeIndexed event = new LocationTypeIndexed(this); event.setNodeType(nodeType); event.setLocation(location); event.setOrchestratorFactory(orchestratorFactory); applicationContext.publishEvent(event); } } } private void injectWorkSpace(Collection<? extends AbstractToscaType> elements, Orchestrator orchestrator, Location location) { for (AbstractToscaType element : elements) { if (element.getTags() == null) { element.setTags(new ArrayList<Tag>()); } element.getTags().add(new Tag("alien-workspace-id", orchestrator.getId() + ":" + location.getId())); element.getTags().add(new Tag("alien-workspace-name", orchestrator.getName() + " - " + location.getName())); } } /** * Delete all archives related to a location, if not exposed or used by another location * * @param location * @return Map of usages per archives if found (that means the deletion wasn't performed successfully), null if everything went well. */ public Map<Csar, List<Usage>> deleteArchives(Orchestrator orchestrator, Location location) { ILocationConfiguratorPlugin configuratorPlugin = getConfiguratorPlugin(location); IOrchestratorPluginFactory orchestratorFactory = orchestratorService.getPluginFactory(orchestrator); List<PluginArchive> pluginArchives = configuratorPlugin.pluginArchives(); // abort if no archive is exposed by this location if (CollectionUtils.isEmpty(pluginArchives)) { return null; } Map<String, List<Location>> allExposedArchivesIds = getAllExposedArchivesIdsExluding(location); Map<Csar, List<Usage>> usages = Maps.newHashMap(); for (PluginArchive pluginArchive : pluginArchives) { Csar csar = pluginArchive.getArchive().getArchive(); List<Location> locationsExposingArchive = allExposedArchivesIds.get(csar.getId()); LocationArchiveDeleteRequested e = new LocationArchiveDeleteRequested(this); e.setCsar(csar); e.setLocation(location); e.setOrchestratorFactory(orchestratorFactory); e.setLocationsExposingArchive(locationsExposingArchive); // only delete if no other location exposed this archive if (locationsExposingArchive == null) { List<Usage> csarUsage = csarService.deleteCsarWithElements(csar); if (CollectionUtils.isNotEmpty(csarUsage)) { usages.put(csar, csarUsage); } e.setDeleted(true); } else { e.setDeleted(false); } applicationContext.publishEvent(e); } return usages.isEmpty() ? null : usages; } private ILocationConfiguratorPlugin getConfiguratorPlugin(Location location) { ILocationConfiguratorPlugin configuratorPlugin; try { IOrchestratorPlugin<Object> orchestratorInstance = orchestratorPluginService.getOrFail(location.getOrchestratorId()); configuratorPlugin = orchestratorInstance.getConfigurator(location.getInfrastructureType()); } catch (OrchestratorDisabledException e) { IOrchestratorPluginFactory orchestratorFactory = orchestratorService.getPluginFactory(orchestratorService.getOrFail(location.getOrchestratorId())); IOrchestratorPlugin<Object> orchestratorInstance = orchestratorFactory.newInstance(); configuratorPlugin = orchestratorInstance.getConfigurator(location.getInfrastructureType()); orchestratorFactory.destroy(orchestratorInstance); } return configuratorPlugin; } /** * Query for csars that are defined by locations. * * @return A maps of <csar_id, list of locations that uses the csar>. */ public Map<String, List<Location>> getAllExposedArchivesIdsExluding(Location excludedLocation) { // exclude a location from the search QueryBuilder query = QueryBuilders.boolQuery() .mustNot(QueryBuilders.idsQuery(Location.class.getSimpleName().toLowerCase()).ids(excludedLocation.getId())); List<Location> locations = alienDAO.customFindAll(Location.class, query); Map<String, List<Location>> archiveIds = Maps.newHashMap(); if (locations != null) { for (Location location : locations) { ILocationConfiguratorPlugin configuratorPlugin = getConfiguratorPlugin(location); List<PluginArchive> pluginArchives = configuratorPlugin.pluginArchives(); for (PluginArchive pluginArchive : pluginArchives) { String archiveId = pluginArchive.getArchive().getArchive().getId(); List<Location> locationsPerArchive = archiveIds.get(archiveId); if (locationsPerArchive == null) { locationsPerArchive = Lists.newArrayList(); archiveIds.put(archiveId, locationsPerArchive); } locationsPerArchive.add(location); } } } return archiveIds; } }
/* * Copyright 2016 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.scanner.embedder; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.eclipse.aether.repository.RemoteRepository; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieScanner; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.maven.integration.embedder.MavenSettings; import org.kie.scanner.AbstractKieCiTest; import org.kie.scanner.KieMavenRepository; import static org.kie.maven.integration.embedder.MavenSettings.CUSTOM_SETTINGS_PROPERTY; import static org.kie.scanner.KieMavenRepository.getKieMavenRepository; public class MavenDeployTest extends AbstractKieCiTest { @Test public void testDeploy() throws IOException { KieServices ks = KieServices.Factory.get(); ReleaseId releaseId = ks.newReleaseId( "org.kie", "scanner-test-deploy", "1.0-SNAPSHOT" ); Path m2Folder = Files.createTempDirectory( "temp-m2" ); Path settingsXmlPath = generateSettingsXml( m2Folder ); String oldSettingsXmlPath = System.getProperty( CUSTOM_SETTINGS_PROPERTY ); try { System.setProperty( CUSTOM_SETTINGS_PROPERTY, settingsXmlPath.toString() ); MavenSettings.reinitSettings(); InternalKieModule kJar1 = createKieJar( ks, releaseId, "rule1", "rule2" ); KieContainer kieContainer = ks.newKieContainer( releaseId ); KieMavenRepository repository = getKieMavenRepository(); RemoteRepository remote = createRemoteRepository( m2Folder ); repository.deployArtifact(remote, releaseId, kJar1, createKPom(m2Folder, releaseId).toFile()); // create a ksesion and check it works as expected KieSession ksession = kieContainer.newKieSession( "KSession1" ); checkKSession(ksession, "rule1", "rule2"); // create a new kjar InternalKieModule kJar2 = createKieJar(ks, releaseId, "rule2", "rule3"); // deploy it on maven repository.deployArtifact(remote, releaseId, kJar2, createKPom(m2Folder, releaseId).toFile()); // since I am not calling start() on the scanner it means it won't have automatic scheduled scanning KieScanner scanner = ks.newKieScanner( kieContainer ); // scan the maven repo to get the new kjar version and deploy it on the kcontainer scanner.scanNow(); // create a ksesion and check it works as expected KieSession ksession2 = kieContainer.newKieSession("KSession1"); checkKSession(ksession2, "rule2", "rule3"); ks.getRepository().removeKieModule(releaseId); } finally { if (oldSettingsXmlPath == null) { System.clearProperty( CUSTOM_SETTINGS_PROPERTY ); } else { System.setProperty( CUSTOM_SETTINGS_PROPERTY, oldSettingsXmlPath ); } MavenSettings.reinitSettings(); } } private static Path generateSettingsXml( Path m2Folder ) throws IOException { String settingsXml = "<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0\n" + " http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n" + " <profiles>\n" + " <profile>\n" + " <id>repos</id>\n" + " <activation>\n" + " <activeByDefault>true</activeByDefault>\n" + " </activation>\n" + " <repositories>\n" + " <repository>\n" + " <id>myTestRepo</id>\n" + " <name>My Test Repo</name>\n" + " <url>" + m2Folder.toUri().toURL().toExternalForm() + "</url>\n" + " <releases><enabled>true</enabled></releases>\n" + " <snapshots><enabled>true</enabled></snapshots>\n" + " </repository>\n" + " </repositories>\n" + " </profile>\n" + " </profiles>\n" + "</settings>\n"; Path settingsXmlPath = Files.createTempFile( m2Folder, "settings", ".xml" ); Files.write( settingsXmlPath, settingsXml.getBytes() ); return settingsXmlPath; } private static RemoteRepository createRemoteRepository(Path m2Folder) throws MalformedURLException { String localRepositoryUrl = m2Folder.toUri().toURL().toExternalForm(); return new RemoteRepository.Builder( "myTestRepo", "default", localRepositoryUrl ).build(); } protected Path createKPom( Path m2Folder, ReleaseId releaseId ) throws IOException { Path pomXmlPath = Files.createTempFile( m2Folder, "pom", ".xml" ); Files.write( pomXmlPath, getPom(releaseId).getBytes() ); return pomXmlPath; } @Test public void testKScannerWithDeployUsingDistributionManagement() throws IOException { KieServices ks = KieServices.Factory.get(); ReleaseId releaseId = ks.newReleaseId( "org.kie", "scanner-test-deploy-dist", "1.0-SNAPSHOT" ); Path m2Folder = Files.createTempDirectory( "temp-m2-dist" ); Path settingsXmlPath = generateSettingsXml( m2Folder ); String oldSettingsXmlPath = System.getProperty( CUSTOM_SETTINGS_PROPERTY ); try { System.setProperty( CUSTOM_SETTINGS_PROPERTY, settingsXmlPath.toString() ); MavenSettings.reinitSettings(); InternalKieModule kJar1 = createKieJar( ks, releaseId, "rule1", "rule2" ); KieContainer kieContainer = ks.newKieContainer( releaseId ); KieMavenRepository repository = getKieMavenRepository(); repository.deployArtifact(releaseId, kJar1, createKPomWithDistributionManagement(m2Folder, releaseId).toFile()); // create a ksesion and check it works as expected KieSession ksession = kieContainer.newKieSession( "KSession1" ); checkKSession(ksession, "rule1", "rule2"); // create a new kjar InternalKieModule kJar2 = createKieJar(ks, releaseId, "rule2", "rule3"); // deploy it on maven repository.deployArtifact(releaseId, kJar2, createKPomWithDistributionManagement(m2Folder, releaseId).toFile()); // since I am not calling start() on the scanner it means it won't have automatic scheduled scanning KieScanner scanner = ks.newKieScanner( kieContainer ); // scan the maven repo to get the new kjar version and deploy it on the kcontainer scanner.scanNow(); // create a ksesion and check it works as expected KieSession ksession2 = kieContainer.newKieSession("KSession1"); checkKSession(ksession2, "rule2", "rule3"); ks.getRepository().removeKieModule(releaseId); } finally { if (oldSettingsXmlPath == null) { System.clearProperty( CUSTOM_SETTINGS_PROPERTY ); } else { System.setProperty( CUSTOM_SETTINGS_PROPERTY, oldSettingsXmlPath ); } MavenSettings.reinitSettings(); } } protected Path createKPomWithDistributionManagement( Path m2Folder, ReleaseId releaseId ) throws IOException { String localRepositoryUrl = m2Folder.toUri().toURL().toExternalForm(); String pom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" + " <modelVersion>4.0.0</modelVersion>\n" + "\n" + " <groupId>" + releaseId.getGroupId() + "</groupId>\n" + " <artifactId>" + releaseId.getArtifactId() + "</artifactId>\n" + " <version>" + releaseId.getVersion() + "</version>\n" + " <distributionManagement>\n" + " <repository>\n" + " <id>myTestRepo</id>\n" + " <name>Releases Repository</name>\n" + " <url>" + localRepositoryUrl + "</url>\n" + " </repository>\n" + " <snapshotRepository>\n" + " <id>myTestRepo-snapshots</id>\n" + " <name>Snapshot Repository</name>\n" + " <url>" + localRepositoryUrl + "</url>\n" + " </snapshotRepository>\n" + " </distributionManagement>" + "</project>"; Path pomXmlPath = Files.createTempFile( m2Folder, "pom", ".xml" ); Files.write( pomXmlPath, pom.getBytes() ); return pomXmlPath; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.salesforce.api.dto.composite; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.annotations.XStreamOmitField; import org.apache.camel.component.salesforce.api.dto.AbstractDescribedSObjectBase; import org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase; import org.apache.camel.component.salesforce.api.dto.RestError; import org.apache.camel.component.salesforce.api.dto.SObjectDescription; import org.apache.camel.util.ObjectHelper; /** * Represents one node in the SObject tree request. SObject trees ({@link SObjectTree}) are composed from instances of * {@link SObjectNode}s. Each {@link SObjectNode} contains {@link Attributes}, the SObject ({@link AbstractSObjectBase}) * and any child records linked to it. SObjects at root level are added to {@link SObjectTree} using * {@link SObjectTree#addObject(AbstractSObjectBase)}, then you can add child records on the {@link SObjectNode} * returned by using {@link #addChild(AbstractDescribedSObjectBase)}, * {@link #addChildren(AbstractDescribedSObjectBase, AbstractDescribedSObjectBase...)} or * {@link #addChild(String, AbstractSObjectBase)} and * {@link #addChildren(String, AbstractSObjectBase, AbstractSObjectBase...)}. * <p/> * Upon submission to the Salesforce Composite API the {@link SObjectTree} and the {@link SObjectNode}s in it might * contain errors that you need to fetch using {@link #getErrors()} method. * * @see SObjectTree * @see RestError */ @XStreamAlias("records") @XStreamConverter(SObjectNodeXStreamConverter.class) public final class SObjectNode implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty final Attributes attributes; @JsonUnwrapped final AbstractSObjectBase object; final Map<String, List<SObjectNode>> records = new HashMap<>(); private List<RestError> errors; @XStreamOmitField private final ReferenceGenerator referenceGenerator; SObjectNode(final SObjectTree tree, final AbstractSObjectBase object) { this(tree.referenceGenerator, typeOf(object), object); } private SObjectNode(final ReferenceGenerator referenceGenerator, final String type, final AbstractSObjectBase object) { this.referenceGenerator = requireNonNull(referenceGenerator, "ReferenceGenerator cannot be null"); this.object = requireNonNull(object, "Root SObject cannot be null"); attributes = new Attributes(referenceGenerator.nextReferenceFor(object), requireNonNull(type, "Object type cannot be null")); } static String pluralOf(final AbstractDescribedSObjectBase object) { final SObjectDescription description = object.description(); return description.getLabelPlural(); } static String typeOf(final AbstractDescribedSObjectBase object) { final SObjectDescription description = object.description(); return description.getName(); } static String typeOf(final AbstractSObjectBase object) { return object.getClass().getSimpleName(); } /** * Add a described child with the metadata needed already present within it to the this node. * * @param child * to add * @return the newly created node, used in builder fashion to add more child objects to it (on the next level) */ public SObjectNode addChild(final AbstractDescribedSObjectBase child) { ObjectHelper.notNull(child, "child"); return addChild(pluralOf(child), child); } /** * Add a child that does not contain the required metadata to the this node. You need to specify the plural form of * the child (e.g. `Account` its `Accounts`). * * @param labelPlural * plural form * @param child * to add * @return the newly created node, used in builder fashion to add more child objects to it (on the next level) */ public SObjectNode addChild(final String labelPlural, final AbstractSObjectBase child) { ObjectHelper.notNull(labelPlural, "labelPlural"); ObjectHelper.notNull(child, "child"); final SObjectNode node = new SObjectNode(referenceGenerator, typeOf(child), child); return addChild(labelPlural, node); } /** * Add multiple described children with the metadata needed already present within them to the this node.. * * @param first * first child to add * @param others * any other children to add */ public void addChildren(final AbstractDescribedSObjectBase first, final AbstractDescribedSObjectBase... others) { ObjectHelper.notNull(first, "first"); ObjectHelper.notNull(others, "others"); addChild(pluralOf(first), first); Arrays.stream(others).forEach(this::addChild); } /** * Add a child that does not contain the required metadata to the this node. You need to specify the plural form of * the child (e.g. `Account` its `Accounts`). * * @param labelPlural * plural form * @param first * first child to add * @param others * any other children to add */ public void addChildren(final String labelPlural, final AbstractSObjectBase first, final AbstractSObjectBase... others) { ObjectHelper.notNull(labelPlural, "labelPlural"); ObjectHelper.notNull(first, "first"); ObjectHelper.notNull(others, "others"); addChild(labelPlural, first); Arrays.stream(others).forEach(c -> addChild(labelPlural, c)); } /** * Returns all children of this node (one level deep). * * @return children of this node */ @JsonIgnore public Stream<SObjectNode> getChildNodes() { return records.values().stream().flatMap(List::stream); } /** * Returns all children of this node (one level deep) of certain type (in plural form). * * @param type * type of child requested in plural form (e.g for `Account` is `Accounts`) * @return children of this node of specified type */ public Stream<SObjectNode> getChildNodesOfType(final String type) { ObjectHelper.notNull(type, "type"); return records.getOrDefault(type, Collections.emptyList()).stream(); } /** * Returns child SObjects of this node (one level deep). * * @return child SObjects of this node */ @JsonIgnore public Stream<AbstractSObjectBase> getChildren() { return records.values().stream().flatMap(List::stream).map(SObjectNode::getObject); } /** * Returns child SObjects of this node (one level deep) of certain type (in plural form) * * @param type * type of child requested in plural form (e.g for `Account` is `Accounts`) * @return child SObjects of this node */ public Stream<AbstractSObjectBase> getChildrenOfType(final String type) { ObjectHelper.notNull(type, "type"); return records.getOrDefault(type, Collections.emptyList()).stream().map(SObjectNode::getObject); } /** * Errors reported against this this node received in response to the SObject tree being submitted. * * @return errors for this node */ @JsonIgnore public List<RestError> getErrors() { return Optional.ofNullable(errors).orElse(Collections.emptyList()); } /** * SObject at this node. * * @return SObject */ @JsonIgnore public AbstractSObjectBase getObject() { return object; } /** * Are there any errors resulted from the submission on this node? * * @return true if there are errors */ public boolean hasErrors() { return errors != null && !errors.isEmpty(); } /** * Size of the branch beginning with this node (number of SObjects in it). * * @return number of objects within this branch */ public int size() { return 1 + records.values().stream().flatMapToInt(r -> r.stream().mapToInt(SObjectNode::size)).sum(); } @Override public String toString() { return "Node<" + getObjectType() + ">"; } SObjectNode addChild(final String labelPlural, final SObjectNode node) { List<SObjectNode> children = records.get(labelPlural); if (children == null) { children = new ArrayList<>(); records.put(labelPlural, children); } children.add(node); return node; } @JsonAnyGetter Map<String, Map<String, List<SObjectNode>>> children() { return records.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Collections.singletonMap("records", e.getValue()))); } Attributes getAttributes() { return attributes; } @JsonIgnore String getObjectType() { return attributes.type; } Stream<Class> objectTypes() { return Stream.concat(Stream.of((Class) object.getClass()), getChildNodes().flatMap(SObjectNode::objectTypes)); } void setErrors(final List<RestError> errors) { this.errors = errors; } }
/* * Copyright (c) OSGi Alliance (2013, 2015). 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.osgi.service.dal; import java.lang.reflect.Array; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; /** * Abstract {@code Function} data wrapper. A subclass must be used for an access * to the property values by all functions. It takes care about the timestamp * and additional metadata. The subclasses are responsible to provide concrete * value and unit if required. */ public abstract class FunctionData implements Comparable { /** * Represents the timestamp field name. The field value is available with * {@link #getTimestamp()}. The field type is {@code long}. The constant can * be used as a key to {@link #FunctionData(Map)}. */ public static final String FIELD_TIMESTAMP = "timestamp"; /** * Represents the metadata field name. The field value is available with * {@link #getMetadata()}. The field type is {@code Map}. The constant can * be used as a key to {@link #FunctionData(Map)}. */ public static final String FIELD_METADATA = "metadata"; /** * Metadata key, which value represents the data description. The property * value type is {@code java.lang.String}. */ public static final String DESCRIPTION = "description"; private final long timestamp; private final Map metadata; /** * Constructs new {@code FunctionData} instance with the specified field * values. The map keys must match to the field names. The map values will * be assigned to the appropriate class fields. For example, the maps can * be: {"timestamp"=Long(1384440775495)}. That map will initialize the * {@link #FIELD_TIMESTAMP} field with 1384440775495. If timestamp is * missing, {@link Long#MIN_VALUE} is used. * <ul> * <li>{@link #FIELD_TIMESTAMP} - optional field. The value type must be * {@code Long}.</li> * <li>{@link #FIELD_METADATA} - optional field. The value type must be * {@code Map}.</li> * </ul> * * @param fields Contains the new {@code FunctionData} instance field * values. * * @throws ClassCastException If the field value types are not expected. * @throws NullPointerException If the fields map is {@code null}. */ public FunctionData(Map fields) { Long timestampLocal = (Long) fields.get(FIELD_TIMESTAMP); this.timestamp = (null != timestampLocal) ? timestampLocal.longValue() : Long.MIN_VALUE; this.metadata = (Map) fields.get(FIELD_METADATA); } /** * Constructs new {@code FunctionData} instance with the specified * arguments. * * @param timestamp The data timestamp optional field. * @param metadata The data metadata optional field. */ public FunctionData(long timestamp, Map metadata) { this.timestamp = timestamp; this.metadata = metadata; } /** * Returns {@code FunctionData} timestamp. The timestamp is the difference * between the value collecting time and midnight, January 1, 1970 UTC. It's * measured in milliseconds. The device driver is responsible to generate * that value when the value is received from the device. * {@link java.lang.Long#MIN_VALUE} value means no timestamp. * * @return {@code FunctionData} timestamp. */ public long getTimestamp() { return this.timestamp; } /** * Returns {@code FunctionData} metadata. It's dynamic metadata related only * to this specific value. Possible keys: * <ul> * <li>{@link #DESCRIPTION}</li> * <li>custom key</li> * </ul> * * @return {@code FunctionData} metadata or {@code null} is there is no * metadata. */ public Map getMetadata() { return this.metadata; } /** * Two {@code FunctionData} instances are equal if their metadata and * timestamp are equivalent. * * @param other The other instance to compare. It must be of * {@code FunctionData} type. * * @return {@code true} if this instance and argument have equivalent * metadata and timestamp, {@code false} otherwise. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof FunctionData)) { return false; } try { return 0 == compareTo(other); } catch (ClassCastException cce) { return false; } } /** * Returns the hash code of this {@code FunctionData}. * * @return {@code FunctionData} hash code. * * @see java.lang.Object#hashCode() */ public int hashCode() { return ((int) (this.timestamp ^ (this.timestamp >>> 32))) + calculateMapHashCode(this.metadata); } /** * Compares this {@code FunctionData} instance with the given argument. If * the argument is not {@code FunctionData}, it throws * {@code ClassCastException}. Otherwise, this method returns: * <ul> * <li>{@code -1} if this instance timestamp is less than the argument * timestamp. If they are equivalent, it can be the result of the metadata * map deep comparison.</li> * <li>{@code 0} if all fields are equivalent.</li> * <li>{@code 1} if this instance timestamp is greater than the argument * timestamp. If they are equivalent, it can be the result of the metadata * map deep comparison.</li> * </ul> * Metadata map deep comparison compares the elements of all nested * {@code java.util.Map} and array instances. {@code null} is less than any * other non-null instance. * * @param o {@code FunctionData} to be compared. * * @return {@code -1}, {@code 0} or {@code 1} depending on the comparison * rules. * * @throws ClassCastException If the method argument is not of type * {@code FunctionData} or metadata maps contain values of different * types for the same key. * @throws NullPointerException If the method argument is {@code null}. * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { FunctionData other = (FunctionData) o; if (this.timestamp == other.timestamp) { return compareMaps(this.metadata, other.metadata); } return (this.timestamp < other.timestamp) ? -1 : 1; } private static int calculateMapHashCode(Map map) { if (null == map) { return 0; } return calculateMapHashCodeDeep(map, null); } private static int calculateMapHashCodeDeep(Map map, IdentityHashMap usedContainers) { int result = 0; for (Iterator entriesIter = map.entrySet().iterator(); entriesIter.hasNext();/* empty */) { Map.Entry currentEntry = (Map.Entry) entriesIter.next(); result += currentEntry.getKey().hashCode(); result += calculateValueHashCodeDeep(currentEntry.getValue(), usedContainers); } return result; } private static int calculateValueHashCodeDeep(Object value, IdentityHashMap usedContainers) { if (null == value) { return 0; } if (value.getClass().isArray()) { if (null == usedContainers) { usedContainers = new IdentityHashMap(); } if (null != usedContainers.put(value, value)) { return 0; } try { return calculateArrayHashCodeDeep(value, usedContainers); } finally { usedContainers.remove(value); } } if (value instanceof Map) { if (null == usedContainers) { usedContainers = new IdentityHashMap(); } if (null != usedContainers.put(value, value)) { return 0; } try { return calculateMapHashCodeDeep((Map) value, usedContainers); } finally { usedContainers.remove(value); } } return value.hashCode(); } private static int calculateArrayHashCodeDeep(Object array, IdentityHashMap usedContainers) { int arrayLength = Array.getLength(array); int result = 0; for (int i = 0; i < arrayLength; i++) { result += calculateValueHashCodeDeep(Array.get(array, i), usedContainers); } return result; } private static int compareMaps(Map thisMap, Map otherMap) { if (null == thisMap) { return (null != otherMap) ? -1 : 0; } if (null == otherMap) { return 1; } return compareMapsDeep(thisMap, otherMap, null); } private static int compareMapsDeep(Map thisMap, Map otherMap, IdentityHashMap thisUsedContainers) { int result = compare(thisMap.size(), otherMap.size()); if (0 != result) { return result; } for (Iterator thisEntriesIter = thisMap.entrySet().iterator(); thisEntriesIter.hasNext();/* empty */) { Map.Entry thisEntry = (Map.Entry) thisEntriesIter.next(); if (otherMap.containsKey(thisEntry.getKey())) { result = compareValuesDeep(thisEntry.getValue(), otherMap.get(thisEntry.getKey()), thisUsedContainers); if (0 != result) { return result; } } else { return 1; } } return 0; } private static int compareValuesDeep(Object thisValue, Object otherValue, IdentityHashMap thisUsedContainers) { if (null == thisValue) { return (null == otherValue) ? 0 : -1; } if (null == otherValue) { return 1; } if (thisValue.getClass().isArray()) { if (otherValue.getClass().isArray()) { if (null == thisUsedContainers) { thisUsedContainers = new IdentityHashMap(); } if (null != thisUsedContainers.put(thisValue, thisValue)) { return -1; } try { return compareArraysDeep(thisValue, otherValue, thisUsedContainers); } finally { thisUsedContainers.remove(thisValue); } } return 1; } if (thisValue instanceof Map) { if (otherValue instanceof Map) { if (null == thisUsedContainers) { thisUsedContainers = new IdentityHashMap(); } if (null != thisUsedContainers.put(thisValue, thisValue)) { return -1; } try { return compareMapsDeep((Map) thisValue, (Map) otherValue, thisUsedContainers); } finally { thisUsedContainers.remove(thisValue); } } return 1; } if (thisValue instanceof Comparable) { return (((Comparable) thisValue)).compareTo(otherValue); } return thisValue.equals(otherValue) ? 0 : 1; } private static int compareArraysDeep(Object thisArray, Object otherArray, IdentityHashMap thisUsedContainers) { int thisArrayLength = Array.getLength(thisArray); int otherArrayLength = Array.getLength(otherArray); int result = compare(thisArrayLength, otherArrayLength); if (0 != result) { return result; } for (int i = 0; i < thisArrayLength; i++) { result = compareValuesDeep(Array.get(thisArray, i), Array.get(otherArray, i), thisUsedContainers); if (0 != result) { return result; } } return 0; } private static int compare(int thisValue, int otherValue) { return (thisValue < otherValue) ? -1 : ((thisValue > otherValue) ? 1 : 0); } }
package net.floodlightcontroller.odin.applications; import java.net.InetAddress; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Scanner; import java.math.*; import java.io.*; import net.floodlightcontroller.odin.master.OdinApplication; import net.floodlightcontroller.odin.master.OdinClient; import net.floodlightcontroller.util.MACAddress; import net.floodlightcontroller.odin.master.OdinMaster.ChannelAssignmentParams; import org.apache.commons.io.output.TeeOutputStream; import com.mathworks.toolbox.javabuilder.*; import getChannelAssignments.*; import java.lang.*; public class ChannelAssignment_II extends OdinApplication { // IMPORTANT: this application only works if all the agents in the //poolfile are activated before the end of the INITIAL_INTERVAL. // Otherwise, the application looks for an object that does not exist //and gets stopped // SSID to scan private final String SCANNED_SSID = "odin_init"; // Scann params private ChannelAssignmentParams CHANNEL_PARAMS; // Scanning agents Map<InetAddress, Integer> scanningAgents = new HashMap<InetAddress, Integer> (); int result; // Result for scanning // Matrix private String matrix = ""; private String avg_dB = ""; // Algorithm results private int[][] channels = null; private long time = 0L; // Compare timestamps in ms private long timeIdle = 0L; // Compare timestamps in ms private int number_scans = 0; private int[] txpowerAPs = null; private int[] channelAPs = null; private double[] coefII = {0.65, 0.8, 0.6, 0.4, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; // To calculate the trigger private int userInt; private Scanner in = new Scanner(System.in); HashSet<OdinClient> clients; @Override public void run() { this.CHANNEL_PARAMS = getChannelAssignmentParams(); String operationMode = CHANNEL_PARAMS.mode; try { Thread.sleep(CHANNEL_PARAMS.time_to_start); } catch (InterruptedException e) { e.printStackTrace(); } int numAPs = getAgents().size(); double[][] pathLosses = new double[numAPs][numAPs]; double[][] matrixII = new double[numAPs][numAPs]; double[][] externalII = new double[11][numAPs]; txpowerAPs = new int[numAPs]; channelAPs = new int[numAPs]; int j=0; // Write on file integration PrintStream stdout = System.out; // To enable return to console FileOutputStream fos = null; PrintStream ps = null; if(CHANNEL_PARAMS.filename.length()>0){ File f = new File(CHANNEL_PARAMS.filename); try { fos = new FileOutputStream(f, true); // If the file exists, it will append data to the eof //we will want to print in standard "System.out" and in "file" TeeOutputStream myOut=new TeeOutputStream(stdout, fos); ps = new PrintStream(myOut, true); //true - auto-flush after println System.setOut(ps); // Both outputs enabled } catch (Exception e) { e.printStackTrace(); } } while (true) { try { matrix = ""; boolean isValidforChAssign = true; int row = 0, column = 0; if(operationMode.equals("manual")){ promptEnterKey(); System.out.println("[ChannelAssignment] ======== Agents information ========"); } // Get TxPower and channels from Agents and change channel if needed for (InetAddress AgentAddr: getAgents()) { channelAPs[j] = getChannelFromAgent(AgentAddr); txpowerAPs[j] = getTxPowerFromAgent(AgentAddr); if(operationMode.equals("manual")){ System.out.println("[ChannelAssignment] [ " + j + " ]"); System.out.println("[ChannelAssignment] Agent:" + AgentAddr); System.out.println("[ChannelAssignment]\tCurrent channel: " + channelAPs[j]); System.out.println("[ChannelAssignment]\tTxPower: " + txpowerAPs[j] + " dBm"); System.out.print("[ChannelAssignment] Select channel for AP " + AgentAddr + "[1-11]:"); userInt = in.nextInt(); // FIXME assume user will use 1-11 System.out.println("[ChannelAssignment] ==================================="); setChannelToAgent(AgentAddr,userInt); channelAPs[j] = userInt; } j++; } // Associate STAs to specific Agent if(operationMode.equals("manual")){ clients = new HashSet<OdinClient>(getClients()); if(clients.size()>0){ System.out.println("\n[ChannelAssignment] ======== Clients information ========"); for (OdinClient oc: clients) { MACAddress eth = oc.getMacAddress(); // client MAC InetAddress clientAddr = oc.getIpAddress(); InetAddress agentAddr = oc.getLvap().getAgent().getIpAddress(); System.out.println("[ChannelAssignment] Client " + clientAddr + " in agent " + agentAddr); System.out.print("[ChannelAssignment] Select Agent for Client " + clientAddr + "[0-"+(j-1)+"]:"); userInt = in.nextInt();// FIXME assume user will use 0-j-1 System.out.println("[ChannelAssignment] ==================================="); InetAddress[] agentsArray = getAgents().toArray(new InetAddress[0]); handoffClientToAp(eth, agentsArray[userInt]); } promptEnterKey(); } } j = 0; time = System.currentTimeMillis(); System.out.println("[ChannelAssignment] Matrix of Distance"); System.out.println("[ChannelAssignment] =================="); System.out.println("[ChannelAssignment]"); //For channel SCANNING_CHANNEL System.out.println("[ChannelAssignment] Scanning channel " + CHANNEL_PARAMS.channel); System.out.println("[ChannelAssignment]"); for (InetAddress beaconAgentAddr: getAgents()) { scanningAgents.clear(); System.out.println("[ChannelAssignment] Agent to send measurement beacon: " + beaconAgentAddr); // For each Agent System.out.println("[ChannelAssignment] Request for scanning during the interval of " + CHANNEL_PARAMS.scanning_interval + " ms in SSID " + SCANNED_SSID); for (InetAddress agentAddr: getAgents()) { if (agentAddr != beaconAgentAddr) { System.out.println("[ChannelAssignment] Agent listening: " + agentAddr); // Request distances result = requestScannedStationsStatsFromAgent(agentAddr, CHANNEL_PARAMS.channel, SCANNED_SSID); scanningAgents.put(agentAddr, result); } } // Request to send measurement beacon if (requestSendMesurementBeaconFromAgent(beaconAgentAddr, CHANNEL_PARAMS.channel, SCANNED_SSID) == 0) { System.out.println("[ChannelAssignment] Agent BUSY during measurement beacon operation"); isValidforChAssign = false; continue; } try { Thread.sleep(CHANNEL_PARAMS.scanning_interval + CHANNEL_PARAMS.added_time); } catch (InterruptedException e) { e.printStackTrace(); } // Stop sending meesurement beacon stopSendMesurementBeaconFromAgent(beaconAgentAddr); matrix = matrix + beaconAgentAddr.toString().substring(1); for (InetAddress agentAddr: getAgents()) { if (agentAddr != beaconAgentAddr) { System.out.println("[ChannelAssignment]"); System.out.println("[ChannelAssignment] Agent: " + agentAddr + " in channel " + CHANNEL_PARAMS.channel); // Reception distances if (scanningAgents.get(agentAddr) == 0) { System.out.println("[ChannelAssignment] Agent BUSY during scanning operation"); isValidforChAssign = false; continue; } Map<MACAddress, Map<String, String>> vals_rx = getScannedStationsStatsFromAgent(agentAddr,SCANNED_SSID); System.out.println("[ChannelAssignment] Timestamp - Scan: " + System.currentTimeMillis() + " ms since epoch"); boolean isMultiple = false; // In case there are multiple replies from agent for (Entry<MACAddress, Map<String, String>> vals_entry_rx: vals_rx.entrySet()) { // NOTE: the clients currently scanned MAY NOT be the same as the clients who have been associated MACAddress APHwAddr = vals_entry_rx.getKey(); avg_dB = vals_entry_rx.getValue().get("avg_signal"); double losses_dB = txpowerAPs[row] - Double.parseDouble(avg_dB); System.out.println("\tAP MAC: " + APHwAddr); System.out.println("\tAP TxPower: " + txpowerAPs[row] + " dBm"); System.out.println("\tavg signal: " + avg_dB + " dBm"); System.out.println("\tpathloss: " + losses_dB + " dB"); System.out.println("\tfrom channel: " + channelAPs[row] + " to channel: "+channelAPs[column]); int channelDistance = Math.abs(channelAPs[row]-channelAPs[column]); System.out.println("\tII coef: " + coefII[channelDistance]); if(!isMultiple) { double losses = Math.pow(10.0, losses_dB / 10.0); // Linear power double average = 0; if(number_scans!=0){ average = Math.pow(10.0, (pathLosses[row][column]) / 10.0); // Linear power average; } average = average + ((losses - average)/(number_scans +1)); // Cumulative moving average pathLosses[row][column] = 10.0*Math.log10(average); //Average power in dBm double avg_signal_dB_II = txpowerAPs[row] - pathLosses[row][column]; //System.out.println("\tavg_signal_II: " + avg_signal_dB_II); double avg_signal_II = Math.pow(10.0, avg_signal_dB_II / 10.0); if(coefII[channelDistance]==0){ matrixII[row][column] = 0; }else{ matrixII[row][column] = 10.0*Math.log10(coefII[channelDistance]*avg_signal_II);//II in dB } avg_dB = String.valueOf(pathLosses[row][column]); // Average string if(avg_dB.length()>6){ matrix = matrix + "\t" + avg_dB.substring(0,6) + " dB"; }else{ matrix = matrix + "\t" + avg_dB + " dB "; } if(++column >= numAPs) { column = 0; row ++; } isMultiple = true; } else { // If there are multiple replies, pathLosses is not valid isValidforChAssign = false; System.out.println("[ChannelAssignment] ==================================="); System.out.println("[ChannelAssignment] ERROR - Multiple replies from agent " + agentAddr); System.out.println("[ChannelAssignment] ==================================="); } } }else{ matrix = matrix + "\t----------"; pathLosses[row][column] = 0; matrixII[row][column] = 0; if(++column >= numAPs) { column = 0; row ++; } } } matrix = matrix + "\n"; } //Print matrix System.out.println("[ChannelAssignment] ==== MATRIX OF PATHLOSS (dB) ===="); System.out.println("[ChannelAssignment] " + (number_scans+1) + " scans\n"); System.out.println(matrix); System.out.println("[ChannelAssignment] ================================="); System.out.println("[ChannelAssignment] Scanning done in: " + (System.currentTimeMillis()-time) + " ms\n"); // Check Number of Scans if(number_scans < (CHANNEL_PARAMS.number_scans-1)){ number_scans++; Thread.sleep(CHANNEL_PARAMS.pause); continue; } timeIdle = System.currentTimeMillis(); boolean notScan = true; // // // // Scan completed, now Internal II while(notScan){ // Update Internal II double sumII = 0; sumII = updateAndPrintInternalII(pathLosses, channelAPs, txpowerAPs, coefII); // End of loop for iteration, as result, a moving mean of the matrix time = System.currentTimeMillis(); if(Double.compare(sumII,CHANNEL_PARAMS.threshold.doubleValue())<0){// Compare System.out.println("[ChannelAssignment] Interference Impact: " + String.format("%.2f",sumII)); System.out.println("[ChannelAssignment] Threshold: " + CHANNEL_PARAMS.threshold); // Print Threshold System.out.println("[ChannelAssignment] ChannelAssignment not necessary"); System.out.println("[ChannelAssignment] ================================="); // Get TxPower and channels from Agents and change channel if needed if(operationMode.equals("manual")){ j = 0; for (InetAddress AgentAddr: getAgents()) { channelAPs[j] = getChannelFromAgent(AgentAddr); txpowerAPs[j] = getTxPowerFromAgent(AgentAddr); System.out.println("[ChannelAssignment] [ " + j + " ]"); System.out.println("[ChannelAssignment] Agent:" + AgentAddr); System.out.println("[ChannelAssignment]\tCurrent channel: " + channelAPs[j]); System.out.println("[ChannelAssignment]\tTxPower: " + txpowerAPs[j] + " dBm"); System.out.print("[ChannelAssignment] Select channel for AP " + AgentAddr + "[1-11]:"); userInt = in.nextInt(); // FIXME assume user will use 1-11 System.out.println("[ChannelAssignment] ==================================="); setChannelToAgent(AgentAddr,userInt); channelAPs[j] = userInt; j++; } j = 0; } if ( (time-timeIdle) > CHANNEL_PARAMS.idle_time*1000){ notScan = false; System.out.println("[ChannelAssignment] IdleTime has passed, rescan pathloss"); }else{ System.out.println("[ChannelAssignment] Pause for " + CHANNEL_PARAMS.pause + " ms\n"); Thread.sleep(CHANNEL_PARAMS.pause); } continue; } else{ if(isValidforChAssign) { // Launch Algorithm System.out.println("[ChannelAssignment] Interference Impact: " + String.format("%.2f",sumII)); System.out.println("[ChannelAssignment] Threshold: " + CHANNEL_PARAMS.threshold); // Print Threshold externalII = getExternalII(CHANNEL_PARAMS.scanning_interval,numAPs); channels = this.getChannelAssignments(pathLosses, CHANNEL_PARAMS.method, externalII); // Method: 1 for WI5, 2 for RANDOM, 3 for LCC System.out.println("[ChannelAssignment] Timestamp - Algorithm: " + System.currentTimeMillis() + " ms since epoch"); int i=0; for (InetAddress agentAddr: getAgents()) { System.out.println("[ChannelAssignment] Setting AP " + agentAddr + " to channel: " + channels[0][i]); setChannelToAgent(agentAddr,channels[0][i]); i++; } }else{ System.out.println("[ChannelAssignment] Matrix not valid for channel assignment"); } } System.out.println("[ChannelAssignment] Processing done in: " + (System.currentTimeMillis()-time) + " ms"); System.out.println("[ChannelAssignment] ================================="); if ( (time-timeIdle) > CHANNEL_PARAMS.idle_time*1000){ notScan = false; System.out.println("[ChannelAssignment] IdleTime has passed, rescan pathloss"); }else{ System.out.println("[ChannelAssignment] Pause for " + CHANNEL_PARAMS.pause + " ms\n"); Thread.sleep(CHANNEL_PARAMS.pause); } } number_scans = 0; pathLosses = new double[numAPs][numAPs]; matrixII = new double[numAPs][numAPs]; } catch (InterruptedException e) { e.printStackTrace(); } } } private int[][] getChannelAssignments(double[][] pathLosses, int methodType, double[][] externalII) { // New parameter in function //System.out.println(System.getProperty("java.library.path")); MWNumericArray n = null; /* Stores method_number */ Object[] result = null; /* Stores the result */ Wi5 channelFinder= null; /* Stores magic class instance */ MWNumericArray pathLossMatrix = null; MWNumericArray externalIIMatrix = null; MWNumericArray channelsArray = null; int[][] channels = null; try { /* Convert and print inputs */ pathLossMatrix = new MWNumericArray(pathLosses, MWClassID.DOUBLE); externalIIMatrix = new MWNumericArray(externalII, MWClassID.DOUBLE); n = new MWNumericArray(methodType, MWClassID.DOUBLE); /* Create new ChannelAssignment object */ channelFinder = new Wi5(); result = channelFinder.getChannelAssignments(1, pathLossMatrix, n, externalIIMatrix); /* Compute magic square and print result */ System.out.println("[ChannelAssignment] =======CHANNEL ASSIGNMENTS======="); System.out.println(result[0]); // result is type Object System.out.println("[ChannelAssignment] ================================="); channelsArray = (MWNumericArray) result[0]; // Object to 2D MWNumericArray channels = (int[][]) channelsArray.toIntArray(); // 2D MWNumericArray to int[][] } catch (Exception e) { System.out.println("Exception: " + e.toString()); } finally { /* Free native resources */ MWArray.disposeArray(pathLossMatrix); MWArray.disposeArray(externalIIMatrix); MWArray.disposeArray(result); MWArray.disposeArray(channelsArray); if (channelFinder != null) channelFinder.dispose(); return channels; } } private void promptEnterKey(){ // Function to ask for a key System.out.println("Press \"ENTER\" to continue..."); Scanner scanner = new Scanner(System.in); scanner.nextLine(); } private double updateAndPrintInternalII(double[][] pathLosses, int[] channelAPs, int[] txpowerAPs, double[] coefII){ // Function to calculate and print Internal Interference Impact int i=0; int j=0; for (InetAddress AgentAddr: getAgents()) { // Update channels channelAPs[i] = getChannelFromAgent(AgentAddr); i++; } int numAPs = channelAPs.length; double[][] matrixII = new double[numAPs][numAPs]; i=0; for (i=0;i<numAPs;i++) { // Create matrixII for (j=0;j<numAPs;j++) { //System.out.println("[ChannelAssignment] ["+i+"]["+j+"]"); if (i != j) { int channelDistance = Math.abs(channelAPs[i]-channelAPs[j]); double avg_signal_dB_II = txpowerAPs[i] - pathLosses[i][j]; double avg_signal_II = Math.pow(10.0, avg_signal_dB_II / 10.0); //System.out.println("[ChannelAssignment] channelDistance["+i+"]["+j+"]: "+ channelDistance); if(coefII[channelDistance]==0){ matrixII[i][j] = 0; }else{ matrixII[i][j] = 10.0*Math.log10(coefII[channelDistance]*avg_signal_II);//II in dB } //System.out.println("[ChannelAssignment] matrixII["+i+"]["+j+"]: "+ matrixII[i][j]); }else{ matrixII[i][j] = 0; } } } System.out.println("[ChannelAssignment] ======================================"); System.out.println("[ChannelAssignment] = INTERNAL INTERFERENCE IMPACT [dBm] =\n"); double sumII = 0; for (double[] arrayCoefII: matrixII) { System.out.print("[ "); for (double coef_II: arrayCoefII) { System.out.print(String.format("%.2f",coef_II)+" "); } System.out.println("]"); } double sumIIlineal = 0; for (double[] arrayCoefII: matrixII) { for (double coef_II: arrayCoefII) { if(coef_II!=0.0){ double coef_II_lineal = Math.pow(10.0, coef_II / 10.0); sumIIlineal += coef_II_lineal; } } } sumII = 10.0*Math.log10(sumIIlineal);//II in dB; System.out.println(""); System.out.println("[ChannelAssignment] ======================================"); return sumII; } private double[][] getExternalII(int scanningInterval, int numAPs){ // Function to get and calculate External Interference Impact double[][] externalII = new double[11][numAPs]; // SSID to scan String SCANNED_SSID = "*"; // Scanning agents Map<InetAddress, Integer> scanningAgents = new HashMap<InetAddress, Integer> (); int result; // Result for scanning HashSet<OdinClient> clients = new HashSet<OdinClient>(getClients()); //For each channel double sumEII = 0; int numAgent = 0; for (int num_channel = 1 ; num_channel <= 11 ; ++num_channel) { sumEII = 0; numAgent = 0; scanningAgents.clear(); // For each Agent for (InetAddress agentAddr: getAgents()) { // Request statistics result = requestScannedStationsStatsFromAgent(agentAddr, num_channel, "*"); scanningAgents.put(agentAddr, result); } try { Thread.sleep(scanningInterval); } catch (InterruptedException e) { e.printStackTrace(); } //System.out.println("[ChannelAssignment - ExternalII] After sleep"); for (InetAddress agentAddr: getAgents()) { //System.out.println("[ChannelAssignment - ExternalII] Agent: " + agentAddr + " scans in channel: " + num_channel); // Reception statistics if (scanningAgents.get(agentAddr) == 0) { System.out.println("[ChannelAssignment - ExternalII] Agent BUSY during scanning operation"); continue; } Map<MACAddress, Map<String, String>> vals_rx = getScannedStationsStatsFromAgent(agentAddr, "*"); //System.out.println("[ChannelAssignment - ExternalII] After get vals_rx"); // for each STA scanned by the Agent for (Entry<MACAddress, Map<String, String>> vals_entry_rx: vals_rx.entrySet()) { // NOTE: the clients currently scanned MAY NOT be the same as the clients who have been associated MACAddress staHwAddr = vals_entry_rx.getKey(); boolean isWi5Sta = false; boolean isWi5Lvap= false; for (OdinClient oc: clients) { // all the clients currently associated if (oc.getMacAddress().equals(staHwAddr)) { isWi5Sta = true; break; } if (oc.getLvap().getBssid().equals(staHwAddr)){ isWi5Lvap = true; break; } } if (isWi5Sta) { continue; } if (isWi5Lvap) { continue; } double signal = Double.parseDouble(vals_entry_rx.getValue().get("avg_signal")); double packets = Double.parseDouble(vals_entry_rx.getValue().get("packets")); double length = Double.parseDouble(vals_entry_rx.getValue().get("avg_len_pkt")); double rate = Double.parseDouble(vals_entry_rx.getValue().get("avg_rate")); double inittime = Double.parseDouble(vals_entry_rx.getValue().get("first_received")); // In seconds double endtime = Double.parseDouble(vals_entry_rx.getValue().get("last_received")); // In seconds if((rate!=0.0)&&(signal!=0.0)){//Without errors in scan //System.out.print("[ChannelAssignment - ExternalII] Scan: " + signal); //System.out.print(" " + packets); //System.out.print(" " + length); //System.out.print(" " + rate); //System.out.println(" " + (endtime-inittime)); double signal_lineal = Math.pow(10.0, (signal) / 10.0); double signal_EII = signal_lineal*((packets*8*length/rate)/(1000*(endtime-inittime))); // (bits/kbits)/ms //System.out.println("[ChannelAssignment - ExternalII] Signal_EII: " + signal_EII); sumEII = sumEII + signal_EII; }else{ //System.out.println("[ChannelAssignment - ExternalII] Rate 0!"); } } //System.out.println("[ChannelAssignment - ExternalII] sumEII: " + 10.0*Math.log10(sumEII)); //System.out.println(""); externalII[num_channel-1][numAgent] = 10.0*Math.log10(sumEII); numAgent++; } } System.out.println("[ChannelAssignment] ================================="); System.out.println("[ChannelAssignment] = EXTERNAL INTERFERENCE IMPACT =\n"); for (double[] arrayCoefII: externalII) { //System.out.println(Arrays.toString(arrayCoefII)); System.out.print("[ "); for (double coef_II: arrayCoefII) { System.out.print(String.format("%.2f",coef_II)+" "); } System.out.println("]"); } System.out.println(""); System.out.println("[ChannelAssignment] =================================\n"); return externalII; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.yarn; import org.apache.flink.api.java.tuple.Tuple4; import org.apache.flink.util.Preconditions; import org.apache.flink.util.function.TriConsumer; import org.apache.flink.util.function.TriFunction; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.client.api.AMRMClient; import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync; import org.apache.hadoop.yarn.client.api.async.impl.AMRMClientAsyncImpl; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; /** * A Yarn {@link AMRMClientAsync} implementation for testing. */ public class TestingYarnAMRMClientAsync extends AMRMClientAsyncImpl<AMRMClient.ContainerRequest> { private final Function<Tuple4<Priority, String, Resource, CallbackHandler>, List<? extends Collection<AMRMClient.ContainerRequest>>> getMatchingRequestsFunction; private final BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> addContainerRequestConsumer; private final BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> removeContainerRequestConsumer; private final BiConsumer<ContainerId, CallbackHandler> releaseAssignedContainerConsumer; private final Consumer<Integer> setHeartbeatIntervalConsumer; private final TriFunction<String, Integer, String, RegisterApplicationMasterResponse> registerApplicationMasterFunction; private final TriConsumer<FinalApplicationStatus, String, String> unregisterApplicationMasterConsumer; private final Runnable clientInitRunnable; private final Runnable clientStartRunnable; private final Runnable clientStopRunnable; private TestingYarnAMRMClientAsync( CallbackHandler callbackHandler, Function<Tuple4<Priority, String, Resource, CallbackHandler>, List<? extends Collection<AMRMClient.ContainerRequest>>> getMatchingRequestsFunction, BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> addContainerRequestConsumer, BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> removeContainerRequestConsumer, BiConsumer<ContainerId, CallbackHandler> releaseAssignedContainerConsumer, Consumer<Integer> setHeartbeatIntervalConsumer, TriFunction<String, Integer, String, RegisterApplicationMasterResponse> registerApplicationMasterFunction, TriConsumer<FinalApplicationStatus, String, String> unregisterApplicationMasterConsumer, Runnable clientInitRunnable, Runnable clientStartRunnable, Runnable clientStopRunnable) { super(0, callbackHandler); this.setHeartbeatIntervalConsumer = Preconditions.checkNotNull(setHeartbeatIntervalConsumer); this.addContainerRequestConsumer = Preconditions.checkNotNull(addContainerRequestConsumer); this.releaseAssignedContainerConsumer = Preconditions.checkNotNull(releaseAssignedContainerConsumer); this.removeContainerRequestConsumer = Preconditions.checkNotNull(removeContainerRequestConsumer); this.registerApplicationMasterFunction = Preconditions.checkNotNull(registerApplicationMasterFunction); this.getMatchingRequestsFunction = Preconditions.checkNotNull(getMatchingRequestsFunction); this.unregisterApplicationMasterConsumer = Preconditions.checkNotNull(unregisterApplicationMasterConsumer); this.clientInitRunnable = Preconditions.checkNotNull(clientInitRunnable); this.clientStartRunnable = Preconditions.checkNotNull(clientStartRunnable); this.clientStopRunnable = Preconditions.checkNotNull(clientStopRunnable); } @Override public List<? extends Collection<AMRMClient.ContainerRequest>> getMatchingRequests(Priority priority, String resourceName, Resource capability) { return getMatchingRequestsFunction.apply(Tuple4.of(priority, resourceName, capability, handler)); } @Override public void addContainerRequest(AMRMClient.ContainerRequest req) { addContainerRequestConsumer.accept(req, handler); } @Override public void removeContainerRequest(AMRMClient.ContainerRequest req) { removeContainerRequestConsumer.accept(req, handler); } @Override public void releaseAssignedContainer(ContainerId containerId) { releaseAssignedContainerConsumer.accept(containerId, handler); } @Override public void setHeartbeatInterval(int interval) { setHeartbeatIntervalConsumer.accept(interval); } @Override public RegisterApplicationMasterResponse registerApplicationMaster(String appHostName, int appHostPort, String appTrackingUrl) { return registerApplicationMasterFunction.apply(appHostName, appHostPort, appTrackingUrl); } @Override public void unregisterApplicationMaster(FinalApplicationStatus appStatus, String appMessage, String appTrackingUrl) { unregisterApplicationMasterConsumer.accept(appStatus, appMessage, appTrackingUrl); } static Builder builder() { return new Builder(); } // ------------------------------------------------------------------------ // Override lifecycle methods to avoid actually starting the service // ------------------------------------------------------------------------ @Override public void init(Configuration conf) { clientInitRunnable.run(); } @Override public void start() { clientStartRunnable.run(); } @Override public void stop() { clientStopRunnable.run(); } /** * Builder class for {@link TestingYarnAMRMClientAsync}. */ public static class Builder { private Function<Tuple4<Priority, String, Resource, CallbackHandler>, List<? extends Collection<AMRMClient.ContainerRequest>>> getMatchingRequestsFunction = ignored -> Collections.emptyList(); private BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> addContainerRequestConsumer = (ignored1, ignored2) -> {}; private BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> removeContainerRequestConsumer = (ignored1, ignored2) -> {}; private BiConsumer<ContainerId, CallbackHandler> releaseAssignedContainerConsumer = (ignored1, ignored2) -> {}; private Consumer<Integer> setHeartbeatIntervalConsumer = (ignored) -> {}; private TriFunction<String, Integer, String, RegisterApplicationMasterResponse> registerApplicationMasterFunction = (ignored1, ignored2, ignored3) -> new TestingRegisterApplicationMasterResponse(Collections::emptyList); private TriConsumer<FinalApplicationStatus, String, String> unregisterApplicationMasterConsumer = (ignored1, ignored2, ignored3) -> {}; private Runnable clientInitRunnable = () -> {}; private Runnable clientStartRunnable = () -> {}; private Runnable clientStopRunnable = () -> {}; private Builder() {} Builder setAddContainerRequestConsumer(BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> addContainerRequestConsumer) { this.addContainerRequestConsumer = addContainerRequestConsumer; return this; } Builder setGetMatchingRequestsFunction(Function<Tuple4<Priority, String, Resource, CallbackHandler>, List<? extends Collection<AMRMClient.ContainerRequest>>> getMatchingRequestsFunction) { this.getMatchingRequestsFunction = getMatchingRequestsFunction; return this; } Builder setRegisterApplicationMasterFunction(TriFunction<String, Integer, String, RegisterApplicationMasterResponse> registerApplicationMasterFunction) { this.registerApplicationMasterFunction = registerApplicationMasterFunction; return this; } Builder setReleaseAssignedContainerConsumer(BiConsumer<ContainerId, CallbackHandler> releaseAssignedContainerConsumer) { this.releaseAssignedContainerConsumer = releaseAssignedContainerConsumer; return this; } Builder setRemoveContainerRequestConsumer(BiConsumer<AMRMClient.ContainerRequest, CallbackHandler> removeContainerRequestConsumer) { this.removeContainerRequestConsumer = removeContainerRequestConsumer; return this; } Builder setSetHeartbeatIntervalConsumer(Consumer<Integer> setHeartbeatIntervalConsumer) { this.setHeartbeatIntervalConsumer = setHeartbeatIntervalConsumer; return this; } Builder setUnregisterApplicationMasterConsumer(TriConsumer<FinalApplicationStatus, String, String> unregisterApplicationMasterConsumer) { this.unregisterApplicationMasterConsumer = unregisterApplicationMasterConsumer; return this; } Builder setClientInitRunnable(Runnable clientInitRunnable) { this.clientInitRunnable = clientInitRunnable; return this; } Builder setClientStartRunnable(Runnable clientStartRunnable) { this.clientStartRunnable = clientStartRunnable; return this; } Builder setClientStopRunnable(Runnable clientStopRunnable) { this.clientStopRunnable = clientStopRunnable; return this; } public TestingYarnAMRMClientAsync build(CallbackHandler callbackHandler) { return new TestingYarnAMRMClientAsync( callbackHandler, getMatchingRequestsFunction, addContainerRequestConsumer, removeContainerRequestConsumer, releaseAssignedContainerConsumer, setHeartbeatIntervalConsumer, registerApplicationMasterFunction, unregisterApplicationMasterConsumer, clientInitRunnable, clientStartRunnable, clientStopRunnable); } } }
// Copyright 2016 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.webapps; import android.content.Intent; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Browser; import androidx.browser.trusted.sharing.ShareData; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.XmlResourceParserImpl; import org.robolectric.annotation.Config; import org.robolectric.res.ResourceTable; import org.robolectric.util.ReflectionHelpers; import org.w3c.dom.Document; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.ShortcutSource; import org.chromium.content_public.common.ScreenOrientationValues; import org.chromium.webapk.lib.common.WebApkConstants; import org.chromium.webapk.lib.common.WebApkMetaDataKeys; import org.chromium.webapk.lib.common.splash.SplashLayout; import org.chromium.webapk.test.WebApkTestHelper; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Tests WebApkInfo. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class WebApkInfoTest { private static final String WEBAPK_PACKAGE_NAME = "org.chromium.webapk.test_package"; private static final String UNBOUND_WEBAPK_PACKAGE_NAME = "unbound.webapk"; // Android Manifest meta data for {@link PACKAGE_NAME}. private static final String START_URL = "https://www.google.com/scope/a_is_for_apple"; private static final String SCOPE = "https://www.google.com/scope"; private static final String NAME = "name"; private static final String SHORT_NAME = "short_name"; private static final String DISPLAY_MODE = "minimal-ui"; private static final String ORIENTATION = "portrait"; private static final String THEME_COLOR = "1L"; private static final String BACKGROUND_COLOR = "2L"; private static final int SHELL_APK_VERSION = 3; private static final String MANIFEST_URL = "https://www.google.com/alphabet.json"; private static final String ICON_URL = "https://www.google.com/scope/worm.png"; private static final String ICON_MURMUR2_HASH = "5"; private static final int PRIMARY_ICON_ID = 12; private static final int PRIMARY_MASKABLE_ICON_ID = 14; private static final int SOURCE = ShortcutSource.NOTIFICATION; /** Fakes the Resources object, allowing lookup of String value. */ private static class FakeResources extends Resources { private final Map<String, Integer> mStringIdMap; private final Map<Integer, String> mIdValueMap; private String mShortcutsXmlContents; private class MockXmlResourceParserImpl extends XmlResourceParserImpl { String mPackageName; public MockXmlResourceParserImpl(Document document, String fileName, String packageName, String applicationPackageName, ResourceTable resourceTable) { super(document, fileName, packageName, applicationPackageName, resourceTable); mPackageName = packageName; } @Override public int getAttributeResourceValue( String namespace, String attribute, int defaultValue) { // Remove the trailing '@'. String attributeValue = getAttributeValue(namespace, attribute).substring(1); if (mStringIdMap.containsKey(attributeValue)) { return mStringIdMap.get(attributeValue); } return defaultValue; } } // Do not warn about deprecated call to Resources(); the documentation says code is not // supposed to create its own Resources object, but we are using it to fake out the // Resources, and there is no other way to do that. @SuppressWarnings("deprecation") public FakeResources() { super(new AssetManager(), null, null); mStringIdMap = new HashMap<>(); mIdValueMap = new HashMap<>(); } @Override public int getIdentifier(String name, String defType, String defPackage) { String key = getKey(name, defType, defPackage); return mStringIdMap.containsKey(key) ? mStringIdMap.get(key) : 0; } @Override public String getString(int id) { if (!mIdValueMap.containsKey(id)) { throw new Resources.NotFoundException("id 0x" + Integer.toHexString(id)); } return mIdValueMap.get(id); } @Override public int getColor(int id, Resources.Theme theme) { return Integer.parseInt(getString(id)); } @Override public XmlResourceParser getXml(int id) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse( new ByteArrayInputStream(mShortcutsXmlContents.getBytes())); return new MockXmlResourceParserImpl( document, "file", WEBAPK_PACKAGE_NAME, WEBAPK_PACKAGE_NAME, null); } catch (Exception e) { Assert.fail("Failed to create XmlResourceParser"); return null; } } void setShortcutsXmlContent(String content) { mShortcutsXmlContents = content; } public void addStringForTesting( String name, String defType, String defPackage, int identifier, String value) { String key = getKey(name, defType, defPackage); mStringIdMap.put(key, identifier); mIdValueMap.put(identifier, value); } public void addColorForTesting(String name, String defPackage, int identifier, int value) { addStringForTesting(name, "color", defPackage, identifier, Integer.toString(value)); } private String getKey(String name, String defType, String defPackage) { return defPackage + ":" + defType + "/" + name; } } @Test public void testSanity() { // Test guidelines: // - Stubbing out native calls in this test likely means that there is a bug. // - For every WebappInfo boolean there should be a test which tests both values. Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.SCOPE, SCOPE); bundle.putString(WebApkMetaDataKeys.NAME, NAME); bundle.putString(WebApkMetaDataKeys.SHORT_NAME, SHORT_NAME); bundle.putString(WebApkMetaDataKeys.DISPLAY_MODE, DISPLAY_MODE); bundle.putString(WebApkMetaDataKeys.ORIENTATION, ORIENTATION); bundle.putString(WebApkMetaDataKeys.THEME_COLOR, THEME_COLOR); bundle.putString(WebApkMetaDataKeys.BACKGROUND_COLOR, BACKGROUND_COLOR); bundle.putInt(WebApkMetaDataKeys.SHELL_APK_VERSION, SHELL_APK_VERSION); bundle.putString(WebApkMetaDataKeys.WEB_MANIFEST_URL, MANIFEST_URL); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); bundle.putString(WebApkMetaDataKeys.ICON_URLS_AND_ICON_MURMUR2_HASHES, ICON_URL + " " + ICON_MURMUR2_HASH); bundle.putInt(WebApkMetaDataKeys.ICON_ID, PRIMARY_ICON_ID); bundle.putInt(WebApkMetaDataKeys.MASKABLE_ICON_ID, PRIMARY_MASKABLE_ICON_ID); Bundle shareActivityBundle = new Bundle(); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ACTION, "action0"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_METHOD, "POST"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ENCTYPE, "multipart/form-data"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_PARAM_TITLE, "title0"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_PARAM_TEXT, "text0"); shareActivityBundle.putString( WebApkMetaDataKeys.SHARE_PARAM_NAMES, "[\"name1\", \"name2\"]"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_PARAM_ACCEPTS, "[[\"text/plain\"], [\"image/png\", \"image/jpeg\"]]"); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, new Bundle[] {shareActivityBundle}); Intent intent = new Intent(); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_PACKAGE_NAME, WEBAPK_PACKAGE_NAME); intent.putExtra(ShortcutHelper.EXTRA_FORCE_NAVIGATION, true); intent.putExtra(ShortcutHelper.EXTRA_URL, START_URL); intent.putExtra(ShortcutHelper.EXTRA_SOURCE, ShortcutSource.NOTIFICATION); intent.putExtra(WebApkConstants.EXTRA_SPLASH_PROVIDED_BY_WEBAPK, true); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(WebApkConstants.WEBAPK_ID_PREFIX + WEBAPK_PACKAGE_NAME, info.id()); Assert.assertEquals(START_URL, info.url()); Assert.assertTrue(info.shouldForceNavigation()); Assert.assertEquals(SCOPE, info.scopeUrl()); Assert.assertEquals(NAME, info.name()); Assert.assertEquals(SHORT_NAME, info.shortName()); Assert.assertEquals(WebDisplayMode.MINIMAL_UI, info.displayMode()); Assert.assertEquals(ScreenOrientationValues.PORTRAIT, info.orientation()); Assert.assertTrue(info.hasValidToolbarColor()); Assert.assertEquals(1L, info.toolbarColor()); Assert.assertTrue(info.hasValidBackgroundColor()); Assert.assertEquals(2L, info.backgroundColor()); Assert.assertEquals(WEBAPK_PACKAGE_NAME, info.webApkPackageName()); Assert.assertEquals(SHELL_APK_VERSION, info.shellApkVersion()); Assert.assertEquals(MANIFEST_URL, info.manifestUrl()); Assert.assertEquals(START_URL, info.manifestStartUrl()); Assert.assertEquals(WebApkDistributor.BROWSER, info.distributor()); Assert.assertEquals(1, info.iconUrlToMurmur2HashMap().size()); Assert.assertTrue(info.iconUrlToMurmur2HashMap().containsKey(ICON_URL)); Assert.assertEquals(ICON_MURMUR2_HASH, info.iconUrlToMurmur2HashMap().get(ICON_URL)); Assert.assertEquals(SOURCE, info.source()); Assert.assertEquals( (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M), info.isSplashProvidedByWebApk()); Assert.assertEquals(PRIMARY_MASKABLE_ICON_ID, info.icon().resourceIdForTesting()); Assert.assertEquals(true, info.isIconAdaptive()); Assert.assertEquals(null, info.splashIcon().bitmap()); WebApkShareTarget shareTarget = info.shareTarget(); Assert.assertNotNull(shareTarget); Assert.assertEquals("action0", shareTarget.getAction()); Assert.assertTrue(shareTarget.isShareMethodPost()); Assert.assertTrue(shareTarget.isShareEncTypeMultipart()); Assert.assertEquals("title0", shareTarget.getParamTitle()); Assert.assertEquals("text0", shareTarget.getParamText()); Assert.assertEquals(new String[] {"name1", "name2"}, shareTarget.getFileNames()); Assert.assertEquals(new String[][] {{"text/plain"}, {"image/png", "image/jpeg"}}, shareTarget.getFileAccepts()); } /** * Test that {@link createWebApkInfo()} ignores the maskable icon on pre-Android-O * Android OSes. */ @Test public void testOsVersionDoesNotSupportAdaptive() { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.N); Bundle bundle = new Bundle(); bundle.putInt(WebApkMetaDataKeys.ICON_ID, PRIMARY_ICON_ID); bundle.putInt(WebApkMetaDataKeys.MASKABLE_ICON_ID, PRIMARY_MASKABLE_ICON_ID); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(PRIMARY_ICON_ID, info.icon().resourceIdForTesting()); Assert.assertEquals(false, info.isIconAdaptive()); } /** * Test that {@link createWebApkInfo()} selects {@link WebApkMetaDataKeys.ICON_ID} if no * maskable icon is provided and that the icon is tagged as non-maskable. */ @Test public void testNoMaskableIcon() { Bundle bundle = new Bundle(); bundle.putInt(WebApkMetaDataKeys.ICON_ID, PRIMARY_ICON_ID); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(PRIMARY_ICON_ID, info.icon().resourceIdForTesting()); Assert.assertEquals(false, info.isIconAdaptive()); } /** * Test that {@link createWebApkInfo()} populates {@link WebApkInfo#url()} with the start URL * from the intent not the start URL in the WebAPK's meta data. When a WebAPK is launched via a * deep link from a URL within the WebAPK's scope, the WebAPK should open at the URL it was deep * linked from not the WebAPK's start URL. */ @Test public void testUseStartUrlOverride() { String intentStartUrl = "https://www.google.com/master_override"; Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, intentStartUrl); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(intentStartUrl, info.url()); // {@link WebApkInfo#manifestStartUrl()} should contain the start URL from the Android // Manifest. Assert.assertEquals(START_URL, info.manifestStartUrl()); } /** * Test that if the scope is empty that the scope is computed from the "start URL specified from * the Web Manifest" not the "URL the WebAPK initially navigated to". Deep links can open a * WebAPK at an arbitrary URL. */ @Test public void testDefaultScopeFromManifestStartUrl() { String manifestStartUrl = START_URL; String intentStartUrl = "https://www.google.com/a/b/c"; String scopeFromManifestStartUrl = ShortcutHelper.getScopeFromUrl(manifestStartUrl); String scopeFromIntentStartUrl = ShortcutHelper.getScopeFromUrl(intentStartUrl); Assert.assertNotEquals(scopeFromManifestStartUrl, scopeFromIntentStartUrl); Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, manifestStartUrl); bundle.putString(WebApkMetaDataKeys.SCOPE, ""); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, intentStartUrl); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(scopeFromManifestStartUrl, info.scopeUrl()); } /** * Test that {@link createWebApkInfo} can read multiple icon URLs and multiple icon murmur2 * hashes from the WebAPK's meta data. */ @Test public void testGetIconUrlAndMurmur2HashFromMetaData() { String iconUrl1 = "/icon1.png"; String murmur2Hash1 = "1"; String iconUrl2 = "/icon2.png"; String murmur2Hash2 = "2"; Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); bundle.putString(WebApkMetaDataKeys.ICON_URLS_AND_ICON_MURMUR2_HASHES, iconUrl1 + " " + murmur2Hash1 + " " + iconUrl2 + " " + murmur2Hash2); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Map<String, String> iconUrlToMurmur2HashMap = info.iconUrlToMurmur2HashMap(); Assert.assertEquals(2, iconUrlToMurmur2HashMap.size()); Assert.assertEquals(murmur2Hash1, iconUrlToMurmur2HashMap.get(iconUrl1)); Assert.assertEquals(murmur2Hash2, iconUrlToMurmur2HashMap.get(iconUrl2)); } /** * WebApkIconHasher generates hashes with values [0, 2^64-1]. 2^64-1 is greater than * {@link Long#MAX_VALUE}. Test that {@link createWebApkInfo()} can read a hash with value * 2^64 - 1. */ @Test public void testGetIconMurmur2HashFromMetaData() { String hash = "18446744073709551615"; // 2^64 - 1 Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); bundle.putString(WebApkMetaDataKeys.ICON_URLS_AND_ICON_MURMUR2_HASHES, "randomUrl " + hash); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Map<String, String> iconUrlToMurmur2HashMap = info.iconUrlToMurmur2HashMap(); Assert.assertEquals(1, iconUrlToMurmur2HashMap.size()); Assert.assertTrue(iconUrlToMurmur2HashMap.containsValue(hash)); } /** * Prior to SHELL_APK_VERSION 2, WebAPKs did not specify * {@link ShortcutHelper#EXTRA_FORCE_NAVIGATION} in the intent. Test that * {@link WebApkInfo#shouldForceNavigation()} defaults to true when the intent extra is not * specified. */ @Test public void testForceNavigationNotSpecified() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertTrue(info.shouldForceNavigation()); } /** * Test that {@link WebApkInfo#source()} returns {@link ShortcutSource#UNKNOWN} if the source * in the launch intent > {@link ShortcutSource#COUNT}. This can occur if the user is using a * new WebAPK and an old version of Chrome. */ @Test public void testOutOfBoundsSource() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); intent.putExtra(ShortcutHelper.EXTRA_SOURCE, ShortcutSource.COUNT + 1); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(ShortcutSource.UNKNOWN, info.source()); } /** * Test that {@link WebApkInfo#name()} and {@link WebApkInfo#shortName()} return the name and * short name from the meta data before they are moved to strings in resources. */ @Test public void testNameAndShortNameFromMetadataWhenStringResourcesDoNotExist() { String name = "WebAPK name"; String shortName = "WebAPK short name"; Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); bundle.putString(WebApkMetaDataKeys.NAME, name); bundle.putString(WebApkMetaDataKeys.SHORT_NAME, shortName); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(name, info.name()); Assert.assertEquals(shortName, info.shortName()); } /** * Test that {@link WebApkInfo#name()} and {@link WebApkInfo#shortName()} return the string * values from the WebAPK resources if exist. */ @Test public void testNameAndShortNameFromWebApkStrings() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); String name = "WebAPK name"; String shortName = "WebAPK short name"; FakeResources res = new FakeResources(); res.addStringForTesting(WebApkIntentDataProviderFactory.RESOURCE_NAME, WebApkIntentDataProviderFactory.RESOURCE_STRING_TYPE, WEBAPK_PACKAGE_NAME, 1, name); res.addStringForTesting(WebApkIntentDataProviderFactory.RESOURCE_SHORT_NAME, WebApkIntentDataProviderFactory.RESOURCE_STRING_TYPE, WEBAPK_PACKAGE_NAME, 2, shortName); WebApkTestHelper.setResource(WEBAPK_PACKAGE_NAME, res); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(name, info.name()); Assert.assertEquals(shortName, info.shortName()); } /** * Test that ShortcutSource#EXTERNAL_INTENT is rewritten to * ShortcutSource#EXTERNAL_INTENT_FROM_CHROME if the WebAPK is launched from a * browser with the same package name (e.g. web page link on Chrome Stable * launches WebAPK whose host browser is Chrome Stable). */ @Test public void testOverrideExternalIntentSourceIfLaunchedFromChrome() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); intent.putExtra(ShortcutHelper.EXTRA_SOURCE, ShortcutSource.EXTERNAL_INTENT); intent.putExtra( Browser.EXTRA_APPLICATION_ID, RuntimeEnvironment.application.getPackageName()); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(ShortcutSource.EXTERNAL_INTENT_FROM_CHROME, info.source()); } /** * Test that ShortcutSource#EXTERNAL_INTENT is not rewritten when the WebAPK is launched * from a non-browser app. */ @Test public void testOverrideExternalIntentSourceIfLaunchedFromNonChromeApp() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); intent.putExtra(ShortcutHelper.EXTRA_SOURCE, ShortcutSource.EXTERNAL_INTENT); intent.putExtra(Browser.EXTRA_APPLICATION_ID, "com.google.android.talk"); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(ShortcutSource.EXTERNAL_INTENT, info.source()); } /** * Test that ShortcutSource#SHARE_TARGET is rewritten to * ShortcutSource#WEBAPK_SHARE_TARGET_FILE if the WebAPK is launched as a result of user sharing * a binary file. */ @Test public void testOverrideShareTargetSourceIfLaunchedFromFileSharing() { Bundle shareActivityBundle = new Bundle(); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ACTION, "/share.html"); Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, new Bundle[] {shareActivityBundle}); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); intent.setAction(Intent.ACTION_SEND); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_SELECTED_SHARE_TARGET_ACTIVITY_CLASS_NAME, "something"); ArrayList<Uri> uris = new ArrayList<>(); uris.add(Uri.parse("mock-uri-3")); intent.putExtra(Intent.EXTRA_STREAM, uris); intent.putExtra(ShortcutHelper.EXTRA_SOURCE, ShortcutSource.WEBAPK_SHARE_TARGET); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(ShortcutSource.WEBAPK_SHARE_TARGET_FILE, info.source()); } /** * Test when a distributor is not specified, the default distributor value for a WebAPK * installed by Chrome is |WebApkDistributor.BROWSER|, while for an Unbound WebAPK is * |WebApkDistributor.Other|. */ @Test public void testWebApkDistributorDefaultValue() { // Test Case: Bound WebAPK Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(WebApkDistributor.BROWSER, info.distributor()); // Test Case: Unbound WebAPK WebApkTestHelper.registerWebApkWithMetaData( UNBOUND_WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); intent = new Intent(); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_PACKAGE_NAME, UNBOUND_WEBAPK_PACKAGE_NAME); intent.putExtra(ShortcutHelper.EXTRA_URL, START_URL); info = createWebApkInfo(intent); Assert.assertEquals(WebApkDistributor.OTHER, info.distributor()); } /** * Test that {@link WebApkInfo#shareTarget()} returns a null object if the WebAPK does not * handle share intents. */ @Test public void testGetShareTargetNullIfDoesNotHandleShareIntents() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData(WEBAPK_PACKAGE_NAME, bundle, null); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertNull(info.shareTarget()); } /** * Tests that {@link WebApkShareTarget#getFileNames()} returns an empty list when the * {@link shareParamNames} <meta-data> tag is not a JSON array. */ @Test public void testPostShareTargetInvalidParamNames() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); Bundle shareActivityBundle = new Bundle(); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_METHOD, "POST"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ENCTYPE, "multipart/form-data"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_PARAM_NAMES, "not an array"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_PARAM_ACCEPTS, "[[\"image/*\"]]"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_PARAM_TEXT, "share-text"); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ACTION, "/share.html"); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, new Bundle[] {shareActivityBundle}); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); WebappInfo info = createWebApkInfo(intent); WebApkShareTarget shareTarget = info.shareTarget(); Assert.assertNotNull(shareTarget); Assert.assertEquals(0, shareTarget.getFileNames().length); } /** * Tests building {@link ShareData} when {@link Intent.EXTRA_STREAM} has a Uri value. */ @Test public void testShareDataUriString() { Bundle shareActivityBundle = new Bundle(); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ACTION, "/share.html"); Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, new Bundle[] {shareActivityBundle}); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); intent.setAction(Intent.ACTION_SEND); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_SELECTED_SHARE_TARGET_ACTIVITY_CLASS_NAME, WebApkTestHelper.getGeneratedShareTargetActivityClassName(0)); Uri sharedFileUri = Uri.parse("mock-uri-1"); intent.putExtra(Intent.EXTRA_STREAM, sharedFileUri); WebappInfo info = createWebApkInfo(intent); ShareData shareData = info.shareData(); Assert.assertNotNull(shareData); Assert.assertNotNull(shareData.uris); Assert.assertThat(shareData.uris, Matchers.contains(sharedFileUri)); } /** * Tests building {@link ShareData} when {@link Intent.EXTRA_STREAM} has an ArrayList * value. */ @Test public void testShareDataUriList() { Bundle shareActivityBundle = new Bundle(); shareActivityBundle.putString(WebApkMetaDataKeys.SHARE_ACTION, "/share.html"); Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, new Bundle[] {shareActivityBundle}); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); intent.setAction(Intent.ACTION_SEND); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_SELECTED_SHARE_TARGET_ACTIVITY_CLASS_NAME, WebApkTestHelper.getGeneratedShareTargetActivityClassName(0)); Uri sharedFileUri = Uri.parse("mock-uri-1"); ArrayList<Uri> uris = new ArrayList<>(); uris.add(sharedFileUri); intent.putExtra(Intent.EXTRA_STREAM, uris); WebappInfo info = createWebApkInfo(intent); ShareData shareData = info.shareData(); Assert.assertNotNull(shareData); Assert.assertNotNull(shareData.uris); Assert.assertThat(shareData.uris, Matchers.contains(sharedFileUri)); } /** * Test that {@link WebApkInfo#backgroundColorFallbackToDefault()} uses * {@link SplashLayout#getDefaultBackgroundColor()} as the default background color if there is * no default background color in the WebAPK's resources. */ @Test public void testBackgroundColorFallbackToDefaultNoCustomDefault() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); bundle.putString(WebApkMetaDataKeys.BACKGROUND_COLOR, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING + "L"); WebApkTestHelper.registerWebApkWithMetaData(WEBAPK_PACKAGE_NAME, bundle, null); Intent intent = new Intent(); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_PACKAGE_NAME, WEBAPK_PACKAGE_NAME); intent.putExtra(ShortcutHelper.EXTRA_URL, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(SplashLayout.getDefaultBackgroundColor(RuntimeEnvironment.application), info.backgroundColorFallbackToDefault()); } /** * Test that {@link WebApkInfo#backgroundColorFallbackToDefault()} uses the default * background color from the WebAPK's resources if present. */ @Test public void testBackgroundColorFallbackToDefaultWebApkHasCustomDefault() { final int defaultBackgroundColorResourceId = 1; final int defaultBackgroundColorInWebApk = 42; Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); bundle.putString(WebApkMetaDataKeys.BACKGROUND_COLOR, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING + "L"); bundle.putInt( WebApkMetaDataKeys.DEFAULT_BACKGROUND_COLOR_ID, defaultBackgroundColorResourceId); WebApkTestHelper.registerWebApkWithMetaData(WEBAPK_PACKAGE_NAME, bundle, null); FakeResources res = new FakeResources(); res.addColorForTesting("mockResource", WEBAPK_PACKAGE_NAME, defaultBackgroundColorResourceId, defaultBackgroundColorInWebApk); WebApkTestHelper.setResource(WEBAPK_PACKAGE_NAME, res); Intent intent = new Intent(); intent.putExtra(WebApkConstants.EXTRA_WEBAPK_PACKAGE_NAME, WEBAPK_PACKAGE_NAME); intent.putExtra(ShortcutHelper.EXTRA_URL, START_URL); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals( defaultBackgroundColorInWebApk, info.backgroundColorFallbackToDefault()); } /** * Test that shortcut items are properly parsed. */ @Test public void testShortcutItemsFromWebApkStrings() { Bundle bundle = new Bundle(); bundle.putString(WebApkMetaDataKeys.START_URL, START_URL); WebApkTestHelper.registerWebApkWithMetaData( WEBAPK_PACKAGE_NAME, bundle, null /* shareTargetMetaData */); FakeResources res = new FakeResources(); res.addStringForTesting(WebApkIntentDataProviderFactory.RESOURCE_SHORTCUTS, WebApkIntentDataProviderFactory.RESOURCE_XML_TYPE, WEBAPK_PACKAGE_NAME, 1, null); res.addStringForTesting("shortcut_1_short_name", WebApkIntentDataProviderFactory.RESOURCE_STRING_TYPE, WEBAPK_PACKAGE_NAME, 2, "short name1"); res.addStringForTesting("shortcut_1_name", WebApkIntentDataProviderFactory.RESOURCE_STRING_TYPE, WEBAPK_PACKAGE_NAME, 3, "name1"); res.addStringForTesting("shortcut_2_short_name", WebApkIntentDataProviderFactory.RESOURCE_STRING_TYPE, WEBAPK_PACKAGE_NAME, 4, "short name2"); res.addStringForTesting("shortcut_2_name", WebApkIntentDataProviderFactory.RESOURCE_STRING_TYPE, WEBAPK_PACKAGE_NAME, 5, "name2"); res.addStringForTesting("shortcut_1_icon", "drawable", WEBAPK_PACKAGE_NAME, 6, null); res.addStringForTesting("shortcut_2_icon", "drawable", WEBAPK_PACKAGE_NAME, 7, null); WebApkTestHelper.setResource(WEBAPK_PACKAGE_NAME, res); Intent intent = WebApkTestHelper.createMinimalWebApkIntent(WEBAPK_PACKAGE_NAME, START_URL); // No shortcuts case. res.setShortcutsXmlContent( "<shortcuts xmlns:android='http://schemas.android.com/apk/res/android'/>"); WebappInfo info = createWebApkInfo(intent); Assert.assertEquals(info.shortcutItems().size(), 0); // One shortcut case. String oneShortcut = "<shortcuts xmlns:android='http://schemas.android.com/apk/res/android'>" + " <shortcut" + " android:shortcutId='shortcut_1'" + " android:icon='@drawable/shortcut_1_icon'" + " iconUrl='https://example.com/icon1.png'" + " iconHash='1234'" + " android:shortcutShortLabel='@string/shortcut_1_short_name'" + " android:shortcutLongLabel='@string/shortcut_1_name'>" + " <intent android:data='https://example.com/launch1' />" + " </shortcut>" + "</shortcuts>"; res.setShortcutsXmlContent(oneShortcut); info = createWebApkInfo(intent); Assert.assertEquals(info.shortcutItems().size(), 1); WebApkExtras.ShortcutItem item = info.shortcutItems().get(0); Assert.assertEquals(item.name, "name1"); Assert.assertEquals(item.shortName, "short name1"); Assert.assertEquals(item.launchUrl, "https://example.com/launch1"); Assert.assertEquals(item.iconUrl, "https://example.com/icon1.png"); Assert.assertEquals(item.iconHash, "1234"); Assert.assertNotNull(item.icon); Assert.assertEquals(item.icon.resourceIdForTesting(), 6); // Multiple shortcuts case. String twoShortcuts = "<shortcuts xmlns:android='http://schemas.android.com/apk/res/android'>" + " <shortcut" + " android:shortcutId='shortcut_1'" + " android:icon='@drawable/shortcut_1_icon'" + " iconUrl='https://example.con/icon1.png'" + " iconHash='1234'" + " android:shortcutShortLabel='@string/shortcut_1_short_name'" + " android:shortcutLongLabel='@string/shortcut_1_name'>" + " <intent android:data='https://example.com/launch1' />" + " </shortcut>" + " <shortcut" + " android:shortcutId='shortcut_2'" + " android:icon='@drawable/shortcut_2_icon'" + " iconUrl='https://example.com/icon2.png'" + " iconHash='2345'" + " android:shortcutShortLabel='@string/shortcut_2_short_name'" + " android:shortcutLongLabel='@string/shortcut_2_name'>" + " <intent android:data='https://example.com/launch2' />" + " </shortcut>" + "</shortcuts>"; res.setShortcutsXmlContent(twoShortcuts); info = createWebApkInfo(intent); Assert.assertEquals(info.shortcutItems().size(), 2); item = info.shortcutItems().get(1); Assert.assertEquals(item.name, "name2"); Assert.assertEquals(item.shortName, "short name2"); Assert.assertEquals(item.launchUrl, "https://example.com/launch2"); Assert.assertEquals(item.iconUrl, "https://example.com/icon2.png"); Assert.assertEquals(item.iconHash, "2345"); Assert.assertNotNull(item.icon); Assert.assertEquals(item.icon.resourceIdForTesting(), 7); } private WebappInfo createWebApkInfo(Intent intent) { return WebappInfo.create(WebApkIntentDataProviderFactory.create(intent)); } }
/* * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.performance; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; import com.intellij.util.IncorrectOperationException; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.PsiReplacementUtil; import com.siyeh.ig.psiutils.CommentTracker; import com.siyeh.ig.psiutils.ParenthesesUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class RandomDoubleForRandomIntegerInspection extends BaseInspection { @Override @NotNull public String getID() { return "UsingRandomNextDoubleForRandomInteger"; } @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "random.double.for.random.integer.display.name"); } @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "random.double.for.random.integer.problem.descriptor"); } @Override public InspectionGadgetsFix buildFix(Object... infos) { return new RandomDoubleForRandomIntegerFix(); } private static class RandomDoubleForRandomIntegerFix extends InspectionGadgetsFix { @Override @NotNull public String getFamilyName() { return InspectionGadgetsBundle.message( "random.double.for.random.integer.replace.quickfix"); } @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiIdentifier name = (PsiIdentifier)descriptor.getPsiElement(); final PsiReferenceExpression expression = (PsiReferenceExpression)name.getParent(); if (expression == null) { return; } final PsiExpression call = (PsiExpression)expression.getParent(); final PsiExpression qualifier = expression.getQualifierExpression(); if (qualifier == null) { return; } final String qualifierText = qualifier.getText(); final PsiBinaryExpression multiplication = (PsiBinaryExpression)getContainingExpression(call); if (multiplication == null) { return; } final PsiExpression cast = getContainingExpression(multiplication); if (cast == null) { return; } CommentTracker commentTracker = new CommentTracker(); final PsiExpression multiplierExpression; final PsiExpression lhs = multiplication.getLOperand(); final PsiExpression strippedLhs = ParenthesesUtils.stripParentheses(lhs); if (call.equals(strippedLhs)) { multiplierExpression = multiplication.getROperand(); } else { multiplierExpression = lhs; } assert multiplierExpression != null; final String multiplierText = commentTracker.markUnchanged(multiplierExpression).getText(); @NonNls final String nextInt = ".nextInt((int) "; commentTracker.markUnchanged(qualifier); PsiReplacementUtil.replaceExpression(cast, qualifierText + nextInt + multiplierText + ')', commentTracker); } } @Override public BaseInspectionVisitor buildVisitor() { return new RandomDoubleForRandomIntegerVisitor(); } private static class RandomDoubleForRandomIntegerVisitor extends BaseInspectionVisitor { @Override public void visitMethodCallExpression( @NotNull PsiMethodCallExpression call) { super.visitMethodCallExpression(call); final PsiReferenceExpression methodExpression = call.getMethodExpression(); final String methodName = methodExpression.getReferenceName(); @NonNls final String nextDouble = "nextDouble"; if (!nextDouble.equals(methodName)) { return; } final PsiMethod method = call.resolveMethod(); if (method == null) { return; } final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { return; } final String className = containingClass.getQualifiedName(); if (!"java.util.Random".equals(className)) { return; } final PsiExpression possibleMultiplierExpression = getContainingExpression(call); if (!isMultiplier(possibleMultiplierExpression)) { return; } final PsiExpression possibleIntCastExpression = getContainingExpression(possibleMultiplierExpression); if (!isIntCast(possibleIntCastExpression)) { return; } registerMethodCallError(call); } private static boolean isMultiplier(PsiExpression expression) { if (expression == null) { return false; } if (!(expression instanceof PsiBinaryExpression)) { return false; } final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; final IElementType tokenType = binaryExpression.getOperationTokenType(); return JavaTokenType.ASTERISK.equals(tokenType); } private static boolean isIntCast(PsiExpression expression) { if (expression == null) { return false; } if (!(expression instanceof PsiTypeCastExpression)) { return false; } final PsiTypeCastExpression castExpression = (PsiTypeCastExpression)expression; final PsiType type = castExpression.getType(); return PsiType.INT.equals(type); } } @Nullable static PsiExpression getContainingExpression(PsiExpression expression) { PsiElement ancestor = expression.getParent(); while (true) { if (ancestor == null) { return null; } if (!(ancestor instanceof PsiExpression)) { return null; } if (!(ancestor instanceof PsiParenthesizedExpression)) { return (PsiExpression)ancestor; } ancestor = ancestor.getParent(); } } }
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.lipstick.listeners; import java.util.List; import java.util.Properties; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.LipstickPigServer; import org.apache.pig.impl.PigContext; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan; import org.apache.pig.tools.pigstats.JobStats; import org.apache.pig.tools.pigstats.OutputStats; import org.apache.pig.tools.pigstats.PigProgressNotificationListener; import com.google.common.collect.Lists; import com.netflix.lipstick.P2jPlanGenerator; import com.netflix.lipstick.pigtolipstick.BasicP2LClient; import com.netflix.lipstick.pigtolipstick.P2LClient; /** * Lipstick Pig Progress notification listener. * * Manages initialization of lipstick clients and routing events to active * clients. * * @author jmagnusson * @author nbates * */ public class LipstickPPNL implements PigProgressNotificationListener { private static final Log LOG = LogFactory.getLog(LipstickPPNL.class); protected static final String LIPSTICK_UUID_PROP_NAME = "lipstick.uuid.prop.name"; protected static final String LIPSTICK_UUID_PROP_DEFAULT = "lipstick.uuid"; protected static final String LIPSTICK_URL_PROP = "lipstick.server.url"; protected LipstickPigServer ps; protected PigContext context; protected List<P2LClient> clients = Lists.newLinkedList(); protected List<PPNLErrorHandler> errorHandlers = Lists.newLinkedList(); /** * Initialize a new LipstickPPNL object. */ public LipstickPPNL() { LOG.info("--- Init TBPPNL ---"); } public void addErrorHandler(PPNLErrorHandler errHandler) { errorHandlers.add(errHandler); } /** * Check if any clients are active. * * @return true, if at least one active client has been initialized */ protected boolean clientIsActive() { if (clients != null && !clients.isEmpty()) { return true; } return false; } /** * Sets a reference to the pig server. * * @param ps * the pig server */ public void setPigServer(LipstickPigServer ps) { this.ps = ps; setPigContext(ps.getPigContext()); } /** * Sets a reference to the pig context. Used if running * without a LipstickPigServer. * * @param context * the pig server */ public void setPigContext(PigContext context) { this.context = context; } /** * Sets the plan generators. Initializes Lipstick clients if they have not * already been initialized. * * @param unoptimizedPlanGenerator * the unoptimized plan generator * @param optimizedPlanGenerator * the optimized plan generator */ public void setPlanGenerators(P2jPlanGenerator unoptimizedPlanGenerator, P2jPlanGenerator optimizedPlanGenerator) { try { // this is the first time we can grab a conf from pig context so // initClients here initClients(); if (clientIsActive()) { Properties props = context.getProperties(); String uuidPropName = props.getProperty(LIPSTICK_UUID_PROP_NAME, LIPSTICK_UUID_PROP_DEFAULT); String uuid = props.getProperty(uuidPropName); if ((uuid == null) || uuid.isEmpty()) { uuid = UUID.randomUUID().toString(); props.put(uuidPropName, uuid); } LOG.info("UUID: " + uuid); LOG.info(clients); for (P2LClient client : clients) { client.setPlanGenerators(unoptimizedPlanGenerator, optimizedPlanGenerator); client.setPigServer(ps); client.setPigContext(context); client.setPlanId(uuid); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handlePlanGeneratorsError(e); } } } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * initialPlanNotification(java.lang.String, * org.apache.pig.backend.hadoop.executionengine * .mapReduceLayer.plans.MROperPlan) */ @Override public void initialPlanNotification(String scriptId, MROperPlan plan) { try { if (clientIsActive()) { for (P2LClient client : clients) { client.createPlan(plan); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handleInitialPlanNotificationError(e); } } } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * launchStartedNotification(java.lang.String, int) */ @Override public void launchStartedNotification(String scriptId, int numJobsToLaunch) { } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * jobsSubmittedNotification(java.lang.String, int) */ @Override public void jobsSubmittedNotification(String scriptId, int numJobsSubmitted) { } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * jobStartedNotification(java.lang.String, java.lang.String) */ @Override public void jobStartedNotification(String scriptId, String assignedJobId) { try { if (clientIsActive()) { for (P2LClient client : clients) { client.jobStarted(assignedJobId); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handleJobStartedNotificationError(e); } } } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * jobFinishedNotification(java.lang.String, * org.apache.pig.tools.pigstats.JobStats) */ @Override public void jobFinishedNotification(String scriptId, JobStats jobStats) { try { if (clientIsActive()) { for (P2LClient client : clients) { client.jobFinished(jobStats); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handleJobFinishedNotificationError(e); } } } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * jobFailedNotification(java.lang.String, * org.apache.pig.tools.pigstats.JobStats) */ @Override public void jobFailedNotification(String scriptId, JobStats jobStats) { try { if (clientIsActive()) { for (P2LClient client : clients) { client.jobFailed(jobStats); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handleJobFailedNotificationError(e); } } } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * outputCompletedNotification(java.lang.String, * org.apache.pig.tools.pigstats.OutputStats) */ @Override public void outputCompletedNotification(String scriptId, OutputStats outputStats) { } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * progressUpdatedNotification(java.lang.String, int) */ @Override public void progressUpdatedNotification(String scriptId, int progress) { try { if (clientIsActive()) { for (P2LClient client : clients) { client.updateProgress(progress); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handleProgressUpdatedNotificationError(e); } } } /* * (non-Javadoc) * * @see org.apache.pig.tools.pigstats.PigProgressNotificationListener# * launchCompletedNotification(java.lang.String, int) */ @Override public void launchCompletedNotification(String scriptId, int numJobsSucceeded) { try { if (clientIsActive()) { for (P2LClient client : clients) { client.planCompleted(); } } } catch (Exception e) { LOG.error("Caught unexpected exception", e); for (PPNLErrorHandler errHandler : errorHandlers) { errHandler.handleLaunchCompletedNotificationError(e); } } } /** * Initialize the clients from properties in the pig context. */ protected void initClients() { // Make sure client list is empty before initializing. // For example, this prevents initailizing multiple times when // executing multiple runs in a grunt shell session. Properties props = ps.getPigContext().getProperties(); if (clients.isEmpty() && props.containsKey(LIPSTICK_URL_PROP)) { // Initialize the client clients.add(new BasicP2LClient(props.getProperty(LIPSTICK_URL_PROP))); } } }
/******************************************************************************* * Copyright 2011 Google Inc. All Rights Reserved. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package nl.sense_os.commonsense.login.client.login; import java.util.List; import java.util.Map.Entry; import java.util.logging.Logger; import nl.sense_os.commonsense.common.client.communication.SessionManager; import nl.sense_os.commonsense.common.client.component.AlertDialogContent; import nl.sense_os.commonsense.lib.client.communication.CommonSenseClient; import nl.sense_os.commonsense.lib.client.model.httpresponse.LoginResponse; import nl.sense_os.commonsense.login.client.LoginClientFactory; import nl.sense_os.commonsense.login.client.forgotpassword.ForgotPasswordPlace; import com.google.gwt.activity.shared.AbstractActivity; import com.google.gwt.event.shared.EventBus; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.UrlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.DialogBox; /** * Activities are started and stopped by an ActivityManager associated with a container Widget. */ public class LoginActivity extends AbstractActivity implements LoginView.Presenter, AlertDialogContent.Presenter { private static final Logger LOG = Logger.getLogger(LoginActivity.class.getName()); /** * Used to obtain views, eventBus, placeController. Alternatively, could be injected via GIN. */ private LoginClientFactory clientFactory; private LoginView view; private DialogBox alertDialog; public LoginActivity(LoginPlace place, LoginClientFactory clientFactory) { this.clientFactory = clientFactory; } @Override public void dismissAlert() { if (null != alertDialog) { alertDialog.hide(); } } @Override public void forgotPassword() { // TODO put the username in the token so it can be pre-filled in clientFactory.getPlaceController().goTo(new ForgotPasswordPlace("")); } @Override public void googleLogin() { CommonSenseClient.getClient().googleLogin(); } private void goToMainPage() { UrlBuilder builder = new UrlBuilder(); builder.setProtocol(Location.getProtocol()); builder.setHost(Location.getHost()); String path = Location.getPath().contains("login.html") ? Location.getPath().replace( "login.html", "index.html") : Location.getPath() + "index.html"; builder.setPath(path); for (Entry<String, List<String>> entry : Location.getParameterMap().entrySet()) { if ("session_id".equals(entry.getKey())) { // do not copy the session id parameter } else { builder.setParameter(entry.getKey(), entry.getValue().toArray(new String[0])); } } Location.replace(builder.buildString().replace("127.0.0.1%3A", "127.0.0.1:")); } /** * Sends a login request to the CommonSense API. * * @param username * The username to use for log in. * @param password * The password to user for log in. Will be hashed before submission. */ @Override public void login(String username, String password) { // prepare request callback RequestCallback callback = new RequestCallback() { @Override public void onError(Request request, Throwable exception) { LOG.warning("login error: " + exception.getMessage()); onLoginFailure(0, exception); } @Override public void onResponseReceived(Request request, Response response) { onLoginResponse(response); } }; // send request CommonSenseClient.getClient().login(callback, username, password); } private void onAuthenticationFailure() { // enable view view.setBusy(false); // show alert alertDialog = new DialogBox(); alertDialog.setHTML(SafeHtmlUtils.fromSafeConstant("<b>Login failed</b>")); AlertDialogContent content = new AlertDialogContent(); content.setMessage("Login failed! Invalid username or password."); content.setPresenter(this); alertDialog.setWidget(content); alertDialog.center(); content.setFocus(true); } private void onLoginFailure(int code, Throwable error) { // enable view view.setBusy(false); // show alert alertDialog = new DialogBox(); alertDialog.setHTML(SafeHtmlUtils.fromSafeConstant("<b>Login failed</b>")); AlertDialogContent content = new AlertDialogContent(); content.setMessage("Login failed! Error: " + code + " (" + error.getMessage() + ")"); content.setPresenter(this); alertDialog.setWidget(content); alertDialog.center(); } private void onLoginResponse(Response response) { LOG.finest("POST login response received: " + response.getStatusText()); final int statusCode = response.getStatusCode(); if (Response.SC_OK == statusCode) { onLoginSuccess(response.getText()); } else if (Response.SC_FORBIDDEN == statusCode) { onAuthenticationFailure(); } else { LOG.warning("POST login returned incorrect status: " + statusCode); onLoginFailure(statusCode, new Exception("Incorrect response status: " + statusCode)); } } private void onLoginSuccess(String response) { if (response != null) { LOG.fine("LOGIN Success..."); // try to get "session_id" object String sessionId = null; LoginResponse jso = LoginResponse.create(response).cast(); if (null != jso) { sessionId = jso.getSessionId(); } LOG.fine("sessionId is " + sessionId); if (null != sessionId) { SessionManager.setSessionId(sessionId); goToMainPage(); } else { onLoginFailure(0, new Exception("Did not receive session ID")); } } else { LOG.severe("Error parsing login response: response=null"); onLoginFailure(0, new Exception("No response content")); } } @Override public void start(AcceptsOneWidget containerWidget, EventBus eventBus) { LOG.info("Start activity: Login"); view = clientFactory.getLoginView(); view.setPresenter(this); containerWidget.setWidget(view.asWidget()); view.setFocus(true); } }
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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 the following location: * * 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.jasig.cas.web.support; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jasig.cas.authentication.principal.WebApplicationService; import org.jasig.cas.logout.LogoutRequest; import org.springframework.util.Assert; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.execution.RequestContext; /** * Common utilities for the web tier. * * @author Scott Battaglia * @since 3.1 */ public final class WebUtils { /** * Instantiates a new web utils instance. */ private WebUtils() {} /** Request attribute that contains message key describing details of authorization failure.*/ public static final String CAS_ACCESS_DENIED_REASON = "CAS_ACCESS_DENIED_REASON"; /** * Gets the http servlet request from the context. * * @param context the context * @return the http servlet request */ public static HttpServletRequest getHttpServletRequest( final RequestContext context) { Assert.isInstanceOf(ServletExternalContext.class, context .getExternalContext(), "Cannot obtain HttpServletRequest from event of type: " + context.getExternalContext().getClass().getName()); return (HttpServletRequest) context.getExternalContext().getNativeRequest(); } /** * Gets the http servlet response. * * @param context the context * @return the http servlet response */ public static HttpServletResponse getHttpServletResponse( final RequestContext context) { Assert.isInstanceOf(ServletExternalContext.class, context .getExternalContext(), "Cannot obtain HttpServletResponse from event of type: " + context.getExternalContext().getClass().getName()); return (HttpServletResponse) context.getExternalContext() .getNativeResponse(); } /** * Gets the service from the request based on given extractors. * * @param argumentExtractors the argument extractors * @param request the request * @return the service, or null. */ public static WebApplicationService getService( final List<ArgumentExtractor> argumentExtractors, final HttpServletRequest request) { for (final ArgumentExtractor argumentExtractor : argumentExtractors) { final WebApplicationService service = argumentExtractor .extractService(request); if (service != null) { return service; } } return null; } /** * Gets the service. * * @param argumentExtractors the argument extractors * @param context the context * @return the service */ public static WebApplicationService getService( final List<ArgumentExtractor> argumentExtractors, final RequestContext context) { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); return getService(argumentExtractors, request); } /** * Gets the service from the flow scope. * * @param context the context * @return the service */ public static WebApplicationService getService( final RequestContext context) { return (WebApplicationService) context.getFlowScope().get("service"); } /** * Put ticket granting ticket in request scope. * * @param context the context * @param ticketValue the ticket value */ public static void putTicketGrantingTicketInRequestScope( final RequestContext context, final String ticketValue) { context.getRequestScope().put("ticketGrantingTicketId", ticketValue); } /** * Put ticket granting ticket in flow scope. * * @param context the context * @param ticketValue the ticket value */ public static void putTicketGrantingTicketInFlowScope( final RequestContext context, final String ticketValue) { context.getFlowScope().put("ticketGrantingTicketId", ticketValue); } /** * Gets the ticket granting ticket id from the request and flow scopes. * * @param context the context * @return the ticket granting ticket id */ public static String getTicketGrantingTicketId( final RequestContext context) { final String tgtFromRequest = (String) context.getRequestScope().get("ticketGrantingTicketId"); final String tgtFromFlow = (String) context.getFlowScope().get("ticketGrantingTicketId"); return tgtFromRequest != null ? tgtFromRequest : tgtFromFlow; } /** * Put service ticket in request scope. * * @param context the context * @param ticketValue the ticket value */ public static void putServiceTicketInRequestScope( final RequestContext context, final String ticketValue) { context.getRequestScope().put("serviceTicketId", ticketValue); } /** * Gets the service ticket from request scope. * * @param context the context * @return the service ticket from request scope */ public static String getServiceTicketFromRequestScope( final RequestContext context) { return context.getRequestScope().getString("serviceTicketId"); } /** * Put login ticket into flow scope. * * @param context the context * @param ticket the ticket */ public static void putLoginTicket(final RequestContext context, final String ticket) { context.getFlowScope().put("loginTicket", ticket); } /** * Gets the login ticket from flow scope. * * @param context the context * @return the login ticket from flow scope */ public static String getLoginTicketFromFlowScope(final RequestContext context) { // Getting the saved LT destroys it in support of one-time-use // See section 3.5.1 of http://www.jasig.org/cas/protocol final String lt = (String) context.getFlowScope().remove("loginTicket"); return lt != null ? lt : ""; } /** * Gets the login ticket from request. * * @param context the context * @return the login ticket from request */ public static String getLoginTicketFromRequest(final RequestContext context) { return context.getRequestParameters().get("lt"); } /** * Put logout requests into flow scope. * * @param context the context * @param requests the requests */ public static void putLogoutRequests(final RequestContext context, final List<LogoutRequest> requests) { context.getFlowScope().put("logoutRequests", requests); } /** * Gets the logout requests from flow scope. * * @param context the context * @return the logout requests */ public static List<LogoutRequest> getLogoutRequests(final RequestContext context) { return (List<LogoutRequest>) context.getFlowScope().get("logoutRequests"); } }
package ro.sci.gms.dao.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Repository; import ro.sci.gms.domain.Blood; import ro.sci.gms.domain.Doctor; import ro.sci.gms.domain.Gender; import ro.sci.gms.domain.Patient; import ro.sci.gms.domain.Role; import ro.sci.gms.temp.Li; /** * Pure JDBC implementation for {@link EmployeeDAO}. * * @author sebi * */ @Repository @DependsOn("JDBCUserDAO") @Qualifier("patientDAO") public class JDBCPatientDAO extends JDBCUserDAO { private static final Logger LOGGER = LoggerFactory.getLogger(JDBCPatientDAO.class); private String host; private String port; private String dbName; private String userName; private String pass; /* * This seems to be required. Doesn't work without it. */ public JDBCPatientDAO() { } public JDBCPatientDAO(String host, String port, String dbName, String userName, String pass) { this.host = host; this.userName = userName; this.pass = pass; this.port = port; this.dbName = dbName; } protected Connection newConnection() { try { Class.forName("org.postgresql.Driver").newInstance(); String url = new StringBuilder()// .append("jdbc:")// .append("postgresql")// .append("://")// .append(host)// .append(":")// .append(port)// .append("/")// .append(dbName)// .append("?user=")// .append(userName)// .append("&password=")// .append(pass).toString(); Connection result = DriverManager.getConnection(url); result.setAutoCommit(false); return result; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("Error getting DB connection. (91)", ex); } } public Patient savePatient(Patient patient) throws SQLException { Li.st("Saving Patient (user data) to DB."); Connection connection = newConnection(); connection.setAutoCommit(false); // First write User data from Patient .to DB update(connection, patient); // Then write Patient specific data .to DB Li.st("Saving Patient (patient data) to DB."); try { PreparedStatement ps = null; ps = connection.prepareStatement( "insert into patient (user_id, date_of_birth, gender, medical_background, blood_type, doctor_id) " + "values (?, ?, ?, ?, ?, ?) returning user_id"); ps.setLong(1, patient.getId()); ps.setTimestamp(2, new Timestamp(patient.getDateOfBirth().getTime())); ps.setString(3, patient.getGender().name()); ps.setString(4, patient.getMedicalBackground()); ps.setString(5, patient.getBloodType().name()); ps.setLong(6, patient.getDoctor().getId()); ps.executeQuery(); // View data on console patient.see(); } catch (Exception ex) { // throw new RuntimeException("Error building prepared statement. // (91)", ex); ex.printStackTrace(); } // Finished writing specific Patient data to DB. Ready to commit // transaction. finally { try { connection.commit(); connection.close(); } catch (Exception ex) { throw new RuntimeException("Error commiting or closing while writing user to DB. (91)", ex); } } return patient; } @Override public Patient findById(Long id) { List<Patient> result = new LinkedList<>(); try (Connection connection = newConnection(); ResultSet rs = connection.createStatement() .executeQuery("select * from users, patient where id=user_id and id= " + id)) { while (rs.next()) { result.add(extractPatient(rs)); } connection.commit(); } catch (SQLException ex) { throw new RuntimeException("(091) Error getting Patient from DB.", ex); } if (result.size() > 1) { throw new IllegalStateException("(091) Multiple Patients/Users for id: " + id); } return result.isEmpty() ? null : result.get(0); } // ? is it ok to pass the user as param or would it be better to only pass // the id public boolean delete(Patient patient) { boolean result = false; try (Connection connection = newConnection()) { Statement statement = connection.createStatement(); result = statement.execute("delete from users where id = " + patient.getId()); result = statement.execute("delete from patient where user_id = " + patient.getId()); connection.commit(); } catch (SQLException ex) { throw new RuntimeException("(091) Error deleting user or patient data.", ex); } return result; } // Still figuring out if needed or not public Collection<Patient> getAllPatients() { return null; } private Patient extractPatient(ResultSet rs) throws SQLException { Patient patient = new Patient(); patient.setUsername(rs.getString("user_name")); patient.setFirstName(rs.getString("first_name")); patient.setLastName(rs.getString("last_name")); patient.setPassword(rs.getString("password")); patient.setId(rs.getLong("id")); patient.setAddress(rs.getString("address")); patient.setPhone(rs.getString("phone")); patient.setEmail(rs.getString("email")); patient.setRole(Role.valueOf(rs.getString("role"))); patient.setDateOfBirth(new Date(rs.getTimestamp("date_of_birth").getTime())); patient.setGender(Gender.valueOf(rs.getString("gender"))); patient.setMedicalBackground(rs.getString("medical_background")); patient.setBloodType(Blood.valueOf(rs.getString("blood_type"))); // After JDBCDoctorDAO is operational, this line needs to be updated. Long retrievedDoctorId = rs.getLong("id"); Doctor retrievedDoctor = new Doctor(); // will be replaced by // doctorDAO.getDoctor(retrievedDoctorId); retrievedDoctor.setId(retrievedDoctorId); patient.setDoctor(retrievedDoctor); return patient; } }
/** * 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.webapp.log; import static org.apache.hadoop.yarn.webapp.YarnWebParams.APP_OWNER; import static org.apache.hadoop.yarn.webapp.YarnWebParams.CONTAINER_ID; import static org.apache.hadoop.yarn.webapp.YarnWebParams.CONTAINER_LOG_TYPE; import static org.apache.hadoop.yarn.webapp.YarnWebParams.ENTITY_STRING; import static org.apache.hadoop.yarn.webapp.YarnWebParams.NM_NODENAME; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat; import org.apache.hadoop.yarn.logaggregation.LogAggregationUtils; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Times; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.PRE; import org.apache.hadoop.yarn.webapp.view.HtmlBlock; import com.google.inject.Inject; @InterfaceAudience.LimitedPrivate({"YARN", "MapReduce"}) public class AggregatedLogsBlock extends HtmlBlock { private final Configuration conf; @Inject AggregatedLogsBlock(Configuration conf) { this.conf = conf; } @Override protected void render(Block html) { ContainerId containerId = verifyAndGetContainerId(html); NodeId nodeId = verifyAndGetNodeId(html); String appOwner = verifyAndGetAppOwner(html); LogLimits logLimits = verifyAndGetLogLimits(html); if (containerId == null || nodeId == null || appOwner == null || appOwner.isEmpty() || logLimits == null) { return; } ApplicationId applicationId = containerId.getApplicationAttemptId() .getApplicationId(); String logEntity = $(ENTITY_STRING); if (logEntity == null || logEntity.isEmpty()) { logEntity = containerId.toString(); } if (!conf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, YarnConfiguration.DEFAULT_LOG_AGGREGATION_ENABLED)) { html.h1() ._("Aggregation is not enabled. Try the nodemanager at " + nodeId) ._(); return; } Path remoteRootLogDir = new Path(conf.get( YarnConfiguration.NM_REMOTE_APP_LOG_DIR, YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR)); Path remoteAppDir = LogAggregationUtils.getRemoteAppLogDir( remoteRootLogDir, applicationId, appOwner, LogAggregationUtils.getRemoteNodeLogDirSuffix(conf)); RemoteIterator<FileStatus> nodeFiles; try { Path qualifiedLogDir = FileContext.getFileContext(conf).makeQualified( remoteAppDir); nodeFiles = FileContext.getFileContext(qualifiedLogDir.toUri(), conf) .listStatus(remoteAppDir); } catch (FileNotFoundException fnf) { html.h1() ._("Logs not available for " + logEntity + ". Aggregation may not be complete, " + "Check back later or try the nodemanager at " + nodeId)._(); return; } catch (Exception ex) { html.h1() ._("Error getting logs at " + nodeId)._(); return; } boolean foundLog = false; String desiredLogType = $(CONTAINER_LOG_TYPE); try { while (nodeFiles.hasNext()) { AggregatedLogFormat.LogReader reader = null; try { FileStatus thisNodeFile = nodeFiles.next(); if (!thisNodeFile.getPath().getName() .contains(LogAggregationUtils.getNodeString(nodeId)) || thisNodeFile.getPath().getName() .endsWith(LogAggregationUtils.TMP_FILE_SUFFIX)) { continue; } long logUploadedTime = thisNodeFile.getModificationTime(); reader = new AggregatedLogFormat.LogReader(conf, thisNodeFile.getPath()); String owner = null; Map<ApplicationAccessType, String> appAcls = null; try { owner = reader.getApplicationOwner(); appAcls = reader.getApplicationAcls(); } catch (IOException e) { LOG.error("Error getting logs for " + logEntity, e); continue; } ApplicationACLsManager aclsManager = new ApplicationACLsManager(conf); aclsManager.addApplication(applicationId, appAcls); String remoteUser = request().getRemoteUser(); UserGroupInformation callerUGI = null; if (remoteUser != null) { callerUGI = UserGroupInformation.createRemoteUser(remoteUser); } if (callerUGI != null && !aclsManager.checkAccess(callerUGI, ApplicationAccessType.VIEW_APP, owner, applicationId)) { html.h1() ._("User [" + remoteUser + "] is not authorized to view the logs for " + logEntity + " in log file [" + thisNodeFile.getPath().getName() + "]")._(); LOG.error("User [" + remoteUser + "] is not authorized to view the logs for " + logEntity); continue; } AggregatedLogFormat.ContainerLogsReader logReader = reader .getContainerLogsReader(containerId); if (logReader == null) { continue; } foundLog = readContainerLogs(html, logReader, logLimits, desiredLogType, logUploadedTime); } catch (IOException ex) { LOG.error("Error getting logs for " + logEntity, ex); continue; } finally { if (reader != null) reader.close(); } } if (!foundLog) { if (desiredLogType.isEmpty()) { html.h1("No logs available for container " + containerId.toString()); } else { html.h1("Unable to locate '" + desiredLogType + "' log for container " + containerId.toString()); } } } catch (IOException e) { html.h1()._("Error getting logs for " + logEntity)._(); LOG.error("Error getting logs for " + logEntity, e); } } private boolean readContainerLogs(Block html, AggregatedLogFormat.ContainerLogsReader logReader, LogLimits logLimits, String desiredLogType, long logUpLoadTime) throws IOException { int bufferSize = 65536; char[] cbuf = new char[bufferSize]; boolean foundLog = false; String logType = logReader.nextLog(); while (logType != null) { if (desiredLogType == null || desiredLogType.isEmpty() || desiredLogType.equals(logType)) { long logLength = logReader.getCurrentLogLength(); if (foundLog) { html.pre()._("\n\n")._(); } html.p()._("Log Type: " + logType)._(); html.p()._("Log Upload Time: " + Times.format(logUpLoadTime))._(); html.p()._("Log Length: " + Long.toString(logLength))._(); long start = logLimits.start < 0 ? logLength + logLimits.start : logLimits.start; start = start < 0 ? 0 : start; start = start > logLength ? logLength : start; long end = logLimits.end < 0 ? logLength + logLimits.end : logLimits.end; end = end < 0 ? 0 : end; end = end > logLength ? logLength : end; end = end < start ? start : end; long toRead = end - start; if (toRead < logLength) { html.p()._("Showing " + toRead + " bytes of " + logLength + " total. Click ") .a(url("logs", $(NM_NODENAME), $(CONTAINER_ID), $(ENTITY_STRING), $(APP_OWNER), logType, "?start=0"), "here"). _(" for the full log.")._(); } long totalSkipped = 0; while (totalSkipped < start) { long ret = logReader.skip(start - totalSkipped); if (ret == 0) { //Read one byte int nextByte = logReader.read(); // Check if we have reached EOF if (nextByte == -1) { throw new IOException( "Premature EOF from container log"); } ret = 1; } totalSkipped += ret; } int len = 0; int currentToRead = toRead > bufferSize ? bufferSize : (int) toRead; PRE<Hamlet> pre = html.pre(); while (toRead > 0 && (len = logReader.read(cbuf, 0, currentToRead)) > 0) { pre._(new String(cbuf, 0, len)); toRead = toRead - len; currentToRead = toRead > bufferSize ? bufferSize : (int) toRead; } pre._(); foundLog = true; } logType = logReader.nextLog(); } return foundLog; } private ContainerId verifyAndGetContainerId(Block html) { String containerIdStr = $(CONTAINER_ID); if (containerIdStr == null || containerIdStr.isEmpty()) { html.h1()._("Cannot get container logs without a ContainerId")._(); return null; } ContainerId containerId = null; try { containerId = ConverterUtils.toContainerId(containerIdStr); } catch (IllegalArgumentException e) { html.h1() ._("Cannot get container logs for invalid containerId: " + containerIdStr)._(); return null; } return containerId; } private NodeId verifyAndGetNodeId(Block html) { String nodeIdStr = $(NM_NODENAME); if (nodeIdStr == null || nodeIdStr.isEmpty()) { html.h1()._("Cannot get container logs without a NodeId")._(); return null; } NodeId nodeId = null; try { nodeId = ConverterUtils.toNodeId(nodeIdStr); } catch (IllegalArgumentException e) { html.h1()._("Cannot get container logs. Invalid nodeId: " + nodeIdStr) ._(); return null; } return nodeId; } private String verifyAndGetAppOwner(Block html) { String appOwner = $(APP_OWNER); if (appOwner == null || appOwner.isEmpty()) { html.h1()._("Cannot get container logs without an app owner")._(); } return appOwner; } private static class LogLimits { long start; long end; } private LogLimits verifyAndGetLogLimits(Block html) { long start = -4096; long end = Long.MAX_VALUE; boolean isValid = true; String startStr = $("start"); if (startStr != null && !startStr.isEmpty()) { try { start = Long.parseLong(startStr); } catch (NumberFormatException e) { isValid = false; html.h1()._("Invalid log start value: " + startStr)._(); } } String endStr = $("end"); if (endStr != null && !endStr.isEmpty()) { try { end = Long.parseLong(endStr); } catch (NumberFormatException e) { isValid = false; html.h1()._("Invalid log end value: " + endStr)._(); } } if (!isValid) { return null; } LogLimits limits = new LogLimits(); limits.start = start; limits.end = end; return limits; } }
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.config; import java.util.ArrayList; import java.util.List; import com.thoughtworks.go.config.exceptions.GoConfigInvalidException; import com.thoughtworks.go.config.remote.PartialConfig; import com.thoughtworks.go.config.validation.GoConfigValidity; import com.thoughtworks.go.domain.ConfigErrors; import com.thoughtworks.go.listener.ConfigChangedListener; import com.thoughtworks.go.serverhealth.HealthStateType; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.serverhealth.ServerHealthState; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static com.thoughtworks.go.util.ExceptionUtils.bomb; /** * @understands when to reload the config file or other config source */ @Component public class MergedGoConfig implements CachedGoConfig, ConfigChangedListener, PartialConfigChangedListener { private static final Logger LOGGER = Logger.getLogger(MergedGoConfig.class); public static final String INVALID_CRUISE_CONFIG_MERGE = "Invalid Merged Configuration"; private CachedFileGoConfig fileService; private GoPartialConfig partialConfig; private final ServerHealthService serverHealthService; private List<ConfigChangedListener> listeners = new ArrayList<ConfigChangedListener>(); // this is merged config when possible private volatile CruiseConfig currentConfig; private volatile CruiseConfig currentConfigForEdit; private volatile GoConfigHolder configHolder; private volatile Exception lastException; @Autowired public MergedGoConfig(ServerHealthService serverHealthService, CachedFileGoConfig fileService, GoPartialConfig partialConfig) { this.serverHealthService = serverHealthService; this.fileService = fileService; this.partialConfig = partialConfig; this.fileService.registerListener(this); this.partialConfig.registerListener(this); } @Override public void onConfigChange(CruiseConfig newCruiseConfig) { this.tryAssembleMergedConfig(this.fileService.loadConfigHolder(),this.partialConfig.lastPartials()); } @Override public void onPartialConfigChanged(List<PartialConfig> partials) { this.tryAssembleMergedConfig(this.fileService.loadConfigHolder(),partials); } /** * attempts to create a new merged cruise config */ public void tryAssembleMergedConfig(GoConfigHolder cruiseConfigHolder,List<PartialConfig> partials) { try { GoConfigHolder newConfigHolder; if (partials.size() == 0) { // no partial configurations // then just use basic configuration from xml newConfigHolder = cruiseConfigHolder; } else { // create merge (uses merge strategy internally) BasicCruiseConfig merge = new BasicCruiseConfig((BasicCruiseConfig) cruiseConfigHolder.config, partials); // validate List<ConfigErrors> allErrors = validate(merge); if (!allErrors.isEmpty()) { throw new GoConfigInvalidException(merge, allErrors); } CruiseConfig basicForEdit = this.fileService.loadForEditing(); CruiseConfig forEdit = new BasicCruiseConfig((BasicCruiseConfig) basicForEdit, partials); //TODO change strategy into merge-edit? - done in UI branch newConfigHolder = new GoConfigHolder(merge, forEdit); } // save to cache and fire event this.saveValidConfigToCache(newConfigHolder); } catch (Exception e) { LOGGER.error(String.format("Failed validation of merged configuration: %s", e)); saveConfigError(e); } } private synchronized void saveConfigError(Exception e) { this.lastException = e; ServerHealthState state = ServerHealthState.error(INVALID_CRUISE_CONFIG_MERGE, GoConfigValidity.invalid(e).errorMessage(), invalidConfigType()); serverHealthService.update(state); } public static List<ConfigErrors> validate(CruiseConfig config) { List<ConfigErrors> validationErrors = new ArrayList<ConfigErrors>(); validationErrors.addAll(config.validateAfterPreprocess()); return validationErrors; } // used in tests public void forceReload() { this.fileService.onTimer(); } public CruiseConfig loadForEditing() { // merged cannot be (entirely) edited but we return it so that all pipelines are rendered in admin->pipelines return currentConfigForEdit; } public CruiseConfig currentConfig() { //returns merged cruise config if appropriate if (currentConfig == null) { currentConfig = new BasicCruiseConfig(); } return currentConfig; } public void loadConfigIfNull() { this.fileService.loadConfigIfNull(); } // no actions on timer now. We only react to events in CachedFileGoConfig and in GoPartialConfig public synchronized ConfigSaveState writeWithLock(UpdateConfigCommand updateConfigCommand) { return this.fileService.writeWithLock(updateConfigCommand,new GoConfigHolder(this.currentConfig,this.currentConfigForEdit)); } private synchronized void saveValidConfigToCache(GoConfigHolder configHolder) { //this operation still exists, it only works differently // we validate entire merged cruise config // then we keep new merged cruise config in memory // then we take out main part of it and keep it for edits LOGGER.debug("[Config Save] Saving (merged) config to the cache"); this.configHolder = configHolder; // this is merged or basic config. this.currentConfig = this.configHolder.config; this.currentConfigForEdit = this.configHolder.configForEdit; serverHealthService.update(ServerHealthState.success(invalidConfigType())); LOGGER.info("About to notify (merged) config listeners"); // but we do notify with merged config notifyListeners(currentConfig); LOGGER.info("Finished notifying all listeners"); } private static HealthStateType invalidConfigType() { return HealthStateType.invalidConfigMerge(); } public String getFileLocation() { return this.fileService.getFileLocation(); } public void save(String configFileContent, boolean shouldMigrate) throws Exception { // this will save new xml, and notify me (as listener) so that I will attempt to update my merged config as well. this.fileService.save(configFileContent,shouldMigrate); } public GoConfigValidity checkConfigFileValid() { return this.fileService.checkConfigFileValid(); } public synchronized void registerListener(ConfigChangedListener listener) { this.listeners.add(listener); if (currentConfig != null) { listener.onConfigChange(currentConfig); } } private synchronized void notifyListeners(CruiseConfig newCruiseConfig) { for (ConfigChangedListener listener : listeners) { try { listener.onConfigChange(newCruiseConfig); } catch (Exception e) { LOGGER.error("failed to fire config changed event for listener: " + listener, e); } } } /** * @deprecated Used only in tests */ public synchronized void clearListeners() { listeners.clear(); } /** * @deprecated Used only in tests */ public void reloadListeners() { notifyListeners(currentConfig()); } public GoConfigHolder loadConfigHolder() { return configHolder; } @Override public boolean hasListener(ConfigChangedListener listener) { return this.listeners.contains(listener); } }
package com.marshalchen.common.demoofui; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.marshalchen.common.demoofui.cooldraganddrop.CoolDragAndDropActivity; import com.marshalchen.common.demoofui.materialAnimations.MaterialAnimationActivity; import com.marshalchen.common.demoofui.materialdesigndemo.MaterialDesignActivity; import com.marshalchen.common.demoofui.materialmenu.MaterialMenuToolbarActivity; import com.marshalchen.common.demoofui.sampleModules.FloatingActionButtonDemo; import com.marshalchen.common.demoofui.sampleModules.GestureTouchActivity; import com.marshalchen.common.demoofui.sampleModules.KenBurnsViewActivity; import com.marshalchen.common.demoofui.sampleModules.MaterialListViewActivity; import com.marshalchen.common.demoofui.sampleModules.MotionSampleActivity; import com.marshalchen.common.demoofui.sampleModules.NumberProgressBarActivity; import com.marshalchen.common.demoofui.sampleModules.RippleEffectActivity; import com.marshalchen.common.demoofui.sampleModules.SearchDrawableActivity; import com.marshalchen.common.demoofui.sampleModules.SignaturePadActivity; import com.marshalchen.common.demoofui.ultimaterecyclerview.UltimateRecyclerViewActivity; import com.marshalchen.common.ui.Typefaces; import com.marshalchen.common.uimodule.enhanceListView.EnhancedListView; import com.marshalchen.common.uimodule.titanic.Titanic; import com.marshalchen.common.uimodule.titanic.TitanicTextView; import com.marshalchen.common.uimodule.viewpagerindicator.CirclePageIndicator; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.ButterKnife; import butterknife.InjectView; public class LandingFragment extends Fragment { View mainView; @InjectView(R.id.landingEnhanceListView) EnhancedListView landingEnhanceListView; List<Map<String, ?>> enhanceList; EnhancedListAdapter enhancedListAdapter; @InjectView(R.id.landingMallViewpager) ViewPager landingMallViewpager; CirclePageIndicator landingMallViewPagerIndicator; private List<View> viewpagerList = new ArrayList<View>(); Titanic titanic; @InjectView(R.id.titanicTextView) TitanicTextView titanicTextView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView = inflater .inflate(R.layout.landing_fragment, container, false); ButterKnife.inject(this, mainView); initTitanicView(); initEnhanceList(); initViewPager(); // CryptoUtils.testCrypto(getActivity()); return mainView; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.reset(this); } private void initTitanicView() { titanic = new Titanic(); titanic.start(titanicTextView); titanicTextView.setTypeface(Typefaces.get(getActivity(), "Satisfy-Regular.ttf")); // HandlerUtils.sendMessageHandlerDelay(titanicHandler, 0, 3000); } Handler titanicHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); titanic.cancel(); landingEnhanceListView.setVisibility(View.VISIBLE); } }; private void initEnhanceList() { enhanceList = getData("com.marshalchen.common.demoofui.sampleModules"); enhancedListAdapter = new EnhancedListAdapter(enhanceList); landingEnhanceListView.setAdapter(enhancedListAdapter); landingEnhanceListView .setDismissCallback(new EnhancedListView.OnDismissCallback() { @Override public EnhancedListView.Undoable onDismiss( EnhancedListView listView, int position) { enhancedListAdapter.remove(position); return null; } }); landingEnhanceListView.setSwipingLayout(R.id.swiping_layout); landingEnhanceListView.setUndoStyle(null); landingEnhanceListView.enableSwipeToDismiss(); landingEnhanceListView .setSwipeDirection(EnhancedListView.SwipeDirection.START); landingEnhanceListView .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = (Intent) enhanceList.get(position).get("intent"); startActivity(intent); // TODO add OnItemClick event } }); } protected List<Map<String, ?>> getData(String prefix) { List<Map<String, ?>> myData = new ArrayList<Map<String, ?>>(); Intent intent = new Intent("com.marshalchen.common.demoofui", null); PackageManager pm = getActivity().getPackageManager(); List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); if (null == list) return myData; int len = list.size(); for (int i = 0; i < len; i++) { ResolveInfo info = list.get(i); String activityName = info.activityInfo.name; String[] labelPath = activityName.split("\\."); String nextLabel = labelPath[labelPath.length - 1]; addItem(myData, nextLabel, activityIntent( info.activityInfo.applicationInfo.packageName, info.activityInfo.name)); } Collections.sort(myData, sDisplayNameComparator); addItemToTop(myData, "SignaturePadActivity", new Intent(getActivity(), SignaturePadActivity.class)); addItemToTop(myData, "SmoothProgressBarActivity", new Intent(getActivity(), SmoothProgressBarActivity.class)); addItemToTop(myData, "RippleEffectActivity", new Intent(getActivity(), RippleEffectActivity.class)); addItemToTop(myData, "NumberProgressBarActivity", new Intent(getActivity(), NumberProgressBarActivity.class)); addItemToTop(myData, "MotionSampleActivity", new Intent(getActivity(), MotionSampleActivity.class)); addItemToTop(myData, "MaterialMenuToolbarActivity", new Intent(getActivity(), MaterialMenuToolbarActivity.class)); // addItemToTop(myData, // "MaterialListViewActivity", // new Intent(getActivity(), MaterialListViewActivity.class)); addItemToTop(myData, "KenBurnsViewActivity", new Intent(getActivity(), KenBurnsViewActivity.class)); addItemToTop(myData, "GestureTouchActivity", new Intent(getActivity(), GestureTouchActivity.class)); addItemToTop(myData, "FloatingActionButtonDemo", new Intent(getActivity(), FloatingActionButtonDemo.class)); addItemToTop(myData, "CoolDragAndDropActivity", new Intent(getActivity(), CoolDragAndDropActivity.class)); addItemToTop(myData, "MaterialDesignActivity", new Intent(getActivity(), MaterialDesignActivity.class)); addItemToTop(myData, "MaterialAnimationActivity", new Intent(getActivity(), MaterialAnimationActivity.class)); addItemToTop(myData, "SearchDrawableActivity", new Intent(getActivity(), SearchDrawableActivity.class)); addItemToTop(myData, "UltimateRecyclerViewActivity", new Intent(getActivity(), UltimateRecyclerViewActivity.class)); return myData; } private final static Comparator<Map<String, ?>> sDisplayNameComparator = new Comparator<Map<String, ?>>() { private final Collator collator = Collator.getInstance(); public int compare(Map<String, ?> map1, Map<String, ?> map2) { return collator.compare(map1.get("title"), map2.get("title")); } }; protected Intent activityIntent(String pkg, String componentName) { Intent result = new Intent(); result.setClassName(pkg, componentName); return result; } protected void addItem(List<Map<String, ?>> data, String name, Intent intent) { Map<String, Object> temp = new HashMap<String, Object>(); temp.put("title", name); temp.put("intent", intent); data.add(temp); } protected void addItemToTop(List<Map<String, ?>> data, String name, Intent intent) { Map<String, Object> temp = new HashMap<String, Object>(); temp.put("title", name); temp.put("intent", intent); data.add(0, temp); } private void initViewPager() { addLandingViewPager(); landingMallViewpager.setAdapter(new CustomViewPagerAdapter( viewpagerList)); landingMallViewpager .setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i2) { } @Override public void onPageSelected(int i) { } @Override public void onPageScrollStateChanged(int i) { // setCurrentDot(i); } }); landingMallViewPagerIndicator = (CirclePageIndicator) mainView .findViewById(R.id.landingMallViewPagerIndicator); landingMallViewPagerIndicator.setViewPager(landingMallViewpager); // final float density = getResources().getDisplayMetrics().density; // landingMallViewPagerIndicator.setBackgroundColor(0xffffff); // landingMallViewPagerIndicator.setRadius(5 * density); // landingMallViewPagerIndicator.setPageColor(getResources().getColor(R.color.black)); // landingMallViewPagerIndicator.setFillColor(getResources().getColor(R.color.white)); // landingMallViewPagerIndicator.setStrokeColor(getResources().getColor(R.color.black)); // landingMallViewPagerIndicator.setStrokeWidth(1 * 1.0f); } private class EnhancedListAdapter extends BaseAdapter { // private List<String> mItems = new ArrayList<String>(); private List<Map<String, ?>> mLists = new ArrayList<>(); // private EnhancedListAdapter(List<String> mItems) { // this.mItems = mItems; // } private EnhancedListAdapter(List<Map<String, ?>> mLists) { this.mLists = mLists; } void resetItems() { mLists.clear(); } public void remove(int position) { mLists.remove(position); notifyDataSetChanged(); } /** * How many items are in the data set represented by this Adapter. * * @return Count of items. */ @Override public int getCount() { return mLists.size(); } /** * Get the data item associated with the specified position in the data * set. * * @param position Position of the item whose data we want within the * adapter's data set. * @return The data at the specified position. */ @Override public Object getItem(int position) { return mLists.get(position); } /** * Get the row id associated with the specified position in the list. * * @param position The position of the item within the adapter's data set * whose row id we want. * @return The id of the item at the specified position. */ @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate( R.layout.list_item_enhance, parent, false); // Clicking the delete icon, will read the position of the item // stored in // the tag and delete it from the list. So we don't need to // generate a new // onClickListener every time the content of this view changes. final View origView = convertView; convertView.findViewById(R.id.action_delete) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // listViewHistory.delete(((ViewHolder) // origView.getTag()).position); } }); holder = new ViewHolder(); assert convertView != null; holder.mTextView = (TextView) convertView .findViewById(R.id.reacolhistextview); // holder.reacolReaLyout = (RelativeLayout) // convertView.findViewById(R.id.reacolReaLyout); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mTextView.setText(mLists.get(position).get("title") .toString()); return convertView; } private class ViewHolder { TextView mTextView; } } private void addLandingViewPager() { if (viewpagerList == null) viewpagerList = new ArrayList<View>(); else viewpagerList.clear(); for (int i = 0; i < 3; i++) { View viewPagerItem = getActivity().getLayoutInflater().inflate( R.layout.landing_viewpager_item, null, false); ViewPagerViewHolder viewHolder = new ViewPagerViewHolder( viewPagerItem); viewHolder.landViewPagerImage.setImageResource(R.drawable.test); // viewHolder.landViewPagerInfo1.setText("hh"+i); // viewPagerItem.setTag(viewHolder); viewpagerList.add(viewPagerItem); } } static class ViewPagerViewHolder { @InjectView(R.id.landViewPagerImage) ImageView landViewPagerImage; @InjectView(R.id.landViewPagerImage1) ImageView landViewPagerImage1; @InjectView(R.id.landViewPagerName) TextView landViewPagerName; @InjectView(R.id.landViewPagerName1) TextView landViewPagerName1; @InjectView(R.id.landViewPagerInfo) TextView landViewPagerInfo; @InjectView(R.id.landViewPagerInfo1) TextView landViewPagerInfo1; public ViewPagerViewHolder(View view) { ButterKnife.inject(this, view); } } class CustomViewPagerAdapter extends PagerAdapter { List<View> viewpagerList; public CustomViewPagerAdapter(List<View> viewpagerList) { this.viewpagerList = viewpagerList; } @Override public int getCount() { return viewpagerList.size(); } @Override public boolean isViewFromObject(View view, Object o) { return view == (o); } @Override public void destroyItem(ViewGroup container, int position, Object object) { // super.destroyItem(container, position, object); if (viewpagerList != null && viewpagerList.size() > position && viewpagerList.get(position) != null) container.removeView(viewpagerList.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewpagerList.get(position), 0); viewpagerList.get(position).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getActivity(), MaterialActivity.class); startActivity(intent); } }); // return super.instantiateItem(container, position); return viewpagerList.get(position); } @Override public void startUpdate(ViewGroup container) { super.startUpdate(container); } @Override public void restoreState(Parcelable state, ClassLoader loader) { super.restoreState(state, loader); } @Override public Parcelable saveState() { return super.saveState(); } } }
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kim.api.role; import org.kuali.rice.core.api.criteria.QueryByCriteria; import org.kuali.rice.core.api.delegation.DelegationType; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.core.api.exception.RiceIllegalStateException; import org.kuali.rice.core.api.util.jaxb.MapStringStringAdapter; import org.kuali.rice.kim.api.KimApiConstants; import org.kuali.rice.kim.api.common.delegate.DelegateMember; import org.kuali.rice.kim.api.common.delegate.DelegateType; import org.kuali.rice.kim.api.permission.Permission; import org.kuali.rice.kim.api.responsibility.Responsibility; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * * This service provides operations for querying role and role qualification * data. * * <p>A role is where permissions and responsibilities are granted. Roles have * a membership consisting of principals, groups or even other roles. By * being assigned as members of a role, the associated principals will be * granted all permissions and responsibilities that have been granted to the * role. * * <p>Each membership assignment on the role can have a qualification which * defines extra information about that particular member of the role. For * example, one may have the role of "Dean" but that can be further qualified * by the school they are the dean of, such as "Dean of Computer Science". * Authorization checks that are then done in the permission service can pass * qualifiers as part of the operation if they want to restrict the subset of * the role against which the check is made. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ @WebService(name = "roleService", targetNamespace = KimApiConstants.Namespaces.KIM_NAMESPACE_2_0 ) @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public interface RoleService { /** * This will create a {@link org.kuali.rice.kim.api.role.Role} exactly like the role passed in. * * @param role the role to create * @return the newly created object. will never be null. * @throws RiceIllegalArgumentException if the role passed in is null * @throws RiceIllegalStateException if the role is already existing in the system */ @WebMethod(operationName="createRole") @WebResult(name = "role") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, Role.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME}, allEntries = true) Role createRole(@WebParam(name = "role") Role role) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * This will update a {@link Role}. * * @param role the role to update * @throws RiceIllegalArgumentException if the role is null * @throws RiceIllegalStateException if the role does not exist in the system */ @WebMethod(operationName="updateRole") @WebResult(name = "role") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, Role.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME}, allEntries = true) Role updateRole(@WebParam(name = "role") Role role) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Get the KIM Role object with the given ID. * * @param id the id of the role. * @return the role with the given id or null if role doesn't exist. * @throws RiceIllegalArgumentException if roleId is null or Blank */ @WebMethod(operationName = "getRole") @WebResult(name = "role") @Cacheable(value= Role.Cache.NAME, key="'id=' + #p0") Role getRole(@WebParam(name = "id") String id) throws RiceIllegalArgumentException; /** * Get the KIM Role objects for the role IDs in the given List. * * @param ids the ids of the roles. * @return a list of roles with the given ids or null if no roles are found. * @throws RiceIllegalArgumentException if ids is null or Blank */ @WebMethod(operationName = "getRoles") @XmlElementWrapper(name = "roles", required = true) @XmlElement(name = "role", required = false) @WebResult(name = "roles") @Cacheable(value= Role.Cache.NAME, key="'ids=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).key(#p0)") List<Role> getRoles( @WebParam(name="ids") List<String> ids ) throws RiceIllegalArgumentException; /** Get the KIM Role object with the unique combination of namespace, component, * and role name. * * @param namespaceCode the namespace code of the role. * @param name the name of the role. * @return a role with the given namespace code and name or null if role does not exist. * @throws RiceIllegalArgumentException if namespaceCode or name is null or blank. */ @WebMethod(operationName = "getRoleByNamespaceCodeAndName") @WebResult(name = "role") @Cacheable(value=Role.Cache.NAME, key="'namespaceCode=' + #p0 + '|' + 'name=' + #p1") Role getRoleByNamespaceCodeAndName(@WebParam(name = "namespaceCode") String namespaceCode, @WebParam(name = "name") String name) throws RiceIllegalArgumentException; /** * Return the Role ID for the given unique combination of namespace, * component and role name. * * @param namespaceCode the namespace code of the role. * @param name the name of the role. * @return a role id for a role with the given namespace code and name or null if role does not exist. * @throws RiceIllegalArgumentException if namespaceCode or name is null or blank. */ @WebMethod(operationName = "getRoleIdByNamespaceCodeAndName") @WebResult(name = "roleId") @Cacheable(value=Role.Cache.NAME, key="'{getRoleIdByNamespaceCodeAndName}' + 'namespaceCode=' + #p0 + '|' + 'name=' + #p1") String getRoleIdByNamespaceCodeAndName(@WebParam(name = "namespaceCode") String namespaceCode, @WebParam(name = "name") String name) throws RiceIllegalArgumentException; /** * Checks whether the role with the given role ID is active. * * @param id the unique id of a role. * @return true if the role with the given id is active. * @throws RiceIllegalArgumentException if id is null or blank. */ @WebMethod(operationName = "isRoleActive") @WebResult(name = "isRoleActive") @Cacheable(value=Role.Cache.NAME, key="'{isRoleActive}' + 'id=' + #p0") boolean isRoleActive( @WebParam(name="id") String id ) throws RiceIllegalArgumentException; /** * Returns a list of role qualifiers that the given principal has without taking into consideration * that the principal may be a member via an assigned group or role. Use in situations where * you are only interested in the qualifiers that are directly assigned to the principal. * * @param principalId the principalId to * @param roleIds the namespace code of the role. * @param qualification the qualifications for the roleIds. * @return a map of role qualifiers for the given principalId, roleIds and qualifications or an empty map if none found. * @throws RiceIllegalArgumentException if principalId is null or blank or roleIds is null. */ @WebMethod(operationName = "getRoleQualifersForPrincipalByRoleIds") @XmlElementWrapper(name = "attributes", required = true) @XmlElement(name = "attribute", required = false) @WebResult(name = "attributes") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) List<Map<String, String>> getRoleQualifersForPrincipalByRoleIds(@WebParam(name = "principalId") String principalId, @WebParam(name = "roleIds") List<String> roleIds, @WebParam(name = "qualification") @XmlJavaTypeAdapter( value = MapStringStringAdapter.class) Map<String, String> qualification) throws RiceIllegalArgumentException; /** * Returns a list of role qualifiers that the given principal has without taking into consideration * that the principal may be a member via an assigned group or role. Use in situations where * you are only interested in the qualifiers that are directly assigned to the principal. * * @param principalId the principalId to * @param namespaceCode the namespace code of the role. * @param roleName the name of the role. * @param qualification the qualifications for the roleIds. * @return a map of role qualifiers for the given parameters or an empty map if none found. * @throws RiceIllegalArgumentException if principalId, namespaceCode, or roleName is null or blank. */ @WebMethod(operationName = "getRoleQualifersForPrincipalByNamespaceAndRolename") @XmlElementWrapper(name = "attributes", required = true) @XmlElement(name = "attribute", required = false) @WebResult(name = "attributes") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) List<Map<String, String>> getRoleQualifersForPrincipalByNamespaceAndRolename( @WebParam(name = "principalId") String principalId, @WebParam(name = "namespaceCode") String namespaceCode, @WebParam(name = "roleName") String roleName, @WebParam(name = "qualification") @XmlJavaTypeAdapter( value = MapStringStringAdapter.class) Map<String, String> qualification) throws RiceIllegalArgumentException; /** * Returns a list of role qualifiers that the given principal. If the principal's membership * is via a group or role, that group or role's qualifier on the given role is returned. * * @param principalId the principalId to * @param namespaceCode the namespace code of the role. * @param roleName the name of the role. * @param qualification the qualifications for the roleIds. * @return a map of nested role qualifiers for the given parameters or an empty map if none found. * @throws RiceIllegalArgumentException if principalId, namespaceCode, or roleName is null or blank. */ @WebMethod(operationName = "getNestedRoleQualifersForPrincipalByNamespaceAndRolename") @XmlElementWrapper(name = "attributes", required = true) @XmlElement(name = "attribute", required = false) @WebResult(name = "attributes") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) List<Map<String, String>> getNestedRoleQualifersForPrincipalByNamespaceAndRolename( @WebParam(name = "principalId") String principalId, @WebParam(name = "namespaceCode") String namespaceCode, @WebParam(name = "roleName") String roleName, @WebParam(name = "qualification") @XmlJavaTypeAdapter( value = MapStringStringAdapter.class) Map<String, String> qualification) throws RiceIllegalArgumentException; /** * Returns a list of role qualifiers that the given principal. If the principal's membership * is via a group or role, that group or role's qualifier on the given role is returned. * * @param principalId the principalId to * @param roleIds the namespace code of the role. * @param qualification the qualifications for the roleIds. * @return a map of role qualifiers for the given roleIds and qualifications or an empty map if none found. * @throws RiceIllegalArgumentException if principalId, namespaceCode, or roleName is null or blank. */ @WebMethod(operationName = "getNestedRoleQualifiersForPrincipalByRoleIds") @XmlElementWrapper(name = "attributes", required = true) @XmlElement(name = "attribute", required = false) @WebResult(name = "attributes") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) List<Map<String, String>> getNestedRoleQualifiersForPrincipalByRoleIds( @WebParam(name = "principalId") String principalId, @WebParam(name = "roleIds") List<String> roleIds, @WebParam(name = "qualification") @XmlJavaTypeAdapter( value = MapStringStringAdapter.class) Map<String, String> qualification) throws RiceIllegalArgumentException; // -------------------- // Role Membership Checks // -------------------- /** * Get all the role members (groups and principals) associated with the given list of roles * where their role membership/assignment matches the given qualification. The list of RoleMemberships returned * will only contain group and principal members. Any nested role members will be resolved and flattened into * the principals and groups that are members of that nested role (assuming qualifications match). * * The return object will have each membership relationship along with the delegations * * @param roleIds a list of role Ids. * @param qualification the qualifications for the roleIds. * @return a list of role members for the given roleIds and qualifications or an empty list if none found. * @throws RiceIllegalArgumentException if roleIds is null. */ @WebMethod(operationName = "getRoleMembers") @XmlElementWrapper(name = "roleMemberships", required = true) @XmlElement(name = "roleMembership", required = false) @WebResult(name = "roleMemberships") @Cacheable(value= RoleMember.Cache.NAME, key="'roleIds=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).key(#p0) + '|' + 'qualification=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).mapKey(#p1)", condition="!T(org.kuali.rice.kim.api.cache.KimCacheUtils).isDynamicRoleMembership(#p0)" ) List<RoleMembership> getRoleMembers( @WebParam(name="roleIds") List<String> roleIds, @WebParam(name="qualification") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualification ) throws RiceIllegalArgumentException; /** * This method gets all the members, then traverses down into members of type role and group to obtain the nested principal ids * * @param namespaceCode the namespace code of the role. * @param roleName the name of the role * @param qualification the qualifications for the roleIds. * @return a list of role member principalIds for the given roleIds and qualifications, or an empty list if none found. * @throws RiceIllegalArgumentException if namespaceCode, or roleName is null or blank. */ @WebMethod(operationName = "getRoleMemberPrincipalIds") @XmlElementWrapper(name = "principalIds", required = true) @XmlElement(name = "principalId", required = false) @WebResult(name = "principalIds") @Cacheable(value= RoleMember.Cache.NAME, key="'namespaceCode=' + #p0 + '|' + 'roleName=' + #p1 + '|' + 'qualification=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).mapKey(#p2)", condition="!T(org.kuali.rice.kim.api.cache.KimCacheUtils).isDynamicMembshipRoleByNamespaceAndName(#p0, #p1)" ) Collection<String> getRoleMemberPrincipalIds(@WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualification") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualification) throws RiceIllegalArgumentException; /** * Returns whether the given principal has any of the passed role IDs with the given qualification. * * @param principalId the principal Id to check. * @param roleIds the list of role ids. * @param qualification the qualifications for the roleIds. * @return true if the principal is assigned the one of the given roleIds with the passed in qualifications. * @throws RiceIllegalArgumentException if roleIds is null or principalId is null or blank. */ @WebMethod(operationName = "principalHasRole") @WebResult(name = "principalHasRole") boolean principalHasRole( @WebParam(name="principalId") String principalId, @WebParam(name="roleIds") List<String> roleIds, @WebParam(name="qualification") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualification ) throws RiceIllegalArgumentException; /** * Returns whether the given principal has any of the passed role IDs with the given qualification. * * @param principalId the principal Id to check. * @param roleIds the list of role ids. * @param qualification the qualifications for the roleIds. * @param checkDelegations whether delegations should be checked or not * @return true if the principal is assigned the one of the given roleIds with the passed in qualifications. * @throws RiceIllegalArgumentException if roleIds is null or principalId is null or blank. * @since 2.1.1 */ @WebMethod(operationName = "principalHasRoleCheckDelegation") @WebResult(name = "principalHasRoleCheckDelegation") boolean principalHasRole( @WebParam(name="principalId") String principalId, @WebParam(name="roleIds") List<String> roleIds, @WebParam(name="qualification") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualification, boolean checkDelegations) throws RiceIllegalArgumentException; /** * Returns the subset of the given principal ID list which has the given role and qualification. * This is designed to be used by lookups of people by their roles. * * @param principalIds the principal Ids to check. * @param roleNamespaceCode the namespaceCode of the role. * @param roleName the name of the role. * @param qualification the qualifications for the roleIds. * @return list of principalIds that is the subset of list passed in with the given role and qualifications or an empty list. * @throws RiceIllegalArgumentException if principalIds is null or the roleNamespaceCode or roleName is null or blank. */ @WebMethod(operationName = "getPrincipalIdSubListWithRole") @XmlElementWrapper(name = "principalIds", required = true) @XmlElement(name = "principalId", required = false) @WebResult(name = "principalIds") @Cacheable(value= RoleMember.Cache.NAME, key="'getPrincipalIdSubListWithRole' + 'principalIds=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).key(#p0) + '|' + 'roleNamespaceCode=' + #p1 + '|' + 'roleName=' + #p2 + '|' + 'qualification=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).mapKey(#p3)", condition="!T(org.kuali.rice.kim.api.cache.KimCacheUtils).isDynamicMembshipRoleByNamespaceAndName(#p1, #p2)" ) List<String> getPrincipalIdSubListWithRole( @WebParam(name="principalIds") List<String> principalIds, @WebParam(name="roleNamespaceCode") String roleNamespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualification") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualification ) throws RiceIllegalArgumentException; /** * * This method gets search results for role lookup * * @param queryByCriteria the qualifications for the roleIds. * @return query results. will never return null. * @throws RiceIllegalArgumentException if queryByCriteria is null. */ @WebMethod(operationName = "getRolesSearchResults") @WebResult(name = "results") RoleQueryResults findRoles(@WebParam(name = "query") QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException; /** * Gets all direct members of the roles that have ids within the given list * of role ids. This method does not recurse into any nested roles. * * <p>The resulting List of role membership will contain membership for * all the roles with the specified ids. The list is not guaranteed to be * in any particular order and may have membership info for the * different roles interleaved with each other. * * @param roleIds a list of role Ids. * @return list of RoleMembership that contains membership for the specified roleIds or empty list if none found. * @throws RiceIllegalArgumentException if roleIds is null. */ @WebMethod(operationName = "getFirstLevelRoleMembers") @XmlElementWrapper(name = "roleMemberships", required = true) @XmlElement(name = "roleMembership", required = false) @WebResult(name = "roleMemberships") @Cacheable(value=RoleMembership.Cache.NAME, key="'roleIds=' + T(org.kuali.rice.core.api.cache.CacheKeyUtils).key(#p0)") List<RoleMembership> getFirstLevelRoleMembers( @WebParam(name="roleIds") List<String> roleIds) throws RiceIllegalArgumentException; /** * Gets role member information based on the given search criteria. * * @param queryByCriteria the qualifications for the roleIds. * @return query results. will never return null. * @throws RiceIllegalArgumentException if queryByCriteria is null. */ @WebMethod(operationName = "findRoleMemberships") @WebResult(name = "results") RoleMembershipQueryResults findRoleMemberships(@WebParam(name = "query") QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException; /** * Gets a list of Roles that the given member belongs to. * * @param memberType the role member type. * @param memberId the role member id (principalId, roleId, groupId). * @return list of RoleMembership that contains membership for the specified roleIds or an empty list if none found. * @throws RiceIllegalArgumentException if memberType or memberId is null or blank. */ @WebMethod(operationName = "getMemberParentRoleIds") @XmlElementWrapper(name = "roleIds", required = true) @XmlElement(name = "roleId", required = false) @WebResult(name = "roleIds") @Cacheable(value=RoleMembership.Cache.NAME, key="'memberType=' + #p0 + '|' + 'memberId=' + #p1") List<String> getMemberParentRoleIds(String memberType, String memberId) throws RiceIllegalArgumentException; /** * Gets role members based on the given search criteria. * * @param queryByCriteria the qualifications for the roleIds. * @return query results. will never return null. * @throws RiceIllegalArgumentException if queryByCriteria is null. */ @WebMethod(operationName = "findRoleMembers") @WebResult(name = "results") RoleMemberQueryResults findRoleMembers(@WebParam(name = "query") QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException; /** * Gets a list of Roles Ids that are a member of the given roleId, including nested membership. * * @param roleId the role id. * @return list of RoleIds that are members of the given role or and empty list if none found. * @throws RiceIllegalArgumentException if roleId is null or blank. */ @WebMethod(operationName = "getRoleTypeRoleMemberIds") @XmlElementWrapper(name = "memberIds", required = true) @XmlElement(name = "memberId", required = false) @WebResult(name = "memberIds") @Cacheable(value=RoleMember.Cache.NAME, key="'{getRoleTypeRoleMemberIds}' + 'roleId=' + #p0") Set<String> getRoleTypeRoleMemberIds(@WebParam(name = "roleId") String roleId) throws RiceIllegalArgumentException; /** * Gets role members based on the given search criteria. * * @param queryByCriteria the qualifications for the roleIds. * @return query results. will never return null. * @throws RiceIllegalArgumentException if queryByCriteria is null. */ @WebMethod(operationName = "findDelegateMembers") @WebResult(name = "results") DelegateMemberQueryResults findDelegateMembers(@WebParam(name = "query") QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException; /** * Gets the delegate members for the given delegation. * * @param delegateId the delegate id. * @return list of delegate members that are members of the given delegation or an empty list if none found. * @throws RiceIllegalArgumentException if delegationId is null or blank. */ @WebMethod(operationName = "getDelegationMembersByDelegationId") @XmlElementWrapper(name = "delegateMembers", required = true) @XmlElement(name = "delegateMember", required = false) @WebResult(name = "delegateMembers") @Cacheable(value=DelegateMember.Cache.NAME, key="'delegateId=' + #p0") List<DelegateMember> getDelegationMembersByDelegationId( @WebParam(name = "delegateId") String delegateId) throws RiceIllegalArgumentException; /** * Gets the delegate member for the given delegationId and memberId. * * @param delegationId the delegate id. * @param memberId the member id matching the DelegateMember * @return the delegate member with the given parameters or null if not found. * @throws RiceIllegalArgumentException if delegationId or memberId is null or blank. */ @WebMethod(operationName = "getDelegationMemberByDelegationAndMemberId") @WebResult(name = "delegateMember") @Cacheable(value=DelegateMember.Cache.NAME, key="'delegationId=' + #p0 + '|' + 'memberId=' + #p1") DelegateMember getDelegationMemberByDelegationAndMemberId( @WebParam(name = "delegationId") String delegationId, @WebParam(name = "memberId") String memberId) throws RiceIllegalArgumentException; /** * Gets the delegate member with the given delegation member id. * * @param id the member id matching the DelegateMember * @return the delegate member with the given parameters or null if not found. * @throws RiceIllegalArgumentException if delegationId or memberId is null or blank. */ @WebMethod(operationName = "getDelegationMemberById") @WebResult(name = "delegateMember") @Cacheable(value=DelegateMember.Cache.NAME, key="'id=' + #p0") DelegateMember getDelegationMemberById(@WebParam(name = "id") String id) throws RiceIllegalArgumentException; /** * Gets a list of role reponsibilities for the given role id. * * @param roleId the role Id. * @return a list of RoleResponsibilities for the given role Id, or an empty list if none found. * @throws RiceIllegalArgumentException if roleId is null or blank. */ @WebMethod(operationName = "getRoleResponsibilities") @XmlElementWrapper(name = "roleResponsibilities", required = true) @XmlElement(name = "roleResponsibility", required = false) @WebResult(name = "roleResponsibilities") @Cacheable(value=RoleResponsibility.Cache.NAME, key="'roleId=' + #p0") List<RoleResponsibility> getRoleResponsibilities(@WebParam(name="roleId") String roleId) throws RiceIllegalArgumentException; /** * Gets a list of RoleResponsibilityActions for the given role member id. * * @param roleMemberId the role member Id. * @return a list of RoleResponsibilityActions for the given role member Id, or an empty list if none found. * @throws RiceIllegalArgumentException if roleMemberId is null or blank. */ @WebMethod(operationName = "getRoleMemberResponsibilityActions") @XmlElementWrapper(name = "roleResponsibilityActions", required = true) @XmlElement(name = "roleResponsibilityAction", required = false) @WebResult(name = "roleResponsibilityActions") @Cacheable(value=RoleResponsibility.Cache.NAME, key="'roleMemberId=' + #p0") List<RoleResponsibilityAction> getRoleMemberResponsibilityActions( @WebParam(name = "roleMemberId") String roleMemberId) throws RiceIllegalArgumentException; /** * Gets a DelegateType for the given role id and delegation type. * * @param roleId the role Id. * @param delegateType type of delegation * @return the DelegateType for the given role Id and delegationType, or null if none found. * @throws RiceIllegalArgumentException if roleId or delegationType is null or blank. */ @WebMethod(operationName = "getDelegateTypeByRoleIdAndDelegateTypeCode") @WebResult(name = "delegateType") @Cacheable(value=DelegateType.Cache.NAME, key="'roleId=' + #p0 + '|' + 'delegateType=' + #p1") DelegateType getDelegateTypeByRoleIdAndDelegateTypeCode(@WebParam(name = "roleId") String roleId, @WebParam(name = "delegateType") DelegationType delegateType) throws RiceIllegalArgumentException; /** * Gets a DelegateType for the given delegation id. * * @param delegationId the id of delegation * @return the DelegateType for the given delegation Id, or null if none found. * @throws RiceIllegalArgumentException if delegationId is null or blank. */ @WebMethod(operationName = "getDelegateTypeByDelegationId") @WebResult(name = "delegateType") @Cacheable(value=DelegateType.Cache.NAME, key="'delegationId=' + #p0") DelegateType getDelegateTypeByDelegationId(@WebParam(name = "delegationId") String delegationId) throws RiceIllegalArgumentException; /** * Assigns the principal with the given id to the role with the specified * namespace code and name with the supplied set of qualifications. * * @param principalId the principalId * @param namespaceCode the namespaceCode of the Role * @param roleName the name of the role * @param qualifications the qualifications for the principalId to be assigned to the role * @return newly created/assigned RoleMember. * @throws RiceIllegalArgumentException if princialId, namespaceCode or roleName is null or blank. */ @WebMethod(operationName = "assignPrincipalToRole") @WebResult(name = "roleMember") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleMember assignPrincipalToRole(@WebParam(name="principalId") String principalId, @WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualifications") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualifications) throws RiceIllegalArgumentException; /** * Assigns the group with the given id to the role with the specified * namespace code and name with the supplied set of qualifications. * * @param groupId the groupId * @param namespaceCode the namespaceCode of the Role * @param roleName the name of the role * @param qualifications the qualifications for the principalId to be assigned to the role * @return newly created/assigned RoleMember. * @throws RiceIllegalArgumentException if groupId, namespaceCode or roleName is null or blank. */ @WebMethod(operationName = "assignGroupToRole") @WebResult(name = "roleMember") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleMember assignGroupToRole(@WebParam(name="groupId") String groupId, @WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualifications") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualifications) throws RiceIllegalArgumentException; /** * Assigns the role with the given id to the role with the specified * namespace code and name with the supplied set of qualifications. * * @param roleId the roleId * @param namespaceCode the namespaceCode of the Role * @param roleName the name of the role * @param qualifications the qualifications for the principalId to be assigned to the role * @return newly created/assigned RoleMember. * @throws RiceIllegalArgumentException if princiapId, namespaceCode or roleName is null or blank. */ @WebMethod(operationName = "assignRoleToRole") @WebResult(name = "roleMember") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleMember assignRoleToRole(@WebParam(name="roleId") String roleId, @WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualifications") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualifications) throws RiceIllegalArgumentException; /** * Creates a new RoleMember. Needs to be passed a valid RoleMember object that does not currently exist. * * @param roleMember the new RoleMember to save. * @return RoleMember as created. * @throws RiceIllegalArgumentException if roleMember is null. * @throws RiceIllegalStateException if roleMember already exists. */ @WebMethod(operationName = "createRoleMember") @WebResult(name = "roleMember") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleMember createRoleMember( @WebParam(name = "roleMember") RoleMember roleMember) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Updates the given roleMember to the values in the passed in roleMember * * @param roleMember the new RoleMember to save. * @return RoleMember as updated. * @throws RiceIllegalArgumentException if roleMember is null. * @throws RiceIllegalStateException if roleMember does not yet exist. */ @WebMethod(operationName = "updateRoleMember") @WebResult(name = "roleMember") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleMember updateRoleMember(@WebParam(name = "roleMember") RoleMember roleMember) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Updates the given delegateMember to the values in the passed in delegateMember * * @param delegateMember the new DelegateMember to save. * @return DelegateMember as updated. * @throws RiceIllegalArgumentException if delegateMember is null. * @throws RiceIllegalStateException if delegateMember does not yet exist. */ @WebMethod(operationName = "updateDelegateMember") @WebResult(name = "delegateMember") @CacheEvict(value={Role.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) DelegateMember updateDelegateMember(@WebParam(name = "delegateMember") DelegateMember delegateMember) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Creates a new DelegateMember. Needs to be passed a valid DelegateMember object that does not currently exist. * * @param delegateMember the new DelegateMember to save. * @return DelegateMember as created. * @throws RiceIllegalArgumentException if delegateMember is null. * @throws RiceIllegalStateException if delegateMember already exists. */ @WebMethod(operationName = "createDelegateMember") @WebResult(name = "delegateMember") @CacheEvict(value={Role.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) DelegateMember createDelegateMember( @WebParam(name = "delegateMember") DelegateMember delegateMember) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Removes existing DelegateMembers. Needs to be passed DelegateMember objects. * * @param DelegateMembers to remove. * @throws RiceIllegalArgumentException if delegateMember is null. */ @WebMethod(operationName = "removeDelegateMembers") @CacheEvict(value={Role.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void removeDelegateMembers( @WebParam(name = "delegateMembers") List<DelegateMember> delegateMembers) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Creates a new RoleResponsibilityAction. Needs to be passed a valid RoleResponsibilityAction * object that does not currently exist. * * @param roleResponsibilityAction the new RoleResponsibilityAction to save. * @return RoleResponsibilityAction as created. * @throws RiceIllegalArgumentException if roleResponsibilityAction is null. * @throws RiceIllegalStateException if roleResponsibilityAction already exists. */ @WebMethod(operationName = "createRoleResponsibilityAction") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleResponsibilityAction createRoleResponsibilityAction(@WebParam(name = "roleResponsibilityAction") RoleResponsibilityAction roleResponsibilityAction) throws RiceIllegalArgumentException; /** * Updates the given RoleResponsibilityAction to the values in the passed in roleResponsibilityAction * * @since 2.1.2 * @param roleResponsibilityAction the new RoleResponsibilityAction to save. * @return RoleResponsibilityAction as updated. * @throws RiceIllegalArgumentException if roleResponsibilityAction is null. * @throws RiceIllegalStateException if roleResponsibilityAction does not exist. */ @WebMethod(operationName = "updateRoleResponsibilityAction") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) RoleResponsibilityAction updateRoleResponsibilityAction(@WebParam(name = "roleResponsibilityAction") RoleResponsibilityAction roleResponsibilityAction) throws RiceIllegalArgumentException; /** * Deletes the given RoleResponsibilityAction * * @since 2.1.2 * @param roleResponsibilityActionId id of the RoleResponsibilityAction to delete. * @throws RiceIllegalArgumentException if roleResponsibilityActionId is null. * @throws RiceIllegalStateException if roleResponsibilityAction does not exist. */ @WebMethod(operationName = "deleteRoleResponsibilityAction") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void deleteRoleResponsibilityAction(@WebParam(name = "roleResponsibilityActionId") String roleResponsibilityActionId) throws RiceIllegalArgumentException; /** * Creates a new DelegateType. Needs to be passed a valid DelegateType * object that does not currently exist. * * @param delegateType the new DelegateType to save. * @return DelegateType as created. * @throws RiceIllegalArgumentException if delegateType is null. * @throws RiceIllegalStateException if delegateType already exists. */ @WebMethod(operationName = "createDelegateType") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) DelegateType createDelegateType(@WebParam(name="delegateType") DelegateType delegateType) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Updates the given DelegateType to the values in the passed in delegateType * * @param delegateType the new DelegateType to save. * @return DelegateType as updated. * @throws RiceIllegalArgumentException if delegateType is null. * @throws RiceIllegalStateException if delegateType does not yet exist. */ @WebMethod(operationName = "updateDelegateType") @CacheEvict(value={Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) DelegateType updateDelegateType(@WebParam(name="delegateType") DelegateType delegateType) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Remove the principal with the given id and qualifications from the role * with the specified namespace code and role name. * * @param principalId the principalId * @param namespaceCode the namespaceCode of the Role * @param roleName the name of the role * @param qualifications the qualifications for the principalId to be assigned to the role * @return void. * @throws RiceIllegalArgumentException if principalId, namespaceCode or roleName is null or blank. */ @WebMethod(operationName = "removePrincipalFromRole") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void removePrincipalFromRole(@WebParam(name="principalId") String principalId, @WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualifications") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualifications) throws RiceIllegalArgumentException; /** * Remove the group with the given id and qualifications from the role * with the specified namespace code and role name. * * @param groupId the groupId * @param namespaceCode the namespaceCode of the Role * @param roleName the name of the role * @param qualifications the qualifications for the principalId to be assigned to the role * @return void. * @throws RiceIllegalArgumentException if groupId, namespaceCode or roleName is null or blank. */ @WebMethod(operationName = "removeGroupFromRole") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void removeGroupFromRole(@WebParam(name="groupId") String groupId, @WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualifications") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualifications) throws RiceIllegalArgumentException; /** * Remove the group with the given id and qualifications from the role * with the specified namespace code and role name. * * @param roleId the roleId * @param namespaceCode the namespaceCode of the Role * @param roleName the name of the role * @param qualifications the qualifications for the principalId to be assigned to the role * @return void. * @throws RiceIllegalArgumentException if roleId, namespaceCode or roleName is null or blank. */ @WebMethod(operationName = "removeRoleFromRole") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void removeRoleFromRole(@WebParam(name="roleId") String roleId, @WebParam(name="namespaceCode") String namespaceCode, @WebParam(name="roleName") String roleName, @WebParam(name="qualifications") @XmlJavaTypeAdapter(value = MapStringStringAdapter.class) Map<String, String> qualifications) throws RiceIllegalArgumentException; /** * Assigns the given permission to the given role * * @param permissionId the permissionId * @param roleId the roleId * @return void. * @throws RiceIllegalArgumentException if permissionId or roleId is null or blank. */ @WebMethod(operationName = "assignPermissionToRole") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void assignPermissionToRole( @WebParam(name = "permissionId") String permissionId, @WebParam(name = "roleId") String roleId) throws RiceIllegalArgumentException; /** * Removes the given permission to the given role * * @param permissionId the permissionId * @param roleId the roleId * @return void. * @throws RiceIllegalArgumentException if permissionId or roleId is null or blank. */ @WebMethod(operationName = "revokePermissionFromRole") @CacheEvict(value={Role.Cache.NAME, Permission.Cache.NAME, Responsibility.Cache.NAME, RoleMembership.Cache.NAME, RoleMember.Cache.NAME, DelegateMember.Cache.NAME, RoleResponsibility.Cache.NAME, DelegateType.Cache.NAME }, allEntries = true) void revokePermissionFromRole( @WebParam(name = "permissionId") String permissionId, @WebParam(name = "roleId") String roleId) throws RiceIllegalArgumentException; /** * Determines if a role with a provided id is a derived role * * @since 2.1.1 * @param roleId the roleId * @return true if role is a derived role * @throws RiceIllegalArgumentException if roleId is null or blank. */ @WebMethod(operationName = "isDerivedRole") @WebResult(name = "isDerivedRole") @Cacheable(value= Role.Cache.NAME, key="'{isDerivedRole}' + 'roleId=' + #p0") boolean isDerivedRole(@WebParam(name = "roleId") String roleId) throws RiceIllegalArgumentException; /** * Determines if a role with a provided id is a uses dynamic role memberships * * @since 2.1.1 * @param roleId the roleId * @return true if role uses dynamic memberships * @throws RiceIllegalArgumentException if roleId is null or blank. */ @WebMethod(operationName = "isDynamicRoleMembership") @WebResult(name = "isDynamicRoleMembership") @Cacheable(value= Role.Cache.NAME, key="'{isDynamicRoleMembership}' + 'roleId=' + #p0") boolean isDynamicRoleMembership(@WebParam(name = "roleId") String roleId) throws RiceIllegalArgumentException; }
/* * Copyright 2019 Mahmoud Romeh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.resilience4j.common.ratelimiter.configuration; import io.github.resilience4j.common.CompositeCustomizer; import io.github.resilience4j.common.circuitbreaker.configuration.CircuitBreakerConfigurationProperties; import io.github.resilience4j.core.ConfigurationNotFoundException; import io.github.resilience4j.ratelimiter.RateLimiterConfig; import org.junit.Test; import java.time.Duration; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * test custom init of rate limiter properties */ public class RateLimiterConfigurationPropertiesTest { @Test public void testRateLimiterRegistry() { //Given RateLimiterConfigurationProperties.InstanceProperties instanceProperties1 = new RateLimiterConfigurationProperties.InstanceProperties(); instanceProperties1.setLimitForPeriod(2); instanceProperties1.setWritableStackTraceEnabled(false); instanceProperties1.setSubscribeForEvents(true); instanceProperties1.setEventConsumerBufferSize(100); instanceProperties1.setLimitRefreshPeriod(Duration.ofMillis(100)); instanceProperties1.setTimeoutDuration(Duration.ofMillis(100)); RateLimiterConfigurationProperties.InstanceProperties instanceProperties2 = new RateLimiterConfigurationProperties.InstanceProperties(); instanceProperties2.setLimitForPeriod(4); instanceProperties2.setSubscribeForEvents(true); instanceProperties2.setWritableStackTraceEnabled(true); RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); rateLimiterConfigurationProperties.getInstances().put("backend1", instanceProperties1); rateLimiterConfigurationProperties.getInstances().put("backend2", instanceProperties2); Map<String,String> globalTagsForRateLimiters=new HashMap<>(); globalTagsForRateLimiters.put("testKey1","testKet2"); rateLimiterConfigurationProperties.setTags(globalTagsForRateLimiters); //Then assertThat(rateLimiterConfigurationProperties.getTags().size()).isEqualTo(1); assertThat(rateLimiterConfigurationProperties.getInstances().size()).isEqualTo(2); assertThat(rateLimiterConfigurationProperties.getLimiters().size()).isEqualTo(2); RateLimiterConfig rateLimiter = rateLimiterConfigurationProperties .createRateLimiterConfig("backend1", compositeRateLimiterCustomizer()); assertThat(rateLimiter).isNotNull(); assertThat(rateLimiter.getLimitForPeriod()).isEqualTo(2); assertThat(rateLimiter.isWritableStackTraceEnabled()).isFalse(); RateLimiterConfig rateLimiter2 = rateLimiterConfigurationProperties .createRateLimiterConfig("backend2", compositeRateLimiterCustomizer()); assertThat(rateLimiter2).isNotNull(); assertThat(rateLimiter2.getLimitForPeriod()).isEqualTo(4); assertThat(rateLimiter2.isWritableStackTraceEnabled()).isTrue(); } @Test public void testCreateRateLimiterRegistryWithSharedConfigs() { //Given RateLimiterConfigurationProperties.InstanceProperties defaultProperties = new RateLimiterConfigurationProperties.InstanceProperties(); defaultProperties.setLimitForPeriod(3); defaultProperties.setLimitRefreshPeriod(Duration.ofNanos(5000000)); defaultProperties.setSubscribeForEvents(true); defaultProperties.setWritableStackTraceEnabled(false); RateLimiterConfigurationProperties.InstanceProperties sharedProperties = new RateLimiterConfigurationProperties.InstanceProperties(); sharedProperties.setLimitForPeriod(2); sharedProperties.setLimitRefreshPeriod(Duration.ofNanos(6000000)); sharedProperties.setSubscribeForEvents(true); RateLimiterConfigurationProperties.InstanceProperties backendWithDefaultConfig = new RateLimiterConfigurationProperties.InstanceProperties(); backendWithDefaultConfig.setBaseConfig("defaultConfig"); backendWithDefaultConfig.setLimitForPeriod(200); backendWithDefaultConfig.setSubscribeForEvents(true); backendWithDefaultConfig.setWritableStackTraceEnabled(true); RateLimiterConfigurationProperties.InstanceProperties backendWithSharedConfig = new RateLimiterConfigurationProperties.InstanceProperties(); backendWithSharedConfig.setBaseConfig("sharedConfig"); backendWithSharedConfig.setLimitForPeriod(300); backendWithSharedConfig.setSubscribeForEvents(true); backendWithSharedConfig.setWritableStackTraceEnabled(true); RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); rateLimiterConfigurationProperties.getConfigs().put("defaultConfig", defaultProperties); rateLimiterConfigurationProperties.getConfigs().put("sharedConfig", sharedProperties); rateLimiterConfigurationProperties.getInstances() .put("backendWithDefaultConfig", backendWithDefaultConfig); rateLimiterConfigurationProperties.getInstances() .put("backendWithSharedConfig", backendWithSharedConfig); //Then assertThat(rateLimiterConfigurationProperties.getInstances().size()).isEqualTo(2); // Should get default config and override LimitForPeriod RateLimiterConfig rateLimiter1 = rateLimiterConfigurationProperties .createRateLimiterConfig("backendWithDefaultConfig", compositeRateLimiterCustomizer()); assertThat(rateLimiter1).isNotNull(); assertThat(rateLimiter1.getLimitForPeriod()).isEqualTo(200); assertThat(rateLimiter1.getLimitRefreshPeriod()).isEqualTo(Duration.ofMillis(5)); assertThat(rateLimiter1.isWritableStackTraceEnabled()).isTrue(); // Should get shared config and override LimitForPeriod RateLimiterConfig rateLimiter2 = rateLimiterConfigurationProperties .createRateLimiterConfig("backendWithSharedConfig", compositeRateLimiterCustomizer()); assertThat(rateLimiter2).isNotNull(); assertThat(rateLimiter2.getLimitForPeriod()).isEqualTo(300); assertThat(rateLimiter2.getLimitRefreshPeriod()).isEqualTo(Duration.ofMillis(6)); assertThat(rateLimiter2.isWritableStackTraceEnabled()).isTrue(); // Unknown backend should get default config of Registry RateLimiterConfig rerateLimiter3 = rateLimiterConfigurationProperties .createRateLimiterConfig("unknownBackend", compositeRateLimiterCustomizer()); assertThat(rerateLimiter3).isNotNull(); assertThat(rerateLimiter3.getLimitForPeriod()).isEqualTo(50); assertThat(rerateLimiter3.isWritableStackTraceEnabled()).isTrue(); } @Test public void testCreateRateLimiterRegistryWithDefaultConfig() { //Given RateLimiterConfigurationProperties.InstanceProperties defaultProperties = new RateLimiterConfigurationProperties.InstanceProperties(); defaultProperties.setLimitForPeriod(3); defaultProperties.setLimitRefreshPeriod(Duration.ofNanos(5000000)); defaultProperties.setSubscribeForEvents(true); defaultProperties.setWritableStackTraceEnabled(false); RateLimiterConfigurationProperties.InstanceProperties sharedProperties = new RateLimiterConfigurationProperties.InstanceProperties(); sharedProperties.setLimitForPeriod(2); sharedProperties.setLimitRefreshPeriod(Duration.ofNanos(6000000)); sharedProperties.setSubscribeForEvents(true); RateLimiterConfigurationProperties.InstanceProperties backendWithoutBaseConfig = new RateLimiterConfigurationProperties.InstanceProperties(); backendWithoutBaseConfig.setLimitForPeriod(200); backendWithoutBaseConfig.setSubscribeForEvents(true); backendWithoutBaseConfig.setWritableStackTraceEnabled(true); RateLimiterConfigurationProperties.InstanceProperties backendWithSharedConfig = new RateLimiterConfigurationProperties.InstanceProperties(); backendWithSharedConfig.setBaseConfig("sharedConfig"); backendWithSharedConfig.setLimitForPeriod(300); backendWithSharedConfig.setSubscribeForEvents(true); backendWithSharedConfig.setWritableStackTraceEnabled(true); RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); rateLimiterConfigurationProperties.getConfigs().put("default", defaultProperties); rateLimiterConfigurationProperties.getConfigs().put("sharedConfig", sharedProperties); rateLimiterConfigurationProperties.getInstances() .put("backendWithoutBaseConfig", backendWithoutBaseConfig); rateLimiterConfigurationProperties.getInstances() .put("backendWithSharedConfig", backendWithSharedConfig); //Then assertThat(rateLimiterConfigurationProperties.getInstances().size()).isEqualTo(2); // Should get default config and override LimitForPeriod RateLimiterConfig rateLimiter1 = rateLimiterConfigurationProperties .createRateLimiterConfig("backendWithoutBaseConfig", compositeRateLimiterCustomizer()); assertThat(rateLimiter1).isNotNull(); assertThat(rateLimiter1.getLimitForPeriod()).isEqualTo(200); assertThat(rateLimiter1.getLimitRefreshPeriod()).isEqualTo(Duration.ofNanos(5000000)); assertThat(rateLimiter1.isWritableStackTraceEnabled()).isTrue(); // Should get shared config and override LimitForPeriod RateLimiterConfig rateLimiter2 = rateLimiterConfigurationProperties .createRateLimiterConfig("backendWithSharedConfig", compositeRateLimiterCustomizer()); assertThat(rateLimiter2).isNotNull(); assertThat(rateLimiter2.getLimitForPeriod()).isEqualTo(300); assertThat(rateLimiter2.getLimitRefreshPeriod()).isEqualTo(Duration.ofMillis(6)); assertThat(rateLimiter2.isWritableStackTraceEnabled()).isTrue(); // Unknown backend should get default config of Registry RateLimiterConfig rateLimiter3 = rateLimiterConfigurationProperties .createRateLimiterConfig("unknownBackend", compositeRateLimiterCustomizer()); assertThat(rateLimiter3).isNotNull(); assertThat(rateLimiter3.getLimitForPeriod()).isEqualTo(3); assertThat(rateLimiter3.isWritableStackTraceEnabled()).isFalse(); } @Test public void testCreateRateLimiterRegistryWithUnknownConfig() { RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); RateLimiterConfigurationProperties.InstanceProperties instanceProperties = new RateLimiterConfigurationProperties.InstanceProperties(); instanceProperties.setBaseConfig("unknownConfig"); rateLimiterConfigurationProperties.getInstances().put("backend", instanceProperties); //When assertThatThrownBy( () -> rateLimiterConfigurationProperties .createRateLimiterConfig("backend", compositeRateLimiterCustomizer())) .isInstanceOf(ConfigurationNotFoundException.class) .hasMessage("Configuration with name 'unknownConfig' does not exist"); } @Test public void testFindRateLimiterProperties() { RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); RateLimiterConfigurationProperties.InstanceProperties instanceProperties = new RateLimiterConfigurationProperties.InstanceProperties(); instanceProperties.setLimitForPeriod(3); instanceProperties.setLimitRefreshPeriod(Duration.ofNanos(5000000)); instanceProperties.setSubscribeForEvents(true); rateLimiterConfigurationProperties.getInstances().put("default", instanceProperties); assertThat( rateLimiterConfigurationProperties.findRateLimiterProperties("default").isPresent()) .isTrue(); assertThat( rateLimiterConfigurationProperties.findRateLimiterProperties("custom").isPresent()) .isFalse(); } @Test public void testRateLimiterConfigWithBaseConfig() { RateLimiterConfigurationProperties.InstanceProperties defaultConfig = new RateLimiterConfigurationProperties.InstanceProperties(); defaultConfig.setLimitForPeriod(2000); defaultConfig.setLimitRefreshPeriod(Duration.ofMillis(100L)); RateLimiterConfigurationProperties.InstanceProperties sharedConfigWithDefaultConfig = new RateLimiterConfigurationProperties.InstanceProperties(); sharedConfigWithDefaultConfig.setLimitRefreshPeriod(Duration.ofMillis(1000L)); sharedConfigWithDefaultConfig.setBaseConfig("defaultConfig"); RateLimiterConfigurationProperties.InstanceProperties instanceWithSharedConfig = new RateLimiterConfigurationProperties.InstanceProperties(); instanceWithSharedConfig.setBaseConfig("sharedConfig"); RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); rateLimiterConfigurationProperties.getConfigs().put("defaultConfig", defaultConfig); rateLimiterConfigurationProperties.getConfigs().put("sharedConfig", sharedConfigWithDefaultConfig); rateLimiterConfigurationProperties.getInstances().put("instanceWithSharedConfig", instanceWithSharedConfig); RateLimiterConfig instance = rateLimiterConfigurationProperties .createRateLimiterConfig(instanceWithSharedConfig, compositeRateLimiterCustomizer(), "instanceWithSharedConfig"); assertThat(instance).isNotNull(); assertThat(instance.getLimitForPeriod()).isEqualTo(2000); assertThat(instance.getLimitRefreshPeriod()).isEqualTo(Duration.ofMillis(1000L)); } @Test(expected = IllegalArgumentException.class) public void testIllegalArgumentOnEventConsumerBufferSize() { RateLimiterConfigurationProperties.InstanceProperties defaultProperties = new RateLimiterConfigurationProperties.InstanceProperties(); defaultProperties.setEventConsumerBufferSize(-1); } @Test public void testFindRateLimiterPropertiesWithoutDefaultConfig() { //Given RateLimiterConfigurationProperties.InstanceProperties backendWithoutBaseConfig = new RateLimiterConfigurationProperties.InstanceProperties(); RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); rateLimiterConfigurationProperties.getInstances().put("backendWithoutBaseConfig", backendWithoutBaseConfig); //Then assertThat(rateLimiterConfigurationProperties.getInstances().size()).isEqualTo(1); // Should get default config and overwrite registerHealthIndicator, allowHealthIndicatorToFail and eventConsumerBufferSize Optional<RateLimiterConfigurationProperties.InstanceProperties> rateLimiterProperties = rateLimiterConfigurationProperties.findRateLimiterProperties("backendWithoutBaseConfig"); assertThat(rateLimiterProperties).isPresent(); assertThat(rateLimiterProperties.get().getRegisterHealthIndicator()).isNull(); assertThat(rateLimiterProperties.get().getAllowHealthIndicatorToFail()).isNull(); assertThat(rateLimiterProperties.get().getEventConsumerBufferSize()).isNull(); } @Test public void testFindCircuitBreakerPropertiesWithDefaultConfig() { //Given RateLimiterConfigurationProperties.InstanceProperties defaultProperties = new RateLimiterConfigurationProperties.InstanceProperties(); defaultProperties.setRegisterHealthIndicator(true); defaultProperties.setEventConsumerBufferSize(99); RateLimiterConfigurationProperties.InstanceProperties backendWithoutBaseConfig = new RateLimiterConfigurationProperties.InstanceProperties(); RateLimiterConfigurationProperties rateLimiterConfigurationProperties = new RateLimiterConfigurationProperties(); rateLimiterConfigurationProperties.getConfigs().put("default", defaultProperties); rateLimiterConfigurationProperties.getInstances().put("backendWithoutBaseConfig", backendWithoutBaseConfig); //Then assertThat(rateLimiterConfigurationProperties.getInstances().size()).isEqualTo(1); // Should get default config and overwrite registerHealthIndicator and eventConsumerBufferSize but not allowHealthIndicatorToFail Optional<RateLimiterConfigurationProperties.InstanceProperties> rateLimiterProperties = rateLimiterConfigurationProperties.findRateLimiterProperties("backendWithoutBaseConfig"); assertThat(rateLimiterProperties).isPresent(); assertThat(rateLimiterProperties.get().getRegisterHealthIndicator()).isTrue(); assertThat(rateLimiterProperties.get().getAllowHealthIndicatorToFail()).isNull(); assertThat(rateLimiterProperties.get().getEventConsumerBufferSize()).isEqualTo(99); } private CompositeCustomizer<RateLimiterConfigCustomizer> compositeRateLimiterCustomizer() { return new CompositeCustomizer<>(Collections.emptyList()); } }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.conf.AttributeType; import org.jgroups.util.ByteArray; import org.jgroups.util.FastArray; import org.jgroups.util.MessageBatch; import org.jgroups.util.Util; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; /** * Fragmentation layer. Fragments messages larger than FRAG_SIZE into smaller * packets. Reassembles fragmented packets into bigger ones. The fragmentation * number is added to the messages as a header (and removed at the receiving side). * <p> * Contrary to {@link org.jgroups.protocols.FRAG2}, FRAG marshals the entire message (including the headers) into * a byte[] buffer and the fragments that buffer. Because {@link BaseMessage#size()} is called rather than * {@link BaseMessage#getLength()}, and because of the overhead of marshalling, this will be slower than * FRAG2. * <p> * Each fragment is identified by (a) the sender (part of the message to which * the header is appended), (b) the fragmentation ID (which is unique per FRAG * layer (monotonically increasing) and (c) the fragement ID which ranges from 0 * to number_of_fragments-1. * <p> * Requirement: lossless delivery (e.g. NAK, ACK). No requirement on ordering. * Works for both unicast and multicast messages. * * @author Bela Ban * @author Filip Hanik */ public class FRAG extends Fragmentation { /** Contains a frag table per sender, this way it becomes easier to clean up if a sender leaves or crashes */ protected final FragmentationList fragment_list=new FragmentationList(); protected final AtomicInteger curr_id=new AtomicInteger(1); protected final List<Address> members=new ArrayList<>(11); protected MessageFactory msg_factory; protected final Predicate<Message> HAS_FRAG_HEADER=msg -> msg.getHeader(id) != null; @ManagedAttribute(description="Number of sent messages",type=AttributeType.SCALAR) long num_sent_msgs; @ManagedAttribute(description="Number of received messages",type=AttributeType.SCALAR) long num_received_msgs; public long getNumberOfSentMessages() {return num_sent_msgs;} public long getNumberOfReceivedMessages() {return num_received_msgs;} public void init() throws Exception { super.init(); msg_factory=getTransport().getMessageFactory(); Map<String,Object> info=new HashMap<>(1); info.put("frag_size", frag_size); down_prot.down(new Event(Event.CONFIG, info)); } public void resetStats() { super.resetStats(); num_sent_msgs=num_received_msgs=0; } /** * Fragment a packet if larger than frag_size (add a header). Otherwise just pass down. Only * add a header if framentation is needed ! */ public Object down(Event evt) { switch(evt.getType()) { case Event.VIEW_CHANGE: handleViewChange(evt.getArg()); break; } return super.down(evt); // Pass on to the layer below us } public Object down(Message msg) { int size=msg.size(); num_sent_msgs++; if(size > frag_size) { if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder("message size is "); sb.append(size).append(", will fragment (frag_size=").append(frag_size).append(')'); log.trace(sb.toString()); } fragment(msg); // Fragment and pass down return null; } return down_prot.down(msg); } /** * If event is a message, if it is fragmented, re-assemble fragments into big message and pass up the stack. */ public Object up(Event evt) { switch(evt.getType()) { case Event.VIEW_CHANGE: handleViewChange(evt.getArg()); break; } return up_prot.up(evt); // Pass up to the layer above us by default } public Object up(Message msg) { FragHeader hdr=msg.getHeader(this.id); if(hdr != null) { // needs to be defragmented Message assembled_msg=unfragment(msg, hdr); if(assembled_msg != null) up_prot.up(assembled_msg); return null; } else { num_received_msgs++; } return up_prot.up(msg); } public void up(MessageBatch batch) { FastArray<Message>.FastIterator it=(FastArray<Message>.FastIterator)batch.iteratorWithFilter(HAS_FRAG_HEADER); while(it.hasNext()) { Message msg=it.next(); FragHeader hdr=msg.getHeader(this.id); Message assembled_msg=unfragment(msg, hdr); if(assembled_msg != null) // the reassembled msg has to be add in the right place (https://issues.jboss.org/browse/JGRP-1648), // and cannot be added at the tail of the batch! it.replace(assembled_msg); else it.remove(); } if(!batch.isEmpty()) up_prot.up(batch); } private void handleViewChange(View view) { List<Address> new_mbrs=view.getMembers(); List<Address> left_mbrs=Util.determineLeftMembers(members, new_mbrs); members.clear(); members.addAll(new_mbrs); for(Address mbr: left_mbrs){ // the new view doesn't contain the sender, it must have left, // hence we will clear all of itsfragmentation tables fragment_list.remove(mbr); if(log.isTraceEnabled()) log.trace("[VIEW_CHANGE] removed " + mbr + " from fragmentation table"); } } /** * Send all fragments as separate messages (with same ID !). * Example: * <pre> * Given the generated ID is 2344, number of fragments=3, message {dst,src,buf} * would be fragmented into: * <p/> * [2344,3,0]{dst,src,buf1}, * [2344,3,1]{dst,src,buf2} and * [2344,3,2]{dst,src,buf3} * </pre> */ private void fragment(Message msg) { Address dest=msg.getDest(), src=msg.getSrc(); long frag_id=curr_id.getAndIncrement(); // used as seqnos int num_frags; try { // write message into a byte buffer and fragment it ByteArray tmp=Util.messageToBuffer(msg); byte[] buffer=tmp.getArray(); byte[][] fragments=Util.fragmentBuffer(buffer, frag_size, tmp.getLength()); num_frags=fragments.length; num_frags_sent.add(num_frags); if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder(); sb.append("fragmenting packet to ").append(dest != null ? dest.toString() : "<all members>") .append(" (size=").append(buffer.length).append(") into ").append(num_frags) .append(" fragment(s) [frag_size=").append(frag_size).append(']'); log.trace(sb.toString()); } for(int i=0; i < num_frags; i++) { Message frag_msg=new BytesMessage(dest, fragments[i]).setSrc(src) .setFlag(msg.getFlags(true), true) .putHeader(this.id, new FragHeader(frag_id, i, num_frags)); down_prot.down(frag_msg); } } catch(Exception e) { log.error(Util.getMessage("ExceptionOccurredTryingToFragmentMessage"), e); } } /** * 1. Get all the fragment buffers * 2. When all are received -> Assemble them into one big buffer * 3. Read headers and byte buffer from big buffer * 4. Set headers and buffer in msg * 5. Pass msg up the stack */ private Message unfragment(Message msg, FragHeader hdr) { Address sender=msg.getSrc(); FragmentationTable frag_table=fragment_list.get(sender); if(frag_table == null) { frag_table=new FragmentationTable(sender); try { fragment_list.add(sender, frag_table); } catch(IllegalArgumentException x) { // the entry has already been added, probably in parallel from another thread frag_table=fragment_list.get(sender); } } num_frags_received.add(1); byte[] buf=frag_table.add(hdr.id, hdr.frag_id, hdr.num_frags, msg.getArray()); if(buf == null) return null; try { Message assembled_msg=Util.messageFromBuffer(buf, 0, buf.length, msg_factory); assembled_msg.setSrc(sender); // needed ? YES, because fragments have a null src !! if(log.isTraceEnabled()) log.trace("assembled_msg is " + assembled_msg); num_received_msgs++; return assembled_msg; } catch(Exception e) { log.error(Util.getMessage("FailedUnfragmentingAMessage"), e); return null; } } /** * A fragmentation list keeps a list of fragmentation tables * sorted by an Address ( the sender ). * This way, if the sender disappears or leaves the group half way * sending the content, we can simply remove this members fragmentation * table and clean up the memory of the receiver. * We do not have to do the same for the sender, since the sender doesn't keep a fragmentation table */ static class FragmentationList { /* initialize the hashtable to hold all the fragmentation tables * 11 is the best growth capacity to start with<br/> * HashMap<Address,FragmentationTable> */ private final HashMap<Address,FragmentationTable> frag_tables=new HashMap<>(11); /** * Adds a fragmentation table for this particular sender * If this sender already has a fragmentation table, an IllegalArgumentException * will be thrown. * @param sender - the address of the sender, cannot be null * @param table - the fragmentation table of this sender, cannot be null * @throws IllegalArgumentException if an entry for this sender already exist */ public void add(Address sender, FragmentationTable table) throws IllegalArgumentException { synchronized(frag_tables) { FragmentationTable healthCheck=frag_tables.get(sender); if(healthCheck == null) { frag_tables.put(sender, table); } else { throw new IllegalArgumentException("Sender <" + sender + "> already exists in the fragementation list"); } } } /** * returns a fragmentation table for this sender * returns null if the sender doesn't have a fragmentation table * @return the fragmentation table for this sender, or null if no table exist */ public FragmentationTable get(Address sender) { synchronized(frag_tables) { return frag_tables.get(sender); } } /** * returns true if this sender already holds a * fragmentation for this sender, false otherwise * @param sender - the sender, cannot be null * @return true if this sender already has a fragmentation table */ public boolean containsSender(Address sender) { synchronized(frag_tables) { return frag_tables.containsKey(sender); } } /** * removes the fragmentation table from the list. * after this operation, the fragementation list will no longer * hold a reference to this sender's fragmentation table * @param sender - the sender who's fragmentation table you wish to remove, cannot be null * @return true if the table was removed, false if the sender doesn't have an entry */ public boolean remove(Address sender) { synchronized(frag_tables) { boolean result=containsSender(sender); frag_tables.remove(sender); return result; } } /** * returns a list of all the senders that have fragmentation tables opened. * @return an array of all the senders in the fragmentation list */ public Address[] getSenders() { Address[] result; int index=0; synchronized(frag_tables) { result=new Address[frag_tables.size()]; for(Iterator<Address> it=frag_tables.keySet().iterator(); it.hasNext();) { result[index++]=it.next(); } } return result; } public String toString() { StringBuilder buf=new StringBuilder("Fragmentation list contains "); synchronized(frag_tables) { buf.append(frag_tables.size()).append(" tables\n"); for(Iterator<Entry<Address,FragmentationTable>> it=frag_tables.entrySet().iterator(); it.hasNext();) { Entry<Address,FragmentationTable> entry=it.next(); buf.append(entry.getKey()).append(": " ).append(entry.getValue()).append("\n"); } } return buf.toString(); } } /** * Keeps track of the fragments that are received. * Reassembles fragements into entire messages when all fragments have been received. * The fragmentation holds a an array of byte arrays for a unique sender * The first dimension of the array is the order of the fragmentation, in case the arrive out of order */ static class FragmentationTable { private final Address sender; /* the hashtable that holds the fragmentation entries for this sender*/ private final Map<Long,FragEntry> table=new HashMap<>(11); // keys: frag_ids, vals: Entrys FragmentationTable(Address sender) { this.sender=sender; } /** * inner class represents an entry for a message * each entry holds an array of byte arrays sorted * once all the byte buffer entries have been filled * the fragmentation is considered complete. */ static class FragEntry { //the total number of fragment in this message int tot_frags=0; // each fragment is a byte buffer byte[][] fragments=null; //the number of fragments we have received int number_of_frags_recvd=0; // the message ID long msg_id=-1; /** * Creates a new entry * * @param tot_frags the number of fragments to expect for this message */ FragEntry(long msg_id, int tot_frags) { this.msg_id=msg_id; this.tot_frags=tot_frags; fragments=new byte[tot_frags][]; for(int i=0; i < tot_frags; i++) { fragments[i]=null; } } /** * adds on fragmentation buffer to the message * * @param frag_id the number of the fragment being added 0..(tot_num_of_frags - 1) * @param frag the byte buffer containing the data for this fragmentation, should not be null */ public void set(int frag_id, byte[] frag) { fragments[frag_id]=frag; number_of_frags_recvd++; } /** * returns true if this fragmentation is complete * ie, all fragmentations have been received for this buffer */ public boolean isComplete() { /*first make the simple check*/ if(number_of_frags_recvd < tot_frags) { return false; } /*then double check just in case*/ for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) return false; } /*all fragmentations have been received*/ return true; } /** * Assembles all the fragmentations into one buffer * this method does not check if the fragmentation is complete * * @return the complete message in one buffer */ public byte[] assembleBuffer() { return Util.defragmentBuffer(fragments); } /** * debug only */ public String toString() { StringBuilder ret=new StringBuilder(); ret.append("[tot_frags=").append(tot_frags).append(", number_of_frags_recvd=").append(number_of_frags_recvd).append(']'); return ret.toString(); } public int hashCode() { return super.hashCode(); } } /** * Creates a new entry if not yet present. Adds the fragment. If all fragements for a given message have been * received, an entire message is reassembled and returned. Otherwise null is returned. * * @param id - the message ID, unique for a sender * @param frag_id the index of this fragmentation (0..tot_frags-1) * @param tot_frags the total number of fragmentations expected * @param fragment - the byte buffer for this fragment */ public synchronized byte[] add(long id, int frag_id, int tot_frags, byte[] fragment) { byte[] retval=null; // initialize the return value to default not complete FragEntry e=table.get(id); if(e == null) { // Create new entry if not yet present e=new FragEntry(id, tot_frags); table.put(id,e); } e.set(frag_id, fragment); if(e.isComplete()) { retval=e.assembleBuffer(); table.remove(id); } return retval; } public String toString() { StringBuilder buf=new StringBuilder("Fragmentation Table Sender:").append(sender).append("\n\t"); for(FragEntry entry: table.values()) { int count=0; for(int i=0; i < entry.fragments.length; i++) { if(entry.fragments[i] != null) count++; } buf.append("Message ID:").append(entry.msg_id).append("\n\t"); buf.append("Total Frags:").append(entry.tot_frags).append("\n\t"); buf.append("Frags Received:").append(count).append("\n\n"); } return buf.toString(); } } }
/* Copyright (c) 2009 ZOHO Corp. All Rights Reserved. * PLEASE READ THE ASSOCIATED COPYRIGHTS FILE FOR MORE DETAILS. * ZOHO CORPORATION MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * ZOHO CORPORATION SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE * OR ITS DERIVATIVES. */ /** * @Version : 6.0.3 Sat Nov 29 15:51:16 BRST 2014 * @Author : WebNMS Agent Toolkit Java Edition */ // Any changes made to this file will be lost, if regenerated. // User code should be added within user tags for code merging support, if regenerated. // Package Name (Dont Delete this comment) package com.ufrgs.gerencia.agent; // SNMP API Imports import com.adventnet.snmp.snmp2.SnmpAPI; import com.adventnet.snmp.snmp2.SnmpVar; import com.adventnet.snmp.snmp2.SnmpVarBind; import com.adventnet.snmp.snmp2.SnmpInt; // SNMP Agent API Imports import com.adventnet.snmp.snmp2.agent.AgentNode; import com.adventnet.snmp.snmp2.agent.AgentSnmpException; import com.adventnet.snmp.snmp2.agent.AgentUtil; import com.adventnet.snmp.snmp2.agent.SimpleRequestHandler; import com.adventnet.snmp.snmp2.agent.VarBindRequestEvent; import com.adventnet.snmp.snmp2.agent.VarBindAndFailure; // Agent Utility API Imports import com.adventnet.utils.agent.utils; import com.adventnet.utils.agent.ScalarModelListener; import com.adventnet.utilities.common.AgentException; // Java Imports import java.util.Hashtable; import java.util.Vector; /** * Handles all requests under * apartment group */ public class ApartmentRequestHandler extends SimpleRequestHandler{ final static int APCOUNT = 1; private final static int[]apartmentOidRep = {1,3,6,1,4,1,12619,1,1}; /** * To get OID array of this Scalar Group * @return OID array of this Scalar Group */ public static int[] getApartmentOidRep(){ return apartmentOidRep; } // This is generated to preserve the old API public int[] getOidRep(){ return getApartmentOidRep(); } public CondominioAgent agentName; /** * Used for retreiving Sub-Ids of the Attributes in this Scalar Group * @return array of Sub-Ids of the Attributes in this Scalar group */ protected int[] getSubidList(){ int[] subidList = {1,}; return subidList; } ApartmentInstrument instrument = null; public void setApartmentInstrument(ApartmentInstrument instrument){ this.instrument = instrument; this.addInstrumentHandler(instrument); } public ApartmentRequestHandler(CondominioAgent agentRef){ agentName = agentRef; } private Hashtable objectHash; private Hashtable objectTypeHash; /** * Used for retreiving Sub-Ids of the Attributes in this Scalar Group * @return Hashtable having AttributeName(String) - SubId(Integer) pairs */ public Hashtable getObjectHash(){ if(objectHash == null){ objectHash = new Hashtable(); objectHash.put("APCOUNT",new Integer(1)); } return objectHash; } /** * Used for retreiving Syntax-Types of the Attributes in this Scalar Group * @return Hashtable having AttributeName(String) - Syntax Type(Integer) pairs */ public Hashtable getObjectTypeHash(){ if(objectTypeHash == null){ objectTypeHash = new Hashtable(); objectTypeHash.put("APCOUNT",new Integer(2)); } return objectTypeHash; } /** * This method is used for processing the incoming GET Requests * @param listOfVarbinds List of SnmpVarbinds for which GET Request is to be performed * @param listOfNodes List of AgentNodes for which GET Request is to be performed * @param pe VarbindRequestEvent */ protected void processGetRequest(Vector listOfVarbinds, Vector listOfNodes, VarBindRequestEvent pe) { SnmpVarBind varb = null; AgentNode node = null; Vector failedList = new Vector(); Vector listOfColumns = new Vector(); int nodeSize = listOfNodes.size(); for(int i=0;i<nodeSize;i++){ try{ node = (AgentNode)listOfNodes.elementAt(i); varb =(SnmpVarBind) listOfVarbinds.elementAt(i); if(node == null){ AgentUtil.throwNoSuchInstance(pe.getVersion()); } int[] oid = (int[] )varb.getObjectID().toValue(); if(oid.length != apartmentOidRep.length + 2){ AgentUtil.throwNoSuchInstance(pe.getVersion()); } int[] inst = AgentUtil.getInstance(oid,apartmentOidRep.length); if(inst[1] != 0){ AgentUtil.throwNoSuchInstance(pe.getVersion()); } listOfColumns.addElement(new Integer(node.getSubId())); }catch(Exception exp){ if(exp instanceof AgentException){ AgentException ae = (AgentException )exp; AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae); failedList.addElement(new VarBindAndFailure(ase,i)); } else if(exp instanceof AgentSnmpException){ failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,i)); } else{ failedList.addElement(new VarBindAndFailure( new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,i)); } utils.handleError(exp); listOfColumns.addElement(new Integer(-1)); } } // end of for loop if(listOfColumns.size() > 0) { getValuesFromInstrument(pe,listOfVarbinds,listOfColumns,failedList); } if(!pe.isRollback()){ pe.setFailedList(failedList); } } /** * This method is used for processing the incoming SET Requests * @param listOfVarbinds List of SnmpVarbinds for which SET Request is to be performed * @param listOfNodes List of Agent Nodes for which SET Request is to be performed * @param pe VarbindRequest Event */ protected void processSetRequest(Vector listOfVarbinds, Vector listOfNodes, VarBindRequestEvent pe) { SnmpVarBind varb = null; AgentNode node = null; Vector failedList = new Vector(); Hashtable toSendHash = new Hashtable(); Vector indexList = new Vector(); Hashtable indexHash = new Hashtable(); Vector trapVector = new Vector(); int nodeSize = listOfNodes.size(); for(int i=0;i<nodeSize;i++){ try{ node = (AgentNode)listOfNodes.elementAt(i); varb =(SnmpVarBind) listOfVarbinds.elementAt(i); if(node == null){ AgentUtil.throwNoCreation(pe.getVersion()); } int[] oid = (int[] )varb.getObjectID().toValue(); if(oid.length != apartmentOidRep.length + 2){ AgentUtil.throwNoCreation(pe.getVersion()); } int[] inst = AgentUtil.getInstance(oid,apartmentOidRep.length); if(inst[1] != 0){ AgentUtil.throwNoCreation(pe.getVersion()); } indexHash.put(new Integer(node.getSubId()),new Integer(i)); SnmpVar var = varb.getVariable(); switch(node.getSubId()){ case APCOUNT: AgentUtil.throwNotWritable(pe.getVersion()); break; default: AgentUtil.throwNoSuchInstance(pe.getVersion()); } }catch(Exception exp){ if(exp instanceof AgentException){ AgentException ae = (AgentException )exp; AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae); failedList.addElement(new VarBindAndFailure(ase,i)); } else if(exp instanceof AgentSnmpException){ failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,i)); } else{ failedList.addElement(new VarBindAndFailure( new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,i)); } utils.handleError(exp); break; } } if(toSendHash.size() > 0){ try{ instrumentHandler.setAttributes(toSendHash,indexList); }catch(Exception exp){ Integer temp = instrumentHandler.getFailedSubId(); temp = (Integer)indexHash.get(temp); if(exp instanceof AgentException){ AgentException ae = (AgentException )exp; AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae); failedList.addElement(new VarBindAndFailure(ase,temp.intValue())); } else{ failedList.addElement(new VarBindAndFailure( new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,temp.intValue())); } pe.setFailedList(failedList); return; } } pe.setFailedList(failedList); } /** * This method will be used for processing the Incoming GETNEXT Requests * @param listOfVarbinds List of SnmpVarbinds for which GETNEXT Request is to be performed * @param listOfNodes List of AgentNodes for which GETNEXT Request is to be performed * @param pe VarbindRequest Event */ protected void processGetNextRequest(Vector listOfVarbinds, Vector listOfNodes, VarBindRequestEvent pe) { SnmpVarBind varb = null; AgentNode node = null; Vector failedList = new Vector(); Vector listOfColumns = new Vector(); //Vector varbVector = new Vector(); int columnID; int nodeSize = listOfNodes.size(); for(int i=0;i<nodeSize;i++){ try{ node = (AgentNode)listOfNodes.elementAt(i); varb =(SnmpVarBind) listOfVarbinds.elementAt(i); if(node == null){ AgentUtil.throwNoNextObject(); } int[] oid = (int[] )varb.getObjectID().toValue(); columnID=node.getSubId(); if(oid.length >= apartmentOidRep.length + 2){ AgentUtil.throwNoNextObject(); } node = node.getNearestLeafCell(oid); listOfColumns.addElement(new Integer(node.getSubId())); }catch(Exception exp){ if(exp instanceof AgentException){ AgentException ae = (AgentException )exp; AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae); failedList.addElement(new VarBindAndFailure(ase,i)); } else if(exp instanceof AgentSnmpException){ failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,i)); } utils.handleError(exp); listOfColumns.addElement(new Integer(-1)); } } // end of for loop if(listOfColumns.size() > 0) { getValuesFromInstrument(pe,listOfVarbinds,listOfColumns,failedList); } pe.setFailedList(failedList); } /** * This method is used for getting the attribute values from Instrument file,while processing GET/GETNEXT requests * @param pe VarbindRequest Event * @param varbVector List of varbinds for which value is to be retreived * @return List of Objects for which GETNEXT is failed */ public void getValuesFromInstrument(VarBindRequestEvent pe, Vector varbVector,Vector columns,Vector failedList) { Hashtable valuesHash = new Hashtable(); int size = columns.size(); try{ valuesHash = instrumentHandler.getAttributes(columns.elements()); }catch(Exception exp) { // Exceptions occured during the getAttributes(Enumeration) call will be handled inside that method itself. // For missing values in 'valuesHash' , appropriate Snmp Error message will be propagated from inside the 'for loop' below. } SnmpVarBind varb=null; int columnID=0; for(int j=0; j< size; j++){ try{ Integer key = (Integer)columns.elementAt(j); if(key.equals(new Integer(-1))) { continue; } if( ! valuesHash.containsKey(key)) { AgentUtil.throwNoSuchInstance(pe.getVersion()); } columnID = key.intValue(); varb=(SnmpVarBind)varbVector.elementAt(j); Object toReturn = null; switch(columnID){ case APCOUNT: toReturn = valuesHash.get(new Integer(APCOUNT)); if(toReturn == null){ AgentUtil.throwNoSuchInstance(pe.getVersion()); } SnmpInt var0 = new SnmpInt(((Integer )toReturn).intValue()); varb.setVariable(var0); break; default: AgentUtil.throwNoSuchInstance(pe.getVersion()); } //end of switch }catch(Exception exp){ if(exp instanceof AgentException){ AgentException ae = (AgentException )exp; AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae); failedList.addElement(new VarBindAndFailure(ase,j)); } else if(exp instanceof AgentSnmpException){ failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,j)); } else{ failedList.addElement(new VarBindAndFailure( new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,j)); } utils.handleError(exp); } varb.setObjectID(AgentUtil.getScalarSnmpOID(apartmentOidRep, columnID)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.protocol.core.impl; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.Channel; import org.apache.activemq.artemis.core.protocol.core.ChannelHandler; import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.ServerSessionPacketHandler; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverReplyMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateQueueMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionResponseMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ReattachSessionMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ReattachSessionResponseMessage; import org.apache.activemq.artemis.core.security.ActiveMQPrincipal; import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.ServerSession; import org.apache.activemq.artemis.core.version.Version; import org.jboss.logging.Logger; /** * A packet handler for all packets that need to be handled at the server level */ public class ActiveMQPacketHandler implements ChannelHandler { private static final Logger logger = Logger.getLogger(ActiveMQPacketHandler.class); private final ActiveMQServer server; private final Channel channel1; private final CoreRemotingConnection connection; private final CoreProtocolManager protocolManager; public ActiveMQPacketHandler(final CoreProtocolManager protocolManager, final ActiveMQServer server, final Channel channel1, final CoreRemotingConnection connection) { this.protocolManager = protocolManager; this.server = server; this.channel1 = channel1; this.connection = connection; } @Override public void handlePacket(final Packet packet) { byte type = packet.getType(); switch (type) { case PacketImpl.CREATESESSION: { CreateSessionMessage request = (CreateSessionMessage) packet; handleCreateSession(request); break; } case PacketImpl.CHECK_FOR_FAILOVER: { CheckFailoverMessage request = (CheckFailoverMessage) packet; handleCheckForFailover(request); break; } case PacketImpl.REATTACH_SESSION: { ReattachSessionMessage request = (ReattachSessionMessage) packet; handleReattachSession(request); break; } case PacketImpl.CREATE_QUEUE: { // Create queue can also be fielded here in the case of a replicated store and forward queue creation CreateQueueMessage request = (CreateQueueMessage) packet; handleCreateQueue(request); break; } default: { ActiveMQServerLogger.LOGGER.invalidPacket(packet); } } } private void handleCheckForFailover(CheckFailoverMessage failoverMessage) { String nodeID = failoverMessage.getNodeID(); boolean okToFailover = nodeID == null || !(server.getHAPolicy().canScaleDown() && !server.hasScaledDown(new SimpleString(nodeID))); channel1.send(new CheckFailoverReplyMessage(okToFailover)); } private void handleCreateSession(final CreateSessionMessage request) { boolean incompatibleVersion = false; Packet response; try { Version version = server.getVersion(); if (!version.isCompatible(request.getVersion())) { throw ActiveMQMessageBundle.BUNDLE.incompatibleClientServer(); } if (!server.isStarted()) { throw ActiveMQMessageBundle.BUNDLE.serverNotStarted(); } // XXX HORNETQ-720 Taylor commented out this test. Should be verified. /*if (!server.checkActivate()) { throw new ActiveMQException(ActiveMQException.SESSION_CREATION_REJECTED, "Server will not accept create session requests"); }*/ if (connection.getClientVersion() == 0) { connection.setClientVersion(request.getVersion()); } else if (connection.getClientVersion() != request.getVersion()) { ActiveMQServerLogger.LOGGER.incompatibleVersionAfterConnect(request.getVersion(), connection.getClientVersion()); } Channel channel = connection.getChannel(request.getSessionChannelID(), request.getWindowSize()); ActiveMQPrincipal activeMQPrincipal = null; if (request.getUsername() == null) { activeMQPrincipal = connection.getDefaultActiveMQPrincipal(); } ServerSession session = server.createSession(request.getName(), activeMQPrincipal == null ? request.getUsername() : activeMQPrincipal.getUserName(), activeMQPrincipal == null ? request.getPassword() : activeMQPrincipal.getPassword(), request.getMinLargeMessageSize(), connection, request.isAutoCommitSends(), request.isAutoCommitAcks(), request.isPreAcknowledge(), request.isXA(), request.getDefaultAddress(), new CoreSessionCallback(request.getName(), protocolManager, channel, connection), true); ServerSessionPacketHandler handler = new ServerSessionPacketHandler(session, server.getStorageManager(), channel); channel.setHandler(handler); // TODO - where is this removed? protocolManager.addSessionHandler(request.getName(), handler); response = new CreateSessionResponseMessage(server.getVersion().getIncrementingVersion()); } catch (ActiveMQException e) { if (e.getType() == ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) { incompatibleVersion = true; logger.debug("Sending ActiveMQException after Incompatible client", e); } else { ActiveMQServerLogger.LOGGER.failedToCreateSession(e); } response = new ActiveMQExceptionMessage(e); } catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToCreateSession(e); response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException()); } // send the exception to the client and destroy // the connection if the client and server versions // are not compatible if (incompatibleVersion) { channel1.sendAndFlush(response); } else { channel1.send(response); } } private void handleReattachSession(final ReattachSessionMessage request) { Packet response = null; try { if (!server.isStarted()) { response = new ReattachSessionResponseMessage(-1, false); } logger.debug("Reattaching request from " + connection.getRemoteAddress()); ServerSessionPacketHandler sessionHandler = protocolManager.getSessionHandler(request.getName()); // HORNETQ-720 XXX ataylor? if (/*!server.checkActivate() || */ sessionHandler == null) { response = new ReattachSessionResponseMessage(-1, false); } else { if (sessionHandler.getChannel().getConfirmationWindowSize() == -1) { // Even though session exists, we can't reattach since confi window size == -1, // i.e. we don't have a resend cache for commands, so we just close the old session // and let the client recreate ActiveMQServerLogger.LOGGER.reattachRequestFailed(connection.getRemoteAddress()); sessionHandler.closeListeners(); sessionHandler.close(); response = new ReattachSessionResponseMessage(-1, false); } else { // Reconnect the channel to the new connection int serverLastConfirmedCommandID = sessionHandler.transferConnection(connection, request.getLastConfirmedCommandID()); response = new ReattachSessionResponseMessage(serverLastConfirmedCommandID, true); } } } catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToReattachSession(e); response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException()); } channel1.send(response); } private void handleCreateQueue(final CreateQueueMessage request) { try { server.createQueue(request.getAddress(), request.getQueueName(), request.getFilterString(), request.isDurable(), request.isTemporary()); } catch (Exception e) { ActiveMQServerLogger.LOGGER.failedToHandleCreateQueue(e); } } }
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.base.evaluators; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.drools.RuntimeDroolsException; import org.drools.base.BaseEvaluator; import org.drools.base.ValueType; import org.drools.common.EventFactHandle; import org.drools.common.InternalFactHandle; import org.drools.common.InternalWorkingMemory; import org.drools.rule.VariableRestriction.LongVariableContextEntry; import org.drools.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.rule.VariableRestriction.VariableContextEntry; import org.drools.spi.Evaluator; import org.drools.spi.FieldValue; import org.drools.spi.InternalReadAccessor; import org.drools.time.Interval; /** * <p>The implementation of the 'coincides' evaluator definition.</p> * * <p>The <b><code>coincides</code></b> evaluator correlates two events and matches when both * happen at the same time. Optionally, the evaluator accept thresholds for the distance between * events' start and finish timestamps.</p> * * <p>Lets look at an example:</p> * * <pre>$eventA : EventA( this coincides $eventB )</pre> * * <p>The previous pattern will match if and only if the start timestamps of both $eventA * and $eventB are the same AND the end timestamp of both $eventA and $eventB also are * the same.</p> * * <p>Optionally, this operator accepts one or two parameters. These parameters are the thresholds * for the distance between matching timestamps. If only one paratemer is given, it is used for * both start and end timestamps. If two parameters are given, then the first is used as a threshold * for the start timestamp and the second one is used as a threshold for the end timestamp. In other * words:</p> * * <pre> $eventA : EventA( this coincides[15s, 10s] $eventB ) </pre> * * Above pattern will match if and only if: * * <pre> * abs( $eventA.startTimestamp - $eventB.startTimestamp ) <= 15s && * abs( $eventA.endTimestamp - $eventB.endTimestamp ) <= 10s * </pre> * * <p><b>NOTE:</b> it makes no sense to use negative interval values for the parameters and the * engine will raise an error if that happens.</p> */ public class CoincidesEvaluatorDefinition implements EvaluatorDefinition { public static final Operator COINCIDES = Operator.addOperatorToRegistry( "coincides", false ); public static final Operator COINCIDES_NOT = Operator.addOperatorToRegistry( "coincides", true ); private static final String[] SUPPORTED_IDS = {COINCIDES.getOperatorString()}; private Map<String, CoincidesEvaluator> cache = Collections.emptyMap(); private volatile TimeIntervalParser parser = new TimeIntervalParser(); @SuppressWarnings("unchecked") public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { cache = (Map<String, CoincidesEvaluator>) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( cache ); } /** * @inheridDoc */ public Evaluator getEvaluator(ValueType type, Operator operator) { return this.getEvaluator( type, operator.getOperatorString(), operator.isNegated(), null ); } /** * @inheridDoc */ public Evaluator getEvaluator(ValueType type, Operator operator, String parameterText) { return this.getEvaluator( type, operator.getOperatorString(), operator.isNegated(), parameterText ); } /** * @inheritDoc */ public Evaluator getEvaluator(final ValueType type, final String operatorId, final boolean isNegated, final String parameterText) { return this.getEvaluator( type, operatorId, isNegated, parameterText, Target.HANDLE, Target.HANDLE ); } /** * @inheritDoc */ public Evaluator getEvaluator(final ValueType type, final String operatorId, final boolean isNegated, final String parameterText, final Target left, final Target right) { if ( this.cache == Collections.EMPTY_MAP ) { this.cache = new HashMap<String, CoincidesEvaluator>(); } String key = left + ":" + right + ":" + isNegated + ":" + parameterText; CoincidesEvaluator eval = this.cache.get( key ); if ( eval == null ) { Long[] params = parser.parse( parameterText ); eval = new CoincidesEvaluator( type, isNegated, params, parameterText, left == Target.FACT, right == Target.FACT ); this.cache.put( key, eval ); } return eval; } /** * @inheritDoc */ public String[] getEvaluatorIds() { return SUPPORTED_IDS; } /** * @inheritDoc */ public boolean isNegatable() { return true; } /** * @inheritDoc */ public Target getTarget() { return Target.BOTH; } /** * @inheritDoc */ public boolean supportsType(ValueType type) { // supports all types, since it operates over fact handles // Note: should we change this interface to allow checking of event classes only? return true; } /** * Implements the 'coincides' evaluator itself */ public static class CoincidesEvaluator extends BaseEvaluator { private static final long serialVersionUID = 510l; private long startDev; private long endDev; private String paramText; private boolean unwrapLeft; private boolean unwrapRight; public CoincidesEvaluator() { } public CoincidesEvaluator(final ValueType type, final boolean isNegated, final Long[] parameters, final String paramText, final boolean unwrapLeft, final boolean unwrapRight) { super( type, isNegated ? COINCIDES_NOT : COINCIDES ); this.paramText = paramText; this.unwrapLeft = unwrapLeft; this.unwrapRight = unwrapRight; this.setParameters( parameters ); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal( in ); startDev = in.readLong(); endDev = in.readLong(); unwrapLeft = in.readBoolean(); unwrapRight = in.readBoolean(); paramText = (String) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal( out ); out.writeLong( startDev ); out.writeLong( endDev ); out.writeBoolean( unwrapLeft ); out.writeBoolean( unwrapRight ); out.writeObject( paramText ); } @Override public Object prepareLeftObject(InternalFactHandle handle) { return unwrapLeft ? handle.getObject() : handle; } @Override public Object prepareRightObject(InternalFactHandle handle) { return unwrapRight ? handle.getObject() : handle; } @Override public boolean isTemporal() { return true; } @Override public Interval getInterval() { if ( this.getOperator().isNegated() ) { return new Interval( Interval.MIN, Interval.MAX ); } return new Interval( 0, 0 ); } public boolean evaluate(InternalWorkingMemory workingMemory, final InternalReadAccessor extractor, final Object object1, final FieldValue object2) { throw new RuntimeDroolsException( "The 'coincides' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if ( context.rightNull ) { return false; } long rightStartTS, rightEndTS; long leftStartTS, leftEndTS; if ( this.unwrapRight ) { if ( context instanceof ObjectVariableContextEntry ) { if ( ((ObjectVariableContextEntry) context).right instanceof Date ) { rightStartTS = ((Date) ((ObjectVariableContextEntry) context).right).getTime(); } else { rightStartTS = ((Number) ((ObjectVariableContextEntry) context).right).longValue(); } } else { rightStartTS = ((LongVariableContextEntry) context).right; } rightEndTS = rightStartTS; } else { rightStartTS = ((EventFactHandle) ((ObjectVariableContextEntry) context).right).getStartTimestamp(); rightEndTS = ((EventFactHandle) ((ObjectVariableContextEntry) context).right).getEndTimestamp(); } leftStartTS = this.unwrapLeft ? context.declaration.getExtractor().getLongValue( workingMemory, left ) : ((EventFactHandle) left).getStartTimestamp(); leftEndTS = this.unwrapLeft ? rightStartTS : ((EventFactHandle) left).getEndTimestamp(); long distStart = Math.abs( rightStartTS - leftStartTS ); long distEnd = Math.abs( rightEndTS - leftEndTS ); return this.getOperator().isNegated() ^ (distStart <= this.startDev && distEnd <= this.endDev); } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if ( context.extractor.isNullValue( workingMemory, right ) ) { return false; } long rightStartTS, rightEndTS; long leftStartTS, leftEndTS; rightStartTS = this.unwrapRight ? context.extractor.getLongValue( workingMemory, right ) : ((EventFactHandle) right).getStartTimestamp(); rightEndTS = this.unwrapRight ? rightStartTS : ((EventFactHandle) right).getEndTimestamp(); if ( this.unwrapLeft ) { if ( context instanceof ObjectVariableContextEntry ) { if ( ((ObjectVariableContextEntry) context).left instanceof Date ) { leftStartTS = ((Date) ((ObjectVariableContextEntry) context).left).getTime(); } else { leftStartTS = ((Number) ((ObjectVariableContextEntry) context).left).longValue(); } } else { leftStartTS = ((LongVariableContextEntry) context).left; } leftEndTS = leftStartTS; } else { leftStartTS = ((EventFactHandle) ((ObjectVariableContextEntry) context).left).getStartTimestamp(); leftEndTS = ((EventFactHandle) ((ObjectVariableContextEntry) context).left).getEndTimestamp(); } long distStart = Math.abs( rightStartTS - leftStartTS ); long distEnd = Math.abs( rightEndTS - leftEndTS ); return this.getOperator().isNegated() ^ (distStart <= this.startDev && distEnd <= this.endDev); } public boolean evaluate(InternalWorkingMemory workingMemory, final InternalReadAccessor extractor1, final Object object1, final InternalReadAccessor extractor2, final Object object2) { if ( extractor1.isNullValue( workingMemory, object1 ) ) { return false; } long rightStartTS, rightEndTS; long leftStartTS, leftEndTS; rightStartTS = this.unwrapRight ? extractor1.getLongValue( workingMemory, object1 ) : ((EventFactHandle) object1).getStartTimestamp(); rightEndTS = this.unwrapRight ? rightStartTS : ((EventFactHandle) object1).getEndTimestamp(); leftStartTS = this.unwrapLeft ? extractor2.getLongValue( workingMemory, object2 ) : ((EventFactHandle) object2).getStartTimestamp(); leftEndTS = this.unwrapLeft ? leftStartTS : ((EventFactHandle) object2).getEndTimestamp(); long distStart = Math.abs( rightStartTS - leftStartTS ); long distEnd = Math.abs( rightEndTS - leftEndTS ); return this.getOperator().isNegated() ^ (distStart <= this.startDev && distEnd <= this.endDev); } public String toString() { return "coincides[" + startDev + ", " + endDev + "]"; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); result = PRIME * result + (int) (endDev ^ (endDev >>> 32)); result = PRIME * result + (int) (startDev ^ (startDev >>> 32)); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( !super.equals( obj ) ) return false; if ( getClass() != obj.getClass() ) return false; final CoincidesEvaluator other = (CoincidesEvaluator) obj; return endDev == other.endDev && startDev == other.startDev; } /** * This methods sets the parameters appropriately. * * @param parameters */ private void setParameters(Long[] parameters) { if ( parameters == null || parameters.length == 0 ) { // open bounded range this.startDev = 0; this.endDev = 0; return; } else { for ( Long param : parameters ) { if ( param.longValue() < 0 ) { throw new RuntimeDroolsException( "[Coincides Evaluator]: negative values not allowed for temporal distance thresholds: '" + paramText + "'" ); } } if ( parameters.length == 1 ) { // same deviation for both this.startDev = parameters[0].longValue(); this.endDev = parameters[0].longValue(); } else if ( parameters.length == 2 ) { // different deviation this.startDev = parameters[0].longValue(); this.endDev = parameters[1].longValue(); } else { throw new RuntimeDroolsException( "[Coincides Evaluator]: Not possible to have more than 2 parameters: '" + paramText + "'" ); } } } } }
package ru.job4j.storage; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ru.job4j.models.Admin; import ru.job4j.models.User; import ru.job4j.models.Viewer; import java.io.InputStream; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by Intellij IDEA. * User: Vitaly Zubov * Email: Zubov.VP@yandex.ru * Version: $Id$ * Date: 01.01.2019 */ public class DBStore implements Store<User> { private static final BasicDataSource SOURCE = new BasicDataSource(); private static final DBStore INSTANCE = new DBStore(); private static final Logger LOGGER = LogManager.getLogger(DBStore.class.getName()); private static final String CREATE_TABLE1 = "CREATE TABLE users(id SERIAL PRIMARY KEY, name CHARACTER VARYING(50) NOT NULL , login CHARACTER VARYING(50) NOT NULL UNIQUE, email CHARACTER VARYING(50) NOT NULL UNIQUE, createDate TIMESTAMP NOT NULL, password CHARACTER VARYING(32) NOT NUll, role CHARACTER VARYING(20) NOT NUll);"; private static final String CREATE_TABLE2 = "CREATE TABLE places (id SERIAL PRIMARY KEY, country CHARACTER VARYING(50) NOT NULL, city CHARACTER VARYING(50) NOT NULL, id_user INTEGER REFERENCES users(id) UNIQUE);"; private static boolean createTable1 = false; private static boolean createTable2 = false; private static final Encryption ENCRYPT = Encryption.getInstance(); public static DBStore getInstance() { return INSTANCE; } /** * Constructor. */ private DBStore() { try (InputStream in = getClass().getClassLoader().getResourceAsStream("db.properties")) { Properties props = new Properties(); props.load(in); Class.forName(props.getProperty("driver-class-name")); SOURCE.setUrl(props.getProperty("url")); SOURCE.setUsername(props.getProperty("username")); SOURCE.setPassword(props.getProperty("password")); SOURCE.setMinIdle(5); SOURCE.setMaxIdle(10); SOURCE.setMaxOpenPreparedStatements(100); } catch (Exception e) { LOGGER.error("Failed to obtain JDBC connection {}.", SOURCE.getUrl()); } } /** * Add element in the database. * * @param user - user. * @return - result. */ @Override public boolean add(User user) { checkTable(); try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("INSERT INTO users(name, login, email, createDate, password, role) VALUES(?, ?, ?, ?, ?, ?)"); PreparedStatement st2 = conn.prepareStatement("INSERT INTO places(country, city, id_user) VALUES(?, ?,?)")) { st.setString(1, user.getName()); st.setString(2, user.getLogin()); st.setString(3, user.getEmail()); st.setTimestamp(4, new Timestamp(user.getCreateDate().getTime())); st.setString(5, ENCRYPT.encrypt(user.getPassword())); st.setString(6, user.getRole()); st.executeUpdate(); st2.setString(1, user.getCountry()); st2.setString(2, user.getCity()); st2.setInt(3, findIdByLogin(user.getLogin())); st2.executeUpdate(); } catch (SQLException e) { LOGGER.error("Failed to add element in the DataBase. User - name = {}, login = {}, email = {}.", user.getName(), user.getLogin(), user.getEmail()); throw new IncorrectDateException(); } return true; } /** * Update element in the database. * * @param user - user. * @return -result. */ @Override public boolean update(User user) { checkTable(); if (user.getRole().equals("admin")) { try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("UPDATE users SET name = ?, login = ?, email = ?, password = ?, role = ? WHERE id = ?"); PreparedStatement st2 = conn.prepareStatement("UPDATE places SET country = ?, city = ? WHERE id_user = ?")) { st.setString(1, user.getName()); st.setString(2, user.getLogin()); st.setString(3, user.getEmail()); st.setString(4, ENCRYPT.encrypt(user.getPassword())); st.setString(5, user.getRole()); st.setInt(6, user.getId()); st.executeUpdate(); st2.setString(1, user.getCountry()); st2.setString(2, user.getCity()); st2.setInt(3, user.getId()); st2.executeUpdate(); } catch (SQLException e) { LOGGER.error("Failed to update element in the DataBase. User - id = {}, login = {}.", user.getId(), user.getLogin()); throw new IncorrectDateException(); } } else if (user.getRole().equals("viewer")) { try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("UPDATE users SET name = ?, login = ?, email = ?, password = ? WHERE id = ?"); PreparedStatement st2 = conn.prepareStatement("UPDATE places SET country = ?, city = ? WHERE id_user = ?")) { st.setString(1, user.getName()); st.setString(2, user.getLogin()); st.setString(3, user.getEmail()); st.setString(4, ENCRYPT.encrypt(user.getPassword())); st.setInt(5, user.getId()); st.executeUpdate(); st2.setString(1, user.getCountry()); st2.setString(2, user.getCity()); st2.setInt(3, user.getId()); st2.executeUpdate(); } catch (SQLException e) { LOGGER.error("Failed to update element in the DataBase. User - id = {}, login = {}.", user.getId(), user.getLogin()); throw new IncorrectDateException(); } } return true; } /** * Delete element in the database. * * @param id - id of the user. * @return - result. */ @Override public boolean delete(int id) { try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("DELETE FROM places WHERE id_user = ?"); PreparedStatement st2 = conn.prepareStatement("DELETE FROM users WHERE id = ?")) { st.setInt(1, id); st.executeUpdate(); st2.setInt(1, id); st2.executeUpdate(); } catch (SQLException e) { LOGGER.error("Error to delete user from the DataBase. Id = {}.", id); return false; } return true; } /** * Return all the users in the database. * * @return - all users. */ @Override public List<User> findAll() { checkTable(); List<User> result = new ArrayList<>(); try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("SELECT * FROM users INNER JOIN places ON (users.id = places.id_user)"); ResultSet rs = st.executeQuery()) { while (rs.next()) { if (rs.getString("role").equals("admin")) { result.add(new Admin(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(rs.getTimestamp("createdate").getTime()), rs.getString("role"), rs.getString("country"), rs.getString("city"))); } else if (rs.getString("role").equals("viewer")) { result.add(new Viewer(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(rs.getTimestamp("createdate").getTime()), rs.getString("role"), rs.getString("country"), rs.getString("city"))); } } } catch (SQLException e) { LOGGER.error("Failed to get all the elements from Database."); } return result; } /** * Find by id of the element. * * @param id - id of the element. * @return - user. */ @Override public User findById(int id) { checkTable(); User resultId = null; try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("SELECT * FROM users INNER JOIN places ON (users.id = places.id_user) WHERE id_user = ?")) { st.setInt(1, id); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { if (rs.getString("role").equals("admin")) { resultId = new Admin(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(rs.getTimestamp("createdate").getTime()), rs.getString("role"), rs.getString("country"), rs.getString("city")); } else if (rs.getString("role").equals("viewer")) { resultId = new Viewer(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(rs.getTimestamp("createdate").getTime()), rs.getString("role"), rs.getString("country"), rs.getString("city")); } } } } catch (SQLException e) { LOGGER.error("Failed to find by id. Id = {}.", id); } return resultId; } /** * Check login and password from the DB. * * @param login - login. * @param password - password. * @return - result. */ @Override public boolean isCredentional(String login, String password) { String ps = null; boolean result; try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("SELECT password FROM users WHERE login = ?")) { st.setString(1, login); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { ps = rs.getString("password"); } } } catch (SQLException e) { LOGGER.error("Failed to find login. Login = {}.", login); } result = ENCRYPT.encrypt(password).equals(ps); return result; } /** * Close connection. */ @Override public void close() { try { SOURCE.close(); } catch (SQLException e) { LOGGER.error("Failed to close BasicDataSource"); } } /** * Find user by login of the element. * * @param login - login. * @return - user. */ @Override public User findByLogin(String login) { User user = null; try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("SELECT * FROM users INNER JOIN places ON (users.id = places.id_user) WHERE login = ?")) { st.setString(1, login); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { if (rs.getString("role").equals("admin")) { user = new Admin(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(rs.getTimestamp("createdate").getTime()), rs.getString("role"), rs.getString("country"), rs.getString("city")); } else if (rs.getString("role").equals("viewer")) { user = new Viewer(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(rs.getTimestamp("createdate").getTime()), rs.getString("role"), rs.getString("country"), rs.getString("city")); } } } } catch (SQLException e) { LOGGER.error("Failed to find login. Login = {}.", login); } return user; } /** * Check table existence. */ private void checkTable() { if (!createTable1) { createTable(CREATE_TABLE1, "users"); createTable1 = true; } if (!createTable2) { createTable(CREATE_TABLE2, "places"); createTable2 = true; } } /** * Create a table. * * @param textCreate - SQL command. */ private void createTable(String textCreate, String tableName) { try (Connection conn = SOURCE.getConnection()) { DatabaseMetaData dbm = conn.getMetaData(); ResultSet rs = dbm.getTables(null, null, tableName, null); if (!rs.next()) { PreparedStatement st = conn.prepareStatement(textCreate); st.executeUpdate(); } } catch (SQLException e) { LOGGER.error(e.getMessage(), e); } } private int findIdByLogin(String login) { int id = 0; try (Connection conn = SOURCE.getConnection(); PreparedStatement st = conn.prepareStatement("SELECT id FROM users WHERE login = ?")) { st.setString(1, login); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { id = rs.getInt("id"); } } } catch (SQLException e) { LOGGER.error("Failed to find login. Login = {}.", login); } return id; } }
/** * Copyright (C) 2014 Stratio (http://stratio.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.stratio.ingestion.sink.mongodb; import static org.fest.assertions.Assertions.assertThat; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.Transaction; import org.apache.flume.channel.MemoryChannel; import org.apache.flume.conf.Configurables; import org.apache.flume.event.EventBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.fakemongo.Fongo; import com.google.common.base.Charsets; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; @RunWith(JUnit4.class) public class MongoSinkTest { private Fongo fongo; private MongoSink mongoSink; private Channel channel; private void setField(Object obj, String fieldName, Object val) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, val); field.setAccessible(false); } private void injectFongo(MongoSink mongoSink) { try { MongoClient mongoClient = fongo.getMongo(); DB mongoDefaultDb = mongoClient.getDB("test"); DBCollection mongoDefaultCollection = mongoDefaultDb.getCollection("test"); setField(mongoSink, "mongoClient", mongoClient); setField(mongoSink, "mongoDefaultDb", mongoDefaultDb); setField(mongoSink, "mongoDefaultCollection", mongoDefaultCollection); } catch (Exception ex) { throw new RuntimeException(ex); } } @Before public void prepareMongo() throws Exception { fongo = new Fongo("mongo test server"); Context mongoContext = new Context(); mongoContext.put("batchSize", "1"); mongoContext.put("mappingFile", "/mapping_definition_1.json"); mongoContext.put("mongoUri", "INJECTED"); mongoSink = new MongoSink(); injectFongo(mongoSink); Configurables.configure(mongoSink, mongoContext); Context channelContext = new Context(); channelContext.put("capacity", "10000"); channelContext.put("transactionCapacity", "200"); channel = new MemoryChannel(); channel.setName("junitChannel"); Configurables.configure(channel, channelContext); mongoSink.setChannel(channel); channel.start(); mongoSink.start(); } @After public void tearDownMongo() { channel.stop(); mongoSink.stop(); } @Test public void basicTest() throws Exception { Transaction tx = channel.getTransaction(); tx.begin(); ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance); jsonBody.put("myString", "foo"); jsonBody.put("myInt32", 32); Map<String, String> headers = new HashMap<String, String>(); headers.put("myString", "bar"); // Overwrites the value defined in JSON body headers.put("myInt64", "64"); headers.put("myBoolean", "true"); headers.put("myDouble", "1.0"); headers.put("myNull", null); Date myDate = new Date(); headers.put("myDate", Long.toString(myDate.getTime())); headers.put("myString2", "baz"); Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers); channel.put(event); tx.commit(); tx.close(); mongoSink.process(); DBObject result = fongo.getDB("test").getCollection("test").findOne(); // System.out.println(result.toString()); assertThat(result).isNotNull(); assertThat(result.get("myString")).isEqualTo("bar"); assertThat(result.get("myInt32")).isEqualTo(32); assertThat(result.get("myInt32")).isInstanceOf(Integer.class); assertThat(result.get("myInt64")).isEqualTo(64L); assertThat(result.get("myInt64")).isInstanceOf(Long.class); assertThat(result.get("myBoolean")).isEqualTo(true); assertThat(result.get("myDouble")).isEqualTo(1.0); assertThat(result.get("myNull")).isNull(); assertThat(result.get("myDate")).isEqualTo(myDate); assertThat(result.get("myString2")).isNull(); assertThat(result.get("myStringMapped")).isEqualTo("baz"); } @Test public void emptyChannel() throws Exception { mongoSink.process(); assertThat(fongo.getDB("test").getCollection("test").count()).isEqualTo(0); } @Test public void batchSize() throws Exception { setField(mongoSink, "batchSize", 100); for (int i = 0; i < 200; i++) { Transaction tx = channel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody("{ }".getBytes(Charsets.UTF_8)); channel.put(event); tx.commit(); tx.close(); } mongoSink.process(); assertThat(fongo.getDB("test").getCollection("test").count()).isEqualTo(100); } @Test public void noFullBatch() throws Exception { setField(mongoSink, "batchSize", 5); for (int i = 0; i < 3; i++) { Transaction tx = channel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody("{ }".getBytes(Charsets.UTF_8)); channel.put(event); tx.commit(); tx.close(); } mongoSink.process(); assertThat(fongo.getDB("test").getCollection("test").count()).isEqualTo(3); } @Test(expected = MongoSinkException.class) public void errorOnProcess() throws Exception { DBCollection mockedCollection = Mockito.mock(DBCollection.class); Mockito.when(mockedCollection.save(Mockito.any(DBObject.class))).thenThrow(Error.class); setField(mongoSink, "mongoDefaultCollection", mockedCollection); Transaction tx = channel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody("{ }".getBytes(Charsets.UTF_8)); channel.put(event); tx.commit(); tx.close(); mongoSink.process(); } @Test(expected = MongoSinkException.class) public void confSingleModeWithNoDefaultDB() throws Exception { final MongoSink mongoSink = new MongoSink(); final Context context = new Context(); context.put("dynamic", "false"); context.put("mongoUri", "mongodb://localhost:10000"); Configurables.configure(mongoSink, context); } @Test(expected = MongoSinkException.class) public void confSingleModeWithNoDefaultDBCollection() throws Exception { final MongoSink mongoSink = new MongoSink(); final Context context = new Context(); context.put("dynamic", "false"); context.put("mongoUri", "mongodb://localhost:10000/test"); Configurables.configure(mongoSink, context); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ibeeproject; import com.sun.rave.web.ui.appbase.AbstractFragmentBean; import ibeeproject.model.cajon.Cajon; import ibeeproject.persistencia.GestorCajon; import java.util.ArrayList; import javax.faces.FacesException; import javax.faces.component.UIParameter; /** * <p>Fragment bean that corresponds to a similarly named JSP page * fragment. This class contains component definitions (and initialization * code) for all components that you have defined on this fragment, as well as * lifecycle methods and event handlers where you may add behavior * to respond to incoming events.</p> * * @version consultarCajones.java * @version Created on 26-ago-2009, 18:40:06 * @author farias.facundo */ public class consultarCajones extends AbstractFragmentBean { // <editor-fold defaultstate="collapsed" desc="Managed Component Definition"> private String campoBusq; private ArrayList cajones = new ArrayList(); // private GestorCajon gestor = new GestorCajon(); private UIParameter parametro; /** * <p>Automatically managed component initialization. <strong>WARNING:</strong> * This method is automatically generated, so any user-specified code inserted * here is subject to being replaced.</p> */ private void _init() throws Exception { } // </editor-fold> public consultarCajones() { } /** * <p>Callback method that is called whenever a page containing * this page fragment is navigated to, either directly via a URL, * or indirectly via page navigation. Override this method to acquire * resources that will be needed for event handlers and lifecycle methods.</p> * * <p>The default implementation does nothing.</p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // Perform application initialization that must complete // *before* managed components are initialized // TODO - add your own initialiation code here // <editor-fold defaultstate="collapsed" desc="Visual-Web-managed Component Initialization"> // Initialize automatically managed components // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("Page1 Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e : new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here this.updateTable(); this.setCabecera(); } /** * <p>Callback method that is called after rendering is completed for * this request, if <code>init()</code> was called. Override this * method to release resources acquired in the <code>init()</code> * resources that will be needed for event handlers and lifecycle methods.</p> * * <p>The default implementation does nothing.</p> */ @Override public void destroy() { } public String add_action() { setCabecera("Home &raquo; Cajones &raquo; Agregar"); Cajones c = (Cajones) getBean("Cajones"); c.setAgregar(true); agregarCajon agregar = (agregarCajon) getBean("agregarCajon"); agregar.setCajon(new Cajon()); return null; } public String modif_action() { setCabecera("Home &raquo; Cajones &raquo; Modificar"); Cajones c = (Cajones) getBean("Cajones"); c.setModificar(true); Cajon cajon = (Cajon) this.parametro.getValue(); modificarCajon modificar = (modificarCajon) getBean("modificarCajon"); modificar.setCajon(cajon); return null; } public String delete_action() { setCabecera("Home &raquo; Cajones &raquo; Eliminar"); Cajones c = (Cajones) getBean("Cajones"); c.setEliminar(true); Cajon cajon = (Cajon) this.parametro.getValue(); eliminarCajon eliminar = (eliminarCajon) getBean("eliminarCajon"); eliminar.setCajon(cajon); return null; } public String query_action() { setCabecera("Home &raquo; Cajones &raquo; Consultar"); Cajones c = (Cajones) getBean("Cajones"); c.setConsultar(true); Cajon cajon = (Cajon) this.parametro.getValue(); consultarCajon consultar = (consultarCajon) getBean("consultarCajon"); consultar.setCajon(cajon); return null; } public String queryAll_action() { setCabecera(); Cajones c = (Cajones) getBean("Cajones"); c.setConsultarAll(true); return null; } /** * @return the cajones */ public ArrayList getCajones() { return cajones; } /** * @param cajones the cajones to set */ public void setCajones(ArrayList cajones) { this.cajones = cajones; } public void updateTable() { this.getCajones().clear(); GestorCajon gestor = new GestorCajon(); setCajones(gestor.getTodos()); } // /** // * @return the gestor // */ // public GestorCajon getGestor() { // return gestor; // } // // /** // * @param gestor the gestor to set // */ // public void setGestor(GestorCajon gestor) { // this.gestor = gestor; // } public void setCabecera(String ruta) { cabecera ca = (cabecera) getBean("cabecera"); ca.setPath(ruta); } public void setCabecera() { cabecera ca = (cabecera) getBean("cabecera"); ca.setPath("Home &raquo; Cajones"); } /** * @return the campoBusq */ public String getCampoBusq() { return campoBusq; } /** * @param campoBusq the campoBusq to set */ public void setCampoBusq(String campoBusq) { this.campoBusq = campoBusq; } /** * @return the parametro */ public UIParameter getParametro() { return parametro; } /** * @param parametro the parametro to set */ public void setParametro(UIParameter parametro) { this.parametro = parametro; } }
/* * Copyright 2016 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.workbench.common.services.refactoring.backend.server; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.enterprise.event.Event; import javax.enterprise.util.TypeLiteral; import org.apache.commons.io.FileUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.search.Query; import org.guvnor.common.services.project.model.Package; import org.junit.AfterClass; import org.junit.BeforeClass; import org.kie.workbench.common.services.refactoring.backend.server.indexing.ImpactAnalysisAnalyzerWrapperFactory; import org.kie.workbench.common.services.shared.project.KieModule; import org.kie.workbench.common.services.shared.project.KieModuleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.uberfire.commons.async.DescriptiveThreadFactory; import org.uberfire.ext.metadata.MetadataConfig; import org.uberfire.ext.metadata.backend.lucene.index.CustomAnalyzerWrapperFactory; import org.uberfire.ext.metadata.engine.IndexerScheduler.Factory; import org.uberfire.ext.metadata.io.ConstrainedIndexerScheduler.ConstraintBuilder; import org.uberfire.ext.metadata.io.IOServiceIndexedImpl; import org.uberfire.ext.metadata.io.IndexerDispatcher; import org.uberfire.ext.metadata.io.IndexerDispatcher.IndexerDispatcherFactory; import org.uberfire.ext.metadata.io.IndexersFactory; import org.uberfire.ext.metadata.io.MetadataConfigBuilder; import org.uberfire.ext.metadata.model.KObject; import org.uberfire.io.IOService; import org.uberfire.java.nio.file.Path; import org.uberfire.workbench.type.ResourceTypeDefinition; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public abstract class IndexingTest<T extends ResourceTypeDefinition> { public static final String TEST_MODULE_ROOT = "/a/mock/module/root"; public static final String TEST_MODULE_NAME = "mock-module"; public static final String TEST_PACKAGE_NAME = "org.kie.workbench.mock.package"; protected static final Logger logger = LoggerFactory.getLogger(IndexingTest.class); protected static final List<File> tempFiles = new ArrayList<>(); private static MetadataConfig config; private IOService ioService = null; private IndexersFactory indexersFactory; private IndexerDispatcherFactory indexerDispatcherFactory; @AfterClass @BeforeClass public static void cleanup() { for (final File tempFile : tempFiles) { FileUtils.deleteQuietly(tempFile); } if (config != null) { config.dispose(); config = null; } } protected static MetadataConfig getConfig() { return config; } protected static File createTempDirectory() throws IOException { final File temp = File.createTempFile("temp", Long.toString(System.nanoTime())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } tempFiles.add(temp); return temp; } protected abstract TestIndexer<T> getIndexer(); protected abstract Map<String, Analyzer> getAnalyzers(); protected CustomAnalyzerWrapperFactory getAnalyzerWrapperFactory() { return ImpactAnalysisAnalyzerWrapperFactory.getInstance(); } protected abstract T getResourceTypeDefinition(); protected void loadProperties(final String fileName, final Path basePath) throws IOException { final Path path = basePath.resolve(fileName); final Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream(fileName)); ioService().write(path, propertiesToString(properties)); } protected String loadText(final String fileName) throws IOException { InputStream fileInputStream = this.getClass().getResourceAsStream(fileName); if (fileInputStream == null) { File file = new File(fileName); if (file.exists()) { fileInputStream = new FileInputStream(file); } } final BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.getProperty("line.separator")); line = br.readLine(); } return sb.toString(); } finally { br.close(); } } protected String propertiesToString(final Properties properties) { final StringBuilder sb = new StringBuilder(); for (String name : properties.stringPropertyNames()) { sb.append(name).append("=").append(properties.getProperty(name)).append("\n"); } return sb.toString(); } protected IOService ioService() { if (ioService == null) { final Map<String, Analyzer> analyzers = getAnalyzers(); MetadataConfigBuilder configBuilder = new MetadataConfigBuilder() .withInMemoryMetaModelStore() .usingAnalyzers(analyzers) .usingAnalyzerWrapperFactory(getAnalyzerWrapperFactory()) .useInMemoryDirectory() // If you want to use Luke to inspect the index, // comment ".useInMemoryDirectory(), and uncomment below.. // .useNIODirectory() .useDirectoryBasedIndex(); if (config == null) { config = configBuilder.build(); } ExecutorService executorService = Executors.newCachedThreadPool(new DescriptiveThreadFactory()); indexersFactory = new IndexersFactory(); Factory schedulerFactory = new ConstraintBuilder().createFactory(); indexerDispatcherFactory = IndexerDispatcher.createFactory(config.getIndexEngine(), schedulerFactory, testEvent(), LoggerFactory.getLogger(IndexerDispatcher.class)); ioService = new IOServiceIndexedImpl(config.getIndexEngine(), executorService, indexersFactory, indexerDispatcherFactory); final TestIndexer indexer = getIndexer(); indexersFactory.clear(); indexersFactory.addIndexer(indexer); //Mock CDI injection and setup indexer.setIOService(ioService); indexer.setModuleService(getModuleService()); indexer.setResourceTypeDefinition(getResourceTypeDefinition()); } return ioService; } private <T> Event<T> testEvent() { return new Event<T>() { @Override public void fire(T event) { } @Override public Event<T> select(Annotation... qualifiers) { return this; } @Override public <U extends T> Event<U> select(Class<U> subtype, Annotation... qualifiers) { return testEvent(); } @Override public <U extends T> Event<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) { return testEvent(); } }; } public void dispose() { ioService().dispose(); ioService = null; } protected KieModuleService getModuleService() { final KieModule mockModule = getKieModuleMock(TEST_MODULE_ROOT, TEST_MODULE_NAME); final Package mockPackage = mock(Package.class); when(mockPackage.getPackageName()).thenReturn(TEST_PACKAGE_NAME); final KieModuleService mockWorkspaceProjectService = mock(KieModuleService.class); when(mockWorkspaceProjectService.resolveModule(any(org.uberfire.backend.vfs.Path.class))).thenReturn(mockModule); when(mockWorkspaceProjectService.resolvePackage(any(org.uberfire.backend.vfs.Path.class))).thenReturn(mockPackage); return mockWorkspaceProjectService; } protected KieModule getKieModuleMock(final String testModuleRoot, final String testModuleName) { final org.uberfire.backend.vfs.Path mockRoot = mock(org.uberfire.backend.vfs.Path.class); when(mockRoot.toURI()).thenReturn(testModuleRoot); final KieModule mockModule = mock(KieModule.class); when(mockModule.getRootPath()).thenReturn(mockRoot); when(mockModule.getModuleName()).thenReturn(testModuleName); return mockModule; } protected void assertContains(final Iterable<KObject> results, final Path path) { for (KObject kObject : results) { final String key = kObject.getKey(); final String fileName = path.getFileName().toString(); if (key.endsWith(fileName)) { return; } } fail("Results do not contain expected Path '" + path.toUri().toString()); } public void searchFor(Query query, int expectedNumHits) throws IOException { searchFor(config.getIndexProvider().getIndices(), query, expectedNumHits); } public void searchFor(List<String> indices, Query query, int expectedNumHits, Path... paths) { int hits = 10 > expectedNumHits ? 10 : expectedNumHits; List<KObject> found = config.getIndexProvider().findByQuery(indices, query, hits); if (paths != null && paths.length > 0) { assertEquals("Number of docs fulfilling the given query criteria", expectedNumHits, found.size()); for (Path path : paths) { assertContains(found, path); } } } }
/* * Copyright (C) 2012 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 android.support.v8.renderscript; import java.io.File; import java.lang.reflect.Field; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Process; import android.util.Log; import android.view.Surface; /** * Renderscript base master class. An instance of this class creates native * worker threads for processing commands from this object. This base class * does not provide any extended capabilities beyond simple data processing. * For extended capabilities use derived classes such as RenderScriptGL. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about creating an application that uses Renderscript, read the * <a href="{@docRoot}guide/topics/graphics/renderscript.html">Renderscript</a> developer guide.</p> * </div> **/ public class RenderScript { static final String LOG_TAG = "RenderScript_jni"; static final boolean DEBUG = false; @SuppressWarnings({"UnusedDeclaration", "deprecation"}) static final boolean LOG_ENABLED = false; private Context mApplicationContext; boolean mUseNativeRS; static class NRS { android.renderscript.RenderScript mRS; android.renderscript.RenderScript getRS() { return mRS; } } NRS mNRS; /* * We use a class initializer to allow the native code to cache some * field offsets. */ @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) static boolean sInitialized; native static void _nInit(); static { sInitialized = false; try { System.loadLibrary("rsjni"); _nInit(); sInitialized = true; } catch (UnsatisfiedLinkError e) { Log.e(LOG_TAG, "Error loading RS jni library: " + e); throw new RSRuntimeException("Error loading RS jni library: " + e); } } // Non-threadsafe functions. native int nDeviceCreate(); native void nDeviceDestroy(int dev); native void nDeviceSetConfig(int dev, int param, int value); native int nContextGetUserMessage(int con, int[] data); native String nContextGetErrorMessage(int con); native int nContextPeekMessage(int con, int[] subID); native void nContextInitToClient(int con); native void nContextDeinitToClient(int con); /** * Name of the file that holds the object cache. */ private static final String CACHE_PATH = "com.android.renderscript.cache"; static String mCachePath; /** * Sets the directory to use as a persistent storage for the * renderscript object file cache. * * @hide * @param cacheDir A directory the current process can write to */ public static void setupDiskCache(File cacheDir) { File f = new File(cacheDir, CACHE_PATH); mCachePath = f.getAbsolutePath(); f.mkdirs(); } // Methods below are wrapped to protect the non-threadsafe // lockless fifo. native int rsnContextCreate(int dev, int ver, int sdkVer); synchronized int nContextCreate(int dev, int ver, int sdkVer) { return rsnContextCreate(dev, ver, sdkVer); } native void rsnContextDestroy(int con); synchronized void nContextDestroy() { validate(); rsnContextDestroy(mContext); } native void rsnContextSetPriority(int con, int p); synchronized void nContextSetPriority(int p) { validate(); rsnContextSetPriority(mContext, p); } native void rsnContextDump(int con, int bits); synchronized void nContextDump(int bits) { validate(); rsnContextDump(mContext, bits); } native void rsnContextFinish(int con); synchronized void nContextFinish() { validate(); rsnContextFinish(mContext); } native void rsnObjDestroy(int con, int id); synchronized void nObjDestroy(int id) { // There is a race condition here. The calling code may be run // by the gc while teardown is occuring. This protects againts // deleting dead objects. if (mContext != 0) { rsnObjDestroy(mContext, id); } } native int rsnElementCreate(int con, int type, int kind, boolean norm, int vecSize); synchronized int nElementCreate(int type, int kind, boolean norm, int vecSize) { validate(); return rsnElementCreate(mContext, type, kind, norm, vecSize); } native int rsnElementCreate2(int con, int[] elements, String[] names, int[] arraySizes); synchronized int nElementCreate2(int[] elements, String[] names, int[] arraySizes) { validate(); return rsnElementCreate2(mContext, elements, names, arraySizes); } native void rsnElementGetNativeData(int con, int id, int[] elementData); synchronized void nElementGetNativeData(int id, int[] elementData) { validate(); rsnElementGetNativeData(mContext, id, elementData); } native void rsnElementGetSubElements(int con, int id, int[] IDs, String[] names, int[] arraySizes); synchronized void nElementGetSubElements(int id, int[] IDs, String[] names, int[] arraySizes) { validate(); rsnElementGetSubElements(mContext, id, IDs, names, arraySizes); } native int rsnTypeCreate(int con, int eid, int x, int y, int z, boolean mips, boolean faces); synchronized int nTypeCreate(int eid, int x, int y, int z, boolean mips, boolean faces) { validate(); return rsnTypeCreate(mContext, eid, x, y, z, mips, faces); } native void rsnTypeGetNativeData(int con, int id, int[] typeData); synchronized void nTypeGetNativeData(int id, int[] typeData) { validate(); rsnTypeGetNativeData(mContext, id, typeData); } native int rsnAllocationCreateTyped(int con, int type, int mip, int usage, int pointer); synchronized int nAllocationCreateTyped(int type, int mip, int usage, int pointer) { validate(); return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer); } native int rsnAllocationCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage); synchronized int nAllocationCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) { validate(); return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage); } native int rsnAllocationCubeCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage); synchronized int nAllocationCubeCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) { validate(); return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage); } native int rsnAllocationCreateBitmapRef(int con, int type, Bitmap bmp); synchronized int nAllocationCreateBitmapRef(int type, Bitmap bmp) { validate(); return rsnAllocationCreateBitmapRef(mContext, type, bmp); } native int rsnAllocationCreateFromAssetStream(int con, int mips, int assetStream, int usage); synchronized int nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) { validate(); return rsnAllocationCreateFromAssetStream(mContext, mips, assetStream, usage); } native void rsnAllocationCopyToBitmap(int con, int alloc, Bitmap bmp); synchronized void nAllocationCopyToBitmap(int alloc, Bitmap bmp) { validate(); rsnAllocationCopyToBitmap(mContext, alloc, bmp); } native void rsnAllocationSyncAll(int con, int alloc, int src); synchronized void nAllocationSyncAll(int alloc, int src) { validate(); rsnAllocationSyncAll(mContext, alloc, src); } native void rsnAllocationGenerateMipmaps(int con, int alloc); synchronized void nAllocationGenerateMipmaps(int alloc) { validate(); rsnAllocationGenerateMipmaps(mContext, alloc); } native void rsnAllocationCopyFromBitmap(int con, int alloc, Bitmap bmp); synchronized void nAllocationCopyFromBitmap(int alloc, Bitmap bmp) { validate(); rsnAllocationCopyFromBitmap(mContext, alloc, bmp); } native void rsnAllocationData1D(int con, int id, int off, int mip, int count, int[] d, int sizeBytes); synchronized void nAllocationData1D(int id, int off, int mip, int count, int[] d, int sizeBytes) { validate(); rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes); } native void rsnAllocationData1D(int con, int id, int off, int mip, int count, short[] d, int sizeBytes); synchronized void nAllocationData1D(int id, int off, int mip, int count, short[] d, int sizeBytes) { validate(); rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes); } native void rsnAllocationData1D(int con, int id, int off, int mip, int count, byte[] d, int sizeBytes); synchronized void nAllocationData1D(int id, int off, int mip, int count, byte[] d, int sizeBytes) { validate(); rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes); } native void rsnAllocationData1D(int con, int id, int off, int mip, int count, float[] d, int sizeBytes); synchronized void nAllocationData1D(int id, int off, int mip, int count, float[] d, int sizeBytes) { validate(); rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes); } native void rsnAllocationElementData1D(int con, int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes); synchronized void nAllocationElementData1D(int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes) { validate(); rsnAllocationElementData1D(mContext, id, xoff, mip, compIdx, d, sizeBytes); } native void rsnAllocationData2D(int con, int dstAlloc, int dstXoff, int dstYoff, int dstMip, int dstFace, int width, int height, int srcAlloc, int srcXoff, int srcYoff, int srcMip, int srcFace); synchronized void nAllocationData2D(int dstAlloc, int dstXoff, int dstYoff, int dstMip, int dstFace, int width, int height, int srcAlloc, int srcXoff, int srcYoff, int srcMip, int srcFace) { validate(); rsnAllocationData2D(mContext, dstAlloc, dstXoff, dstYoff, dstMip, dstFace, width, height, srcAlloc, srcXoff, srcYoff, srcMip, srcFace); } native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes); synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes) { validate(); rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes); } native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes); synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes) { validate(); rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes); } native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes); synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes) { validate(); rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes); } native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes); synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes) { validate(); rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes); } native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, Bitmap b); synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, Bitmap b) { validate(); rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b); } native void rsnAllocationRead(int con, int id, byte[] d); synchronized void nAllocationRead(int id, byte[] d) { validate(); rsnAllocationRead(mContext, id, d); } native void rsnAllocationRead(int con, int id, short[] d); synchronized void nAllocationRead(int id, short[] d) { validate(); rsnAllocationRead(mContext, id, d); } native void rsnAllocationRead(int con, int id, int[] d); synchronized void nAllocationRead(int id, int[] d) { validate(); rsnAllocationRead(mContext, id, d); } native void rsnAllocationRead(int con, int id, float[] d); synchronized void nAllocationRead(int id, float[] d) { validate(); rsnAllocationRead(mContext, id, d); } native int rsnAllocationGetType(int con, int id); synchronized int nAllocationGetType(int id) { validate(); return rsnAllocationGetType(mContext, id); } native void rsnAllocationResize1D(int con, int id, int dimX); synchronized void nAllocationResize1D(int id, int dimX) { validate(); rsnAllocationResize1D(mContext, id, dimX); } native void rsnAllocationResize2D(int con, int id, int dimX, int dimY); synchronized void nAllocationResize2D(int id, int dimX, int dimY) { validate(); rsnAllocationResize2D(mContext, id, dimX, dimY); } native void rsnScriptBindAllocation(int con, int script, int alloc, int slot); synchronized void nScriptBindAllocation(int script, int alloc, int slot) { validate(); rsnScriptBindAllocation(mContext, script, alloc, slot); } native void rsnScriptSetTimeZone(int con, int script, byte[] timeZone); synchronized void nScriptSetTimeZone(int script, byte[] timeZone) { validate(); rsnScriptSetTimeZone(mContext, script, timeZone); } native void rsnScriptInvoke(int con, int id, int slot); synchronized void nScriptInvoke(int id, int slot) { validate(); rsnScriptInvoke(mContext, id, slot); } native void rsnScriptForEach(int con, int id, int slot, int ain, int aout, byte[] params); native void rsnScriptForEach(int con, int id, int slot, int ain, int aout); synchronized void nScriptForEach(int id, int slot, int ain, int aout, byte[] params) { validate(); if (params == null) { rsnScriptForEach(mContext, id, slot, ain, aout); } else { rsnScriptForEach(mContext, id, slot, ain, aout, params); } } native void rsnScriptInvokeV(int con, int id, int slot, byte[] params); synchronized void nScriptInvokeV(int id, int slot, byte[] params) { validate(); rsnScriptInvokeV(mContext, id, slot, params); } native void rsnScriptSetVarI(int con, int id, int slot, int val); synchronized void nScriptSetVarI(int id, int slot, int val) { validate(); rsnScriptSetVarI(mContext, id, slot, val); } native void rsnScriptSetVarJ(int con, int id, int slot, long val); synchronized void nScriptSetVarJ(int id, int slot, long val) { validate(); rsnScriptSetVarJ(mContext, id, slot, val); } native void rsnScriptSetVarF(int con, int id, int slot, float val); synchronized void nScriptSetVarF(int id, int slot, float val) { validate(); rsnScriptSetVarF(mContext, id, slot, val); } native void rsnScriptSetVarD(int con, int id, int slot, double val); synchronized void nScriptSetVarD(int id, int slot, double val) { validate(); rsnScriptSetVarD(mContext, id, slot, val); } native void rsnScriptSetVarV(int con, int id, int slot, byte[] val); synchronized void nScriptSetVarV(int id, int slot, byte[] val) { validate(); rsnScriptSetVarV(mContext, id, slot, val); } native void rsnScriptSetVarVE(int con, int id, int slot, byte[] val, int e, int[] dims); synchronized void nScriptSetVarVE(int id, int slot, byte[] val, int e, int[] dims) { validate(); rsnScriptSetVarVE(mContext, id, slot, val, e, dims); } native void rsnScriptSetVarObj(int con, int id, int slot, int val); synchronized void nScriptSetVarObj(int id, int slot, int val) { validate(); rsnScriptSetVarObj(mContext, id, slot, val); } native int rsnScriptCCreate(int con, String resName, String cacheDir, byte[] script, int length); synchronized int nScriptCCreate(String resName, String cacheDir, byte[] script, int length) { validate(); return rsnScriptCCreate(mContext, resName, cacheDir, script, length); } native int rsnScriptIntrinsicCreate(int con, int id, int eid); synchronized int nScriptIntrinsicCreate(int id, int eid) { validate(); return rsnScriptIntrinsicCreate(mContext, id, eid); } native int rsnScriptKernelIDCreate(int con, int sid, int slot, int sig); synchronized int nScriptKernelIDCreate(int sid, int slot, int sig) { validate(); return rsnScriptKernelIDCreate(mContext, sid, slot, sig); } native int rsnScriptFieldIDCreate(int con, int sid, int slot); synchronized int nScriptFieldIDCreate(int sid, int slot) { validate(); return rsnScriptFieldIDCreate(mContext, sid, slot); } native int rsnScriptGroupCreate(int con, int[] kernels, int[] src, int[] dstk, int[] dstf, int[] types); synchronized int nScriptGroupCreate(int[] kernels, int[] src, int[] dstk, int[] dstf, int[] types) { validate(); return rsnScriptGroupCreate(mContext, kernels, src, dstk, dstf, types); } native void rsnScriptGroupSetInput(int con, int group, int kernel, int alloc); synchronized void nScriptGroupSetInput(int group, int kernel, int alloc) { validate(); rsnScriptGroupSetInput(mContext, group, kernel, alloc); } native void rsnScriptGroupSetOutput(int con, int group, int kernel, int alloc); synchronized void nScriptGroupSetOutput(int group, int kernel, int alloc) { validate(); rsnScriptGroupSetOutput(mContext, group, kernel, alloc); } native void rsnScriptGroupExecute(int con, int group); synchronized void nScriptGroupExecute(int group) { validate(); rsnScriptGroupExecute(mContext, group); } native int rsnSamplerCreate(int con, int magFilter, int minFilter, int wrapS, int wrapT, int wrapR, float aniso); synchronized int nSamplerCreate(int magFilter, int minFilter, int wrapS, int wrapT, int wrapR, float aniso) { validate(); return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso); } int mDev; int mContext; @SuppressWarnings({"FieldCanBeLocal"}) MessageThread mMessageThread; Element mElement_U8; Element mElement_I8; Element mElement_U16; Element mElement_I16; Element mElement_U32; Element mElement_I32; Element mElement_U64; Element mElement_I64; Element mElement_F32; Element mElement_F64; Element mElement_BOOLEAN; Element mElement_ELEMENT; Element mElement_TYPE; Element mElement_ALLOCATION; Element mElement_SAMPLER; Element mElement_SCRIPT; Element mElement_A_8; Element mElement_RGB_565; Element mElement_RGB_888; Element mElement_RGBA_5551; Element mElement_RGBA_4444; Element mElement_RGBA_8888; Element mElement_FLOAT_2; Element mElement_FLOAT_3; Element mElement_FLOAT_4; Element mElement_DOUBLE_2; Element mElement_DOUBLE_3; Element mElement_DOUBLE_4; Element mElement_UCHAR_2; Element mElement_UCHAR_3; Element mElement_UCHAR_4; Element mElement_CHAR_2; Element mElement_CHAR_3; Element mElement_CHAR_4; Element mElement_USHORT_2; Element mElement_USHORT_3; Element mElement_USHORT_4; Element mElement_SHORT_2; Element mElement_SHORT_3; Element mElement_SHORT_4; Element mElement_UINT_2; Element mElement_UINT_3; Element mElement_UINT_4; Element mElement_INT_2; Element mElement_INT_3; Element mElement_INT_4; Element mElement_ULONG_2; Element mElement_ULONG_3; Element mElement_ULONG_4; Element mElement_LONG_2; Element mElement_LONG_3; Element mElement_LONG_4; Element mElement_MATRIX_4X4; Element mElement_MATRIX_3X3; Element mElement_MATRIX_2X2; Sampler mSampler_CLAMP_NEAREST; Sampler mSampler_CLAMP_LINEAR; Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR; Sampler mSampler_WRAP_NEAREST; Sampler mSampler_WRAP_LINEAR; Sampler mSampler_WRAP_LINEAR_MIP_LINEAR; /////////////////////////////////////////////////////////////////////////////////// // /** * Base class application should derive from for handling RS messages * coming from their scripts. When a script calls sendToClient the data * fields will be filled in and then the run method called by a message * handling thread. This will occur some time after sendToClient completes * in the script. * */ public static class RSMessageHandler implements Runnable { protected int[] mData; protected int mID; protected int mLength; public void run() { } } /** * If an application is expecting messages it should set this field to an * instance of RSMessage. This instance will receive all the user messages * sent from sendToClient by scripts from this context. * */ RSMessageHandler mMessageCallback = null; public void setMessageHandler(RSMessageHandler msg) { mMessageCallback = msg; } public RSMessageHandler getMessageHandler() { return mMessageCallback; } /** * Runtime error base class. An application should derive from this class * if it wishes to install an error handler. When errors occur at runtime * the fields in this class will be filled and the run method called. * */ public static class RSErrorHandler implements Runnable { protected String mErrorMessage; protected int mErrorNum; public void run() { } } /** * Application Error handler. All runtime errors will be dispatched to the * instance of RSAsyncError set here. If this field is null a * RSRuntimeException will instead be thrown with details about the error. * This will cause program termaination. * */ RSErrorHandler mErrorCallback = null; public void setErrorHandler(RSErrorHandler msg) { mErrorCallback = msg; } public RSErrorHandler getErrorHandler() { return mErrorCallback; } /** * RenderScript worker threads priority enumeration. The default value is * NORMAL. Applications wishing to do background processing such as * wallpapers should set their priority to LOW to avoid starving forground * processes. */ public enum Priority { LOW (Process.THREAD_PRIORITY_BACKGROUND + (5 * Process.THREAD_PRIORITY_LESS_FAVORABLE)), NORMAL (Process.THREAD_PRIORITY_DISPLAY); int mID; Priority(int id) { mID = id; } } void validate() { if (mContext == 0) { throw new RSInvalidStateException("Calling RS with no Context active."); } } /** * Change the priority of the worker threads for this context. * * @param p New priority to be set. */ public void setPriority(Priority p) { validate(); nContextSetPriority(p.mID); } static class MessageThread extends Thread { RenderScript mRS; boolean mRun = true; int[] mAuxData = new int[2]; static final int RS_MESSAGE_TO_CLIENT_NONE = 0; static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1; static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2; static final int RS_MESSAGE_TO_CLIENT_ERROR = 3; static final int RS_MESSAGE_TO_CLIENT_USER = 4; static final int RS_ERROR_FATAL_UNKNOWN = 0x1000; MessageThread(RenderScript rs) { super("RSMessageThread"); mRS = rs; } public void run() { // This function is a temporary solution. The final solution will // used typed allocations where the message id is the type indicator. int[] rbuf = new int[16]; mRS.nContextInitToClient(mRS.mContext); while(mRun) { rbuf[0] = 0; int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData); int size = mAuxData[1]; int subID = mAuxData[0]; if (msg == RS_MESSAGE_TO_CLIENT_USER) { if ((size>>2) >= rbuf.length) { rbuf = new int[(size + 3) >> 2]; } if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) != RS_MESSAGE_TO_CLIENT_USER) { throw new RSDriverException("Error processing message from Renderscript."); } if(mRS.mMessageCallback != null) { mRS.mMessageCallback.mData = rbuf; mRS.mMessageCallback.mID = subID; mRS.mMessageCallback.mLength = size; mRS.mMessageCallback.run(); } else { throw new RSInvalidStateException("Received a message from the script with no message handler installed."); } continue; } if (msg == RS_MESSAGE_TO_CLIENT_ERROR) { String e = mRS.nContextGetErrorMessage(mRS.mContext); if (subID >= RS_ERROR_FATAL_UNKNOWN) { throw new RSRuntimeException("Fatal error " + subID + ", details: " + e); } if(mRS.mErrorCallback != null) { mRS.mErrorCallback.mErrorMessage = e; mRS.mErrorCallback.mErrorNum = subID; mRS.mErrorCallback.run(); } else { // Do not throw here. In these cases, we do not have // a fatal error. } continue; } // 2: teardown. // But we want to avoid starving other threads during // teardown by yielding until the next line in the destructor // can execute to set mRun = false try { sleep(1, 0); } catch(InterruptedException e) { } } Log.d(LOG_TAG, "MessageThread exiting."); } } RenderScript(Context ctx) { if (ctx != null) { mApplicationContext = ctx.getApplicationContext(); } } /** * Gets the application context associated with the RenderScript context. * * @return The application context. */ public final Context getApplicationContext() { return mApplicationContext; } /** * Create a basic RenderScript context. * * @hide * @param ctx The context. * @return RenderScript */ public static RenderScript create(Context ctx, int sdkVersion) { RenderScript rs = new RenderScript(ctx); rs.mDev = rs.nDeviceCreate(); rs.mContext = rs.nContextCreate(rs.mDev, 0, sdkVersion); if (rs.mContext == 0) { throw new RSDriverException("Failed to create RS context."); } rs.mMessageThread = new MessageThread(rs); rs.mMessageThread.start(); return rs; } /** * Create a basic RenderScript context. * * @param ctx The context. * @return RenderScript */ public static RenderScript create(Context ctx) { int v = ctx.getApplicationInfo().targetSdkVersion; return create(ctx, v); } /** * Print the currently available debugging information about the state of * the RS context to the log. * */ public void contextDump() { validate(); nContextDump(0); } /** * Wait for any commands in the fifo between the java bindings and native to * be processed. * */ public void finish() { nContextFinish(); } /** * Destroy this renderscript context. Once this function is called its no * longer legal to use this or any objects created by this context. * */ public void destroy() { validate(); nContextDeinitToClient(mContext); mMessageThread.mRun = false; try { mMessageThread.join(); } catch(InterruptedException e) { } nContextDestroy(); mContext = 0; nDeviceDestroy(mDev); mDev = 0; } boolean isAlive() { return mContext != 0; } int safeID(BaseObj o) { if(o != null) { return o.getID(this); } return 0; } }
package org.apache.jsp.include_005fjsp.mySrv; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import net.violet.platform.util.StaticTools; import net.violet.platform.util.SessionTools; import net.violet.platform.datamodel.Lang; import net.violet.platform.util.DicoTools; import net.violet.platform.util.MyConstantes; public final class inc_005ftaichi_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static java.util.List _jspx_dependants; static { _jspx_dependants = new java.util.ArrayList(1); _jspx_dependants.add("/include_jsp/utils/inc_dico.jsp"); } private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_bean_define_property_name_id_nobody; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_form_styleId_styleClass_action; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_select_styleId_property_name; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_optionsCollection_value_property_name_label_nobody; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_hidden_value_property_name_nobody; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_hidden_value_styleId_property_nobody; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_logic_notEqual_value_name; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_button_value_styleClass_property_onclick; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_logic_equal_value_name; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_html_submit_value_styleClass_property_onclick; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _jspx_tagPool_bean_define_property_name_id_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_form_styleId_styleClass_action = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_select_styleId_property_name = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_optionsCollection_value_property_name_label_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_hidden_value_property_name_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_hidden_value_styleId_property_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_logic_notEqual_value_name = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_button_value_styleClass_property_onclick = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_logic_equal_value_name = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _jspx_tagPool_html_submit_value_styleClass_property_onclick = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); } public void _jspDestroy() { _jspx_tagPool_bean_define_property_name_id_nobody.release(); _jspx_tagPool_html_form_styleId_styleClass_action.release(); _jspx_tagPool_html_select_styleId_property_name.release(); _jspx_tagPool_html_optionsCollection_value_property_name_label_nobody.release(); _jspx_tagPool_html_hidden_value_property_name_nobody.release(); _jspx_tagPool_html_hidden_value_styleId_property_nobody.release(); _jspx_tagPool_logic_notEqual_value_name.release(); _jspx_tagPool_html_button_value_styleClass_property_onclick.release(); _jspx_tagPool_logic_equal_value_name.release(); _jspx_tagPool_html_submit_value_styleClass_property_onclick.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n\r\n\r\n"); response.setContentType("text/html;charset=UTF-8"); out.write("\r\n\n\r\n\r\n\r\n\r\n"); out.write('\n'); out.write('\r'); out.write('\n'); out.write("\r\n\r\n\n"); Lang dico_lang = SessionTools.getLangFromSession(session, request); out.write('\n'); out.write('\r'); out.write('\n'); // bean:define org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_define_0 = (org.apache.struts.taglib.bean.DefineTag) _jspx_tagPool_bean_define_property_name_id_nobody.get(org.apache.struts.taglib.bean.DefineTag.class); _jspx_th_bean_define_0.setPageContext(_jspx_page_context); _jspx_th_bean_define_0.setParent(null); _jspx_th_bean_define_0.setProperty("isReg"); _jspx_th_bean_define_0.setName("mySrvTaichiForm"); _jspx_th_bean_define_0.setId("isReg"); int _jspx_eval_bean_define_0 = _jspx_th_bean_define_0.doStartTag(); if (_jspx_th_bean_define_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_bean_define_property_name_id_nobody.reuse(_jspx_th_bean_define_0); return; } _jspx_tagPool_bean_define_property_name_id_nobody.reuse(_jspx_th_bean_define_0); java.lang.Object isReg = null; isReg = (java.lang.Object) _jspx_page_context.findAttribute("isReg"); out.write("\r\n<div class=\"main-cadre-contener\">\r\n\t<div class=\"main-cadre-top\"><h2>"); out.print(DicoTools.dico(dico_lang , "services/configure")); out.write("</h2></div>\r\n\t<div class=\"main-cadre-content\">\r\n\t\t<hr class=\"spacer\"/>\r\n\t\t<!-- ******************************************** CONTENT ***************************************************** --> \r\n\t\t"); // html:form org.apache.struts.taglib.html.FormTag _jspx_th_html_form_0 = (org.apache.struts.taglib.html.FormTag) _jspx_tagPool_html_form_styleId_styleClass_action.get(org.apache.struts.taglib.html.FormTag.class); _jspx_th_html_form_0.setPageContext(_jspx_page_context); _jspx_th_html_form_0.setParent(null); _jspx_th_html_form_0.setAction("/action/srvTaichiConfig"); _jspx_th_html_form_0.setStyleId("srvTaichiConfig"); _jspx_th_html_form_0.setStyleClass("srvConfigForm"); int _jspx_eval_html_form_0 = _jspx_th_html_form_0.doStartTag(); if (_jspx_eval_html_form_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n\t\t\t\r\n\t\t\t<label style=\"width:200px;\" >"); out.print(DicoTools.dico(dico_lang , "srv_taichi/choose_frequency")); out.write("</label>\r\n\t\t\t"); if (_jspx_meth_html_select_0(_jspx_th_html_form_0, _jspx_page_context)) return; out.write("\r\n\t\t\t\r\n\t\t\t"); if (_jspx_meth_html_hidden_0(_jspx_th_html_form_0, _jspx_page_context)) return; out.write("\t\r\n\t\t\t\r\n\t\t\t<hr class=\"spacer\" />\r\n\t\t\t\r\n\t\t\t"); if (_jspx_meth_html_hidden_1(_jspx_th_html_form_0, _jspx_page_context)) return; out.write("\r\n\t\t\t\r\n\t\t\t<div align=\"center\">\r\n\t\t\t\t"); /* Supression */ out.write("\t\t\r\n\t\t\t\t"); // logic:notEqual org.apache.struts.taglib.logic.NotEqualTag _jspx_th_logic_notEqual_0 = (org.apache.struts.taglib.logic.NotEqualTag) _jspx_tagPool_logic_notEqual_value_name.get(org.apache.struts.taglib.logic.NotEqualTag.class); _jspx_th_logic_notEqual_0.setPageContext(_jspx_page_context); _jspx_th_logic_notEqual_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0); _jspx_th_logic_notEqual_0.setName("isReg"); _jspx_th_logic_notEqual_0.setValue("0"); int _jspx_eval_logic_notEqual_0 = _jspx_th_logic_notEqual_0.doStartTag(); if (_jspx_eval_logic_notEqual_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n\t\t\t\t\t"); // html:button org.apache.struts.taglib.html.ButtonTag _jspx_th_html_button_0 = (org.apache.struts.taglib.html.ButtonTag) _jspx_tagPool_html_button_value_styleClass_property_onclick.get(org.apache.struts.taglib.html.ButtonTag.class); _jspx_th_html_button_0.setPageContext(_jspx_page_context); _jspx_th_html_button_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_logic_notEqual_0); _jspx_th_html_button_0.setProperty("delete"); _jspx_th_html_button_0.setValue(DicoTools.dico(dico_lang , "srv_taichi/deactivate")); _jspx_th_html_button_0.setStyleClass("genericDeleteBt"); _jspx_th_html_button_0.setOnclick("serviceDelete();"); int _jspx_eval_html_button_0 = _jspx_th_html_button_0.doStartTag(); if (_jspx_eval_html_button_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_html_button_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_html_button_0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_html_button_0.doInitBody(); } do { out.print(DicoTools.dico(dico_lang , "srv_taichi/deactivate")); int evalDoAfterBody = _jspx_th_html_button_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_html_button_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_html_button_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_button_value_styleClass_property_onclick.reuse(_jspx_th_html_button_0); return; } _jspx_tagPool_html_button_value_styleClass_property_onclick.reuse(_jspx_th_html_button_0); out.write("\r\n\t\t\t\t"); int evalDoAfterBody = _jspx_th_logic_notEqual_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_logic_notEqual_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_logic_notEqual_value_name.reuse(_jspx_th_logic_notEqual_0); return; } _jspx_tagPool_logic_notEqual_value_name.reuse(_jspx_th_logic_notEqual_0); out.write("\r\n\t\t\t\t\r\n\t\t\t\t"); /* Creation */ out.write("\r\n\t\t\t\t"); // logic:equal org.apache.struts.taglib.logic.EqualTag _jspx_th_logic_equal_0 = (org.apache.struts.taglib.logic.EqualTag) _jspx_tagPool_logic_equal_value_name.get(org.apache.struts.taglib.logic.EqualTag.class); _jspx_th_logic_equal_0.setPageContext(_jspx_page_context); _jspx_th_logic_equal_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0); _jspx_th_logic_equal_0.setName("isReg"); _jspx_th_logic_equal_0.setValue("0"); int _jspx_eval_logic_equal_0 = _jspx_th_logic_equal_0.doStartTag(); if (_jspx_eval_logic_equal_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n\t\t\t\t\t"); // html:submit org.apache.struts.taglib.html.SubmitTag _jspx_th_html_submit_0 = (org.apache.struts.taglib.html.SubmitTag) _jspx_tagPool_html_submit_value_styleClass_property_onclick.get(org.apache.struts.taglib.html.SubmitTag.class); _jspx_th_html_submit_0.setPageContext(_jspx_page_context); _jspx_th_html_submit_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_logic_equal_0); _jspx_th_html_submit_0.setProperty("activate"); _jspx_th_html_submit_0.setValue(DicoTools.dico(dico_lang , "srv_taichi/activate")); _jspx_th_html_submit_0.setStyleClass("genericBt"); _jspx_th_html_submit_0.setOnclick("goDispatch('activate', 'dispatchConfig')"); int _jspx_eval_html_submit_0 = _jspx_th_html_submit_0.doStartTag(); if (_jspx_eval_html_submit_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_html_submit_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_html_submit_0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_html_submit_0.doInitBody(); } do { out.print(DicoTools.dico(dico_lang , "srv_taichi/activate")); int evalDoAfterBody = _jspx_th_html_submit_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_html_submit_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_html_submit_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_submit_value_styleClass_property_onclick.reuse(_jspx_th_html_submit_0); return; } _jspx_tagPool_html_submit_value_styleClass_property_onclick.reuse(_jspx_th_html_submit_0); out.write("\t\r\n\t\t\t\t"); int evalDoAfterBody = _jspx_th_logic_equal_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_logic_equal_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_logic_equal_value_name.reuse(_jspx_th_logic_equal_0); return; } _jspx_tagPool_logic_equal_value_name.reuse(_jspx_th_logic_equal_0); out.write("\r\n\t\t\t\t\r\n\t\t\t\t"); /* Mise a jour */ out.write("\t\t\t\r\n\t\t\t\t"); // logic:notEqual org.apache.struts.taglib.logic.NotEqualTag _jspx_th_logic_notEqual_1 = (org.apache.struts.taglib.logic.NotEqualTag) _jspx_tagPool_logic_notEqual_value_name.get(org.apache.struts.taglib.logic.NotEqualTag.class); _jspx_th_logic_notEqual_1.setPageContext(_jspx_page_context); _jspx_th_logic_notEqual_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0); _jspx_th_logic_notEqual_1.setName("isReg"); _jspx_th_logic_notEqual_1.setValue("0"); int _jspx_eval_logic_notEqual_1 = _jspx_th_logic_notEqual_1.doStartTag(); if (_jspx_eval_logic_notEqual_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n\t\t\t\t\t"); // html:submit org.apache.struts.taglib.html.SubmitTag _jspx_th_html_submit_1 = (org.apache.struts.taglib.html.SubmitTag) _jspx_tagPool_html_submit_value_styleClass_property_onclick.get(org.apache.struts.taglib.html.SubmitTag.class); _jspx_th_html_submit_1.setPageContext(_jspx_page_context); _jspx_th_html_submit_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_logic_notEqual_1); _jspx_th_html_submit_1.setProperty("update"); _jspx_th_html_submit_1.setValue(DicoTools.dico(dico_lang , "srv_taichi/update")); _jspx_th_html_submit_1.setStyleClass("genericBt"); _jspx_th_html_submit_1.setOnclick("goDispatch('update', 'dispatchConfig')"); int _jspx_eval_html_submit_1 = _jspx_th_html_submit_1.doStartTag(); if (_jspx_eval_html_submit_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_html_submit_1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_html_submit_1.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_html_submit_1.doInitBody(); } do { out.print(DicoTools.dico(dico_lang , "srv_taichi/update")); int evalDoAfterBody = _jspx_th_html_submit_1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_html_submit_1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_html_submit_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_submit_value_styleClass_property_onclick.reuse(_jspx_th_html_submit_1); return; } _jspx_tagPool_html_submit_value_styleClass_property_onclick.reuse(_jspx_th_html_submit_1); out.write("\r\n\t\t\t\t"); int evalDoAfterBody = _jspx_th_logic_notEqual_1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_logic_notEqual_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_logic_notEqual_value_name.reuse(_jspx_th_logic_notEqual_1); return; } _jspx_tagPool_logic_notEqual_value_name.reuse(_jspx_th_logic_notEqual_1); out.write("\r\n\t\t\t</div>\r\n\t\t\t\t\t\t\r\n\t\t"); int evalDoAfterBody = _jspx_th_html_form_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_html_form_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_form_styleId_styleClass_action.reuse(_jspx_th_html_form_0); return; } _jspx_tagPool_html_form_styleId_styleClass_action.reuse(_jspx_th_html_form_0); out.write("\r\n\t\r\n\t</div>\r\n</div>\r\n\r\n<script language=\"javascript\">\r\n\t$(\"#contentSrvConfig form\").submit(function(){\r\n\t\treturn nablifeValidateTaichiConfig("); if (_jspx_meth_logic_equal_1(_jspx_page_context)) return; out.write(");\r\n\t});\r\n</script>"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_html_select_0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_form_0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // html:select org.apache.struts.taglib.html.SelectTag _jspx_th_html_select_0 = (org.apache.struts.taglib.html.SelectTag) _jspx_tagPool_html_select_styleId_property_name.get(org.apache.struts.taglib.html.SelectTag.class); _jspx_th_html_select_0.setPageContext(_jspx_page_context); _jspx_th_html_select_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0); _jspx_th_html_select_0.setName("mySrvTaichiForm"); _jspx_th_html_select_0.setProperty("freqSrv"); _jspx_th_html_select_0.setStyleId("freqSrv"); int _jspx_eval_html_select_0 = _jspx_th_html_select_0.doStartTag(); if (_jspx_eval_html_select_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_html_select_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_html_select_0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_html_select_0.doInitBody(); } do { out.write("\r\n\t\t\t\t<option value=\"\"></option>\n\t\t\t\t<!-- FrequenceData -->\r\n\t\t\t\t"); if (_jspx_meth_html_optionsCollection_0(_jspx_th_html_select_0, _jspx_page_context)) return true; out.write("\r\n\t\t\t"); int evalDoAfterBody = _jspx_th_html_select_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_html_select_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_html_select_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_select_styleId_property_name.reuse(_jspx_th_html_select_0); return true; } _jspx_tagPool_html_select_styleId_property_name.reuse(_jspx_th_html_select_0); return false; } private boolean _jspx_meth_html_optionsCollection_0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_select_0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // html:optionsCollection org.apache.struts.taglib.html.OptionsCollectionTag _jspx_th_html_optionsCollection_0 = (org.apache.struts.taglib.html.OptionsCollectionTag) _jspx_tagPool_html_optionsCollection_value_property_name_label_nobody.get(org.apache.struts.taglib.html.OptionsCollectionTag.class); _jspx_th_html_optionsCollection_0.setPageContext(_jspx_page_context); _jspx_th_html_optionsCollection_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_select_0); _jspx_th_html_optionsCollection_0.setName("mySrvTaichiForm"); _jspx_th_html_optionsCollection_0.setProperty("freqSrvList"); _jspx_th_html_optionsCollection_0.setLabel("label"); _jspx_th_html_optionsCollection_0.setValue("id"); int _jspx_eval_html_optionsCollection_0 = _jspx_th_html_optionsCollection_0.doStartTag(); if (_jspx_th_html_optionsCollection_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_optionsCollection_value_property_name_label_nobody.reuse(_jspx_th_html_optionsCollection_0); return true; } _jspx_tagPool_html_optionsCollection_value_property_name_label_nobody.reuse(_jspx_th_html_optionsCollection_0); return false; } private boolean _jspx_meth_html_hidden_0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_form_0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // html:hidden org.apache.struts.taglib.html.HiddenTag _jspx_th_html_hidden_0 = (org.apache.struts.taglib.html.HiddenTag) _jspx_tagPool_html_hidden_value_property_name_nobody.get(org.apache.struts.taglib.html.HiddenTag.class); _jspx_th_html_hidden_0.setPageContext(_jspx_page_context); _jspx_th_html_hidden_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0); _jspx_th_html_hidden_0.setName("mySrvTaichiForm"); _jspx_th_html_hidden_0.setProperty("add"); _jspx_th_html_hidden_0.setValue("1"); int _jspx_eval_html_hidden_0 = _jspx_th_html_hidden_0.doStartTag(); if (_jspx_th_html_hidden_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_hidden_value_property_name_nobody.reuse(_jspx_th_html_hidden_0); return true; } _jspx_tagPool_html_hidden_value_property_name_nobody.reuse(_jspx_th_html_hidden_0); return false; } private boolean _jspx_meth_html_hidden_1(javax.servlet.jsp.tagext.JspTag _jspx_th_html_form_0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // html:hidden org.apache.struts.taglib.html.HiddenTag _jspx_th_html_hidden_1 = (org.apache.struts.taglib.html.HiddenTag) _jspx_tagPool_html_hidden_value_styleId_property_nobody.get(org.apache.struts.taglib.html.HiddenTag.class); _jspx_th_html_hidden_1.setPageContext(_jspx_page_context); _jspx_th_html_hidden_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_form_0); _jspx_th_html_hidden_1.setStyleId("dispatchConfig"); _jspx_th_html_hidden_1.setProperty("dispatch"); _jspx_th_html_hidden_1.setValue("load"); int _jspx_eval_html_hidden_1 = _jspx_th_html_hidden_1.doStartTag(); if (_jspx_th_html_hidden_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_html_hidden_value_styleId_property_nobody.reuse(_jspx_th_html_hidden_1); return true; } _jspx_tagPool_html_hidden_value_styleId_property_nobody.reuse(_jspx_th_html_hidden_1); return false; } private boolean _jspx_meth_logic_equal_1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // logic:equal org.apache.struts.taglib.logic.EqualTag _jspx_th_logic_equal_1 = (org.apache.struts.taglib.logic.EqualTag) _jspx_tagPool_logic_equal_value_name.get(org.apache.struts.taglib.logic.EqualTag.class); _jspx_th_logic_equal_1.setPageContext(_jspx_page_context); _jspx_th_logic_equal_1.setParent(null); _jspx_th_logic_equal_1.setName("isReg"); _jspx_th_logic_equal_1.setValue("1"); int _jspx_eval_logic_equal_1 = _jspx_th_logic_equal_1.doStartTag(); if (_jspx_eval_logic_equal_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("true"); int evalDoAfterBody = _jspx_th_logic_equal_1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_logic_equal_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_logic_equal_value_name.reuse(_jspx_th_logic_equal_1); return true; } _jspx_tagPool_logic_equal_value_name.reuse(_jspx_th_logic_equal_1); return false; } }
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.humantask.model.ht.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.wso2.developerstudio.eclipse.humantask.model.ht.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.wso2.developerstudio.eclipse.humantask.model.ht.HTPackage * @generated */ public class HTAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static HTPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public HTAdapterFactory() { if (modelPackage == null) { modelPackage = HTPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected HTSwitch<Adapter> modelSwitch = new HTSwitch<Adapter>() { @Override public Adapter caseDocumentRoot(DocumentRoot object) { return createDocumentRootAdapter(); } @Override public Adapter caseTArgument(TArgument object) { return createTArgumentAdapter(); } @Override public Adapter caseTBooleanExpr(TBooleanExpr object) { return createTBooleanExprAdapter(); } @Override public Adapter caseTDeadline(TDeadline object) { return createTDeadlineAdapter(); } @Override public Adapter caseTDeadlineExpr(TDeadlineExpr object) { return createTDeadlineExprAdapter(); } @Override public Adapter caseTDeadlines(TDeadlines object) { return createTDeadlinesAdapter(); } @Override public Adapter caseTDelegation(TDelegation object) { return createTDelegationAdapter(); } @Override public Adapter caseTDescription(TDescription object) { return createTDescriptionAdapter(); } @Override public Adapter caseTDocumentation(TDocumentation object) { return createTDocumentationAdapter(); } @Override public Adapter caseTDurationExpr(TDurationExpr object) { return createTDurationExprAdapter(); } @Override public Adapter caseTEscalation(TEscalation object) { return createTEscalationAdapter(); } @Override public Adapter caseTExpression(TExpression object) { return createTExpressionAdapter(); } @Override public Adapter caseTExtensibleElements(TExtensibleElements object) { return createTExtensibleElementsAdapter(); } @Override public Adapter caseTExtensibleMixedContentElements(TExtensibleMixedContentElements object) { return createTExtensibleMixedContentElementsAdapter(); } @Override public Adapter caseTExtension(TExtension object) { return createTExtensionAdapter(); } @Override public Adapter caseTExtensions(TExtensions object) { return createTExtensionsAdapter(); } @Override public Adapter caseTFrom(TFrom object) { return createTFromAdapter(); } @Override public Adapter caseTGenericHumanRole(TGenericHumanRole object) { return createTGenericHumanRoleAdapter(); } @Override public Adapter caseTGrouplist(TGrouplist object) { return createTGrouplistAdapter(); } @Override public Adapter caseTHumanInteractions(THumanInteractions object) { return createTHumanInteractionsAdapter(); } @Override public Adapter caseTImport(TImport object) { return createTImportAdapter(); } @Override public Adapter caseTLiteral(TLiteral object) { return createTLiteralAdapter(); } @Override public Adapter caseTLocalNotification(TLocalNotification object) { return createTLocalNotificationAdapter(); } @Override public Adapter caseTLogicalPeopleGroup(TLogicalPeopleGroup object) { return createTLogicalPeopleGroupAdapter(); } @Override public Adapter caseTLogicalPeopleGroups(TLogicalPeopleGroups object) { return createTLogicalPeopleGroupsAdapter(); } @Override public Adapter caseTNotification(TNotification object) { return createTNotificationAdapter(); } @Override public Adapter caseTNotificationInterface(TNotificationInterface object) { return createTNotificationInterfaceAdapter(); } @Override public Adapter caseTNotifications(TNotifications object) { return createTNotificationsAdapter(); } @Override public Adapter caseTOrganizationalEntity(TOrganizationalEntity object) { return createTOrganizationalEntityAdapter(); } @Override public Adapter caseTParameter(TParameter object) { return createTParameterAdapter(); } @Override public Adapter caseTPeopleAssignments(TPeopleAssignments object) { return createTPeopleAssignmentsAdapter(); } @Override public Adapter caseTPresentationElements(TPresentationElements object) { return createTPresentationElementsAdapter(); } @Override public Adapter caseTPresentationParameter(TPresentationParameter object) { return createTPresentationParameterAdapter(); } @Override public Adapter caseTPresentationParameters(TPresentationParameters object) { return createTPresentationParametersAdapter(); } @Override public Adapter caseTPriority(TPriority object) { return createTPriorityAdapter(); } @Override public Adapter caseTQuery(TQuery object) { return createTQueryAdapter(); } @Override public Adapter caseTReassignment(TReassignment object) { return createTReassignmentAdapter(); } @Override public Adapter caseTRendering(TRendering object) { return createTRenderingAdapter(); } @Override public Adapter caseTRenderings(TRenderings object) { return createTRenderingsAdapter(); } @Override public Adapter caseTTask(TTask object) { return createTTaskAdapter(); } @Override public Adapter caseTTaskInterface(TTaskInterface object) { return createTTaskInterfaceAdapter(); } @Override public Adapter caseTTasks(TTasks object) { return createTTasksAdapter(); } @Override public Adapter caseTText(TText object) { return createTTextAdapter(); } @Override public Adapter caseTToPart(TToPart object) { return createTToPartAdapter(); } @Override public Adapter caseTToParts(TToParts object) { return createTToPartsAdapter(); } @Override public Adapter caseTUserlist(TUserlist object) { return createTUserlistAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.DocumentRoot <em>Document Root</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.DocumentRoot * @generated */ public Adapter createDocumentRootAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TArgument <em>TArgument</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TArgument * @generated */ public Adapter createTArgumentAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TBooleanExpr <em>TBoolean Expr</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TBooleanExpr * @generated */ public Adapter createTBooleanExprAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDeadline <em>TDeadline</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDeadline * @generated */ public Adapter createTDeadlineAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDeadlineExpr <em>TDeadline Expr</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDeadlineExpr * @generated */ public Adapter createTDeadlineExprAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDeadlines <em>TDeadlines</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDeadlines * @generated */ public Adapter createTDeadlinesAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDelegation <em>TDelegation</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDelegation * @generated */ public Adapter createTDelegationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDescription <em>TDescription</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDescription * @generated */ public Adapter createTDescriptionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDocumentation <em>TDocumentation</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDocumentation * @generated */ public Adapter createTDocumentationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TDurationExpr <em>TDuration Expr</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TDurationExpr * @generated */ public Adapter createTDurationExprAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TEscalation <em>TEscalation</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TEscalation * @generated */ public Adapter createTEscalationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TExpression <em>TExpression</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TExpression * @generated */ public Adapter createTExpressionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TExtensibleElements <em>TExtensible Elements</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TExtensibleElements * @generated */ public Adapter createTExtensibleElementsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TExtensibleMixedContentElements <em>TExtensible Mixed Content Elements</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TExtensibleMixedContentElements * @generated */ public Adapter createTExtensibleMixedContentElementsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TExtension <em>TExtension</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TExtension * @generated */ public Adapter createTExtensionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TExtensions <em>TExtensions</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TExtensions * @generated */ public Adapter createTExtensionsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TFrom <em>TFrom</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TFrom * @generated */ public Adapter createTFromAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TGenericHumanRole <em>TGeneric Human Role</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TGenericHumanRole * @generated */ public Adapter createTGenericHumanRoleAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TGrouplist <em>TGrouplist</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TGrouplist * @generated */ public Adapter createTGrouplistAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.THumanInteractions <em>THuman Interactions</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.THumanInteractions * @generated */ public Adapter createTHumanInteractionsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TImport <em>TImport</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TImport * @generated */ public Adapter createTImportAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TLiteral <em>TLiteral</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TLiteral * @generated */ public Adapter createTLiteralAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TLocalNotification <em>TLocal Notification</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TLocalNotification * @generated */ public Adapter createTLocalNotificationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TLogicalPeopleGroup <em>TLogical People Group</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TLogicalPeopleGroup * @generated */ public Adapter createTLogicalPeopleGroupAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TLogicalPeopleGroups <em>TLogical People Groups</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TLogicalPeopleGroups * @generated */ public Adapter createTLogicalPeopleGroupsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TNotification <em>TNotification</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TNotification * @generated */ public Adapter createTNotificationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TNotificationInterface <em>TNotification Interface</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TNotificationInterface * @generated */ public Adapter createTNotificationInterfaceAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TNotifications <em>TNotifications</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TNotifications * @generated */ public Adapter createTNotificationsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TOrganizationalEntity <em>TOrganizational Entity</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TOrganizationalEntity * @generated */ public Adapter createTOrganizationalEntityAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TParameter <em>TParameter</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TParameter * @generated */ public Adapter createTParameterAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TPeopleAssignments <em>TPeople Assignments</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TPeopleAssignments * @generated */ public Adapter createTPeopleAssignmentsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TPresentationElements <em>TPresentation Elements</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TPresentationElements * @generated */ public Adapter createTPresentationElementsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TPresentationParameter <em>TPresentation Parameter</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TPresentationParameter * @generated */ public Adapter createTPresentationParameterAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TPresentationParameters <em>TPresentation Parameters</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TPresentationParameters * @generated */ public Adapter createTPresentationParametersAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TPriority <em>TPriority</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TPriority * @generated */ public Adapter createTPriorityAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TQuery <em>TQuery</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TQuery * @generated */ public Adapter createTQueryAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TReassignment <em>TReassignment</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TReassignment * @generated */ public Adapter createTReassignmentAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TRendering <em>TRendering</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TRendering * @generated */ public Adapter createTRenderingAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TRenderings <em>TRenderings</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TRenderings * @generated */ public Adapter createTRenderingsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TTask <em>TTask</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TTask * @generated */ public Adapter createTTaskAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TTaskInterface <em>TTask Interface</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TTaskInterface * @generated */ public Adapter createTTaskInterfaceAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TTasks <em>TTasks</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TTasks * @generated */ public Adapter createTTasksAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TText <em>TText</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TText * @generated */ public Adapter createTTextAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TToPart <em>TTo Part</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TToPart * @generated */ public Adapter createTToPartAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TToParts <em>TTo Parts</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TToParts * @generated */ public Adapter createTToPartsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.wso2.developerstudio.eclipse.humantask.model.ht.TUserlist <em>TUserlist</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.wso2.developerstudio.eclipse.humantask.model.ht.TUserlist * @generated */ public Adapter createTUserlistAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //HTAdapterFactory
/* * 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/bigquery/migration/v2alpha/migration_error_details.proto package com.google.cloud.bigquery.migration.v2alpha; /** * * * <pre> * Provides details for errors, e.g. issues that where encountered when * processing a subtask. * </pre> * * Protobuf type {@code google.cloud.bigquery.migration.v2alpha.ErrorDetail} */ public final class ErrorDetail extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.migration.v2alpha.ErrorDetail) ErrorDetailOrBuilder { private static final long serialVersionUID = 0L; // Use ErrorDetail.newBuilder() to construct. private ErrorDetail(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ErrorDetail() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ErrorDetail(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ErrorDetail( 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; case 10: { com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.Builder subBuilder = null; if (location_ != null) { subBuilder = location_.toBuilder(); } location_ = input.readMessage( com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(location_); location_ = subBuilder.buildPartial(); } break; } case 18: { com.google.rpc.ErrorInfo.Builder subBuilder = null; if (errorInfo_ != null) { subBuilder = errorInfo_.toBuilder(); } errorInfo_ = input.readMessage(com.google.rpc.ErrorInfo.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(errorInfo_); errorInfo_ = subBuilder.buildPartial(); } 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.bigquery.migration.v2alpha.MigrationErrorDetailsProto .internal_static_google_cloud_bigquery_migration_v2alpha_ErrorDetail_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.migration.v2alpha.MigrationErrorDetailsProto .internal_static_google_cloud_bigquery_migration_v2alpha_ErrorDetail_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.class, com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.Builder.class); } public static final int LOCATION_FIELD_NUMBER = 1; private com.google.cloud.bigquery.migration.v2alpha.ErrorLocation location_; /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the location field is set. */ @java.lang.Override public boolean hasLocation() { return location_ != null; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The location. */ @java.lang.Override public com.google.cloud.bigquery.migration.v2alpha.ErrorLocation getLocation() { return location_ == null ? com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.getDefaultInstance() : location_; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.bigquery.migration.v2alpha.ErrorLocationOrBuilder getLocationOrBuilder() { return getLocation(); } public static final int ERROR_INFO_FIELD_NUMBER = 2; private com.google.rpc.ErrorInfo errorInfo_; /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return Whether the errorInfo field is set. */ @java.lang.Override public boolean hasErrorInfo() { return errorInfo_ != null; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The errorInfo. */ @java.lang.Override public com.google.rpc.ErrorInfo getErrorInfo() { return errorInfo_ == null ? com.google.rpc.ErrorInfo.getDefaultInstance() : errorInfo_; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public com.google.rpc.ErrorInfoOrBuilder getErrorInfoOrBuilder() { return getErrorInfo(); } 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 { if (location_ != null) { output.writeMessage(1, getLocation()); } if (errorInfo_ != null) { output.writeMessage(2, getErrorInfo()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (location_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getLocation()); } if (errorInfo_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getErrorInfo()); } 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.bigquery.migration.v2alpha.ErrorDetail)) { return super.equals(obj); } com.google.cloud.bigquery.migration.v2alpha.ErrorDetail other = (com.google.cloud.bigquery.migration.v2alpha.ErrorDetail) obj; if (hasLocation() != other.hasLocation()) return false; if (hasLocation()) { if (!getLocation().equals(other.getLocation())) return false; } if (hasErrorInfo() != other.hasErrorInfo()) return false; if (hasErrorInfo()) { if (!getErrorInfo().equals(other.getErrorInfo())) return false; } 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(); if (hasLocation()) { hash = (37 * hash) + LOCATION_FIELD_NUMBER; hash = (53 * hash) + getLocation().hashCode(); } if (hasErrorInfo()) { hash = (37 * hash) + ERROR_INFO_FIELD_NUMBER; hash = (53 * hash) + getErrorInfo().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail 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.bigquery.migration.v2alpha.ErrorDetail parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail 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.bigquery.migration.v2alpha.ErrorDetail parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail 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.bigquery.migration.v2alpha.ErrorDetail parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail 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.bigquery.migration.v2alpha.ErrorDetail parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail 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.bigquery.migration.v2alpha.ErrorDetail 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> * Provides details for errors, e.g. issues that where encountered when * processing a subtask. * </pre> * * Protobuf type {@code google.cloud.bigquery.migration.v2alpha.ErrorDetail} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.migration.v2alpha.ErrorDetail) com.google.cloud.bigquery.migration.v2alpha.ErrorDetailOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.migration.v2alpha.MigrationErrorDetailsProto .internal_static_google_cloud_bigquery_migration_v2alpha_ErrorDetail_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.migration.v2alpha.MigrationErrorDetailsProto .internal_static_google_cloud_bigquery_migration_v2alpha_ErrorDetail_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.class, com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.Builder.class); } // Construct using com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.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(); if (locationBuilder_ == null) { location_ = null; } else { location_ = null; locationBuilder_ = null; } if (errorInfoBuilder_ == null) { errorInfo_ = null; } else { errorInfo_ = null; errorInfoBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.migration.v2alpha.MigrationErrorDetailsProto .internal_static_google_cloud_bigquery_migration_v2alpha_ErrorDetail_descriptor; } @java.lang.Override public com.google.cloud.bigquery.migration.v2alpha.ErrorDetail getDefaultInstanceForType() { return com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.migration.v2alpha.ErrorDetail build() { com.google.cloud.bigquery.migration.v2alpha.ErrorDetail result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.migration.v2alpha.ErrorDetail buildPartial() { com.google.cloud.bigquery.migration.v2alpha.ErrorDetail result = new com.google.cloud.bigquery.migration.v2alpha.ErrorDetail(this); if (locationBuilder_ == null) { result.location_ = location_; } else { result.location_ = locationBuilder_.build(); } if (errorInfoBuilder_ == null) { result.errorInfo_ = errorInfo_; } else { result.errorInfo_ = errorInfoBuilder_.build(); } 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.bigquery.migration.v2alpha.ErrorDetail) { return mergeFrom((com.google.cloud.bigquery.migration.v2alpha.ErrorDetail) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.bigquery.migration.v2alpha.ErrorDetail other) { if (other == com.google.cloud.bigquery.migration.v2alpha.ErrorDetail.getDefaultInstance()) return this; if (other.hasLocation()) { mergeLocation(other.getLocation()); } if (other.hasErrorInfo()) { mergeErrorInfo(other.getErrorInfo()); } 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.bigquery.migration.v2alpha.ErrorDetail parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.bigquery.migration.v2alpha.ErrorDetail) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.cloud.bigquery.migration.v2alpha.ErrorLocation location_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.migration.v2alpha.ErrorLocation, com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.Builder, com.google.cloud.bigquery.migration.v2alpha.ErrorLocationOrBuilder> locationBuilder_; /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the location field is set. */ public boolean hasLocation() { return locationBuilder_ != null || location_ != null; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The location. */ public com.google.cloud.bigquery.migration.v2alpha.ErrorLocation getLocation() { if (locationBuilder_ == null) { return location_ == null ? com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.getDefaultInstance() : location_; } else { return locationBuilder_.getMessage(); } } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setLocation(com.google.cloud.bigquery.migration.v2alpha.ErrorLocation value) { if (locationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } location_ = value; onChanged(); } else { locationBuilder_.setMessage(value); } return this; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setLocation( com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.Builder builderForValue) { if (locationBuilder_ == null) { location_ = builderForValue.build(); onChanged(); } else { locationBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeLocation(com.google.cloud.bigquery.migration.v2alpha.ErrorLocation value) { if (locationBuilder_ == null) { if (location_ != null) { location_ = com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.newBuilder(location_) .mergeFrom(value) .buildPartial(); } else { location_ = value; } onChanged(); } else { locationBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearLocation() { if (locationBuilder_ == null) { location_ = null; onChanged(); } else { location_ = null; locationBuilder_ = null; } return this; } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.Builder getLocationBuilder() { onChanged(); return getLocationFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.bigquery.migration.v2alpha.ErrorLocationOrBuilder getLocationOrBuilder() { if (locationBuilder_ != null) { return locationBuilder_.getMessageOrBuilder(); } else { return location_ == null ? com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.getDefaultInstance() : location_; } } /** * * * <pre> * Optional. The exact location within the resource (if applicable). * </pre> * * <code> * .google.cloud.bigquery.migration.v2alpha.ErrorLocation location = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.migration.v2alpha.ErrorLocation, com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.Builder, com.google.cloud.bigquery.migration.v2alpha.ErrorLocationOrBuilder> getLocationFieldBuilder() { if (locationBuilder_ == null) { locationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.migration.v2alpha.ErrorLocation, com.google.cloud.bigquery.migration.v2alpha.ErrorLocation.Builder, com.google.cloud.bigquery.migration.v2alpha.ErrorLocationOrBuilder>( getLocation(), getParentForChildren(), isClean()); location_ = null; } return locationBuilder_; } private com.google.rpc.ErrorInfo errorInfo_; private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.ErrorInfo, com.google.rpc.ErrorInfo.Builder, com.google.rpc.ErrorInfoOrBuilder> errorInfoBuilder_; /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return Whether the errorInfo field is set. */ public boolean hasErrorInfo() { return errorInfoBuilder_ != null || errorInfo_ != null; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The errorInfo. */ public com.google.rpc.ErrorInfo getErrorInfo() { if (errorInfoBuilder_ == null) { return errorInfo_ == null ? com.google.rpc.ErrorInfo.getDefaultInstance() : errorInfo_; } else { return errorInfoBuilder_.getMessage(); } } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setErrorInfo(com.google.rpc.ErrorInfo value) { if (errorInfoBuilder_ == null) { if (value == null) { throw new NullPointerException(); } errorInfo_ = value; onChanged(); } else { errorInfoBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setErrorInfo(com.google.rpc.ErrorInfo.Builder builderForValue) { if (errorInfoBuilder_ == null) { errorInfo_ = builderForValue.build(); onChanged(); } else { errorInfoBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder mergeErrorInfo(com.google.rpc.ErrorInfo value) { if (errorInfoBuilder_ == null) { if (errorInfo_ != null) { errorInfo_ = com.google.rpc.ErrorInfo.newBuilder(errorInfo_).mergeFrom(value).buildPartial(); } else { errorInfo_ = value; } onChanged(); } else { errorInfoBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder clearErrorInfo() { if (errorInfoBuilder_ == null) { errorInfo_ = null; onChanged(); } else { errorInfo_ = null; errorInfoBuilder_ = null; } return this; } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.rpc.ErrorInfo.Builder getErrorInfoBuilder() { onChanged(); return getErrorInfoFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.rpc.ErrorInfoOrBuilder getErrorInfoOrBuilder() { if (errorInfoBuilder_ != null) { return errorInfoBuilder_.getMessageOrBuilder(); } else { return errorInfo_ == null ? com.google.rpc.ErrorInfo.getDefaultInstance() : errorInfo_; } } /** * * * <pre> * Required. Describes the cause of the error with structured detail. * </pre> * * <code>.google.rpc.ErrorInfo error_info = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.ErrorInfo, com.google.rpc.ErrorInfo.Builder, com.google.rpc.ErrorInfoOrBuilder> getErrorInfoFieldBuilder() { if (errorInfoBuilder_ == null) { errorInfoBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.ErrorInfo, com.google.rpc.ErrorInfo.Builder, com.google.rpc.ErrorInfoOrBuilder>( getErrorInfo(), getParentForChildren(), isClean()); errorInfo_ = null; } return errorInfoBuilder_; } @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.bigquery.migration.v2alpha.ErrorDetail) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.migration.v2alpha.ErrorDetail) private static final com.google.cloud.bigquery.migration.v2alpha.ErrorDetail DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.migration.v2alpha.ErrorDetail(); } public static com.google.cloud.bigquery.migration.v2alpha.ErrorDetail getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ErrorDetail> PARSER = new com.google.protobuf.AbstractParser<ErrorDetail>() { @java.lang.Override public ErrorDetail parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ErrorDetail(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ErrorDetail> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ErrorDetail> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.migration.v2alpha.ErrorDetail getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spi.impl.operationservice.impl; import com.hazelcast.config.Config; import com.hazelcast.config.ServiceConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.instance.Node; import com.hazelcast.nio.Address; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.spi.BackupAwareOperation; import com.hazelcast.spi.BackupOperation; import com.hazelcast.spi.InternalCompletableFuture; import com.hazelcast.spi.NodeEngine; import com.hazelcast.spi.Operation; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.spi.impl.operationservice.impl.operations.Backup; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static com.hazelcast.test.TestPartitionUtils.getReplicaVersions; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(HazelcastSerialClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class OperationOutOfOrderBackupTest extends HazelcastTestSupport { private final ValueHolderService service = new ValueHolderService(); private int partitionId; private NodeEngineImpl nodeEngine1; private NodeEngineImpl nodeEngine2; @Before public void setup() { Config config = new Config(); config.getServicesConfig().addServiceConfig(new ServiceConfig() .setImplementation(service).setName(ValueHolderService.NAME).setEnabled(true)); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz1 = factory.newHazelcastInstance(config); HazelcastInstance hz2 = factory.newHazelcastInstance(config); warmUpPartitions(hz2, hz1); partitionId = getPartitionId(hz1); nodeEngine1 = getNodeEngineImpl(hz1); nodeEngine2 = getNodeEngineImpl(hz2); } @Test public void test() throws InterruptedException { // set 1st value int oldValue = 111; setValue(nodeEngine1, partitionId, oldValue); long[] initialReplicaVersions = getReplicaVersions(nodeEngine1.getNode(), partitionId); assertBackupReplicaVersions(nodeEngine2.getNode(), partitionId, initialReplicaVersions); // set 2nd value int newValue = 222; setValue(nodeEngine1, partitionId, newValue); long[] lastReplicaVersions = getReplicaVersions(nodeEngine1.getNode(), partitionId); assertBackupReplicaVersions(nodeEngine2.getNode(), partitionId, lastReplicaVersions); // run a stale backup runBackup(nodeEngine2, oldValue, initialReplicaVersions, nodeEngine1.getThisAddress()); long[] backupReplicaVersions = getReplicaVersions(nodeEngine2.getNode(), partitionId); assertArrayEquals(lastReplicaVersions, backupReplicaVersions); assertEquals(newValue, service.value.get()); } private void runBackup(NodeEngine nodeEngine, int value, long[] replicaVersions, Address sender) throws InterruptedException { Backup backup = new Backup(new SampleBackupOperation(value), sender, replicaVersions, false); backup.setPartitionId(partitionId).setReplicaIndex(1).setNodeEngine(nodeEngine); nodeEngine.getOperationService().execute(backup); LatchOperation latchOp = new LatchOperation(1); nodeEngine.getOperationService().execute(latchOp.setPartitionId(partitionId)); assertTrue(latchOp.latch.await(1, TimeUnit.MINUTES)); } private void assertBackupReplicaVersions(final Node node, final int partitionId, final long[] expectedReplicaVersions) { assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { long[] backupReplicaVersions = getReplicaVersions(node, partitionId); assertArrayEquals(expectedReplicaVersions, backupReplicaVersions); } }); } private void setValue(NodeEngine nodeEngine, int partitionId, int value) { InternalCompletableFuture<Object> future = nodeEngine.getOperationService() .invokeOnPartition(new SampleBackupAwareOperation(value).setPartitionId(partitionId)); future.join(); } private static class ValueHolderService { static final String NAME = "value-holder-service"; final AtomicLong value = new AtomicLong(); } private static class SampleBackupAwareOperation extends Operation implements BackupAwareOperation { long value; public SampleBackupAwareOperation() { } public SampleBackupAwareOperation(long value) { this.value = value; } @Override public void run() throws Exception { NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine(); ValueHolderService service = nodeEngine.getService(ValueHolderService.NAME); service.value.set(value); } @Override public boolean shouldBackup() { return true; } @Override public int getSyncBackupCount() { return 1; } @Override public int getAsyncBackupCount() { return 0; } @Override public Operation getBackupOperation() { return new SampleBackupOperation(value); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(value); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); value = in.readLong(); } } private static class SampleBackupOperation extends Operation implements BackupOperation { final CountDownLatch latch = new CountDownLatch(1); long value; public SampleBackupOperation() { } public SampleBackupOperation(long value) { this.value = value; } @Override public void run() throws Exception { try { NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine(); ValueHolderService service = nodeEngine.getService(ValueHolderService.NAME); service.value.set(value); } finally { latch.countDown(); } } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(value); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); value = in.readLong(); } } private static class LatchOperation extends Operation { final CountDownLatch latch; private LatchOperation(int count) { latch = new CountDownLatch(count); } @Override public void run() throws Exception { latch.countDown(); } @Override public boolean returnsResponse() { return false; } @Override public boolean validatesTarget() { return false; } } }
// pNSGAIIRegion.java // // Author(s): // Simos Gerasimou <simos@cs.york.ac.uk> // Antonio J. Nebro <antonio@lcc.uma.es> // // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package evochecker.genetic.jmetal.metaheuristics; import java.util.List; import evochecker.auxiliary.Constants; import evochecker.auxiliary.KnowledgeSingleton; import evochecker.auxiliary.Utility; import evochecker.genetic.jmetal.encoding.solution.RegionSolution; import evochecker.genetic.jmetal.util.ExampleRegionDistance; import evochecker.genetic.jmetal.util.RegionDistance; import evochecker.genetic.jmetal.util.RegionDominanceComparator; import evochecker.genetic.jmetal.util.RegionRanking; import evochecker.genetic.jmetal.util.eDominanceWorstCaseDominanceComparator; import jmetal.core.Algorithm; import jmetal.core.Operator; import jmetal.core.Problem; import jmetal.core.Solution; import jmetal.core.SolutionSet; import jmetal.qualityIndicator.QualityIndicator; import jmetal.util.JMException; import jmetal.util.comparators.CrowdingComparator; /** * Modified implementation of NSGA-II for regions * */ public class pNSGAIIRegion extends Algorithm { /** Parallel evaluator handler*/ IParallelEvaluator parallelEvaluator_ ; /** Region comparator handler*/ RegionDominanceComparator regionDominanceComparator; /** Region distance handler*/ RegionDistance regionDistance; /** Knowledge singleton*/ KnowledgeSingleton knowledge = KnowledgeSingleton.getInstance(); int currentGeneration = 0; /** * Constructor * @param problem Problem to solve * @param evaluator Parallel evaluator */ public pNSGAIIRegion(Problem problem, IParallelEvaluator evaluator) { super (problem) ; this.parallelEvaluator_ = evaluator; //New commands for regions: SET THE DOMINANCE & DISTANCE COMPARATOR for (Constants.DOMINANCE d : Constants.DOMINANCE.values()) { if (Utility.getProperty(Constants.DOMINANCE_KEYWORD).trim().equals(d.name().trim())) { this.regionDominanceComparator = d.getDominance(d); break; } } // this.regionDominanceComparator = new eDominanceWorstCaseDominanceComparator(); this.regionDistance = new ExampleRegionDistance(); } // pNSGAII /** * Runs the NSGA-II algorithm. * @return a <code>SolutionSet</code> that is a set of non dominated solutions * as a result of the algorithm execution * @throws JMException */ public SolutionSet execute() throws JMException, ClassNotFoundException { int populationSize; int maxEvaluations; int evaluations; QualityIndicator indicators; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; //Read the parameters populationSize = ((Integer) getInputParameter("populationSize")).intValue(); maxEvaluations = ((Integer) getInputParameter("maxEvaluations")).intValue(); indicators = (QualityIndicator) getInputParameter("indicators"); parallelEvaluator_.startEvaluator(problem_) ; //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = operators_.get("mutation"); crossoverOperator = operators_.get("crossover"); selectionOperator = operators_.get("selection"); // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new RegionSolution(problem_); //Solution(problem_); parallelEvaluator_.addSolutionForEvaluation(newSolution) ; } List<Solution> solutionList = parallelEvaluator_.parallelEvaluation() ; for (Solution solution : solutionList) { population.add(solution) ; evaluations ++ ; } //process generation knowledge.processGeneration(population, currentGeneration++); // Generations while (evaluations < maxEvaluations) { System.out.println("Evaluations:\t" + evaluations); knowledge.addMessage("Evaluations:\t" + evaluations); // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize); Solution[] parents = new Solution[2]; for (int i = 0; i < (populationSize / 2); i++) { if (evaluations < maxEvaluations) { //obtain parents parents[0] = (Solution) selectionOperator.execute(population); parents[1] = (Solution) selectionOperator.execute(population); Solution[] offSpring = (Solution[]) crossoverOperator.execute(parents); mutationOperator.execute(offSpring[0]); mutationOperator.execute(offSpring[1]); parallelEvaluator_.addSolutionForEvaluation(new RegionSolution(offSpring[0])) ; parallelEvaluator_.addSolutionForEvaluation(new RegionSolution(offSpring[1])) ; } // if } // for List<Solution> solutions = parallelEvaluator_.parallelEvaluation() ; for(Solution solution : solutions) { offspringPopulation.add(solution); evaluations++; } // Create the solutionSet union of solutionSet and offSpring union = ((SolutionSet) population).union(offspringPopulation); // Ranking the union //Ranking ranking = new Ranking(union); RegionRanking ecRanking = new RegionRanking(union, regionDominanceComparator); int remain = populationSize; int index = 0; SolutionSet front = null; population.clear(); // Obtain the next front front = ecRanking.getSubfront(index); while ((remain > 0) && (remain >= front.size())) { //Assign crowding distance to individuals regionDistance.crowdingDistanceAssignment(front, problem_.getNumberOfObjectives()); //Add the individuals of this front for (int k = 0; k < front.size(); k++) { population.add(front.get(k)); } // for //Decrement remain remain = remain - front.size(); //Obtain the next front index++; if (remain > 0) { front = ecRanking.getSubfront(index); } // if } // while // Remain is less than front(index).size, insert only the best one if (remain > 0) { // front contains individuals to insert regionDistance.crowdingDistanceAssignment(front, problem_.getNumberOfObjectives()); front.sort(new CrowdingComparator()); for (int k = 0; k < remain; k++) { population.add(front.get(k)); } // for remain = 0; } // if //process generation knowledge.processGeneration(ecRanking.getSubfront(0), currentGeneration++); // This piece of code shows how to use the indicator object into the code // of NSGA-II. In particular, it finds the number of evaluations required // by the algorithm to obtain a Pareto front with a hypervolume higher // than the hypervolume of the true Pareto front. // if ((indicators != null) && // (requiredEvaluations == 0)) { // double HV = indicators.getHypervolume(population); // if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) { // requiredEvaluations = evaluations; // } // if // }// if } // while parallelEvaluator_.stopEvaluators(); // Return as output parameter the required evaluations setOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front RegionRanking ecRanking = new RegionRanking(population, regionDominanceComparator); return ecRanking.getSubfront(0); } // execute } // pNSGAII
package org.jge; import static org.lwjgl.opengl.GL11.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import javax.imageio.ImageIO; import org.jge.Profiler.ProfileTimer; import org.jge.cl.GPUProgramResource; import org.jge.game.Game; import org.jge.game.Input; import org.jge.phys.PhysicsEngine; import org.jge.render.RenderEngine; import org.jge.render.Texture; import org.jge.render.shaders.JavaShader; import org.jge.sound.Music; import org.jge.sound.SoundEngine; import org.jge.util.LWJGLHandler; import org.jge.util.Log; import org.jge.util.OpenGLUtils; import org.jge.util.Strings; import org.jglrxavpok.jlsl.BytecodeDecoder; import org.jglrxavpok.jlsl.glsl.GLSLEncoder; import org.lwjgl.openal.AL; import org.lwjgl.openal.AL10; import org.lwjgl.opencl.CL; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GLContext; /** * The MIT License (MIT) * * Copyright (c) 2014 jglrxavpok * * 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. * * @author jglrxavpok * */ public final class CoreEngine { private ProfileTimer sleepTimer = new ProfileTimer(); private ProfileTimer windowUpdateTimer = new ProfileTimer(); private boolean running; private Window window; private RenderEngine renderEngine; private SoundEngine soundEngine; private ClasspathSimpleResourceLoader classResLoader; private Game game; private int frame; private int fps; private double expectedFrameRate = 60.0; private double timeBetweenUpdates = 1000000000 / expectedFrameRate; private final int maxUpdatesBeforeRender = 2; private double lastUpdateTime = System.nanoTime(); private double lastRenderTime = System.nanoTime(); // If we are able to get as high as this FPS, don't render again. private final double TARGET_FPS = 60; private final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS; private int lastSecondTime = (int)(lastUpdateTime / 1000000000); private boolean paused = false; private PhysicsEngine physEngine; private DiskSimpleResourceLoader diskResLoader; private static CoreEngine current; private ArrayList<ITickable> tickables = new ArrayList<ITickable>(); private boolean debug; public boolean updateOnly; public CoreEngine(Game game) { current = this; JGEngine.setGame(game.setEngine(this)); this.game = game; } public Game getGame() { return game; } public boolean isRunning() { return running; } public void start(Window window) { start(window, new String[0]); } public void start(Window window, String args[]) { new Thread(() -> { try { new ThreadReadConsoleInput().start(); classResLoader = new ClasspathSimpleResourceLoader(); diskResLoader = new DiskSimpleResourceLoader(); running = true; if(window != null) { this.window = window; expectedFrameRate = window.getFPSCap(); } else { expectedFrameRate = 60; } timeBetweenUpdates = 1000000000 / expectedFrameRate; try { if(!updateOnly) { LWJGLHandler.load(new File(JGEngine.getEngineFolder(), "natives")); window.setTitle(game.getGameName()); window.init(); } String currentParameter = null; HashMap<String, String> props = new HashMap<String, String>(); props.put("debugAll", "false"); for(int i = 0; i < args.length; i++ ) { if(args[i].startsWith("-")) { currentParameter = args[i].substring(1); } else { props.put(currentParameter, args[i]); } } if(props.get("debugAll").equals("true")) { Log.save = true; GLSLEncoder.DEBUG = true; BytecodeDecoder.DEBUG = true; JavaShader.DEBUG_PRINT_GLSL_TRANSLATION = true; debug = true; } if(!updateOnly) { if(!GLContext.getCapabilities().OpenGL33) { Log.message("Incompatible OpenGL version: " + OpenGLUtils.getOpenGLVersion()); Log.message("Must be at least: 3.3.0"); cleanup(); } soundEngine = new SoundEngine(); OpenGLUtils.loadCapNames(); CL.create(); Log.message("[------OpenGL infos------]"); Log.message(" Version: " + OpenGLUtils.getOpenGLVersion()); Log.message(" Vendor: " + OpenGLUtils.getOpenGLVendor()); Log.message("[------OpenAL infos------]"); Log.message(" Version: " + AL10.alGetString(AL10.AL_VERSION)); Log.message(" Vendor: " + AL10.alGetString(AL10.AL_VENDOR)); Log.message("[------Engine infos------]"); Log.message(" Version: " + JGEngine.getEngineVersion()); Log.message("------------------------"); } } catch(Exception e) { e.printStackTrace(); } physEngine = new PhysicsEngine(); if(!updateOnly) { renderEngine = new RenderEngine(); renderEngine.getEventBus().registerListener(game); RenderEngine.printIfGLError(); Texture loadingScreenText = null; try { loadingScreenText = renderEngine.loadTexture(classResLoader.getResource(new ResourceLocation("textures", "loadingScreen.png"))); } catch(Exception e) { e.printStackTrace(); System.exit(-1); } LoadingScreen loadingScreen = new MonoThreadedLoadingScreen(game); loadingScreen.setBackgroundImage(loadingScreenText); game.setLoadingScreen(loadingScreen); game.drawLoadingScreen("Loading..."); } Properties properties = new Properties(); File propsFile = new File(game.getGameFolder(), "properties.txt"); if(!propsFile.exists()) { propsFile.createNewFile(); } properties.load(new FileInputStream(propsFile)); game.setProperties(properties); game.onPropertiesLoad(properties); if(!updateOnly) { renderEngine.init(); soundEngine.init(); } physEngine.init(); game.init(); boolean b = true; while(running && b && game.isRunning()) { tick(); if(window != null && !updateOnly) b = !window.shouldBeClosed(); } } catch(Exception e) { e.printStackTrace(); } cleanup(); System.exit(0); }).start(); } private void cleanup() { running = false; if(!updateOnly) { AL.destroy(); GPUProgramResource.destroyAll(); CL.destroy(); } JGEngine.disposeAll(); if(!updateOnly) { window.disposeWindow(); } try { game.saveProperties(); Log.finish(); } catch(Exception e) { e.printStackTrace(); } } private final void tick() { if(!updateOnly) { if(game.getCursor() != null) window.hideCursor(); } double now = System.nanoTime(); int updateCount = 0; if(!paused) { if(!updateOnly) { Input.pollEvents(); } double delta = timeBetweenUpdates / 1000000000; while(now - lastUpdateTime > timeBetweenUpdates && updateCount < maxUpdatesBeforeRender) { update(delta); lastUpdateTime += timeBetweenUpdates; updateCount++ ; } if(now - lastUpdateTime > timeBetweenUpdates) { lastUpdateTime = now - timeBetweenUpdates; } render(delta); if(!updateOnly) { windowUpdateTimer.startInvocation(); window.refresh(); windowUpdateTimer.endInvocation(); } lastRenderTime = now; // Update the frames we got. int thisSecond = (int)(lastUpdateTime / 1000000000); frame++ ; if(thisSecond > lastSecondTime) { fps = frame; double totalTime = (1000.0 * (double)(thisSecond - lastSecondTime)) / (double)frame; double totalRecordedTime = 0; if(Profiler.display) { totalRecordedTime += physEngine.displayProfileInfo((double)frame); totalRecordedTime += game.displayUpdateTime((double)frame); totalRecordedTime += renderEngine.displayRenderTime((double)frame); totalRecordedTime += renderEngine.displayWindowSyncTime((double)frame); totalRecordedTime += windowUpdateTimer.displayAndReset("Window update time", (double)frame); totalRecordedTime += sleepTimer.displayAndReset("Sleep time", (double)frame); Log.message("Non-profiled time: " + (totalTime - totalRecordedTime) + " ms"); Log.message("Total time: " + totalTime + " ms"); Log.message(fps + " fps"); } frame = 0; lastSecondTime = thisSecond; } while(now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < timeBetweenUpdates) { sleepTimer.startInvocation(); Thread.yield(); try { Thread.sleep(1); } catch(Exception e) { } now = System.nanoTime(); sleepTimer.endInvocation(); } } if(!updateOnly) if(!window.isActive()) try { window.setFullscreen(false); } catch(EngineException e) { e.printStackTrace(); } } private boolean screenshotKey = false; private int tick; private void update(double delta) { if(!updateOnly) { if(Input.isKeyDown(Input.KEY_F2) && !screenshotKey) { screenshotKey = true; try { File screenshotsFolder = new File(game.getGameFolder(), "screenshots"); if(!screenshotsFolder.exists()) { screenshotsFolder.mkdirs(); } ImageIO.write(LWJGLHandler.takeScreenshot(), "png", new File(screenshotsFolder, Strings.createCorrectedFileName(Time.getTimeAsString()) + ".png")); } catch(IOException e) { e.printStackTrace(); } } else if(!Input.isKeyDown(Input.KEY_F2) && screenshotKey) { screenshotKey = false; } } Time.setDelta(delta); int lastRecordedTick = tick; while(game.getLoadingScreen() != null && !game.getLoadingScreen().isFinished() && !updateOnly) { for(Music m : Music.musicsPlaying()) { m.stop(); } if(game.getLoadingScreen().getType() == LoadingScreenType.MULTI_THREADED) { Display.sync(60); } tick++ ; // We fake the tick counter to update animations tickTickables(true); game.getLoadingScreen().refreshScreen(); game.getLoadingScreen().runFirstTaskGroupAvailable(); } tick = lastRecordedTick; physEngine.update(delta); if(!updateOnly) { soundEngine.update(delta); } game.update(delta); tickTickables(false); tick++ ; } private void tickTickables(boolean inLoadingScreen) { for(ITickable tickable : tickables) tickable.tick(inLoadingScreen); } public RenderEngine getRenderEngine() { return renderEngine; } private void render(double delta) { if(updateOnly) { return; } window.updateSizeIfNeeded(); renderEngine.clearBuffers(); glColor4f(1, 1, 1, 1); game.render(renderEngine, delta); } public ResourceLoader getClasspathResourceLoader() { return classResLoader; } public Window getWindow() { return window; } public static CoreEngine getCurrent() { return current; } public SoundEngine getSoundEngine() { return soundEngine; } public PhysicsEngine getPhysicsEngine() { return physEngine; } public ResourceLoader getDiskResourceLoader() { return diskResLoader; } public int getTick() { return tick; } public void kill() { running = false; cleanup(); } public void addTickableObject(ITickable tickable) { tickables.add(tickable); } public boolean isDebug() { return debug; } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.example.android.sunshine.ForecastAdapter.ForecastAdapterOnClickHandler; import com.example.android.sunshine.data.SunshinePreferences; import com.example.android.sunshine.utilities.NetworkUtils; import com.example.android.sunshine.utilities.OpenWeatherJsonUtils; import java.net.URL; public class MainActivity extends AppCompatActivity implements ForecastAdapterOnClickHandler { private static final String TAG = MainActivity.class.getSimpleName(); private RecyclerView mRecyclerView; private ForecastAdapter mForecastAdapter; private TextView mErrorMessageDisplay; private ProgressBar mLoadingIndicator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forecast); /* * Using findViewById, we get a reference to our RecyclerView from xml. This allows us to * do things like set the adapter of the RecyclerView and toggle the visibility. */ mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_forecast); /* This TextView is used to display errors and will be hidden if there are no errors */ mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display); /* * LinearLayoutManager can support HORIZONTAL or VERTICAL orientations. The reverse layout * parameter is useful mostly for HORIZONTAL layouts that should reverse for right to left * languages. */ LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(layoutManager); /* * Use this setting to improve performance if you know that changes in content do not * change the child layout size in the RecyclerView */ mRecyclerView.setHasFixedSize(true); /* * The ForecastAdapter is responsible for linking our weather data with the Views that * will end up displaying our weather data. */ mForecastAdapter = new ForecastAdapter(this); /* Setting the adapter attaches it to the RecyclerView in our layout. */ mRecyclerView.setAdapter(mForecastAdapter); /* * The ProgressBar that will indicate to the user that we are loading data. It will be * hidden when no data is loading. * * Please note: This so called "ProgressBar" isn't a bar by default. It is more of a * circle. We didn't make the rules (or the names of Views), we just follow them. */ mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator); /* Once all of our views are setup, we can load the weather data. */ loadWeatherData(); } /** * This method will get the user's preferred location for weather, and then tell some * background method to get the weather data in the background. */ private void loadWeatherData() { String location = SunshinePreferences.getPreferredWeatherLocation(this); new FetchWeatherTask().execute(location); } /** * This method is overridden by our MainActivity class in order to handle RecyclerView item * clicks. * * @param weatherForDay The weather for the day that was clicked */ @Override public void onClick(String weatherForDay) { Context context = this; Class destinationClass = DetailActivity.class; Intent intentToStartDetailActivity = new Intent(context, destinationClass); intentToStartDetailActivity.putExtra(Intent.EXTRA_TEXT, weatherForDay); startActivity(intentToStartDetailActivity); } /** * This method will make the View for the weather data visible and * hide the error message. * <p> * Since it is okay to redundantly set the visibility of a View, we don't * need to check whether each view is currently visible or invisible. */ private void showWeatherDataView() { /* First, make sure the error is invisible */ mErrorMessageDisplay.setVisibility(View.INVISIBLE); /* Then, make sure the weather data is visible */ mRecyclerView.setVisibility(View.VISIBLE); } /** * This method will make the error message visible and hide the weather * View. * <p> * Since it is okay to redundantly set the visibility of a View, we don't * need to check whether each view is currently visible or invisible. */ private void showErrorMessage() { /* First, hide the currently visible data */ mRecyclerView.setVisibility(View.INVISIBLE); /* Then, show the error */ mErrorMessageDisplay.setVisibility(View.VISIBLE); } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { @Override protected void onPreExecute() { super.onPreExecute(); mLoadingIndicator.setVisibility(View.VISIBLE); } @Override protected String[] doInBackground(String... params) { /* If there's no zip code, there's nothing to look up. */ if (params.length == 0) { return null; } String location = params[0]; URL weatherRequestUrl = NetworkUtils.buildUrl(location); try { String jsonWeatherResponse = NetworkUtils .getResponseFromHttpUrl(weatherRequestUrl); String[] simpleJsonWeatherData = OpenWeatherJsonUtils .getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse); return simpleJsonWeatherData; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String[] weatherData) { mLoadingIndicator.setVisibility(View.INVISIBLE); if (weatherData != null) { showWeatherDataView(); mForecastAdapter.setWeatherData(weatherData); } else { showErrorMessage(); } } } /** * This method uses the URI scheme for showing a location found on a * map. This super-handy intent is detailed in the "Common Intents" * page of Android's developer site: * * @see <a"http://developer.android.com/guide/components/intents-common.html#Maps"> * * Hint: Hold Command on Mac or Control on Windows and click that link * to automagically open the Common Intents page */ private void openLocationInMap() { String addressString = "1600 Ampitheatre Parkway, CA"; Uri geoLocation = Uri.parse("geo:0,0?q=" + addressString); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(geoLocation); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { Log.d(TAG, "Couldn't call " + geoLocation.toString() + ", no receiving apps installed!"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ inflater.inflate(R.menu.forecast, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_refresh) { mForecastAdapter.setWeatherData(null); loadWeatherData(); return true; } // COMPLETED (2) Launch the map when the map menu item is clicked if (id == R.id.action_map) { openLocationInMap(); return true; } return super.onOptionsItemSelected(item); } }
/* * 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.sis.metadata.sql; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLNonTransientException; import org.apache.sis.internal.metadata.sql.SQLBuilder; /** * Checks the existence of identifiers (usually primary keys) in a set of tables. * This class implements a very naive algorithm and is used only when some reasonably meaningful ID are wanted. * If "meaningful" ID is not a requirement, then it is much more efficient to rely on the ID numbers generated * automatically by the database. * * <p>This class checks if a given identifier exists in the database. If it exists, then it searches for an unused * {@code "proposal-n"} identifier, where {@code "proposal"} is the given identifier and {@code "n"} is a number. * The algorithm in this class takes advantage of the fact that alphabetical order is not the same than numerical * order for scanning a slightly smaller amount of records (however the gain is significant only in special cases. * Generally speaking this class is not for tables having thousands of identifier beginning with the given prefix). * However the selected numbers are not guaranteed to be in increasing order if there is "holes" in the sequence of * numbers (i.e. if some old records have been deleted). Generating strictly increasing sequence is not a goal of this * class, since it would be too costly.</p> * * <div class="section">Assumptions</div> * <ul> * <li>{@code SELECT DISTINCT "ID" FROM "Table" WHERE "ID" LIKE 'proposal%' ORDER BY "ID";} is assumed efficient. * For example in the case of a PostgreSQL database, it requires PostgreSQL 8.0 or above with a {@code btree} * index and C locale.</li> * <li>The ordering of the {@code '-'} and {@code '0'} to {@code '9'} characters compared to other characters * is the same than ASCII. This condition needs to hold only for those particular characters (the ordering * between letters does not matter).</li> * </ul> * * @author Martin Desruisseaux (Geomatys) * @version 0.8 * @since 0.8 * @module */ final class IdentifierGenerator implements AutoCloseable { /** * The character to be used as a separator between the prefix and the sequence number. */ static final char SEPARATOR = '-'; /** * The statement to use for searching free identifiers. */ private final PreparedStatement statement; /** * A helper object for building SQL statements, determined from database metadata. */ private final SQLBuilder buffer; /** * Index of the first character to parse in the identifier in order to get its sequential number. */ private int parseAt; /** * The greatest sequential number found during the search for a free identifier. * This will be used only if we found no "hole" in the sequence of numbers. */ private int maximalSequenceNumber; /** * If different than 0, the suggested sequential number to append to the identifier. */ private int freeSequenceNumber; /** * Creates a new generator. * * @param schema the schema, or {@code null} if none. * @param table the table name where to search for an identifier. * @param source information about the metadata database. * @param column name of the identifier (primary key) column. * @param buffer a helper object for building SQL statements, determined from database metadata. */ IdentifierGenerator(final MetadataSource source, final String schema, final String table, final String column, final SQLBuilder buffer) throws SQLException { assert Thread.holdsLock(source); this.buffer = buffer; buffer.clear().append("SELECT DISTINCT ") .appendIdentifier(column).append(" FROM ").appendIdentifier(schema, table).append(" WHERE ") .appendIdentifier(column).append(" LIKE ? ORDER BY ") .appendIdentifier(column); statement = source.connection().prepareStatement(buffer.toString()); } /** * Searches for a free identifier. If the given proposal is already in use, then this method will search * for another identifier of the form {@code "proposal-n"} not in use, where {@code "n"} is a number. * * @param proposal the proposed identifier. It will be returned if not currently used. * @return an identifier which does not exist at the time this method has been invoked. * @throws SQLException if an error occurred while searching for an identifier. */ final String identifier(String proposal) throws SQLException { statement.setString(1, buffer.clear().appendEscaped(proposal).append('%').toString()); try (ResultSet rs = statement.executeQuery()) { if (rs.next()) { String current = rs.getString(1); if (current.equals(proposal)) { /* * The proposed identifier is already used. If there is no other identifiers, * just append "-1" and we are done. Otherwise we need to search for a "hole" * in the sequence of number suffixes. */ parseAt = proposal.length() + 1; freeSequenceNumber = 0; maximalSequenceNumber = 0; int expected = 0; searchValidRecord: while (rs.next()) { current = rs.getString(1); assert current.startsWith(proposal) : current; while (current.length() > parseAt) { int c = current.codePointBefore(parseAt); if (c < SEPARATOR) continue searchValidRecord; if (c > SEPARATOR) break searchValidRecord; c = current.codePointAt(parseAt); /* * Intentionally exclude any record having leading zeros, * since it would confuse our algorithm. */ if (c < '1') continue searchValidRecord; if (c > '9') break searchValidRecord; final String prefix = current.substring(0, parseAt); current = search(rs, current, prefix, ++expected); if (current == null) { break searchValidRecord; } } } int n = freeSequenceNumber; // The hole found during iteration. if (n == 0) { n = maximalSequenceNumber + 1; // If no hole, use the maximal number + 1. } proposal = proposal + SEPARATOR + n; } } } return proposal; } /** * Searches for an available identifier, assuming that the elements in the given * {@code ResultSet} are sorted in alphabetical (not numerical) order. * * @param rs the result set from which to get next records. Its cursor position is the * <strong>second</strong> record to inspect (i.e. a record has already been * extracted before the call to this method). * @param current the ID of the record which has been extracted before the call to this method. * It must start with {@code prefix} while not equals to {@code prefix}. * @param prefix the prefix that an ID must have in order to be accepted. * @param expected the next expected number. If this number is not found, then it will be assumed available. * @return the ID that stopped the search (which is going to be the first element of the next iteration), * or {@code null} if we should stop the search. * @throws SQLException if an error occurred while querying the database. */ private String search(final ResultSet rs, String current, final String prefix, int expected) throws SQLException { /* * The first condition below should have been verified by the caller. If that * condition holds, then the second condition is a consequence of the DISTINCT * keyword in the SELECT statement, which should ensure !current.equals(prefix). */ assert current.startsWith(prefix); assert current.length() > prefix.length() : current; do { final int n; try { n = Integer.parseInt(current.substring(parseAt)); } catch (NumberFormatException e) { /* * We expect only records with an identifier compliant with our syntax. If we * encounter a non-compliant identifier, just ignore it. There is no risk of * key collision since we are not going to generate a non-compliant ID. */ if (rs.next()) { current = rs.getString(1); continue; } return null; } /* * If we found a higher number than the expected one, then we found a "hole" in the * sequence of numbers. Remember the value of the hole and returns null for stopping * the search. */ if (n > expected) { freeSequenceNumber = expected; return null; } if (n != expected) { // Following should never happen (I think). throw new SQLNonTransientException(current); } expected++; /* * Remember the highest value found so far. This will be used only * if we failed to find any "hole" in the sequence of numbers. */ if (n > maximalSequenceNumber) { maximalSequenceNumber = n; } if (!rs.next()) { return null; } /* * Gets the next record, skipping every ones starting with the current one. * For example if the current record is "proposal-1", then the following block * will skip "proposal-10", "proposal-11", etc. until it reaches "proposal-2". */ final String next = current.substring(0, prefix.length() + 1); current = rs.getString(1); if (current.startsWith(next)) { current = search(rs, current, next, n*10); if (current == null) { return null; } } } while (current.startsWith(prefix)); return current; } /** * Releases resources used by this {@code IdentifierGenerator}. */ @Override public void close() throws SQLException { statement.close(); } }
package com.carrotsearch.randomizedtesting; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.TimeZone; import org.junit.Assert; import org.junit.Assume; import org.junit.runner.RunWith; import com.carrotsearch.randomizedtesting.annotations.Listeners; import com.carrotsearch.randomizedtesting.annotations.Nightly; import com.carrotsearch.randomizedtesting.generators.*; /** * Common scaffolding for subclassing randomized tests. * * @see Listeners * @see RandomizedContext */ @RunWith(RandomizedRunner.class) public class RandomizedTest extends Assert { /** * The global multiplier property (Double). * * @see #multiplier() */ public static final String SYSPROP_MULTIPLIER = "randomized.multiplier"; /* Commonly used charsets (these must be supported by every JVM). */ protected static final Charset UTF8 = Charset.forName("UTF-8"); protected static final Charset UTF16 = Charset.forName("UTF-16"); protected static final Charset ISO8859_1 = Charset.forName("ISO-8859-1"); protected static final Charset US_ASCII = Charset.forName("US-ASCII"); /* This charset does not need to be supported, but I don't know any JVM under which it wouldn't be. */ protected static final Charset UTF32 = Charset.forName("UTF-32"); /** * Default multiplier. * * @see #SYSPROP_MULTIPLIER */ private static final double DEFAULT_MULTIPLIER = 1.0d; /** * Shortcut for {@link RandomizedContext#current()}. */ public static RandomizedContext getContext() { return RandomizedContext.current(); } /** * Returns true if we're running nightly tests. * @see Nightly */ public static boolean isNightly() { return getContext().isNightly(); } /** * Shortcut for {@link RandomizedContext#getRandom()}. Even though this method * is static, it returns per-thread {@link Random} instance, so no race conditions * can occur. * * <p>It is recommended that specific methods are used to pick random values. */ public static Random getRandom() { return getContext().getRandom(); } // // Random value pickers. Shortcuts to methods in {@link #getRandom()} mostly. // public static boolean randomBoolean() { return getRandom().nextBoolean(); } public static byte randomByte() { return (byte) getRandom().nextInt(); } public static short randomShort() { return (short) getRandom().nextInt(); } public static int randomInt() { return getRandom().nextInt(); } public static float randomFloat() { return getRandom().nextFloat(); } public static double randomDouble() { return getRandom().nextDouble(); } public static long randomLong() { return getRandom().nextLong(); } /** @see Random#nextGaussian() */ public static double randomGaussian() { return getRandom().nextGaussian(); } // // Delegates to RandomInts. // /** * A random integer from 0..max (inclusive). */ public static int randomInt(int max) { return RandomInts.randomInt(getRandom(), max); } /** * A random integer from <code>min</code> to <code>max</code> (inclusive). * * @see #scaledRandomIntBetween(int, int) */ public static int randomIntBetween(int min, int max) { return RandomInts.randomIntBetween(getRandom(), min, max); } /** * An alias for {@link #randomIntBetween(int, int)}. * * @see #scaledRandomIntBetween(int, int) */ public static int between(int min, int max) { return randomIntBetween(min, max); } /** * Returns a random value greater or equal to <code>min</code>. The value * picked is affected by {@link #isNightly()} and {@link #multiplier()}. * * @see #scaledRandomIntBetween(int, int) */ public static int atLeast(int min) { if (min < 0) throw new IllegalArgumentException("atLeast requires non-negative argument: " + min); return scaledRandomIntBetween(min, Integer.MAX_VALUE); } /** * Returns a non-negative random value smaller or equal <code>max</code>. The value * picked is affected by {@link #isNightly()} and {@link #multiplier()}. * * <p>This method is effectively an alias to: * <pre> * scaledRandomIntBetween(0, max) * </pre> * * @see #scaledRandomIntBetween(int, int) */ public static int atMost(int max) { if (max < 0) throw new IllegalArgumentException("atMost requires non-negative argument: " + max); return scaledRandomIntBetween(0, max); } /** * Rarely returns <code>true</code> in about 10% of all calls (regardless of the * {@link #isNightly()} mode). */ public static boolean rarely() { return randomInt(100) >= 90; } /** * The exact opposite of {@link #rarely()}. */ public static boolean frequently() { return !rarely(); } // // Delegates to RandomPicks // /** * Pick a random object from the given array. The array must not be empty. */ public static <T> T randomFrom(T [] array) { return RandomPicks.randomFrom(getRandom(), array); } /** * Pick a random object from the given list. */ public static <T> T randomFrom(List<T> list) { return RandomPicks.randomFrom(getRandom(), list); } // // "multiplied" or scaled value pickers. These will be affected by global multiplier. // /** * A multiplier can be used to linearly scale certain values. It can be used to make data * or iterations of certain tests "heavier" for nightly runs, for example. * * <p>The default multiplier value is 1.</p> * * @see #SYSPROP_MULTIPLIER * @see #DEFAULT_MULTIPLIER */ public static double multiplier() { checkContext(); return systemPropertyAsDouble(SYSPROP_MULTIPLIER, DEFAULT_MULTIPLIER); } /** * Returns a "scaled" number of iterations for loops which can have a variable * iteration count. This method is effectively * an alias to {@link #scaledRandomIntBetween(int, int)}. */ public static int iterations(int min, int max) { return scaledRandomIntBetween(min, max); } /** * Returns a "scaled" random number between min and max (inclusive). The number of * iterations will fall between [min, max], but the selection will also try to * achieve the points below: * <ul> * <li>the multiplier can be used to move the number of iterations closer to min * (if it is smaller than 1) or closer to max (if it is larger than 1). Setting * the multiplier to 0 will always result in picking min.</li> * <li>on normal runs, the number will be closer to min than to max.</li> * <li>on nightly runs, the number will be closer to max than to min.</li> * </ul> * * @see #multiplier() * * @param min Minimum (inclusive). * @param max Maximum (inclusive). * @return Returns a random number between min and max. */ public static int scaledRandomIntBetween(int min, int max) { if (min < 0) throw new IllegalArgumentException("min must be >= 0: " + min); if (min > max) throw new IllegalArgumentException("max must be >= min: " + min + ", " + max); double point = Math.min(1, Math.abs(randomGaussian()) * 0.3) * multiplier(); double range = max - min; int scaled = (int) Math.round(Math.min(point * range, range)); if (isNightly()) { return max - scaled; } else { return min + scaled; } } // Methods to help with I/O and environment. /** * @see #globalTempDir() */ private static File globalTempDir; /** * Subfolders under {@link #globalTempDir} are created synchronously, so we don't need * to mangle filenames. */ private static int tempSubFileNameCount; /** * Global temporary directory created for the duration of this class's lifespan. If * multiple class loaders are used, there may be more global temp dirs, but it * shouldn't really be the case in practice. */ public static File globalTempDir() { checkContext(); synchronized (RandomizedTest.class) { if (globalTempDir == null) { String tempDirPath = System.getProperty("java.io.tmpdir"); if (tempDirPath == null) throw new Error("No property java.io.tmpdir?"); File tempDir = new File(tempDirPath); if (!tempDir.isDirectory() || !tempDir.canWrite()) { throw new Error("Temporary folder not accessible: " + tempDir.getAbsolutePath()); } SimpleDateFormat tsFormat = new SimpleDateFormat("'tests-'yyyyMMddHHmmss'-'SSS"); int retries = 10; do { String dirName = tsFormat.format(new Date()); final File tmpFolder = new File(tempDir, dirName); // I assume mkdir is filesystem-atomic and only succeeds if the // directory didn't previously exist? if (tmpFolder.mkdir()) { globalTempDir = tmpFolder; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { forceDeleteRecursively(globalTempDir); } catch (IOException e) { // Not much else to do but to log and quit. System.err.println("Error while deleting temporary folder '" + globalTempDir.getAbsolutePath() + "': " + e.getMessage()); } if (globalTempDir.exists()) { System.err.println("Could not delete temporary folder entirely: " + globalTempDir.getAbsolutePath()); } } }); return globalTempDir; } } while (retries-- > 0); throw new RuntimeException("Could not create temporary space in: " + tempDir); } return globalTempDir; } } /** * Creates a new temporary directory for the {@link LifecycleScope#TEST} duration. * * @see #globalTempDir() */ public File newTempDir() { return newTempDir(LifecycleScope.TEST); } /** * Creates a temporary directory, deleted after the given lifecycle phase. * Temporary directory is created relative to a globally picked temporary directory. */ public static File newTempDir(LifecycleScope scope) { checkContext(); synchronized (RandomizedTest.class) { File tempDir = new File(globalTempDir(), nextTempName()); if (!tempDir.mkdir()) throw new RuntimeException("Could not create temporary folder: " + tempDir.getAbsolutePath()); getContext().closeAtEnd(new TempPathResource(tempDir), scope); return tempDir; } } /** * Registers a {@link Closeable} resource that should be closed after the test * completes. * * @return <code>resource</code> (for call chaining). */ public <T extends Closeable> T closeAfterTest(T resource) { return getContext().closeAtEnd(resource, LifecycleScope.TEST); } /** * Registers a {@link Closeable} resource that should be closed after the suite * completes. * * @return <code>resource</code> (for call chaining). */ public static <T extends Closeable> T closeAfterSuite(T resource) { return getContext().closeAtEnd(resource, LifecycleScope.SUITE); } /** * Creates a new temporary file for the {@link LifecycleScope#TEST} duration. */ public File newTempFile() { return newTempFile(LifecycleScope.TEST); } /** * Creates a new temporary file deleted after the given lifecycle phase completes. * The file is physically created on disk, but is not locked or opened. */ public static File newTempFile(LifecycleScope scope) { checkContext(); synchronized (RandomizedTest.class) { File tempFile = new File(globalTempDir(), nextTempName()); try { if (!tempFile.createNewFile()) throw new RuntimeException("Could not create temporary file: " + tempFile.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException("Could not create temporary file: " + tempFile.getAbsolutePath(), e); } getContext().closeAtEnd(new TempPathResource(tempFile), scope); return tempFile; } } /** Next temporary filename. */ private static String nextTempName() { return String.format("%04d has-space", tempSubFileNameCount++); } /** * Recursively delete a folder (or file). This attempts to delete everything that * can be deleted, but possibly can leave things behind if files are locked for example. */ static void forceDeleteRecursively(File fileOrDir) throws IOException { if (fileOrDir.isDirectory()) { // We are not checking for symlinks here! for (File f : fileOrDir.listFiles()) { forceDeleteRecursively(f); } } if (!fileOrDir.delete()) { RandomizedRunner.logger.warning("Could not delete: " + fileOrDir.getAbsolutePath()); } } /** * Assign a temporary server socket. If you need a temporary port one can * assign a server socket and close it immediately, just to acquire its port * number. * * @param scope * The lifecycle scope to close the socket after. If the socket is * closed earlier, nothing happens (silently dropped). */ public static ServerSocket newServerSocket(LifecycleScope scope) throws IOException { final ServerSocket socket = new ServerSocket(0); getContext().closeAtEnd(new Closeable() { public void close() throws IOException { if (!socket.isClosed()) socket.close(); } }, scope); return socket; } /** * Return a random Locale from the available locales on the system. * * <p>Warning: This test assumes the returned array of locales is repeatable from jvm execution * to jvm execution. It _may_ be different from jvm to jvm and as such, it can render * tests execute in a different way.</p> */ public static Locale randomLocale() { Locale[] availableLocales = Locale.getAvailableLocales(); Arrays.sort(availableLocales, new Comparator<Locale>() { public int compare(Locale o1, Locale o2) { return o1.toString().compareTo(o2.toString()); } }); return randomFrom(availableLocales); } /** * Return a random TimeZone from the available timezones on the system. * * <p>Warning: This test assumes the returned array of time zones is repeatable from jvm execution * to jvm execution. It _may_ be different from jvm to jvm and as such, it can render * tests execute in a different way.</p> */ public static TimeZone randomTimeZone() { final String[] availableIDs = TimeZone.getAvailableIDs(); Arrays.sort(availableIDs); return TimeZone.getTimeZone(randomFrom(availableIDs)); } // // Characters and strings. Delegates to RandomStrings and that in turn to StringGenerators. // /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomAsciiOfLengthBetween(int minCodeUnits, int maxCodeUnits) { return RandomStrings.randomAsciiOfLengthBetween(getRandom(), minCodeUnits, maxCodeUnits); } /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomAsciiOfLength(int codeUnits) { return RandomStrings.randomAsciiOfLength(getRandom(), codeUnits); } /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { return RandomStrings.randomUnicodeOfLengthBetween(getRandom(), minCodeUnits, maxCodeUnits); } /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomUnicodeOfLength(int codeUnits) { return RandomStrings.randomUnicodeOfLength(getRandom(), codeUnits); } /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ public static String randomUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) { return RandomStrings.randomUnicodeOfCodepointLengthBetween(getRandom(), minCodePoints, maxCodePoints); } /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ public static String randomUnicodeOfCodepointLength(int codePoints) { return RandomStrings .randomUnicodeOfCodepointLength(getRandom(), codePoints); } /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomRealisticUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { return RandomStrings.randomRealisticUnicodeOfLengthBetween(getRandom(), minCodeUnits, maxCodeUnits); } /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomRealisticUnicodeOfLength(int codeUnits) { return RandomStrings.randomRealisticUnicodeOfLength(getRandom(), codeUnits); } /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ public static String randomRealisticUnicodeOfCodepointLengthBetween( int minCodePoints, int maxCodePoints) { return RandomStrings.randomRealisticUnicodeOfCodepointLengthBetween( getRandom(), minCodePoints, maxCodePoints); } /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ public static String randomRealisticUnicodeOfCodepointLength(int codePoints) { return RandomStrings.randomRealisticUnicodeOfCodepointLength(getRandom(), codePoints); } /** * This is an absolutely hacky utility to take a vararg as input and return the array * of arguments as output. The name is a dollar for brevity, idea borrowed from * http://code.google.com/p/junitparams/. */ public static Object [] $(Object... objects) { return objects; } /** * @see #$ */ public static Object [][] $$(Object[]... objects) { return objects; } // // wrappers for utility methods elsewhere that don't require try..catch blocks // and rethrow the original checked exception if needed. dirty a bit, but saves // keystrokes... // /** * Same as {@link Thread#sleep(long)}. */ public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Rethrow.rethrow(e); } } // // Extensions of Assume (with a message). // /** * Making {@link Assume#assumeTrue(boolean)} directly available. */ public static void assumeTrue(boolean condition) { Assume.assumeTrue(condition); } /** * Reverse of {@link #assumeTrue(boolean)}. */ public static void assumeFalse(boolean condition) { assumeTrue(!condition); } /** * Making {@link Assume#assumeNotNull(Object...)} directly available. */ public static void assumeNotNull(Object... objects) { Assume.assumeNotNull(objects); } /** * @param condition * If <code>false</code> an {@link InternalAssumptionViolatedException} is * thrown by this method and the test case (should be) ignored (or * rather technically, flagged as a failure not passing a certain * assumption). Tests that are assumption-failures do not break * builds (again: typically). * @param message * Message to be included in the exception's string. */ public static void assumeTrue(String message, boolean condition) { if (!condition) { // @see {@link Rants#RANT_2}. throw new InternalAssumptionViolatedException(message); } } /** * Reverse of {@link #assumeTrue(String, boolean)}. */ public static void assumeFalse(String message, boolean condition) { assumeTrue(message, !condition); } /** * Assume <code>t</code> is <code>null</code>. */ public static void assumeNoException(String msg, Throwable t) { if (t != null) { // This does chain the exception as the cause. throw new InternalAssumptionViolatedException(msg, t); } } /** * Making {@link Assume#assumeNoException(Throwable)} directly available. */ public static void assumeNoException(Throwable t) { Assume.assumeNoException(t); } // // System properties and their conversion to common types, with defaults. // /** * Get a system property and convert it to a double, if defined. Otherwise, return the default value. */ public static double systemPropertyAsDouble(String propertyName, double defaultValue) { String v = System.getProperty(propertyName); if (v != null && !v.trim().isEmpty()) { try { return Double.parseDouble(v.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Double value expected for property " + propertyName + ": " + v, e); } } else { return defaultValue; } } /** * Get a system property and convert it to a float, if defined. Otherwise, return the default value. */ public static float systemPropertyAsFloat(String propertyName, float defaultValue) { String v = System.getProperty(propertyName); if (v != null && !v.trim().isEmpty()) { try { return Float.parseFloat(v.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Float value expected for property " + propertyName + ": " + v, e); } } else { return defaultValue; } } /** * Get a system property and convert it to an int, if defined. Otherwise, return the default value. */ public static int systemPropertyAsInt(String propertyName, int defaultValue) { String v = System.getProperty(propertyName); if (v != null && !v.trim().isEmpty()) { try { return Integer.parseInt(v.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Integer value expected for property " + propertyName + ": " + v, e); } } else { return defaultValue; } } /** * Get a system property and convert it to a long, if defined. Otherwise, return the default value. */ public static float systemPropertyAsLong(String propertyName, int defaultValue) { String v = System.getProperty(propertyName); if (v != null && !v.trim().isEmpty()) { try { return Long.parseLong(v.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Long value expected for property " + propertyName + ": " + v, e); } } else { return defaultValue; } } /** Boolean constants mapping. */ @SuppressWarnings("serial") private final static HashMap<String, Boolean> BOOLEANS = new HashMap<String, Boolean>() {{ put( "true", true); put( "false", false); put( "on", true); put( "off", false); put( "yes", true); put( "no", false); put("enabled", true); put("disabled", false); }}; /** * Get a system property and convert it to a boolean, if defined. This method returns * <code>true</code> if the property exists an is set to any of the following strings * (case-insensitive): <code>true</code>, <code>on</code>, <code>yes</code>, <code>enabled</code>. * * <p><code>false</code> is returned if the property exists and is set to any of the * following strings (case-insensitive): * <code>false</code>, <code>off</code>, <code>no</code>, <code>disabled</code>. */ public static boolean systemPropertyAsBoolean(String propertyName, boolean defaultValue) { String v = System.getProperty(propertyName); if (v != null && !v.trim().isEmpty()) { v = v.trim(); Boolean result = BOOLEANS.get(v); if (result != null) return result.booleanValue(); else throw new IllegalArgumentException("Boolean value expected for property " + propertyName + " " + "(true/false, on/off, enabled/disabled, yes/no): " + v); } else { return defaultValue; } } // // Miscellaneous infrastructure. // /** * Ensures we're running with an initialized {@link RandomizedContext}. */ private static void checkContext() { // Will throw an exception if not available. RandomizedContext.current(); } }
package android.content.pm; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public abstract class PackageManager { // Classes public static class NameNotFoundException extends android.util.AndroidException { // Constructors public NameNotFoundException(){ super(); } public NameNotFoundException(java.lang.String arg1){ super(); } } // Fields public static final int GET_ACTIVITIES = 1; public static final int GET_RECEIVERS = 2; public static final int GET_SERVICES = 4; public static final int GET_PROVIDERS = 8; public static final int GET_INSTRUMENTATION = 16; public static final int GET_INTENT_FILTERS = 32; public static final int GET_SIGNATURES = 64; public static final int GET_RESOLVED_FILTER = 64; public static final int GET_META_DATA = 128; public static final int GET_GIDS = 256; public static final int GET_DISABLED_COMPONENTS = 512; public static final int GET_SHARED_LIBRARY_FILES = 1024; public static final int GET_URI_PERMISSION_PATTERNS = 2048; public static final int GET_PERMISSIONS = 4096; public static final int GET_UNINSTALLED_PACKAGES = 8192; public static final int GET_CONFIGURATIONS = 16384; public static final int MATCH_DEFAULT_ONLY = 65536; public static final int PERMISSION_GRANTED = 0; public static final int PERMISSION_DENIED = -1; public static final int SIGNATURE_MATCH = 0; public static final int SIGNATURE_NEITHER_SIGNED = 1; public static final int SIGNATURE_FIRST_NOT_SIGNED = -1; public static final int SIGNATURE_SECOND_NOT_SIGNED = -2; public static final int SIGNATURE_NO_MATCH = -3; public static final int SIGNATURE_UNKNOWN_PACKAGE = -4; public static final int COMPONENT_ENABLED_STATE_DEFAULT = 0; public static final int COMPONENT_ENABLED_STATE_ENABLED = 1; public static final int COMPONENT_ENABLED_STATE_DISABLED = 2; public static final int COMPONENT_ENABLED_STATE_DISABLED_USER = 3; public static final int INSTALL_FORWARD_LOCK = 1; public static final int INSTALL_REPLACE_EXISTING = 2; public static final int INSTALL_ALLOW_TEST = 4; public static final int INSTALL_EXTERNAL = 8; public static final int INSTALL_INTERNAL = 16; public static final int INSTALL_FROM_ADB = 32; public static final int DONT_KILL_APP = 1; public static final int INSTALL_SUCCEEDED = 1; public static final int INSTALL_FAILED_ALREADY_EXISTS = -1; public static final int INSTALL_FAILED_INVALID_APK = -2; public static final int INSTALL_FAILED_INVALID_URI = -3; public static final int INSTALL_FAILED_INSUFFICIENT_STORAGE = -4; public static final int INSTALL_FAILED_DUPLICATE_PACKAGE = -5; public static final int INSTALL_FAILED_NO_SHARED_USER = -6; public static final int INSTALL_FAILED_UPDATE_INCOMPATIBLE = -7; public static final int INSTALL_FAILED_SHARED_USER_INCOMPATIBLE = -8; public static final int INSTALL_FAILED_MISSING_SHARED_LIBRARY = -9; public static final int INSTALL_FAILED_REPLACE_COULDNT_DELETE = -10; public static final int INSTALL_FAILED_DEXOPT = -11; public static final int INSTALL_FAILED_OLDER_SDK = -12; public static final int INSTALL_FAILED_CONFLICTING_PROVIDER = -13; public static final int INSTALL_FAILED_NEWER_SDK = -14; public static final int INSTALL_FAILED_TEST_ONLY = -15; public static final int INSTALL_FAILED_CPU_ABI_INCOMPATIBLE = -16; public static final int INSTALL_FAILED_MISSING_FEATURE = -17; public static final int INSTALL_FAILED_CONTAINER_ERROR = -18; public static final int INSTALL_FAILED_INVALID_INSTALL_LOCATION = -19; public static final int INSTALL_FAILED_MEDIA_UNAVAILABLE = -20; public static final int INSTALL_FAILED_VERIFICATION_TIMEOUT = -21; public static final int INSTALL_FAILED_VERIFICATION_FAILURE = -22; public static final int INSTALL_FAILED_PACKAGE_CHANGED = -23; public static final int INSTALL_PARSE_FAILED_NOT_APK = -100; public static final int INSTALL_PARSE_FAILED_BAD_MANIFEST = -101; public static final int INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION = -102; public static final int INSTALL_PARSE_FAILED_NO_CERTIFICATES = -103; public static final int INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES = -104; public static final int INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING = -105; public static final int INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME = -106; public static final int INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID = -107; public static final int INSTALL_PARSE_FAILED_MANIFEST_MALFORMED = -108; public static final int INSTALL_PARSE_FAILED_MANIFEST_EMPTY = -109; public static final int INSTALL_FAILED_INTERNAL_ERROR = -110; public static final int DONT_DELETE_DATA = 1; public static final int DELETE_SUCCEEDED = 1; public static final int DELETE_FAILED_INTERNAL_ERROR = -1; public static final int DELETE_FAILED_DEVICE_POLICY_MANAGER = -2; public static final int MOVE_SUCCEEDED = 1; public static final int MOVE_FAILED_INSUFFICIENT_STORAGE = -1; public static final int MOVE_FAILED_DOESNT_EXIST = -2; public static final int MOVE_FAILED_SYSTEM_PACKAGE = -3; public static final int MOVE_FAILED_FORWARD_LOCKED = -4; public static final int MOVE_FAILED_INVALID_LOCATION = -5; public static final int MOVE_FAILED_INTERNAL_ERROR = -6; public static final int MOVE_FAILED_OPERATION_PENDING = -7; public static final int MOVE_INTERNAL = 1; public static final int MOVE_EXTERNAL_MEDIA = 2; public static final int VERIFICATION_ALLOW_WITHOUT_SUFFICIENT = 2; public static final int VERIFICATION_ALLOW = 1; public static final int VERIFICATION_REJECT = -1; public static final int PER_USER_RANGE = 100000; public static final java.lang.String FEATURE_AUDIO_LOW_LATENCY = "android.hardware.audio.low_latency"; public static final java.lang.String FEATURE_BLUETOOTH = "android.hardware.bluetooth"; public static final java.lang.String FEATURE_CAMERA = "android.hardware.camera"; public static final java.lang.String FEATURE_CAMERA_AUTOFOCUS = "android.hardware.camera.autofocus"; public static final java.lang.String FEATURE_CAMERA_FLASH = "android.hardware.camera.flash"; public static final java.lang.String FEATURE_CAMERA_FRONT = "android.hardware.camera.front"; public static final java.lang.String FEATURE_LOCATION = "android.hardware.location"; public static final java.lang.String FEATURE_LOCATION_GPS = "android.hardware.location.gps"; public static final java.lang.String FEATURE_LOCATION_NETWORK = "android.hardware.location.network"; public static final java.lang.String FEATURE_MICROPHONE = "android.hardware.microphone"; public static final java.lang.String FEATURE_NFC = "android.hardware.nfc"; public static final java.lang.String FEATURE_SENSOR_ACCELEROMETER = "android.hardware.sensor.accelerometer"; public static final java.lang.String FEATURE_SENSOR_BAROMETER = "android.hardware.sensor.barometer"; public static final java.lang.String FEATURE_SENSOR_COMPASS = "android.hardware.sensor.compass"; public static final java.lang.String FEATURE_SENSOR_GYROSCOPE = "android.hardware.sensor.gyroscope"; public static final java.lang.String FEATURE_SENSOR_LIGHT = "android.hardware.sensor.light"; public static final java.lang.String FEATURE_SENSOR_PROXIMITY = "android.hardware.sensor.proximity"; public static final java.lang.String FEATURE_TELEPHONY = "android.hardware.telephony"; public static final java.lang.String FEATURE_TELEPHONY_CDMA = "android.hardware.telephony.cdma"; public static final java.lang.String FEATURE_TELEPHONY_GSM = "android.hardware.telephony.gsm"; public static final java.lang.String FEATURE_USB_HOST = "android.hardware.usb.host"; public static final java.lang.String FEATURE_USB_ACCESSORY = "android.hardware.usb.accessory"; public static final java.lang.String FEATURE_SIP = "android.software.sip"; public static final java.lang.String FEATURE_SIP_VOIP = "android.software.sip.voip"; public static final java.lang.String FEATURE_TOUCHSCREEN = "android.hardware.touchscreen"; public static final java.lang.String FEATURE_TOUCHSCREEN_MULTITOUCH = "android.hardware.touchscreen.multitouch"; public static final java.lang.String FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT = "android.hardware.touchscreen.multitouch.distinct"; public static final java.lang.String FEATURE_TOUCHSCREEN_MULTITOUCH_JAZZHAND = "android.hardware.touchscreen.multitouch.jazzhand"; public static final java.lang.String FEATURE_FAKETOUCH = "android.hardware.faketouch"; public static final java.lang.String FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT = "android.hardware.faketouch.multitouch.distinct"; public static final java.lang.String FEATURE_FAKETOUCH_MULTITOUCH_JAZZHAND = "android.hardware.faketouch.multitouch.jazzhand"; public static final java.lang.String FEATURE_SCREEN_PORTRAIT = "android.hardware.screen.portrait"; public static final java.lang.String FEATURE_SCREEN_LANDSCAPE = "android.hardware.screen.landscape"; public static final java.lang.String FEATURE_LIVE_WALLPAPER = "android.software.live_wallpaper"; public static final java.lang.String FEATURE_WIFI = "android.hardware.wifi"; public static final java.lang.String FEATURE_WIFI_DIRECT = "android.hardware.wifi.direct"; public static final java.lang.String ACTION_CLEAN_EXTERNAL_STORAGE = "android.content.pm.CLEAN_EXTERNAL_STORAGE"; public static final java.lang.String EXTRA_VERIFICATION_URI = "android.content.pm.extra.VERIFICATION_URI"; public static final java.lang.String EXTRA_VERIFICATION_ID = "android.content.pm.extra.VERIFICATION_ID"; public static final java.lang.String EXTRA_VERIFICATION_INSTALLER_PACKAGE = "android.content.pm.extra.VERIFICATION_INSTALLER_PACKAGE"; public static final java.lang.String EXTRA_VERIFICATION_INSTALL_FLAGS = "android.content.pm.extra.VERIFICATION_INSTALL_FLAGS"; // Constructors public PackageManager(){ } // Methods public abstract int checkPermission(java.lang.String arg1, java.lang.String arg2); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getPackageInfo", pos = 1, report = "-") public abstract PackageInfo getPackageInfo(java.lang.String arg1, int arg2) throws PackageManager.NameNotFoundException; @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getApplicationInfo", pos = 1, report = "-") public abstract ApplicationInfo getApplicationInfo(java.lang.String arg1, int arg2) throws PackageManager.NameNotFoundException; public abstract java.lang.CharSequence getText(java.lang.String arg1, int arg2, ApplicationInfo arg3); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.deletePackage", pos = 1, report = "-") public abstract void deletePackage(java.lang.String arg1, IPackageDeleteObserver arg2, int arg3); public static int getUid(int arg1, int arg2){ return 0; } @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getActivityInfo", pos = 1, report = "-") public abstract ActivityInfo getActivityInfo(android.content.ComponentName arg1, int arg2) throws PackageManager.NameNotFoundException; public abstract android.graphics.drawable.Drawable getDrawable(java.lang.String arg1, int arg2, ApplicationInfo arg3); public abstract ProviderInfo getProviderInfo(android.content.ComponentName arg1, int arg2) throws PackageManager.NameNotFoundException; @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getServiceInfo", pos = 1, report = "-") public abstract ServiceInfo getServiceInfo(android.content.ComponentName arg1, int arg2) throws PackageManager.NameNotFoundException; public abstract android.content.res.XmlResourceParser getXml(java.lang.String arg1, int arg2, ApplicationInfo arg3); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getReceiverInfo", pos = 1, report = "-") public abstract ActivityInfo getReceiverInfo(android.content.ComponentName arg1, int arg2) throws PackageManager.NameNotFoundException; @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.hasSystemFeature", pos = 1, report = "-") public abstract boolean hasSystemFeature(java.lang.String arg1); public abstract java.util.List<ResolveInfo> queryIntentActivities(android.content.Intent arg1, int arg2); public abstract void setInstallerPackageName(java.lang.String arg1, java.lang.String arg2); public abstract java.lang.String getInstallerPackageName(java.lang.String arg1); public abstract java.util.List<ResolveInfo> queryIntentServices(android.content.Intent arg1, int arg2); public abstract java.lang.String [] getPackagesForUid(int arg1); public abstract java.util.List<ResolveInfo> queryIntentActivityOptions(android.content.ComponentName arg1, android.content.Intent [] arg2, android.content.Intent arg3, int arg4); public abstract void freeStorageAndNotify(long arg1, IPackageDataObserver arg2); public abstract int getUidForSharedUser(java.lang.String arg1) throws PackageManager.NameNotFoundException; public abstract PermissionInfo getPermissionInfo(java.lang.String arg1, int arg2) throws PackageManager.NameNotFoundException; public abstract PermissionGroupInfo getPermissionGroupInfo(java.lang.String arg1, int arg2) throws PackageManager.NameNotFoundException; @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.installPackage", pos = 1, report = "-") public abstract void installPackage(android.net.Uri arg1, IPackageInstallObserver arg2, int arg3, java.lang.String arg4); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getInstalledPackages", pos = 1, report = "-") public abstract java.util.List<PackageInfo> getInstalledPackages(int arg1); public abstract int [] getPackageGids(java.lang.String arg1) throws PackageManager.NameNotFoundException; public abstract java.lang.String [] currentToCanonicalPackageNames(java.lang.String [] arg1); public abstract java.lang.String [] canonicalToCurrentPackageNames(java.lang.String [] arg1); public abstract java.util.List<PermissionInfo> queryPermissionsByGroup(java.lang.String arg1, int arg2) throws PackageManager.NameNotFoundException; public abstract java.util.List<PermissionGroupInfo> getAllPermissionGroups(int arg1); public abstract boolean addPermission(PermissionInfo arg1); public abstract void removePermission(java.lang.String arg1); public abstract int checkSignatures(java.lang.String arg1, java.lang.String arg2); public abstract int checkSignatures(int arg1, int arg2); public abstract java.lang.String getNameForUid(int arg1); public abstract ResolveInfo resolveService(android.content.Intent arg1, int arg2); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getInstalledApplications", pos = 1, report = "-") public abstract java.util.List<ApplicationInfo> getInstalledApplications(int arg1); public abstract ProviderInfo resolveContentProvider(java.lang.String arg1, int arg2); public abstract java.util.List<ProviderInfo> queryContentProviders(java.lang.String arg1, int arg2, int arg3); public abstract InstrumentationInfo getInstrumentationInfo(android.content.ComponentName arg1, int arg2) throws PackageManager.NameNotFoundException; public abstract java.util.List<InstrumentationInfo> queryInstrumentation(java.lang.String arg1, int arg2); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.addPackageToPreferred", pos = 1, report = "-") public abstract void addPackageToPreferred(java.lang.String arg1); public abstract void removePackageFromPreferred(java.lang.String arg1); public abstract java.util.List<PackageInfo> getPreferredPackages(int arg1); public abstract void addPreferredActivity(android.content.IntentFilter arg1, int arg2, android.content.ComponentName [] arg3, android.content.ComponentName arg4); public abstract void replacePreferredActivity(android.content.IntentFilter arg1, int arg2, android.content.ComponentName [] arg3, android.content.ComponentName arg4); public abstract void clearPackagePreferredActivities(java.lang.String arg1); public abstract int getPreferredActivities(java.util.List<android.content.IntentFilter> arg1, java.util.List<android.content.ComponentName> arg2, java.lang.String arg3); public abstract void setComponentEnabledSetting(android.content.ComponentName arg1, int arg2, int arg3); public abstract int getComponentEnabledSetting(android.content.ComponentName arg1); public abstract void setApplicationEnabledSetting(java.lang.String arg1, int arg2, int arg3); public abstract int getApplicationEnabledSetting(java.lang.String arg1); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.freeStorage", pos = 1, report = "-") public abstract void freeStorage(long arg1, android.content.IntentSender arg2); public abstract void deleteApplicationCacheFiles(java.lang.String arg1, IPackageDataObserver arg2); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.clearApplicationUserData", pos = 1, report = "-") public abstract void clearApplicationUserData(java.lang.String arg1, IPackageDataObserver arg2); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.getPackageSizeInfo", pos = 1, report = "-") public abstract void getPackageSizeInfo(java.lang.String arg1, IPackageStatsObserver arg2); @com.francetelecom.rd.stubs.annotation.UseRule(value = "PackageManager.getSystemSharedLibraryNames", report = "-") public abstract java.lang.String [] getSystemSharedLibraryNames(); @com.francetelecom.rd.stubs.annotation.UseRule(value = "PackageManager.getSystemAvailableFeatures", report = "-") public abstract FeatureInfo [] getSystemAvailableFeatures(); public abstract boolean isSafeMode(); @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "PackageManager.movePackage", pos = 1, report = "-") public abstract void movePackage(java.lang.String arg1, IPackageMoveObserver arg2, int arg3); public abstract boolean addPermissionAsync(PermissionInfo arg1); public abstract UserInfo createUser(java.lang.String arg1, int arg2); public abstract boolean removeUser(int arg1); public abstract void installPackageWithVerification(android.net.Uri arg1, @com.francetelecom.rd.stubs.annotation.CallBackRegister("packageInstallObserver") IPackageInstallObserver arg2, int arg3, java.lang.String arg4, android.net.Uri arg5, ManifestDigest arg6); public abstract void verifyPendingInstall(int arg1, int arg2); public abstract VerifierDeviceIdentity getVerifierDeviceIdentity(); public abstract java.util.List<UserInfo> getUsers(); public abstract android.content.res.Resources getResourcesForApplication(ApplicationInfo arg1) throws PackageManager.NameNotFoundException; public abstract android.content.res.Resources getResourcesForApplication(java.lang.String arg1) throws PackageManager.NameNotFoundException; public abstract java.util.List<ResolveInfo> queryBroadcastReceivers(android.content.Intent arg1, int arg2); public abstract java.lang.CharSequence getApplicationLabel(ApplicationInfo arg1); public abstract ResolveInfo resolveActivity(android.content.Intent arg1, int arg2); public abstract android.graphics.drawable.Drawable getDefaultActivityIcon(); public abstract android.content.Intent getLaunchIntentForPackage(java.lang.String arg1); public abstract android.graphics.drawable.Drawable getActivityIcon(android.content.ComponentName arg1) throws PackageManager.NameNotFoundException; public abstract android.graphics.drawable.Drawable getActivityIcon(android.content.Intent arg1) throws PackageManager.NameNotFoundException; public abstract android.graphics.drawable.Drawable getApplicationIcon(ApplicationInfo arg1); public abstract android.graphics.drawable.Drawable getApplicationIcon(java.lang.String arg1) throws PackageManager.NameNotFoundException; public abstract android.graphics.drawable.Drawable getActivityLogo(android.content.ComponentName arg1) throws PackageManager.NameNotFoundException; public abstract android.graphics.drawable.Drawable getActivityLogo(android.content.Intent arg1) throws PackageManager.NameNotFoundException; public abstract android.graphics.drawable.Drawable getApplicationLogo(ApplicationInfo arg1); public abstract android.graphics.drawable.Drawable getApplicationLogo(java.lang.String arg1) throws PackageManager.NameNotFoundException; public abstract android.content.res.Resources getResourcesForActivity(android.content.ComponentName arg1) throws PackageManager.NameNotFoundException; public abstract void updateUserName(int arg1, java.lang.String arg2); public abstract void updateUserFlags(int arg1, int arg2); public PackageInfo getPackageArchiveInfo(java.lang.String arg1, int arg2){ return (PackageInfo) null; } public static boolean isSameUser(int arg1, int arg2){ return false; } public static int getUserId(int arg1){ return 0; } public static int getAppId(int arg1){ return 0; } }
package com.atlassian.selenium; import com.atlassian.selenium.pageobjects.PageElement; import com.thoughtworks.selenium.Selenium; import junit.framework.Assert; import org.apache.log4j.Logger; import java.util.Arrays; public class SeleniumChecks { private static final Logger log = Logger.getLogger(SeleniumAssertions.class); private final Selenium client; private final long conditionCheckInterval; private final long defaultMaxWait; public SeleniumChecks(Selenium client, SeleniumConfiguration config) { this.client = client; this.conditionCheckInterval = config.getConditionCheckInterval(); this.defaultMaxWait = config.getActionWait(); } public boolean visibleByTimeout(String locator) { return byTimeout(Conditions.isVisible(locator)); } public boolean visibleByTimeout(PageElement element) { return visibleByTimeout(element.getLocator()); } /** * This will wait until an element is visible. If it doesnt become visible in * maxMillis return false * * @param locator the selenium element locator * @param maxMillis how long to wait as most in milliseconds */ public boolean visibleByTimeout(String locator, long maxMillis) { return byTimeout(Conditions.isVisible(locator), maxMillis); } public boolean visibleByTimeout(PageElement element, long maxMillis) { return visibleByTimeout(element.getLocator(), maxMillis); } public boolean notVisibleByTimeout(String locator) { return byTimeout(Conditions.isNotVisible(locator)); } public boolean notVisibleByTimeout(PageElement element) { return notVisibleByTimeout(element.getLocator()); } public boolean notVisibleByTimeout(String locator, long maxMillis) { return byTimeout(Conditions.isNotVisible(locator), maxMillis); } public boolean notVisibleByTimeout(PageElement element, long maxMillis) { return notVisibleByTimeout(element.getLocator(), maxMillis); } public boolean elementPresentByTimeout(String locator) { return byTimeout(Conditions.isPresent(locator)); } public boolean elementPresentByTimeout(PageElement element) { return elementPresentByTimeout(element.getLocator()); } public boolean elementPresentByTimeout(String locator, long maxMillis) { return byTimeout(Conditions.isPresent(locator), maxMillis); } public boolean elementPresentByTimeout(PageElement element, long maxMillis) { return elementPresentByTimeout(element.getLocator(), maxMillis); } public boolean elementPresentUntilTimeout(String locator) { return untilTimeout(Conditions.isPresent(locator)); } public boolean elementPresentUntilTimeout(PageElement element) { return elementPresentUntilTimeout(element.getLocator()); } public boolean elementPresentUntilTimeout(String locator, long maxMillis) { return untilTimeout(Conditions.isPresent(locator), maxMillis); } public boolean elementPresentUntilTimeout(PageElement element, long maxMillis) { return elementPresentUntilTimeout(element.getLocator(), maxMillis); } public boolean elementNotPresentByTimeout(String locator) { return byTimeout(Conditions.isNotPresent(locator)); } public boolean elementNotPresentByTimeout(PageElement element) { return elementNotPresentByTimeout(element.getLocator()); } public boolean elementNotPresentUntilTimeout(String locator) { return untilTimeout(Conditions.isNotPresent(locator)); } public boolean elementNotPresentUntilTimeout(PageElement element) { return elementNotPresentUntilTimeout(element.getLocator()); } public boolean elementNotPresentUntilTimeout(String locator, long maxMillis) { return untilTimeout(Conditions.isNotPresent(locator), maxMillis); } public boolean elementNotPresentUntilTimeout(PageElement element, long maxMillis) { return elementNotPresentUntilTimeout(element.getLocator(), maxMillis); } public boolean textPresentByTimeout(String text, long maxMillis) { return byTimeout(Conditions.isTextPresent(text), maxMillis); } public boolean textPresentByTimeout(String text) { return byTimeout(Conditions.isTextPresent(text)); } public boolean textNotPresentByTimeout(String text, long maxMillis) { return byTimeout(Conditions.isTextNotPresent(text), maxMillis); } public boolean textNotPresentByTimeout(String text) { return byTimeout(Conditions.isTextNotPresent(text)); } /** * This will wait until an element is not present. If it doesnt become not present in * maxMillis * * @param locator the selenium element locator * @param maxMillis how long to wait as most in milliseconds */ public boolean elementNotPresentByTimeout(String locator, long maxMillis) { return byTimeout(Conditions.isNotPresent(locator), maxMillis); } public boolean elementNotPresentByTimeout(PageElement element, long maxMillis) { return elementNotPresentByTimeout(element.getLocator(), maxMillis); } public boolean byTimeout(Condition condition) { return byTimeout(condition, defaultMaxWait); } public boolean byTimeout(Condition condition, long maxWaitTime) { long startTime = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - startTime >= maxWaitTime) { return condition.executeTest(client); } if (condition.executeTest(client)) return true; try { Thread.sleep(conditionCheckInterval); } catch (InterruptedException e) { throw new RuntimeException("Thread was interupted", e); } } } public boolean untilTimeout(Condition condition) { return untilTimeout(condition, defaultMaxWait); } public boolean untilTimeout(Condition condition, long maxWaitTime) { long startTime = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - startTime >= maxWaitTime) { return true; } if (!condition.executeTest(client)) { return false; } try { Thread.sleep(conditionCheckInterval); } catch (InterruptedException e) { throw new RuntimeException("Thread was interupted", e); } } } /** * @param text Asserts that text is present in the current page */ public boolean textPresent(String text) { return client.isTextPresent(text); } /** * @param text Asserts that text is not present in the current page */ public boolean textNotPresent(String text) { return !client.isTextPresent(text); } /** * Asserts that a given element has a specified value * @param locator Locator for element using the standard selenium locator syntax * @param value The value the element is expected to contain */ public boolean formElementEquals(String locator, String value) { return value.equals(client.getValue(locator)); } /** * Asserts that a given element is present * @param locator Locator for the element that should be present given using the standard selenium locator syntax */ public boolean elementPresent(String locator) { return client.isElementPresent(locator); } public boolean elementPresent(PageElement element) { return elementPresent(element.getLocator()); } /** * Asserts that a given element is not present on the current page * @param locator Locator for the element that should not be present given using the standard selenium locator syntax */ public boolean elementNotPresent(String locator) { return client.isElementPresent(locator); } public boolean elementNotPresent(PageElement element) { return elementNotPresent(element.getLocator()); } /** * Asserts that a given element is present and is visible. Under some browsers just calling the seleinium.isVisible method * on an element that doesn't exist causes selenium to throw an exception. * @param locator Locator for the element that should be visible specified in the standard selenium syntax */ public boolean elementVisible(String locator) { return (client.isElementPresent(locator) && client.isVisible(locator)); } public boolean elementVisible(PageElement element) { return elementVisible(element.getLocator()); } /** * Asserts that a given element is not present and visible. Calling selenium's native selenium.isVisible method on * an element that doesn't exist causes selenium to throw an exception * @param locator Locator for the element that should not be visible specified in the standard selenium syntax */ public boolean elementNotVisible(String locator) { return (client.isElementPresent(locator) && client.isVisible(locator)); } public boolean elementNotVisible(PageElement element) { return elementNotVisible(element.getLocator()); } /** * Asserts that a given element is visible and also contains the given text. * @param locator Locator for the element that should be visible specified in the standard selenium syntax * @param text the text that the element should contain */ public boolean elementVisibleContainsText(String locator, String text) { return (elementVisible(locator) && elementContainsText(locator, text)); } public boolean elementVisibleContainsText(PageElement element, String text) { return elementVisibleContainsText(element.getLocator(), text); } /** * Asserts that a particular piece of HTML is present in the HTML source. It is recommended that the elementPresent, elementHasText or some other method * be used because browsers idiosyncratically add white space to the HTML source * @param html Lower case representation of HTML string that should not be present */ public boolean htmlPresent(String html) { return (client.getHtmlSource().toLowerCase().indexOf(html) >= 0); } /** * Asserts that a particular piece of HTML is not present in the HTML source. It is recommended that the elementNotPresent, elementDoesntHaveText or * some other method be used because browsers idiosyncratically add white space to the HTML source * @param html Lower case representation of HTML string that should not be present */ public boolean htmlNotPresent(String html) { return !(client.getHtmlSource().toLowerCase().indexOf(html) >= 0); } /** * Asserts that the element specified by the locator contains the specified text * @param locator Locator given in standard selenium syntax * @param text The text that the element designated by the locator should contain */ public boolean elementHasText(String locator, String text) { return (client.getText(locator).indexOf(text) >= 0); } public boolean elementHasText(PageElement element, String text) { return elementHasText(element.getLocator(), text); } /** * Asserts that the element specified by the locator does not contain the specified text * @param locator Locator given in standard selenium syntax * @param text The text that the element designated by the locator should not contain */ public boolean elementDoesntHaveText(String locator, String text) { return !elementHasText(locator, text); } public boolean elementDoesntHaveText(PageElement element, String text) { return elementDoesntHaveText(element.getLocator(), text); } /** * Asserts that the element given by the locator has an attribute which contains the required value. * @param locator Locator given in standard selenium syntax * @param attribute The element attribute * @param value The value expected to be found in the element's attribute */ public boolean attributeContainsValue(String locator, String attribute, String value) { String attributeValue = client.getAttribute(locator + "@" + attribute); return (attributeValue.indexOf(value) >= 0); } public boolean attributeContainsValue(PageElement element, String attribute, String value) { return attributeContainsValue(element.getLocator(), attribute, value); } /** * Asserts that the element given by the locator has an attribute which does not contain the given value. * @param locator Locator given in standard selenium syntax * @param attribute The element attribute * @param value The value expected to be found in the element's attribute */ public boolean attributeDoesntContainValue(String locator, String attribute, String value) { String attributeValue = client.getAttribute(locator + "@" + attribute); return (attributeValue.indexOf(value) >= 0); } public boolean attributeDoesntContainValue(PageElement element, String attribute, String value) { return attributeDoesntContainValue(element.getLocator(), attribute, value); } /** * Asserts that a link containing the given text appears on the page * @param text The text that a link on the page should contain * @see #linkVisibleWithText(String) also */ public boolean linkPresentWithText(String text) { return client.isElementPresent("link=" + text); } /** * Asserts that no link exists on the page containing the given text * @param text The text that no link on the page should contain */ public boolean linkNotPresentWithText(String text) { return !client.isElementPresent("link=" + text); } /** * Asserts that a link containin the given text is present and visible. * @param text The text that a link on the page should contain */ public boolean linkVisibleWithText(String text) { return linkPresentWithText(text) && client.isVisible("link=" + text); } /** * Asserts that two elements (located by selenium syntax) are vertically within deltaPixels of each other. * @param locator1 Locator for element 1 given in standard selenium syntax * @param locator2 Locator for element 2 given in standard selenium syntax * @param deltaPixels The maximum allowable distance between the two element */ public boolean elementsVerticallyAligned(String locator1, String locator2, int deltaPixels) { int middle1 = client.getElementPositionTop(locator1).intValue() + (client.getElementHeight(locator1).intValue() / 2); int middle2 = client.getElementPositionTop(locator2).intValue() + (client.getElementHeight(locator2).intValue() / 2); String message = "Vertical position of element '" + locator1 + "' (" + middle1 + ") was not within " + deltaPixels + " pixels of the vertical position of element '" + locator2 + "' (" + middle2 + ")"; return plusMinusEqual(middle1, middle2, deltaPixels); } public boolean elementsVerticallyAligned(PageElement element1, PageElement element2, int deltaPixels) { return elementsVerticallyAligned(element1.getLocator(), element2.getLocator(), deltaPixels); } public boolean elementsSameHeight(final String locator1, final String locator2, final int deltaPixels) { int height1 = client.getElementHeight(locator1).intValue(); int height2 = client.getElementHeight(locator2).intValue(); String message = "Height of element '" + locator1 + "' (" + height1 + ") was not within " + deltaPixels + " pixels of the height of element '" + locator2 + "' (" + height2 + ")"; return plusMinusEqual(height1, height2, deltaPixels); } public boolean elementsSameHeight(PageElement element1, PageElement element2, final int deltaPixels) { return elementsSameHeight(element1.getLocator(), element2.getLocator(), deltaPixels); } private boolean plusMinusEqual(int x, int y, int delta) { return (Math.abs(x - y) <= delta); } /** * Asserts that an element contains the given text. */ public boolean elementContainsText(String locator, String text) { String elementText = client.getText(locator); return (elementText.indexOf(text) >= 0); } public boolean elementContainsText(PageElement element, String text) { return elementContainsText(element.getLocator(), text); } /** * Asserts that an element does not contain the given text. */ public boolean elementDoesNotContainText(String locator, String text) { return !(client.getText(locator).indexOf(text) >= 0); } public boolean elementDoesNotContainText(PageElement element, String text) { return elementDoesNotContainText(element.getLocator(), text); } public boolean windowClosed(String windowName) { return !windowOpen(windowName); } public boolean windowOpen(String windowName) { return Arrays.asList(client.getAllWindowNames()).contains(windowName); } }
/* * File: MixtureOfGaussiansTest.java * Authors: Kevin R. Dixon * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright August 1, 2006, Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000, there is a non-exclusive license for use of this work by * or on behalf of the U.S. Government. Export of this program may require a * license from the United States Government. See CopyrightHistory.txt for * complete details. * */ package gov.sandia.cognition.statistics.distribution; import gov.sandia.cognition.learning.algorithm.clustering.KMeansClusterer; import gov.sandia.cognition.learning.algorithm.clustering.cluster.GaussianCluster; import gov.sandia.cognition.learning.algorithm.clustering.cluster.GaussianClusterCreator; import gov.sandia.cognition.learning.algorithm.clustering.divergence.GaussianClusterDivergenceFunction; import gov.sandia.cognition.learning.algorithm.clustering.initializer.NeighborhoodGaussianClusterInitializer; import gov.sandia.cognition.math.matrix.VectorFactory; import gov.sandia.cognition.math.matrix.Matrix; import gov.sandia.cognition.math.matrix.MatrixFactory; import gov.sandia.cognition.math.matrix.Vector; import gov.sandia.cognition.statistics.method.KolmogorovSmirnovConfidence; import gov.sandia.cognition.util.NamedValue; import java.util.Random; import java.util.ArrayList; import java.util.Arrays; /** * Test for class MixtureOfGaussians * @author krdixon */ public class MixtureOfGaussiansTest extends MultivariateMixtureDensityModelTest { public MixtureOfGaussiansTest( String testName) { super(testName); } @Override public MixtureOfGaussians.PDF createInstance() { return createMixture(3, 2, RANDOM); } /** * Tests the Learner */ public void testLearner() { System.out.println( "Learner" ); int N = 2; double r = 2.0; double rC = 0.5; Matrix s1 = MatrixFactory.getDefault().createUniformRandom( N, N, -rC, rC, RANDOM ); Matrix C1 = s1.transpose().times( s1 ); Vector m1 = VectorFactory.getDefault().createUniformRandom(N, -r, r, RANDOM ); Matrix s2 = MatrixFactory.getDefault().createUniformRandom( N, N, -rC, rC, RANDOM ); Matrix C2 = s2.transpose().times( s2 ); Vector m2 = VectorFactory.getDefault().createUniformRandom(N, -r, r, RANDOM ); double p1 = RANDOM.nextDouble(); double[] p = new double[]{ p1, 1.0-p1 }; ArrayList<MultivariateGaussian.PDF> gs = new ArrayList<MultivariateGaussian.PDF>( Arrays.asList( new MultivariateGaussian.PDF( m1, C1 ), new MultivariateGaussian.PDF( m2, C2 ) ) ); MixtureOfGaussians.PDF mog = new MixtureOfGaussians.PDF( gs, p ); ArrayList<Vector> samples = mog.sample(RANDOM, 10*NUM_SAMPLES); System.out.println( "MOG: " + mog ); int k = 2; KMeansClusterer<Vector,GaussianCluster> kmeans = new KMeansClusterer<Vector,GaussianCluster>( k, 100, new NeighborhoodGaussianClusterInitializer(RANDOM), GaussianClusterDivergenceFunction.INSTANCE, new GaussianClusterCreator() ); MixtureOfGaussians.Learner learner = new MixtureOfGaussians.Learner( kmeans ); learner.learn(samples); MixtureOfGaussians.PDF moghat = learner.getResult(); System.out.println( "moghat: " + moghat ); assertEquals( 2, moghat.getDistributionCount() ); // This is kludgey, but I can't think of a better way to get the // automated test that I'm looking for... // -- krdixon, 2009-03-04 // Vector phat = moghat.getPriorProbabilities(); // System.out.println( "Delta: " + p.minus(phat) ); // assertTrue( p.equals( phat, 1e-2 ) ); // Vector m1hat = moghat.getRandomVariables().get(0).getMean(); // assertTrue( m1.equals( m1hat, 1e-2 ) ); // // Vector m2hat = moghat.getRandomVariables().get(1).getMean(); // assertTrue( m2.equals( m2hat, 1e-2 ) ); NamedValue<? extends Number> value = learner.getPerformance(); assertNotNull( value ); System.out.println( "Value: " + value.getName() + " = " + value.getValue() ); MixtureOfGaussians.Learner l2 = new MixtureOfGaussians.Learner(null); try { l2.getResult(); fail( "Null pointer exception" ); } catch (Exception e) { System.out.println( "Good: " + e ); } } public void testComputeWeightedZ() { System.out.println( "computeWeightedZ" ); int numGaussians = 2; int numDimensions = 2; MixtureOfGaussians.PDF mog = createMixture(numGaussians, numDimensions, RANDOM); ArrayList<Vector> samples = mog.sample(RANDOM, NUM_SAMPLES); ArrayList<Double> zs = new ArrayList<Double>( samples.size() ); for( Vector input : samples ) { double z = mog.computeWeightedZSquared(input); zs.add( z ); } ChiSquareDistribution.CDF chi = new ChiSquareDistribution.CDF(numDimensions); KolmogorovSmirnovConfidence.Statistic kstest = KolmogorovSmirnovConfidence.evaluateNullHypothesis(zs, chi); System.out.println( "K-S test: " + kstest ); final double confidence = 0.95; assertEquals( 1.0, kstest.getNullHypothesisProbability(), confidence ); } /** * Test of fitSingleGaussian method, of class gov.sandia.isrc.math.MultivariateGaussian. */ public void testFitSingleGaussian() { System.out.println( "fitSingleGaussian" ); int num = (int) (this.RANDOM.nextDouble() * 5) + 2; int dim = 2; MixtureOfGaussians.PDF mixture = MixtureOfGaussiansTest.createMixture( num, dim, RANDOM ); ArrayList<Vector> draws = mixture.sample( RANDOM, NUM_SAMPLES ); MultivariateGaussian sample = MultivariateGaussian.MaximumLikelihoodEstimator.learn( draws, 0.0 ); MultivariateGaussian result = mixture.fitSingleGaussian(); double tolerance = 10 * dim * dim / (2 * Math.log( NUM_SAMPLES )); double EPSILON = 1e-5; System.out.println( "Tolerance = " + tolerance ); System.out.println( "Mean: Mixture: " + mixture.getMean() + " Result: " + result.getMean() + " Sample: " + sample.getMean() ); assertTrue( mixture.getMean().equals( result.getMean(), EPSILON ) ); assertTrue( sample.getMean().equals( result.getMean(), tolerance ) ); System.out.println( "Covariance:\nResult:\n" + result.getCovariance() + "\nSample:\n" + sample.getCovariance() ); System.out.println( "Tolerance: " + tolerance + " Residual:\n" + result.getCovariance().minus( sample.getCovariance() ) ); assertTrue( sample.getCovariance().equals( result.getCovariance(), tolerance ) ); } @Override public void testConstructors() { System.out.println( "Constructors" ); MultivariateGaussian g1 = new MultivariateGaussian(); MixtureOfGaussians.PDF instance = new MixtureOfGaussians.PDF ( g1 ); assertEquals( 1, instance.getDistributionCount() ); assertSame( g1, instance.getDistributions().get(0) ); assertEquals( 1.0, instance.getPriorWeights()[0] ); MultivariateGaussian g2 = new MultivariateGaussian(); MixtureOfGaussians.PDF i2 = new MixtureOfGaussians.PDF( g1, g2 ); instance = new MixtureOfGaussians.PDF( i2 ); assertEquals( i2.getDistributionCount(), instance.getDistributionCount() ); assertNotSame( i2.getDistributions(), instance.getDistributions() ); assertNotSame( i2.getPriorWeights(), instance.getPriorWeights() ); assertEquals( i2.getPriorWeightSum(), instance.getPriorWeightSum() ); } @Override public void testProbabilityFunctionConstructors() { System.out.println( "PDF Constructors" ); MultivariateGaussian g1 = new MultivariateGaussian(); MultivariateMixtureDensityModel.PDF<MultivariateGaussian> instance = new MultivariateMixtureDensityModel.PDF<MultivariateGaussian>( Arrays.asList(g1) ); assertEquals( 1, instance.getDistributionCount() ); assertSame( g1, instance.getDistributions().get(0) ); assertEquals( 1.0, instance.getPriorWeights()[0] ); MultivariateGaussian g2 = new MultivariateGaussian(); MultivariateMixtureDensityModel.PDF<MultivariateGaussian> i2 = new MultivariateMixtureDensityModel.PDF<MultivariateGaussian>( Arrays.asList(g1, g2) ); instance = new MultivariateMixtureDensityModel.PDF<MultivariateGaussian>( i2 ); assertEquals( i2.getDistributionCount(), instance.getDistributionCount() ); assertNotSame( i2.getDistributions(), instance.getDistributions() ); assertNotSame( i2.getPriorWeights(), instance.getPriorWeights() ); assertEquals( i2.getPriorWeightSum(), instance.getPriorWeightSum() ); } /** * EMLearner 2 Gaussians */ public void testEMLearner2Gaussians() { System.out.println( "EMLearner 2 Gaussians" ); ArrayList<MultivariateGaussian.PDF> gs = new ArrayList<MultivariateGaussian.PDF>( 2 ); int dim = 2; gs.add( new MultivariateGaussian.PDF( VectorFactory.getDefault().createVector(dim, -1.0), MatrixFactory.getDefault().createIdentity(dim, dim) ) ); gs.add( new MultivariateGaussian.PDF( VectorFactory.getDefault().createVector(dim, 1.0), MatrixFactory.getDefault().createIdentity(dim, dim) ) ); MixtureOfGaussians.PDF target = new MixtureOfGaussians.PDF( gs ); ArrayList<Vector> samples = target.sample(RANDOM, NUM_SAMPLES); MixtureOfGaussians.EMLearner learner = new MixtureOfGaussians.EMLearner( 2, RANDOM ); MixtureOfGaussians.PDF estimate = learner.learn(samples); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package com.microsoft.azure.iothub.transport.https; import com.microsoft.azure.iothub.IotHubMessage; import com.microsoft.azure.iothub.IotHubMessageProperty; import com.microsoft.azure.iothub.IotHubServiceboundMessage; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; /** A single HTTPS message. */ public final class HttpsSingleMessage implements HttpsMessage { public static final String HTTPS_SINGLE_MESSAGE_CONTENT_TYPE = "binary/octet-stream"; protected byte[] body; protected boolean base64Encoded; protected IotHubMessageProperty[] properties; /** * Returns the HTTPS message represented by the service-bound message. * * @param msg the service-bound message to be mapped to its HTTPS message * equivalent. * * @return the HTTPS message represented by the service-bound message. */ public static HttpsSingleMessage parseHttpsMessage( IotHubServiceboundMessage msg) { HttpsSingleMessage httpsMsg = new HttpsSingleMessage(); // Codes_SRS_HTTPSSINGLEMESSAGE_11_001: [The parsed HttpsSingleMessage shall have a copy of the original message body as its body.] byte[] msgBody = msg.getBody(); httpsMsg.body = Arrays.copyOf(msgBody, msgBody.length); // Codes_SRS_HTTPSSINGLEMESSAGE_11_002: [The parsed HttpsSingleMessage shall have the same base64Encoded value as that of the original message.] httpsMsg.base64Encoded = msg.isBase64Encoded(); // Codes_SRS_HTTPSSINGLEMESSAGE_11_003: [The parsed HttpsSingleMessage shall add the prefix 'iothub-app-' to each of the message properties.] IotHubMessageProperty[] msgProperties = msg.getProperties(); httpsMsg.properties = new IotHubMessageProperty[msgProperties.length]; for (int i = 0; i < msgProperties.length; ++i) { IotHubMessageProperty property = msgProperties[i]; httpsMsg.properties[i] = new IotHubMessageProperty( HTTPS_APP_PROPERTY_PREFIX + property.getName(), property.getValue()); } return httpsMsg; } /** * Returns the HTTPS message represented by the HTTPS response. * * @param response the HTTPS response. * * @return the HTTPS message represented by the HTTPS response. */ public static HttpsSingleMessage parseHttpsMessage( HttpsResponse response) { HttpsSingleMessage msg = new HttpsSingleMessage(); // Codes_SRS_HTTPSSINGLEMESSAGE_11_004: [The parsed HttpsSingleMessage shall have a copy of the original response body as its body.] byte[] responseBody = response.getBody(); msg.body = Arrays.copyOf(responseBody, responseBody.length); // Codes_SRS_HTTPSSINGLEMESSAGE_11_005: [The parsed HttpsSingleMessage shall not be Base64-encoded.] msg.base64Encoded = false; // Codes_SRS_HTTPSSINGLEMESSAGE_11_006: [The parsed HttpsSingleMessage shall include all valid HTTPS application-defined properties in the response header as message properties.] ArrayList<IotHubMessageProperty> properties = new ArrayList<>(); Map<String, String> headerFields = response.getHeaderFields(); for (Map.Entry<String, String> field : headerFields.entrySet()) { String propertyName = field.getKey(); String propertyValue = field.getValue(); if (isValidHttpsAppProperty(propertyName, propertyValue)) { properties.add(new IotHubMessageProperty(propertyName, propertyValue)); } } msg.properties = new IotHubMessageProperty[properties.size()]; msg.properties = properties.toArray(msg.properties); return msg; } /** * Returns the Iot Hub message represented by the HTTPS message. * * @return the IoT Hub message represented by the HTTPS message. */ public IotHubMessage toMessage() { // Codes_SRS_HTTPSSINGLEMESSAGE_11_007: [The function shall return an IoT Hub message with a copy of the message body as its body.] IotHubMessage msg = new IotHubMessage(this.getBody()); // Codes_SRS_HTTPSSINGLEMESSAGE_11_008: [The function shall return an IoT Hub message with application-defined properties that have the prefix 'iothub-app' removed.] for (IotHubMessageProperty property : this.properties) { String propertyName = httpsAppPropertyToAppProperty(property.getName()); msg.setProperty(propertyName, property.getValue()); } return msg; } /** * Returns a copy of the message body. * * @return a copy of the message body. */ public byte[] getBody() { // Codes_SRS_HTTPSSINGLEMESSAGE_11_009: [The function shall return a copy of the message body.] return Arrays.copyOf(this.body, this.body.length); } /** * Returns the message body as a string. The body is encoded using charset * UTF-8. * * @return the message body as a string. */ public String getBodyAsString() { // Codes_SRS_HTTPSSINGLEMESSAGE_11_010: [The function shall return the message body as a string encoded using charset UTF-8.] return new String(this.body, IotHubMessage.IOTHUB_MESSAGE_DEFAULT_CHARSET); } /** * Returns the message content-type as 'binary/octet-stream'. * * @return the message content-type as 'binary/octet-stream'. */ public String getContentType() { // Codes_SRS_HTTPSSINGLEMESSAGE_11_011: [The function shall return the message content-type as 'binary/octet-stream'.] return HTTPS_SINGLE_MESSAGE_CONTENT_TYPE; } /** * Returns whether the message is Base64-encoded. * * @return whether the message is Base64-encoded. */ public boolean isBase64Encoded() { // Codes_SRS_HTTPSSINGLEMESSAGE_11_012: [The function shall return whether the message is Base64-encoded.] return this.base64Encoded; } /** * Returns a copy of the message properties. * * @return a copy of the message properties. */ public IotHubMessageProperty[] getProperties() { // Codes_SRS_HTTPSSINGLEMESSAGE_11_013: [The function shall return a copy of the message properties.] int propertiesSize = this.properties.length; IotHubMessageProperty[] propertiesCopy = new IotHubMessageProperty[propertiesSize]; for (int i = 0; i < propertiesSize; ++i) { IotHubMessageProperty property = this.properties[i]; IotHubMessageProperty propertyCopy = new IotHubMessageProperty(property.getName(), property.getValue()); propertiesCopy[i] = propertyCopy; } return propertiesCopy; } /** * Returns whether the property name and value constitute a valid HTTPS * application property. The property is valid if it is a valid application * property and its name begins with 'iothub-app-'. * * @param name the property name. * @param value the property value. * * @return whether the property is a valid HTTPS property. */ protected static boolean isValidHttpsAppProperty(String name, String value) { String lowercaseName = name.toLowerCase(); if (IotHubMessageProperty.isValidAppProperty(name, value) && lowercaseName.startsWith(HTTPS_APP_PROPERTY_PREFIX)) { return true; } return false; } /** * Returns an application-defined property name with the prefix 'iothub-app' * removed. If the prefix is not present, the property name is left * untouched. * * @param httpsAppProperty the HTTPS property name. * * @return the property name with the prefix 'iothub-app' removed. */ protected static String httpsAppPropertyToAppProperty( String httpsAppProperty) { String canonicalizedProperty = httpsAppProperty.toLowerCase(); if (canonicalizedProperty.startsWith(HTTPS_APP_PROPERTY_PREFIX)) { return canonicalizedProperty .substring(HTTPS_APP_PROPERTY_PREFIX.length()); } return canonicalizedProperty; } protected HttpsSingleMessage() { } }
/* * 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.river.test.spec.security.proxytrust.util; import java.util.logging.Level; // java import java.io.File; import java.net.MalformedURLException; import java.rmi.RemoteException; import java.rmi.server.RMIClassLoader; import java.util.ArrayList; import java.util.List; import java.lang.reflect.Method; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; // org.apache.river import org.apache.river.qa.harness.QATestEnvironment; // net.jini import org.apache.river.qa.harness.Test; import net.jini.export.Exporter; import net.jini.security.TrustVerifier; import net.jini.security.proxytrust.ProxyTrustExporter; import net.jini.security.proxytrust.ProxyTrustVerifier; import net.jini.security.proxytrust.ProxyTrustIterator; import net.jini.security.proxytrust.ProxyTrust; import net.jini.security.proxytrust.ProxyTrustInvocationHandler; import net.jini.core.constraint.RemoteMethodControl; import net.jini.core.constraint.MethodConstraints; import net.jini.constraint.BasicMethodConstraints; import net.jini.core.constraint.InvocationConstraint; import net.jini.core.constraint.InvocationConstraints; import net.jini.core.constraint.Integrity; import net.jini.loader.ClassLoading; /** * Base class for proxytrust spec-tests. */ public abstract class AbstractTestBase extends QATestEnvironment implements Test { /** * Holds expected results for 'isTrustedObject' method calls of * ProxyTrustVerifier. */ protected ExpResults expResults; /* Number of BaseTrustVerifierContext 'isTrustedObject' method calls. */ private int ctxCallsNum; /* Last thrown RemoteException. */ private RemoteException lastRE; /** ProxyTrust.getProxyVerifier method */ protected static MethodConstraints validMC; static { try { validMC = new BasicMethodConstraints( new BasicMethodConstraints.MethodDesc[] { new BasicMethodConstraints.MethodDesc( "getProxyVerifier", new InvocationConstraints( new InvocationConstraint[] { Integrity.YES }, null)) }); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } /** * Print arguments specified and then create ProxyTrustExporter with * specified arguments. * * @param mainExporter Main exporter for ProxyTrustExporter * @param bootExporter Boot exporter for ProxyTrustExporter * @return ProxyTrustExporter */ public ProxyTrustExporter createPTE(Exporter mainExporter, Exporter bootExporter) { logger.fine("Creating ProxyTrustExporter[mainExporter = " + mainExporter + ", bootExporter = " + bootExporter + "]"); return new ProxyTrustExporter(mainExporter, bootExporter); } /** * Print arguments specified and then create ProxyTrustInvocationHandler * with specified arguments. * * @param main the main proxy * @param boot the bootstrap proxy * @return ProxyTrustInvocationHandler */ public ProxyTrustInvocationHandler createPTIH(RemoteMethodControl main, ProxyTrust boot) { logger.fine("Creating ProxyTrustInvocationHandler[main = " + main + ", boot = " + boot + "]"); return new ProxyTrustInvocationHandler(main, boot); } /** * Print arguments specified and then call 'invoke' method of * ProxyTrustInvocationHandler specified. * * @param ptih ProxyTrustInvocationHandler * @param proxy the proxy object * @param method the method being invoked * @param args the arguments to the specified method * @return result of 'invoke' method call * @throws NullPointerException if ptih is null * @throws rethrow any exception thrown by invoke method */ public Object ptihInvoke(ProxyTrustInvocationHandler ptih, Object proxy, Method method, Object[] args) throws Exception { if (ptih == null) { throw new NullPointerException( "ProxyTrustInvocationHandler specified is null."); } logger.fine("Call 'invoke(): Proxy" + ProxyTrustUtil.interfacesToString(proxy) + ", Method: " + method + ", Args: " + ProxyTrustUtil.arrayToString(args) + "'."); try { return ptih.invoke(proxy, method, args); } catch (Throwable t) { if (t instanceof Exception) { throw ((Exception) t); } else { throw new Error(t); } } } /** * Print arguments specified and then call 'checkTrustEquivalence' method of * ProxyTrustInvocationHandler specified. * * @param ptih ProxyTrustInvocationHandler * @param obj parameter to 'checkTrustEquivalence' method * @return result of 'checkTrustEquivalence' method call * @throws NullPointerException if ptih is null */ public boolean ptihCheckTrustEquivalence(ProxyTrustInvocationHandler ptih, Object obj) { if (ptih == null) { throw new NullPointerException( "ProxyTrustInvocationHandler specified is null."); } logger.fine("Call 'checkTrustEquivalence(" + obj + ")' method of " + ptih + "."); return ptih.checkTrustEquivalence(obj); } /** * Print arguments specified and then call 'equals' method of * ProxyTrustInvocationHandler specified. * * @param ptih ProxyTrustInvocationHandler * @param obj parameter to 'equals' method * @return result of 'equals' method call * @throws NullPointerException if ptih is null */ public boolean ptihEquals(ProxyTrustInvocationHandler ptih, Object obj) { if (ptih == null) { throw new NullPointerException( "ProxyTrustInvocationHandler specified is null."); } logger.fine("Call 'equals(" + obj + ")' method of " + ptih + "."); return ptih.equals(obj); } /** * Create proxy implementing RemoteMethodControl and TrustEquivalence * interfaces to be used as ValidMainProxy. * * @return proxy created */ public RemoteMethodControl createValidMainProxy() { return (RemoteMethodControl) ProxyTrustUtil.newProxyInstance( new RMCTEImpl()); } /** * Create proxy implementing RemoteMethodControl, ProxyTrust and * TrustEquivalence interfaces to be used as ValidBootProxy. * * @return proxy created */ public ProxyTrust createValidBootProxy() { return (ProxyTrust) ProxyTrustUtil.newProxyInstance(new RMCPTTEImpl()); } /** * Creates main proxy. * * @param impl * @return proxy created */ public RemoteMethodControl newMainProxy(Object impl) { TestClassLoader cl = new TestClassLoader(); InvocationHandler ih = new InvHandler(impl); return (RemoteMethodControl) ProxyTrustUtil.newProxyInstance(impl, ih, cl); } /** * Creates main proxy in RMI child loader. * * @param impl * @return proxy created */ public RemoteMethodControl newRMIMainProxy(Object impl) { String jarURL = "file:" + (getConfig().getStringConfigVal("qa.home", null) + "/lib").replace(File.separatorChar, '/') + "/qa1.jar"; InvocationHandler ih = new InvHandler(impl); try { return (RemoteMethodControl) ProxyTrustUtil.newProxyInstance( impl, ih, ClassLoading.getClassLoader(jarURL)); } catch (MalformedURLException e) { throw new AssertionError(e); } } /** * Creates boot proxy. * * @param impl * @return proxy created */ public ProxyTrust newBootProxy(Object impl) { TestClassLoader cl = new TestClassLoader(); InvocationHandler ih = new InvHandler(impl); return (ProxyTrust) ProxyTrustUtil.newProxyInstance(impl, ih, cl); } /** * Returns true if object specified != null, is instance of Boolean and * equal to value expected. In this case success message will be printed. * Otherwise false will be returned. * * @param obj object for checking * @param value expected value * @return true if obj != null, is instance of Boolean and equal to value * and false otherwise */ public boolean isOk(Object obj, boolean value) { if ((obj == null) || !(obj instanceof Boolean) || ((Boolean) obj).booleanValue() != value) { // FAIL return false; } // PASS logger.fine("'invoke' method of constructed " + "ProxyTrustInvocationHandler returned " + value + " as expected."); return true; } /** * Print arguments specified, fills array of expected calls and then call * 'isTrustedObject' method of ProxyTrustVerifier. * * @param ptv tested ProxyTrustVerifier * @param obj parameter to 'isTrustedObject' method * @param ctx context-parameter to 'isTrustedObject' method * @return result of 'isTrustedObject' method call * @throws Exception rethrow any exception thrown by 'isTrustedObject' * method call * @throws NullPointerException if ptv is null * @throws IllegalArgumentException if ctx is not null and is not an * instance of BaseTrustVerifierContext */ public boolean ptvIsTrustedObject(ProxyTrustVerifier ptv, Object obj, TrustVerifier.Context ctx) throws RemoteException { if (ptv == null) { throw new NullPointerException("ProxyTrustVerifier can't be null."); } if (ctx != null && !(ctx instanceof BaseTrustVerifierContext)) { throw new IllegalArgumentException( "ctx is not an instance of BaseTrustVerifierContext."); } logger.fine("Call 'isTrustedObject(Object = [" + obj + "], Context = [" + ctx + "])' method of ProxyTrustVerifier."); if (obj != null && ctx != null) { expResults = new ExpResults(obj, ctx); expResults.objs = getExpArray(obj, ctx); BaseIsTrustedObjectClass.initClassesArray(); } return ptv.isTrustedObject(obj, ctx); } /** * Returns array of expected objects for checking results of testing. * Sets variables for expected result to appropriate values. * * @param obj Object for 'isTrustedObject' method * @param ctx Context for 'isTrustedObject' method * @return array of expected objects * @throws IllegalArgumentException if ctx is not an instance of * BaseTrustVerifierContext */ private BaseIsTrustedObjectClass[] getExpArray(Object obj, TrustVerifier.Context ctx) { if (!(ctx instanceof BaseTrustVerifierContext)) { throw new IllegalArgumentException( "ctx is not an instance of BaseTrustVerifierContext."); } ctxCallsNum = 0; List list = new ArrayList(); if (((BaseTrustVerifierContext) ctx).containsValidMC()) { addExpColl(list, obj, ctx); } if (list.isEmpty() || expResults.res == null) { if (expResults.exList.size() > 0) { expResults.res = expResults.exList.get( expResults.exList.size() - 1); } else { expResults.res = new Boolean(false); } } return (BaseIsTrustedObjectClass []) list.toArray( new BaseIsTrustedObjectClass[list.size()]); } /* * Adds to list of expected objects. * Sets variables for expected result to appropriate values. */ private void addExpColl(List list, Object obj, TrustVerifier.Context ctx) { if (!(obj instanceof ProxyTrust) && Proxy.isProxyClass(obj.getClass())) { obj = Proxy.getInvocationHandler(obj); if (!Proxy.isProxyClass(obj.getClass())) { addExpColl(list, obj, ctx); } } else if (obj instanceof NonProxyObjectThrowingRE) { // must be called 'setException' method of TrustIterator int size = ((NonProxyObjectThrowingRE) obj).getObjArray().length; TrustIteratorThrowingRE ti = (TrustIteratorThrowingRE) ((NonProxyObjectThrowingRE) obj).getProxyTrustIterator(); for (int i = 0; i < size; ++i) { list.add(ti); expResults.exList.add(ti.getException()); } } else if (obj instanceof ValidNonProxyObject) { // must be called 'getProxyTrustIterator' method of obj list.add(obj); Object[] objs = ((ValidNonProxyObject) obj).getObjArray(); for (int i = 0; i < objs.length; ++i) { lastRE = null; addExpColl(list, objs[i], ctx); if (lastRE != null) { // must be called 'setException' method of TrustIterator list.add(((ValidNonProxyObject) obj).getProxyTrustIterator()); } if (expResults.res != null) { return; } } lastRE = null; } else if (obj instanceof BaseProxyTrust) { // must be called 'isTrustedObject' method of ctx list.add(ctx); expResults.btvcObjs.add(obj); addExpColl2(list, obj, ctx); } else if (obj instanceof ProxyTrust && obj instanceof RemoteMethodControl && Proxy.isProxyClass(obj.getClass())) { Object ih = Proxy.getInvocationHandler(obj); if (!list.isEmpty()) { list.add(ctx); expResults.btvcObjs.add(obj); addExpColl2(list, ((InvHandler) ih).obj, ctx); } if (proper(obj.getClass())) { list.add(ctx); expResults.btvcObjs.add(new NewProxy(obj)); addExpColl2(list, ((InvHandler) ih).obj, ctx); } } } /* * Returns true if c's loader is a proper RMI child of its parent. */ private static boolean proper(Class c) { ClassLoader cl = c.getClassLoader(); if (cl == null) { return false; } String cb = ClassLoading.getClassAnnotation(c); ClassLoader pl = cl.getParent(); Thread t = Thread.currentThread(); ClassLoader ccl = t.getContextClassLoader(); try { t.setContextClassLoader(pl); return cl == ClassLoading.getClassLoader(cb); } catch (MalformedURLException e) { return false; } finally { t.setContextClassLoader(ccl); } } /* * Adds to collection of expected objects. * Sets variables for expected result to appropriate values. */ private void addExpColl2(List list, Object obj, TrustVerifier.Context ctx) { if (ctx instanceof ThrowingRE) { // RemoteException must be thrown lastRE = ((ThrowingRE) ctx).getException(); expResults.exList.add(lastRE); return; } else if (ctx instanceof TrustVerifierContext && (++ctxCallsNum <= ((TrustVerifierContext) ctx).limit)) { return; } // must be called 'getProxyVerifier' method of obj list.add(obj); TrustVerifier tv = null; if (!(obj instanceof ProxyTrustThrowingRE1)) { try { tv = ((BaseProxyTrust) obj).getProxyVerifier(); } catch (RemoteException re) { throw new Error(re); } } if (tv != null) { // must be called 'isTrustedObject' method of trust verifier list.add(tv); } if (obj instanceof TrueProxyTrust) { expResults.res = new Boolean(true); } else if (obj instanceof ProxyTrustThrowingRE1) { // RemoteException must be thrown lastRE = ((ThrowingRE) obj).getException(); expResults.exList.add(lastRE); } else if (obj instanceof ProxyTrustThrowingRE2) { // RemoteException must be thrown expResults.exList.add(((ThrowingRE) tv).getException()); } else { expResults.res = new Boolean(false); } } /** * Checks expected result with actual one. Returns non-null string * indicating first error or null if everything was as expected. * * @param res result of 'isTrustedObject' method call (could be exception) * @return non-null string indicating first error or null if everything was * as expected */ public String checkResult(Object res) { int index = 0; int exIndex = 0; BaseIsTrustedObjectClass[] actArray = BaseIsTrustedObjectClass.getClassesArray(); int len = 0; if (expResults.objs == null || expResults.objs.length == 0) { if (actArray != null && actArray.length != 0) { // FAIL return "'isTrustedObject' method of ProxyTrustVerifier does " + "not satisfy specification. Expected: no " + "intermediate checked methods calls. Got: '" + actArray[0].getMethodName() + "' method call of " + actArray[0] + "."; } } else { if (actArray == null || actArray.length == 0) { // FAIL return "'isTrustedObject' method of ProxyTrustVerifier does " + "not satisfy specification. Expected: '" + expResults.objs[0].getMethodName() + "' method call of " + expResults.objs[0] + ". Got: no intermediate checked method calls."; } len = Math.min(expResults.objs.length, actArray.length); } for (int i = 0; i < len; ++i) { if (expResults.objs[i] != actArray[i]) { // FAIL return "'isTrustedObject' method of ProxyTrustVerifier does " + "not satisfy specification. Expected: '" + expResults.objs[i].getMethodName() + "' method call of " + expResults.objs[i] + ". Got: '" + actArray[i].getMethodName() + "' method call of " + actArray[i] + "."; } // PASS logger.fine("Check " + (i + 1) + ": '" + expResults.objs[i].getMethodName() + "' method of " + actArray[i] + " was called as expected."); if (expResults.objs[i] instanceof ThrowingRE) { ++exIndex; } // check that parameters for checked method are ok if (expResults.objs[i] instanceof BaseProxyTrust) { MethodConstraints mc = ((BaseProxyTrust) expResults.objs[i]).getConstraints(); if (expResults.mc != mc) { // FAIL return "'" + expResults.objs[i].getMethodName() + "' method was invoked with: " + mc + " MethodConstraints while " + expResults.mc + " was expected."; } } else if (expResults.objs[i] instanceof BaseTrustVerifierContext) { Object actObj = ((BaseTrustVerifierContext) expResults.objs[i]).getObjsList().get(index); Object expObj = expResults.btvcObjs.get(index); ++index; if (!(actObj == expObj || (expObj instanceof NewProxy && ((NewProxy) expObj).equal(actObj)))) { // FAIL return "'" + expResults.objs[i].getMethodName() + "' method was invoked with: " + actObj + " parameter while " + expObj + " was expected."; } } else if (expResults.objs[i] instanceof BaseTrustVerifier) { Object obj = ((BaseTrustVerifier) expResults.objs[i]).getObj(); TrustVerifier.Context ctx = ((BaseTrustVerifier) expResults.objs[i]).getCtx(); if (expResults.btvObj != obj || expResults.btvCtx != ctx) { // FAIL return "'" + expResults.objs[i].getMethodName() + "' method was invoked with: Object = " + obj + ", Context = " + ctx + ", while: Object = " + expResults.btvObj + ", Context = " + expResults.btvCtx + " was expected."; } } else if ((expResults.objs[i] instanceof TestTrustIterator) && !(expResults.objs[i] instanceof ThrowingRE)) { RemoteException actRE = ((TestTrustIterator) expResults.objs[i]).nextException(); RemoteException expRE = (RemoteException) expResults.exList.get(exIndex - 1); if (actRE != expRE) { // FAIL return "'" + expResults.objs[i].getMethodName() + "' method was invoked with " + actRE + " exception whil " + expRE + " was expected."; } } // PASS logger.fine("Parameters passed to this method were as expected."); } if (expResults.objs != null && actArray != null && expResults.objs.length != actArray.length) { // FAIL if (expResults.objs.length > actArray.length) { return "'isTrustedObject' method of ProxyTrustVerifier does " + "not satisfy specification. Expected: '" + expResults.objs[len].getMethodName() + "' method call of " + expResults.objs[len] + ". Got: no more checked method calls."; } else { return "'isTrustedObject' method of ProxyTrustVerifier does " + "not satisfy specification. Expected: no " + "more checked methods calls. Got: '" + actArray[len].getMethodName() + "' method call of " + actArray[len] + "."; } } if (res instanceof Boolean) { // Boolean result was expected if (((Boolean) expResults.res).booleanValue() != ((Boolean) res).booleanValue()) { // FAIL return "'isTrustedObject' method of ProxyTrustVerifier " + "returned " + res + " while " + expResults.res + " was expected."; } // PASS logger.fine("'isTrustedObject' method of ProxyTrustVerifier " + "returned " + res + " as expected."); return null; } else { // RemoteException was expected if (expResults.res != res) { // FAIL return "'isTrustedObject' method of ProxyTrustVerifier " + "threw " + res + " while " + expResults.res + " was expected."; } // PASS logger.fine("'isTrustedObject' method of ProxyTrustVerifier " + "threw " + res + " as expected."); return null; } } /** * Class holding various information expected from 'isTrustedObject' method * calls. */ class ExpResults { /** Array of expected objects whose checked method should be called. */ public BaseIsTrustedObjectClass[] objs; /** Expected result of 'isTrustedObject' method call */ public Object res; /** * Expected MethodConstraints passed to 'getProxyVerifier' method * of BaseProxyTrust classes. */ public MethodConstraints mc; /** * Expected list of objects which will be passed to multiple * 'isTrustedObject' method calls of BaseTrustVerifierContext classes. */ public ArrayList btvcObjs; /** * Expected list of RemoteExceptions which should be produced. */ public ArrayList exList; /** * Expected object passed 'isTrustedObject' method of * BaseTrustVerifier classes. */ public Object btvObj; /** * Expected context passed 'isTrustedObject' method of * BaseTrustVerifier classes. */ public TrustVerifier.Context btvCtx; /** * Constructor initializing variables. * * @param expBtvObj expected object passed 'isTrustedObject' method of * BaseTrustVerifier classes * @param expBtvCtx expected context passed 'isTrustedObject' method of * BaseTrustVerifier classes */ public ExpResults(Object expBtvObj, TrustVerifier.Context expBtvCtx) { objs = null; res = null; btvcObjs = new ArrayList(); exList = new ArrayList(); btvObj = expBtvObj; btvCtx = expBtvCtx; mc = ((BaseTrustVerifierContext) expBtvCtx).getValidMC(); } } class NewProxy { private Object obj; NewProxy(Object obj) { this.obj = obj; } boolean equal(Object obj) { Class c = obj.getClass(); return (Proxy.isProxyClass(c) && c.getClassLoader() == getClass().getClassLoader() && Proxy.getInvocationHandler(obj) == Proxy.getInvocationHandler(this.obj) && obj instanceof ProxyTrust && obj instanceof RemoteMethodControl && c.getInterfaces().length == 2); } } }
package tintor.sokoban; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; import lombok.AllArgsConstructor; import lombok.Cleanup; import lombok.val; import lombok.experimental.ExtensionMethod; import tintor.common.Array; import tintor.common.AutoTimer; import tintor.common.BipartiteMatching; import tintor.common.Bits; import tintor.common.Flags; import tintor.common.For; import tintor.common.Util; import tintor.sokoban.Cell.Dir; // TODO move inside Cell class final class Move { Cell cell; final Dir dir; Dir exit_dir; // in case of dead tunnels if can be different from dir int dist; boolean alive = true; Move(Cell cell, Dir dir, int dist, boolean alive) { assert cell != null; assert dir != null; assert dist > 0; this.cell = cell; this.dir = this.exit_dir = dir; this.dist = dist; this.alive = alive; } } @ExtensionMethod(Array.class) public final class Level { public final String name; private final char[] buffer; // all three arrays are sorted in the same order: goals first, then non-goal alive, then dead cells public Cell[] cells; public Cell[] alive; public Cell[] goals; int[] goal_set; public final int num_boxes; public final CellVisitor visitor; public final State start; public final CellLevelTransforms transforms; public final Cell goal_section_entrance; // sections are rooms of alive cells only public final boolean has_goal_zone; private static final Flags.Bool enable_tunnels = new Flags.Bool("enable_tunnels", true); public static class MoreThan1024CellsError extends Error { private static final long serialVersionUID = 1L; } public static Iterable<Level> loadAll(String filename) { return Util.iterable(p -> { final int count = LevelLoader.numberOfLevels(filename); for (int i = 1; i <= count; i++) try { p.accept(load(filename + ":" + i)); } catch (MoreThan1024CellsError e) { } }); } private static final Flags.Int weaken = new Flags.Int("weaken", 0); public static Level load(String filename) { return new Level(LevelLoader.load(filename), filename, weaken.value); } private void weaken(Cell[] grid, int amount) { if (amount == 0) return; ArrayList<Cell> boxes = new ArrayList<>(); ArrayList<Cell> goals = new ArrayList<>(); for (Cell a : grid) if (a != null) { if (a.box) boxes.add(a); if (a.goal) goals.add(a); } ThreadLocalRandom rand = ThreadLocalRandom.current(); for (int i = 0; i < amount; i++) { // remove one box int b = rand.nextInt(boxes.size()); boxes.get(b).box = false; boxes.remove(b); // remove one goal int g = rand.nextInt(goals.size()); goals.get(g).goal = false; goals.remove(g); } } Level(char[] buffer, String name, int weaken_amount) { int w = 0; while (buffer[w] != '\n') w++; assert buffer.length % (w + 1) == 0; this.name = name; this.buffer = buffer; Cell[] grid = create_cell_grid(w); weaken(grid, weaken_amount); connect_nearby_cells(grid, w); Cell agent = find_agent(grid); val p = move_agent_from_deadend(grid, agent); int dist = p.dist; agent = p.agent; remove_deadend_cells(grid, agent); visitor = new CellVisitor(buffer.length); remove_unreachable_cells(agent, grid); clean_buffer_chars(w); init_cells_goals_and_ids(); if (name == null) { transforms = null; start = null; goal_section_entrance = null; has_goal_zone = false; num_boxes = 0; alive = null; return; } add_nice_walls(w); // Check boxes and goals num_boxes = Array.count(cells, c -> c.box); if (num_boxes == 0) throw new IllegalArgumentException("no boxes"); if (num_boxes != Array.count(cells, c -> c.goal)) throw new IllegalArgumentException("count(box) != count(goal)"); // Make sure all goals are reachable by boxes CellPairVisitor pair_visitor = new CellPairVisitor(cells.length, cells.length, cells); if (!are_all_goals_reachable_full(pair_visitor, false)) throw new IllegalArgumentException("level contains unreachable goal"); compute_alive_cells(pair_visitor); remove_useless_alive_cells(); // Set alive of all Moves for (Cell a : cells) for (Move am : a.moves) am.alive = a.alive && am.cell.alive; if (enable_tunnels.value) { compress_dead_tunnels(agent); compress_cell_ids(); } pair_visitor.cells = cells; alive = Arrays.copyOf(cells, repartition(goals.length, c -> c.alive)); compute_distances_to_each_goal(Array.count(cells, c -> c.goal), pair_visitor); start = compute_goal_and_start(agent, dist); transforms = new CellLevelTransforms(this, w + 1, buffer.length / (w + 1), grid); find_bottlenecks(agent, new int[cells.length], null, new int[1]); find_box_bottlenecks(cells[0], new int[alive.length], null, new int[1]); int room_count = compute_rooms(); goal_section_entrance = goal_section_entrance(room_count); // At least three goals next to each other has_goal_zone = For.any(cells, a -> a.goal && Array.count(a.moves, e -> e.cell.goal) >= 2); } private Cell[] create_cell_grid(int w) { Cell[] grid = new Cell[buffer.length]; for (int y = w + 1; y < buffer.length - w - 1; y += w + 1) for (int xy = y + 1; xy < y + w - 1; xy++) if (buffer[xy] != Code.Wall) grid[xy] = new Cell(this, xy, buffer[xy]); return grid; } private void connect_nearby_cells(Cell[] grid, int w) { Move[] m = new Move[4]; for (Cell c : grid) if (c != null) { int p = 0; for (Dir dir : Dir.values()) { int xy = move(c.xy, dir, w + 1, buffer.length); if (grid[xy] != null) c.dir[dir.ordinal()] = m[p++] = new Move(grid[xy], dir, 1, true); } c.moves = Arrays.copyOf(m, p); } } private Cell find_agent(Cell[] grid) { if (Array.count(grid, c -> c != null && (buffer[c.xy] == Code.Agent || buffer[c.xy] == Code.AgentGoal)) != 1) throw new IllegalArgumentException("need exactly one agent"); Cell agent = null; for (Cell c : grid) if (c != null && (buffer[c.xy] == Code.Agent || buffer[c.xy] == Code.AgentGoal)) agent = c; return agent; } @AllArgsConstructor static class DistAgent { int dist; Cell agent; } private DistAgent move_agent_from_deadend(Cell[] grid, Cell agent) { int dist = 0; while (!agent.goal && agent.moves.length == 1) { Cell b = agent.moves[0].cell; if (b.box) { Move m = b.move(agent.moves[0].dir); if (m == null) break; Cell c = m.cell; if (c.box) break; b.box = false; c.box = true; buffer[c.xy] = c.goal ? Code.BoxGoal : Code.Box; } buffer[agent.xy] = Code.Wall; buffer[b.xy] = Code.Agent; grid[agent.xy] = null; detach(b, agent); agent = b; assert grid[agent.xy] != null; dist += 1; } return new DistAgent(dist, agent); } private void remove_deadend_cells(Cell[] grid, Cell agent) { for (Cell a : grid) while (a != null && a != agent && a.moves.length == 1 && !a.goal && !a.box) { Cell b = a.moves[0].cell; buffer[a.xy] = Code.Wall; grid[a.xy] = null; detach(b, a); a = b; } } private void remove_unreachable_cells(Cell agent, Cell[] grid) { visitor.add(agent); for (Cell a : visitor) for (Move e : grid[a.xy].moves) visitor.try_add(e.cell); for (int i = 0; i < grid.length; i++) if (!visitor.visited()[i]) grid[i] = null; } private void clean_buffer_chars(int w) { for (int i = 0; i < buffer.length; i++) if (!visitor.visited(i) && buffer[i] != '\n' & buffer[i] != Code.Space) if (!is_close_to_visited(i, visitor.visited(), w + 1, buffer.length / (w + 1), false)) buffer[i] = Code.Space; } private void init_cells_goals_and_ids() { int count = visitor.tail(); // TODO move this after tunnel compression, as cell count will decrease if (count > 1024) throw new MoreThan1024CellsError(); // until I make compute_alive() faster cells = new Cell[count]; Array.copy(visitor.queue(), 0, cells, 0, count); goals = Arrays.copyOf(cells, repartition(0, p -> p.goal)); for (int i = 0; i < cells.length; i++) cells[i].id = i; } private void add_nice_walls(int w) { for (int i = 0; i < buffer.length; i++) if (!visitor.visited(i) && buffer[i] != '\n' && buffer[i] != Code.Wall) if (is_close_to_visited(i, visitor.visited(), w + 1, buffer.length / (w + 1), true)) buffer[i] = Code.Wall; } private void remove_useless_alive_cells() { for (Cell a : cells) while (true) { Cell b = end_of_half_tunnel(a); if (b == null || a.box || a.goal) break; a.alive = false; a = b; } } private static Cell end_of_half_tunnel(Cell pos) { if (!pos.alive || pos.moves.length > 2) return null; int count = 0; Cell b = null; for (Move e : pos.moves) if (e.cell.alive) { count += 1; b = e.cell; } if (count != 1 || b.moves.length != 2) return null; return Array.count(b.moves, e -> e.cell.alive) == 2 ? b : null; } private int compute_rooms() { int room_count = 0; for (Cell a : cells) { if (a.straight() || a.room > 0) continue; room_count += 1; for (Cell b : visitor.init(a)) { b.room = room_count; for (Move e : b.moves) if (!e.cell.straight() && e.dist == 1) visitor.try_add(e.cell); } } return room_count; } private void compress_dead_tunnels(Cell agent) { // TODO if agent is inside empty tunnel we can move agent to both sides to avoid breaking tunnel into two (will have 2 start states) for (Cell a : cells) if (a != null && (a.alive || a.moves.length != 2)) for (Move am : a.moves) { Cell b = am.cell; while (!b.alive && b.moves.length == 2 && b != agent && !b.goal && !b.box) { // remove B, and connect A and C directly Move bma = b.rmove(am.exit_dir); Move bmc = Array.find(b.moves, m -> m != bma); Cell c = bmc.cell; if (a.connected_to(c)) break; Move cm = c.rmove(bmc.exit_dir); cells[b.id] = null; buffer[b.xy] = Code.DeadTunnel; am.cell = c; am.dist += bmc.dist; am.alive = false; am.exit_dir = bmc.exit_dir; cm.cell = a; cm.dist += bma.dist; cm.alive = false; cm.exit_dir = bma.exit_dir; b = c; } } } private void compress_cell_ids() { int id = 0; for (int i = 0; i < cells.length; i++) if (cells[i] != null) cells[id++] = cells[i]; cells = Arrays.copyOf(cells, id); for (int i = 0; i < cells.length; i++) cells[i].id = i; } private int repartition(int offset, Predicate<Cell> fn) { int p = offset, q = cells.length - 1; while (true) { while (p < q && fn.test(cells[p])) p += 1; while (p < q && !fn.test(cells[q])) q -= 1; if (p >= q) break; Cell e = cells[p]; cells[p] = cells[q]; cells[q] = e; cells[p].id = p++; cells[q].id = q--; assert fn.test(cells[p - 1]); assert !fn.test(cells[q + 1]); } final int count = fn.test(cells[p]) ? p + 1 : p; assert Util.all(count, e -> fn.test(cells[e])); assert Util.all(count, cells.length, e -> !fn.test(cells[e])); return count; } private Cell goal_section_entrance(int room_count) { Cell best = null; int best_size = Integer.MAX_VALUE; for (Cell b : alive) if (b.box_bottleneck) { int size = box_bottleneck_goal_zone_size(b); if (size < best_size) { best = b; best_size = size; } } return best_size < alive.length * 4 / 5 ? best : null; } public int state_space() { // Discount cells in alive tunnels (count them as 1 cell) and bottleneck tunnels (count them as 0 cells) int discount = 0; for (Cell a : alive) if (!a.straight()) for (Move am : a.moves) if ((am.dir == Dir.Right || am.dir == Dir.Down) && am.cell.straight() && am.dist == 1) { // found a tunnel entrance int len = 1; Cell b = am.cell; while (true) { Move m = b.move(am.dir); if (m == null || m.dist != 1) break; Cell c = m.cell; if (c == null || !c.alive || c.goal || !c.straight()) break; b = c; len += 1; } discount += b.bottleneck ? len : len - 1; } BigInteger agent_positions = BigInteger.valueOf(cells.length - discount - num_boxes); return Util.combinations(alive.length - discount, num_boxes).multiply(agent_positions).bitLength(); } private static int find_bottlenecks(Cell a, int[] discovery, Cell parent, int[] time) { int children = 0; int low_a = discovery[a.id] = ++time[0]; for (Move e : a.moves) if (discovery[e.cell.id] == 0) { children += 1; int low_b = find_bottlenecks(e.cell, discovery, a, time); low_a = Math.min(low_a, low_b); if (parent != null && low_b >= discovery[a.id]) a.bottleneck = true; } else if (e.cell != parent) low_a = Math.min(low_a, discovery[e.cell.id]); if (parent == null && children > 1) a.bottleneck = true; return low_a; } private static int find_box_bottlenecks(Cell a, int[] discovery, Cell parent, int[] time) { assert a.alive; int children = 0; int low_a = discovery[a.id] = ++time[0]; for (Move e : a.moves) if (e.cell.alive && e.dist == 1) if (discovery[e.cell.id] == 0) { children += 1; int low_b = find_box_bottlenecks(e.cell, discovery, a, time); low_a = Math.min(low_a, low_b); if (parent != null && low_b >= discovery[a.id]) a.box_bottleneck = true; } else if (e.cell != parent) low_a = Math.min(low_a, discovery[e.cell.id]); if (parent == null && children > 1) a.box_bottleneck = true; return low_a; } private void compute_distances_to_each_goal(int goals, CellPairVisitor pair_visitor) { For.each(cells, g -> g.distance_box = Array.ofInt(goals, Cell.Infinity)); int[][] distance = new int[cells.length][alive.length]; for (Cell g : cells) if (g.goal) { pair_visitor.init(); Array.fill(distance, Cell.Infinity); for (Move e : g.moves) if (pair_visitor.try_add(e.cell, g)) distance[e.cell.id][g.id] = e.dist - 1; g.distance_box[g.id] = 0; while (!pair_visitor.done()) { final Cell agent = pair_visitor.first(); final Cell box = pair_visitor.second(); assert distance[agent.id][box.id] != Cell.Infinity; box.distance_box[g.id] = Math.min(box.distance_box[g.id], distance[agent.id][box.id]); for (Move e : agent.moves) { // TODO moves included only if ! optimal Cell c = e.cell; if (c != box && pair_visitor.try_add(c, box)) distance[c.id][box.id] = distance[agent.id][box.id];//+ e.dist; Move m = agent.rmove(e.dir); if (agent.alive && m != null && m.cell == box && pair_visitor.try_add(c, agent)) distance[c.id][agent.id] = distance[agent.id][box.id] + e.dist; } } /*print(p -> { if (p == g) return Code.GoalRoomEntrance; if (!p.alive) return Code.Dead; if (distance[cells[cells.length - 1].id][p.id] >= Cell.Infinity) return Code.Space; return (char) ((int) '0' + (distance[cells[cells.length - 1].id][p.id] % 10)); });*/ } for (Cell b : alive) b.distance_box_min = Array.min(b.distance_box); } private State compute_goal_and_start(Cell agent, int dist) { int[] box_set = new int[(alive.length + 31) / 32]; goal_set = new int[(alive.length + 31) / 32]; for (Cell c : cells) { if (c.box) Bits.set(box_set, c.id); if (c.goal) Bits.set(goal_set, c.id); } return new State(agent.id, box_set, 0, dist, 0, 0, 0); } public boolean are_all_goals_reachable_full(CellPairVisitor visitor, boolean is_valid_level) { int[] num = new int[1]; int[] box_ordinal = Array.ofInt(cells.length, p -> cells[p].box ? num[0]++ : -1); int num_boxes = num[0]; if (num_boxes == 0) return true; boolean[][] can_reach = new boolean[num_boxes][num_boxes]; main: for (Cell g : cells) { if (!g.goal) continue; int count = 0; if (g.box) { can_reach[box_ordinal[g.id]][g.id] = true; if (++count == num_boxes) continue main; } visitor.init(); for (Move e : g.moves) visitor.add(e.cell, g); while (!visitor.done()) { final Cell a = visitor.first(); final Cell b = visitor.second(); for (Move e : a.moves) { Cell c = e.cell; if (c == b) continue; visitor.try_add(c, b); Move m = a.rmove(e.dir); if (m != null && m.cell == b && visitor.try_add(c, a)) if (a.box && !can_reach[box_ordinal[a.id]][g.id]) { can_reach[box_ordinal[a.id]][g.id] = true; if (++count == num_boxes) continue main; } } } if (count == 0) return false; } if (is_valid_level) { @Cleanup val t = timer_max_bpm.open(); return BipartiteMatching.maxBPM(can_reach) == num_boxes; } else { return BipartiteMatching.maxBPM(can_reach) == num_boxes; } } static final AutoTimer timer_max_bpm = new AutoTimer("max_bpm"); // TODO instead of searching forward N times => search backward once from every goal private void compute_alive_cells(CellPairVisitor visitor) { for (Cell b : cells) { if (b.goal) { b.alive = true; continue; } visitor.init(); for (Move e : b.moves) visitor.add(e.cell, b); loop: while (!visitor.done()) { final Cell agent = visitor.first(); final Cell box = visitor.second(); for (Move e : agent.moves) { if (e.cell != box) { visitor.try_add(e.cell, box); continue; } final Move q = e.cell.move(e.dir); if (q == null) continue; if (q.cell.goal) { b.alive = true; break loop; } visitor.try_add(e.cell, q.cell); } } } } private static boolean is_close_to_visited(int pos, boolean[] visited, int width, int height, boolean diagonal) { int x = pos % width, y = pos / width; for (int ax = Math.max(0, x - 1); ax <= Math.min(x + 1, width - 2); ax++) for (int ay = Math.max(0, y - 1); ay <= Math.min(y + 1, height - 1); ay++) if ((diagonal || ax == x || ay == y) && visited[ay * width + ax]) return true; return false; } private static int move(int xy, Dir dir, int width, int length) { if (dir == Dir.Left && (xy % width) > 0) return xy - 1; if (dir == Dir.Right && (xy + 1) % width != 0) return xy + 1; if (dir == Dir.Up && xy >= width) return xy - width; if (dir == Dir.Down && xy + width < length) return xy + width; return 0; } private static void detach(Cell a, Cell b) { for (int i = 0; i < a.moves.length; i++) if (a.moves[i].cell == b) { a.dir[a.moves[i].dir.ordinal()] = null; a.moves = Array.remove(a.moves, i); return; } throw new Error(); } public char[] render(CellToChar ch) { char[] copy = buffer.clone(); for (Cell c : cells) if (c != null) copy[c.xy] = ch.fn(c); return copy; } public char[] render(StateKey s) { return render(c -> { if (s.agent == c.id) return c.goal ? Code.AgentGoal : Code.Agent; if (s.box(c.id)) { if (!c.goal) return Code.Box; return LevelUtil.is_frozen_on_goal(c, s.box) ? Code.FrozenOnGoal : Code.BoxGoal; } if (!c.alive) return Code.Dead; if (c == goal_section_entrance) return Code.GoalRoomEntrance; return c.goal ? Code.Goal : Code.Space; }); } public void print(CellToChar ch) { System.out.print(Code.emojify(render(ch))); } public void print(StateKey s) { System.out.print(Code.emojify(render(s))); } public boolean is_solved(int[] box_set) { for (int i = 0; i < box_set.length; i++) if ((box_set[i] | goal_set[i]) != goal_set[i]) return false; return true; } public boolean is_solved_fast(int[] box_set) { assert num_boxes == Bits.count(box_set); return Arrays.equals(box_set, goal_set); } static final AutoTimer timer_isvalidlevel = new AutoTimer("is_valid_level"); static final Flags.Bool all_goals_reachable_full = new Flags.Bool("all_goals_reachable_full", false); public boolean is_valid_level(char[] buffer, boolean allow_more_goals_than_boxes) { @Cleanup val t = timer_isvalidlevel.open(); Level clone = new Level(buffer, null, 0); if (allow_more_goals_than_boxes) { if (Array.count(clone.cells, c -> c.box) > Array.count(clone.cells, c -> c.goal)) return false; CellPairVisitor visitor = new CellPairVisitor(clone.cells.length, clone.cells.length, clone.cells); return clone.are_all_goals_reachable_quick(visitor, goal_section_entrance); } else { if (Array.count(clone.cells, c -> c.box) != Array.count(clone.cells, c -> c.goal)) return false; CellPairVisitor visitor = new CellPairVisitor(clone.cells.length, clone.cells.length, clone.cells); return all_goals_reachable_full.value ? clone.are_all_goals_reachable_full(visitor, true) : clone.are_all_goals_reachable_quick(visitor, goal_section_entrance); } } private boolean are_all_goals_reachable_quick(CellPairVisitor visitor, Cell entrance) { main: for (Cell g : cells) { if (!g.goal || g.box) continue; visitor.init(); for (Move e : g.moves) { visitor.add(e.cell, g); if (e.cell == entrance) continue main; } while (!visitor.done()) { final Cell a = visitor.first(); final Cell b = visitor.second(); if (a == entrance) continue; for (Move e : a.moves) { if (e.cell == b) continue; visitor.try_add(e.cell, b); Move m = a.rmove(e.dir); if (m != null && m.cell == b && visitor.try_add(e.cell, a)) if (!a.goal && !e.cell.goal) continue main; } } return false; } return true; } // box_bottleneck splits alive cells into two sets // if all goals are in one set, return number of alive cells in that set, // otherwise return Integer.MAX_VALUE private int box_bottleneck_goal_zone_size(Cell b) { assert b.box_bottleneck; int result = Integer.MAX_VALUE; for (Move bm : b.moves) if (bm.cell.alive && bm.dist == 1) { int num_alive = 0; int num_goals = 0; for (Cell a : visitor.init(bm.cell).markVisited(b)) { num_alive += 1; if (a.goal) num_goals += 1; for (Move m : a.moves) if (m.dist == 1 && m.cell.alive) visitor.try_add(m.cell); } if (num_goals == (b.goal ? num_boxes - 1 : num_boxes)) result = Math.min(result, num_alive); } return result; } }
/** * Copyright 2016 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.github.ambry.clustermap; import com.codahale.metrics.MetricRegistry; import com.github.ambry.config.ClusterMapConfig; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.github.ambry.utils.Utils.*; /** * ClusterMapManager allows components in Ambry to query the topology. This covers the {@link HardwareLayout} and the * {@link PartitionLayout}. */ public class ClusterMapManager implements ClusterMap { protected final HardwareLayout hardwareLayout; protected final PartitionLayout partitionLayout; private final MetricRegistry metricRegistry; private final ClusterMapMetrics clusterMapMetrics; private Logger logger = LoggerFactory.getLogger(getClass()); /** * How many data nodes to put in a random sample for partition allocation. 2 node samples provided the best balance * of speed and allocation quality in testing. Larger samples (ie 3 nodes) took longer to generate but did not * improve the quality of the allocated partitions. */ private static final int NUM_CHOICES = 2; public ClusterMapManager(PartitionLayout partitionLayout) { if (logger.isTraceEnabled()) { logger.trace("ClusterMapManager " + partitionLayout); } this.hardwareLayout = partitionLayout.getHardwareLayout(); this.partitionLayout = partitionLayout; this.metricRegistry = new MetricRegistry(); this.clusterMapMetrics = new ClusterMapMetrics(this.hardwareLayout, this.partitionLayout, this.metricRegistry); } public ClusterMapManager(String hardwareLayoutPath, String partitionLayoutPath, ClusterMapConfig clusterMapConfig) throws IOException, JSONException { logger.trace("ClusterMapManager " + hardwareLayoutPath + ", " + partitionLayoutPath); this.hardwareLayout = new HardwareLayout(new JSONObject(readStringFromFile(hardwareLayoutPath)), clusterMapConfig); this.partitionLayout = new PartitionLayout(hardwareLayout, new JSONObject(readStringFromFile(partitionLayoutPath))); this.metricRegistry = new MetricRegistry(); this.clusterMapMetrics = new ClusterMapMetrics(this.hardwareLayout, this.partitionLayout, this.metricRegistry); } public void persist(String hardwareLayoutPath, String partitionLayoutPath) throws IOException, JSONException { logger.trace("persist " + hardwareLayoutPath + ", " + partitionLayoutPath); writeJsonToFile(hardwareLayout.toJSONObject(), hardwareLayoutPath); writeJsonToFile(partitionLayout.toJSONObject(), partitionLayoutPath); } public List<PartitionId> getAllPartitions() { return partitionLayout.getPartitions(); } // Implementation of ClusterMap interface // -------------------------------------- @Override public List<PartitionId> getWritablePartitionIds() { return partitionLayout.getWritablePartitions(); } @Override public PartitionId getPartitionIdFromStream(DataInputStream stream) throws IOException { PartitionId partitionId = partitionLayout.getPartition(stream); if (partitionId == null) { throw new IOException("Partition id from stream is null"); } return partitionId; } @Override public boolean hasDatacenter(String datacenterName) { return hardwareLayout.findDatacenter(datacenterName) != null; } @Override public DataNodeId getDataNodeId(String hostname, int port) { return hardwareLayout.findDataNode(hostname, port); } @Override public List<ReplicaId> getReplicaIds(DataNodeId dataNodeId) { List<Replica> replicas = getReplicas(dataNodeId); return new ArrayList<ReplicaId>(replicas); } public List<Replica> getReplicas(DataNodeId dataNodeId) { List<Replica> replicas = new ArrayList<Replica>(); for (PartitionId partition : partitionLayout.getPartitions()) { for (Replica replica : ((Partition) partition).getReplicas()) { if (replica.getDataNodeId().equals(dataNodeId)) { replicas.add(replica); } } } return replicas; } @Override public List<DataNodeId> getDataNodeIds() { List<DataNodeId> dataNodeIds = new ArrayList<DataNodeId>(); for (Datacenter datacenter : hardwareLayout.getDatacenters()) { dataNodeIds.addAll(datacenter.getDataNodes()); } return dataNodeIds; } @Override public MetricRegistry getMetricRegistry() { return metricRegistry; } // Administrative API // ----------------------- public long getRawCapacityInBytes() { return hardwareLayout.getRawCapacityInBytes(); } public long getAllocatedRawCapacityInBytes() { return partitionLayout.getAllocatedRawCapacityInBytes(); } public long getAllocatedUsableCapacityInBytes() { return partitionLayout.getAllocatedUsableCapacityInBytes(); } public long getAllocatedRawCapacityInBytes(Datacenter datacenter) { long allocatedRawCapacityInBytes = 0; for (PartitionId partition : partitionLayout.getPartitions()) { for (Replica replica : ((Partition) partition).getReplicas()) { Disk disk = (Disk) replica.getDiskId(); if (disk.getDataNode().getDatacenter().equals(datacenter)) { allocatedRawCapacityInBytes += replica.getCapacityInBytes(); } } } return allocatedRawCapacityInBytes; } public long getAllocatedRawCapacityInBytes(DataNodeId dataNode) { long allocatedRawCapacityInBytes = 0; for (PartitionId partition : partitionLayout.getPartitions()) { for (Replica replica : ((Partition) partition).getReplicas()) { Disk disk = (Disk) replica.getDiskId(); if (disk.getDataNode().equals(dataNode)) { allocatedRawCapacityInBytes += replica.getCapacityInBytes(); } } } return allocatedRawCapacityInBytes; } public long getAllocatedRawCapacityInBytes(Disk disk) { long allocatedRawCapacityInBytes = 0; for (PartitionId partition : partitionLayout.getPartitions()) { for (Replica replica : ((Partition) partition).getReplicas()) { Disk currentDisk = (Disk) replica.getDiskId(); if (currentDisk.equals(disk)) { allocatedRawCapacityInBytes += replica.getCapacityInBytes(); } } } return allocatedRawCapacityInBytes; } public long getUnallocatedRawCapacityInBytes() { return getRawCapacityInBytes() - getAllocatedRawCapacityInBytes(); } public long getUnallocatedRawCapacityInBytes(Datacenter datacenter) { return datacenter.getRawCapacityInBytes() - getAllocatedRawCapacityInBytes(datacenter); } public long getUnallocatedRawCapacityInBytes(DataNode dataNode) { return dataNode.getRawCapacityInBytes() - getAllocatedRawCapacityInBytes(dataNode); } public long getUnallocatedRawCapacityInBytes(Disk disk) { return disk.getRawCapacityInBytes() - getAllocatedRawCapacityInBytes(disk); } public DataNode getDataNodeWithMostUnallocatedRawCapacity(Datacenter dc, Set nodesToExclude) { DataNode maxCapacityNode = null; List<DataNode> dataNodes = dc.getDataNodes(); for (DataNode dataNode : dataNodes) { if (!nodesToExclude.contains(dataNode) && (maxCapacityNode == null || getUnallocatedRawCapacityInBytes(dataNode) > getUnallocatedRawCapacityInBytes(maxCapacityNode))) { maxCapacityNode = dataNode; } } return maxCapacityNode; } public Disk getDiskWithMostUnallocatedRawCapacity(DataNode node, long minCapacity) { Disk maxCapacityDisk = null; List<Disk> disks = node.getDisks(); for (Disk disk : disks) { if ((maxCapacityDisk == null || getUnallocatedRawCapacityInBytes(disk) > getUnallocatedRawCapacityInBytes( maxCapacityDisk)) && getUnallocatedRawCapacityInBytes(disk) >= minCapacity) { maxCapacityDisk = disk; } } return maxCapacityDisk; } public PartitionId addNewPartition(List<Disk> disks, long replicaCapacityInBytes) { return partitionLayout.addNewPartition(disks, replicaCapacityInBytes); } // Determine if there is enough capacity to allocate a PartitionId. private boolean checkEnoughUnallocatedRawCapacity(int replicaCountPerDatacenter, long replicaCapacityInBytes) { for (Datacenter datacenter : hardwareLayout.getDatacenters()) { if (getUnallocatedRawCapacityInBytes(datacenter) < replicaCountPerDatacenter * replicaCapacityInBytes) { logger.warn("Insufficient unallocated space in datacenter {} ({} bytes unallocated)", datacenter.getName(), getUnallocatedRawCapacityInBytes(datacenter)); return false; } int rcpd = replicaCountPerDatacenter; for (DataNode dataNode : datacenter.getDataNodes()) { for (Disk disk : dataNode.getDisks()) { if (getUnallocatedRawCapacityInBytes(disk) >= replicaCapacityInBytes) { rcpd--; break; // Only one replica per DataNodeId. } } } if (rcpd > 0) { logger.warn("Insufficient DataNodes ({}) with unallocated space in datacenter {} for {} Replicas)", rcpd, datacenter.getName(), replicaCountPerDatacenter); return false; } } return true; } /** * Get a sampling of {@code numChoices} random disks from a list of {@link DataNode}s and choose the * {@link Disk} on the {@link DataNode} with the most free space. * NOTE 1: This method will change the ordering of the nodes in {@code dataNodes} * NOTE 2: This method can return null, if a disk with enough free space could not be found. * * @param dataNodes the list of {@link DataNode}s to sample from * @param dataNodesUsed the set of {@link DataNode}s to exclude from the sample * @param replicaCapacityInBytes the minimum amount of free space that a disk in the sample should have * @param rackAware if {@code true}, only return disks in nodes that do not share racks with the nodes * in {@code dataNodesUsed} * @param numChoices how many disks in the sample to choose between * @return The {@link Disk} on the {@link DataNode} in the sample with the most free space, or {@code null } if a disk * with enough free space could not be found. */ private Disk getBestDiskCandidate(List<DataNode> dataNodes, Set<DataNode> dataNodesUsed, long replicaCapacityInBytes, boolean rackAware, int numChoices) { Set<Long> rackIdsUsed = new HashSet<>(); if (rackAware) { for (DataNode dataNode : dataNodesUsed) { rackIdsUsed.add(dataNode.getRackId()); } } int numFound = 0; int selectionBound = dataNodes.size(); Random randomGen = new Random(); Disk bestDisk = null; while ((selectionBound > 0) && (numFound < numChoices)) { int selectionIndex = randomGen.nextInt(selectionBound); DataNode candidate = dataNodes.get(selectionIndex); if (!dataNodesUsed.contains(candidate) && !rackIdsUsed.contains(candidate.getRackId())) { Disk diskCandidate = getDiskWithMostUnallocatedRawCapacity(candidate, replicaCapacityInBytes); if (diskCandidate != null) { if ((bestDisk == null) || (getUnallocatedRawCapacityInBytes(diskCandidate.getDataNode()) >= getUnallocatedRawCapacityInBytes(bestDisk.getDataNode()))) { bestDisk = diskCandidate; } numFound++; } } selectionBound--; Collections.swap(dataNodes, selectionIndex, selectionBound); } return bestDisk; } /** * Return a list of disks for a new partition in the specified {@link Datacenter}. Does not retry if fewer than * {@code replicaCountPerDatacenter} disks cannot be allocated. * * @param replicaCountPerDatacenter how many replicas to attempt to allocate in the datacenter * @param replicaCapacityInBytes the minimum amount of free space on a disk for a replica * @param datacenter the {@link Datacenter} to allocate replicas in * @param rackAware if {@code true}, attempt a rack-aware allocation * @return A list of {@link Disk}s */ private List<Disk> getDiskCandidatesForPartition(int replicaCountPerDatacenter, long replicaCapacityInBytes, Datacenter datacenter, boolean rackAware) { ArrayList<Disk> disksToAllocate = new ArrayList<Disk>(); Set<DataNode> nodesToExclude = new HashSet<>(); List<DataNode> dataNodes = new ArrayList<>(datacenter.getDataNodes()); for (int i = 0; i < replicaCountPerDatacenter; i++) { Disk bestDisk = getBestDiskCandidate(dataNodes, nodesToExclude, replicaCapacityInBytes, rackAware, NUM_CHOICES); if (bestDisk != null) { disksToAllocate.add(bestDisk); nodesToExclude.add(bestDisk.getDataNode()); } else { break; } } return disksToAllocate; } /** * Return a list of disks for a new partition in the specified {@link Datacenter}. Retry a non rack-aware allocation * in certain cases described below if {@code attemptNonRackAwareOnFailure} is enabled. * * @param replicaCountPerDatacenter how many replicas to attempt to allocate in the datacenter * @param replicaCapacityInBytes the minimum amount of free space on a disk for a replica * @param datacenter the {@link Datacenter} to allocate replicas in * @param attemptNonRackAwareOnFailure {@code true} if we should attempt a non rack-aware allocation if a rack-aware * one is not possible. * @return a list of {@code replicaCountPerDatacenter} or fewer disks that can be allocated for a new partition in * the specified datacenter */ private List<Disk> allocateDisksForPartition(int replicaCountPerDatacenter, long replicaCapacityInBytes, Datacenter datacenter, boolean attemptNonRackAwareOnFailure) { List<Disk> disks; if (datacenter.isRackAware()) { disks = getDiskCandidatesForPartition(replicaCountPerDatacenter, replicaCapacityInBytes, datacenter, true); if ((disks.size() < replicaCountPerDatacenter) && attemptNonRackAwareOnFailure) { System.err.println("Rack-aware allocation failed for a partition on datacenter:" + datacenter.getName() + "; attempting to perform a non rack-aware allocation."); disks = getDiskCandidatesForPartition(replicaCountPerDatacenter, replicaCapacityInBytes, datacenter, false); } } else if (!attemptNonRackAwareOnFailure) { throw new IllegalArgumentException( "attemptNonRackAwareOnFailure is false, but the datacenter: " + datacenter.getName() + " does not have rack information"); } else { disks = getDiskCandidatesForPartition(replicaCountPerDatacenter, replicaCapacityInBytes, datacenter, false); } if (disks.size() < replicaCountPerDatacenter) { System.err.println( "Could only allocate " + disks.size() + "/" + replicaCountPerDatacenter + " replicas in datacenter: " + datacenter.getName()); } return disks; } /** * Allocate partitions for {@code numPartitions} new partitions on all datacenters. * * @param numPartitions How many partitions to allocate. * @param replicaCountPerDatacenter The number of replicas per partition on each datacenter * @param replicaCapacityInBytes How large each replica (of a partition) should be * @param attemptNonRackAwareOnFailure {@code true} if we should attempt a non rack-aware allocation if a rack-aware * one is not possible. * @return A list of the new {@link PartitionId}s. */ public List<PartitionId> allocatePartitions(int numPartitions, int replicaCountPerDatacenter, long replicaCapacityInBytes, boolean attemptNonRackAwareOnFailure) { ArrayList<PartitionId> partitions = new ArrayList<PartitionId>(numPartitions); int partitionsAllocated = 0; while (checkEnoughUnallocatedRawCapacity(replicaCountPerDatacenter, replicaCapacityInBytes) && partitionsAllocated < numPartitions) { List<Disk> disksToAllocate = new ArrayList<>(); for (Datacenter datacenter : hardwareLayout.getDatacenters()) { List<Disk> disks = allocateDisksForPartition(replicaCountPerDatacenter, replicaCapacityInBytes, datacenter, attemptNonRackAwareOnFailure); disksToAllocate.addAll(disks); } partitions.add(partitionLayout.addNewPartition(disksToAllocate, replicaCapacityInBytes)); partitionsAllocated++; System.out.println("Allocated " + partitionsAllocated + " new partitions so far."); } return partitions; } /** * Add a set of replicas on a new datacenter for an existing partition. * * @param partitionId The partition to add to the new datacenter * @param dataCenterName The name of the new datacenter * @param attemptNonRackAwareOnFailure {@code true} if a non rack-aware allocation should be attempted if a rack-aware one * is not possible. */ public void addReplicas(PartitionId partitionId, String dataCenterName, boolean attemptNonRackAwareOnFailure) { List<ReplicaId> replicaIds = partitionId.getReplicaIds(); Map<String, Integer> replicaCountByDatacenter = new HashMap<String, Integer>(); long capacityOfReplicasInBytes = 0; // we ensure that the datacenter provided does not have any replicas for (ReplicaId replicaId : replicaIds) { if (replicaId.getDataNodeId().getDatacenterName().compareToIgnoreCase(dataCenterName) == 0) { throw new IllegalArgumentException( "Data center " + dataCenterName + " provided already contains replica for partition " + partitionId); } capacityOfReplicasInBytes = replicaId.getCapacityInBytes(); Integer numberOfReplicas = replicaCountByDatacenter.get(replicaId.getDataNodeId().getDatacenterName()); if (numberOfReplicas == null) { numberOfReplicas = new Integer(0); } numberOfReplicas++; replicaCountByDatacenter.put(replicaId.getDataNodeId().getDatacenterName(), numberOfReplicas); } if (replicaCountByDatacenter.size() == 0) { throw new IllegalArgumentException("No existing replicas present for partition " + partitionId + " in cluster."); } // verify that all data centers have the same replica int numberOfReplicasPerDatacenter = 0; int index = 0; for (Map.Entry<String, Integer> entry : replicaCountByDatacenter.entrySet()) { if (index == 0) { numberOfReplicasPerDatacenter = entry.getValue(); } if (numberOfReplicasPerDatacenter != entry.getValue()) { throw new IllegalStateException("Datacenters have different replicas for partition " + partitionId); } index++; } Datacenter datacenterToAdd = hardwareLayout.findDatacenter(dataCenterName); List<Disk> disksForReplicas = allocateDisksForPartition(numberOfReplicasPerDatacenter, capacityOfReplicasInBytes, datacenterToAdd, attemptNonRackAwareOnFailure); partitionLayout.addNewReplicas((Partition) partitionId, disksForReplicas); System.out.println("Added partition " + partitionId + " to datacenter " + dataCenterName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterMapManager that = (ClusterMapManager) o; if (hardwareLayout != null ? !hardwareLayout.equals(that.hardwareLayout) : that.hardwareLayout != null) { return false; } return !(partitionLayout != null ? !partitionLayout.equals(that.partitionLayout) : that.partitionLayout != null); } public void onReplicaEvent(ReplicaId replicaId, ReplicaEventType event) { switch (event) { case Disk_Error: ((Disk) replicaId.getDiskId()).onDiskError(); break; case Disk_Ok: ((Disk) replicaId.getDiskId()).onDiskOk(); break; case Node_Timeout: ((DataNode) replicaId.getDataNodeId()).onNodeTimeout(); break; case Node_Response: ((DataNode) replicaId.getDataNodeId()).onNodeResponse(); break; case Partition_ReadOnly: ((Partition) replicaId.getPartitionId()).onPartitionReadOnly(); break; } } }
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.buildutils; import aQute.lib.osgi.Instruction; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.maven.plugins.shade.relocation.Relocator; import org.apache.maven.plugins.shade.resource.ManifestResourceTransformer; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; import static org.codehaus.plexus.util.IOUtil.close; import static org.codehaus.plexus.util.StringUtils.join; /** * This transformer implementation is used to merge MANIFEST and OSGi * bundle metadata in conjunction with the Maven Shade plugin when * integrating multiple dependencies into one output JAR. */ public class HazelcastManifestTransformer extends ManifestResourceTransformer { private static final String VERSION_PREFIX = "version="; private static final String RESOLUTION_PREFIX = "resolution:="; private static final String USES_PREFIX = "uses:="; private static final int VERSION_OFFSET = 8; private static final int USES_OFFSET = 7; private static final String IMPORT_PACKAGE = "Import-Package"; private static final String EXPORT_PACKAGE = "Export-Package"; // configuration @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Filled by Maven") String mainClass; @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Filled by Maven") Map<String, Attributes> manifestEntries; @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Filled by Maven") Map<String, String> overrideInstructions; private final Map<String, PackageDefinition> importedPackages = new HashMap<String, PackageDefinition>(); private final Map<String, PackageDefinition> exportedPackages = new HashMap<String, PackageDefinition>(); private final List<InstructionDefinition> importOverrideInstructions = new ArrayList<InstructionDefinition>(); private final List<InstructionDefinition> exportOverrideInstructions = new ArrayList<InstructionDefinition>(); private Manifest shadedManifest; @Override public boolean canTransformResource(String resource) { return JarFile.MANIFEST_NAME.equalsIgnoreCase(resource); } @Override public void processResource(String resource, InputStream inputStream, List<Relocator> relocators) throws IOException { Attributes attributes; if (shadedManifest == null) { shadedManifest = new Manifest(inputStream); attributes = shadedManifest.getMainAttributes(); } else { Manifest manifest = new Manifest(inputStream); attributes = manifest.getMainAttributes(); } String importPackages = attributes.getValue(IMPORT_PACKAGE); if (importPackages != null) { List<String> definitions = ElementParser.parseDelimitedString(importPackages, ',', true); for (String definition : definitions) { PackageDefinition packageDefinition = new PackageDefinition(definition); String packageName = packageDefinition.packageName; PackageDefinition oldPackageDefinition = importedPackages.get(packageName); importedPackages.put(packageName, findStrongerDefinition(packageDefinition, oldPackageDefinition)); } } String exportPackages = attributes.getValue(EXPORT_PACKAGE); if (exportPackages != null) { List<String> definitions = ElementParser.parseDelimitedString(exportPackages, ',', true); for (String definition : definitions) { PackageDefinition packageDefinition = new PackageDefinition(definition); String packageName = packageDefinition.packageName; PackageDefinition oldPackageDefinition = exportedPackages.get(packageName); exportedPackages.put(packageName, mergeExportUsesConstraint(packageDefinition, oldPackageDefinition)); } } close(inputStream); } private PackageDefinition findStrongerDefinition(PackageDefinition packageDefinition, PackageDefinition oldPackageDefinition) { // if the override is a remove instruction skip all other tests if (packageDefinition.removeImport) { return packageDefinition; } // if no old definition or new definition is required import we take the new one if (oldPackageDefinition == null || oldPackageDefinition.resolutionOptional && !packageDefinition.resolutionOptional) { return packageDefinition; } // if old definition was required import but new isn't we take the old one if (!oldPackageDefinition.resolutionOptional && packageDefinition.resolutionOptional) { return oldPackageDefinition; } if (oldPackageDefinition.version == null && packageDefinition.version != null) { return packageDefinition; } if (oldPackageDefinition.version != null && packageDefinition.version == null) { return oldPackageDefinition; } return oldPackageDefinition; } private PackageDefinition mergeExportUsesConstraint(PackageDefinition packageDefinition, PackageDefinition oldPackageDefinition) { Set<String> uses = new LinkedHashSet<String>(); if (oldPackageDefinition != null) { uses.addAll(oldPackageDefinition.uses); } uses.addAll(packageDefinition.uses); String packageName = packageDefinition.packageName; boolean resolutionOptional = packageDefinition.resolutionOptional; String version = packageDefinition.version; return new PackageDefinition(packageName, resolutionOptional, version, uses); } @Override public boolean hasTransformedResource() { return true; } @Override @SuppressWarnings("Since15") public void modifyOutputStream(JarOutputStream jarOutputStream) throws IOException { if (shadedManifest == null) { shadedManifest = new Manifest(); } precompileOverrideInstructions(); Attributes attributes = shadedManifest.getMainAttributes(); attributes.putValue(IMPORT_PACKAGE, join(shadeImports().iterator(), ",")); attributes.putValue(EXPORT_PACKAGE, join(shadeExports().iterator(), ",")); attributes.putValue("Created-By", "HazelcastManifestTransformer through Shade Plugin"); if (mainClass != null) { attributes.put(Attributes.Name.MAIN_CLASS, mainClass); } if (manifestEntries != null) { for (Map.Entry<String, Attributes> entry : manifestEntries.entrySet()) { attributes.put(new Attributes.Name(entry.getKey()), entry.getValue()); } } jarOutputStream.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME)); shadedManifest.write(jarOutputStream); jarOutputStream.flush(); } @SuppressFBWarnings(value = "NP_UNWRITTEN_FIELD", justification = "Field is set by Maven") private void precompileOverrideInstructions() { String importPackageInstructions = overrideInstructions.get(IMPORT_PACKAGE); if (importPackageInstructions != null) { List<String> packageInstructions = ElementParser.parseDelimitedString(importPackageInstructions, ',', true); for (String packageInstruction : packageInstructions) { PackageDefinition packageDefinition = new PackageDefinition(packageInstruction); Instruction instruction = Instruction.getPattern(packageDefinition.packageName); System.out.println("Compiled import instruction '" + packageInstruction + "' -> " + instruction); importOverrideInstructions.add(new InstructionDefinition(packageDefinition, instruction)); } } String exportPackageInstructions = overrideInstructions.get(EXPORT_PACKAGE); if (exportPackageInstructions != null) { List<String> packageInstructions = ElementParser.parseDelimitedString(exportPackageInstructions, ',', true); for (String packageInstruction : packageInstructions) { PackageDefinition packageDefinition = new PackageDefinition(packageInstruction); Instruction instruction = Instruction.getPattern(packageDefinition.packageName); System.out.println("Compiled export instruction '" + packageInstruction + "' -> " + instruction); exportOverrideInstructions.add(new InstructionDefinition(packageDefinition, instruction)); } } } private Set<String> shadeExports() { Set<String> exports = new LinkedHashSet<String>(); for (Map.Entry<String, PackageDefinition> entry : exportedPackages.entrySet()) { String definition = entry.getValue().buildDefinition(false); exports.add(definition); System.out.println("Adding shaded export -> " + definition); } return exports; } private Set<String> shadeImports() { for (String export : exportedPackages.keySet()) { PackageDefinition definition = new PackageDefinition(export); importedPackages.remove(definition.packageName); } Set<String> imports = new LinkedHashSet<String>(); for (Map.Entry<String, PackageDefinition> entry : importedPackages.entrySet()) { PackageDefinition original = entry.getValue(); PackageDefinition overridden = overridePackageDefinitionResolution(original); if (overridden != null) { String definition = overridden.buildDefinition(true); imports.add(definition); System.out.println("Adding shaded import -> " + definition); } else { System.out.println("Removing shaded import -> " + entry.getValue().packageName); } } return imports; } private PackageDefinition overridePackageDefinitionResolution(PackageDefinition packageDefinition) { for (InstructionDefinition instructionDefinition : importOverrideInstructions) { Instruction instruction = instructionDefinition.instruction; if (instruction.matches(packageDefinition.packageName)) { // is remove instruction? if (instruction.isNegated()) { System.out.println("Instruction '" + instruction + "' -> package '" + packageDefinition.packageName + "'"); return null; } System.out.println("Instruction '" + instruction + "' -> package '" + packageDefinition.packageName + "'"); PackageDefinition override = instructionDefinition.packageDefinition; String packageName = packageDefinition.packageName; String version = packageDefinition.version; Set<String> uses = packageDefinition.uses; return new PackageDefinition(packageName, override.resolutionOptional, version, uses); } } return packageDefinition; } static final class PackageDefinition { private final boolean removeImport; private final String packageName; private final boolean resolutionOptional; private final String version; private final Set<String> uses; PackageDefinition(String definition) { String[] tokens = definition.split(";"); this.removeImport = tokens[0].startsWith("!"); this.packageName = tokens[0]; this.resolutionOptional = findResolutionConstraint(tokens); this.version = findVersionConstraint(tokens); this.uses = findUsesConstraint(tokens); } PackageDefinition(String packageName, boolean resolutionOptional, String version, Set<String> uses) { this.removeImport = packageName.startsWith("!"); this.packageName = packageName; this.resolutionOptional = resolutionOptional; this.version = version; this.uses = new LinkedHashSet<String>(uses); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PackageDefinition that = (PackageDefinition) o; if (packageName != null ? !packageName.equals(that.packageName) : that.packageName != null) { return false; } return true; } @Override public int hashCode() { return packageName != null ? packageName.hashCode() : 0; } @Override public String toString() { return "PackageDefinition{" + "packageName='" + packageName + '\'' + ", resolutionOptional=" + resolutionOptional + ", version='" + version + '\'' + ", uses=" + uses + '}'; } String buildDefinition(boolean addResolutionConstraint) { StringBuilder sb = new StringBuilder(packageName); if (addResolutionConstraint && resolutionOptional) { sb.append(";").append(RESOLUTION_PREFIX).append("optional"); } if (version != null) { sb.append(";").append(VERSION_PREFIX).append(version); } if (uses != null && !uses.isEmpty()) { sb.append(";").append(USES_PREFIX).append('"').append(join(uses.iterator(), ",")).append('"'); } return sb.toString(); } private String findVersionConstraint(String[] tokens) { for (String token : tokens) { if (token.startsWith(VERSION_PREFIX)) { return token.substring(VERSION_OFFSET); } } return null; } private boolean findResolutionConstraint(String[] tokens) { for (String token : tokens) { if (token.startsWith(RESOLUTION_PREFIX)) { return token.equalsIgnoreCase("resolution:=optional"); } } return false; } @SuppressWarnings("unchecked") private Set<String> findUsesConstraint(String[] tokens) { for (String token : tokens) { if (token.startsWith(USES_PREFIX)) { String packages = token.substring(USES_OFFSET, token.length() - 1); String[] sepPackages = packages.split(","); return new LinkedHashSet<String>(asList(sepPackages)); } } return emptySet(); } } static final class InstructionDefinition { private final PackageDefinition packageDefinition; private final Instruction instruction; InstructionDefinition(PackageDefinition packageDefinition, Instruction instruction) { this.packageDefinition = packageDefinition; this.instruction = instruction; } @Override public String toString() { return "InstructionDefinition{" + "packageDefinition=" + packageDefinition + ", instruction=" + instruction + '}'; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws2.iam; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.InvalidPayloadException; import org.apache.camel.Message; import org.apache.camel.support.DefaultProducer; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.AddUserToGroupRequest; import software.amazon.awssdk.services.iam.model.AddUserToGroupResponse; import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest; import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse; import software.amazon.awssdk.services.iam.model.CreateGroupRequest; import software.amazon.awssdk.services.iam.model.CreateGroupResponse; import software.amazon.awssdk.services.iam.model.CreateUserRequest; import software.amazon.awssdk.services.iam.model.CreateUserResponse; import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest; import software.amazon.awssdk.services.iam.model.DeleteAccessKeyResponse; import software.amazon.awssdk.services.iam.model.DeleteGroupRequest; import software.amazon.awssdk.services.iam.model.DeleteGroupResponse; import software.amazon.awssdk.services.iam.model.DeleteUserRequest; import software.amazon.awssdk.services.iam.model.DeleteUserResponse; import software.amazon.awssdk.services.iam.model.GetUserRequest; import software.amazon.awssdk.services.iam.model.GetUserResponse; import software.amazon.awssdk.services.iam.model.ListAccessKeysRequest; import software.amazon.awssdk.services.iam.model.ListAccessKeysResponse; import software.amazon.awssdk.services.iam.model.ListGroupsRequest; import software.amazon.awssdk.services.iam.model.ListGroupsResponse; import software.amazon.awssdk.services.iam.model.ListUsersRequest; import software.amazon.awssdk.services.iam.model.ListUsersResponse; import software.amazon.awssdk.services.iam.model.RemoveUserFromGroupRequest; import software.amazon.awssdk.services.iam.model.RemoveUserFromGroupResponse; import software.amazon.awssdk.services.iam.model.StatusType; import software.amazon.awssdk.services.iam.model.UpdateAccessKeyRequest; import software.amazon.awssdk.services.iam.model.UpdateAccessKeyResponse; /** * A Producer which sends messages to the Amazon IAM Service <a href="http://aws.amazon.com/iam/">AWS IAM</a> */ public class IAM2Producer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(IAM2Producer.class); private transient String iamProducerToString; public IAM2Producer(Endpoint endpoint) { super(endpoint); } @Override public void process(Exchange exchange) throws Exception { switch (determineOperation(exchange)) { case listAccessKeys: listAccessKeys(getEndpoint().getIamClient(), exchange); break; case createAccessKey: createAccessKey(getEndpoint().getIamClient(), exchange); break; case deleteAccessKey: deleteAccessKey(getEndpoint().getIamClient(), exchange); break; case updateAccessKey: updateAccessKey(getEndpoint().getIamClient(), exchange); break; case createUser: createUser(getEndpoint().getIamClient(), exchange); break; case deleteUser: deleteUser(getEndpoint().getIamClient(), exchange); break; case getUser: getUser(getEndpoint().getIamClient(), exchange); break; case listUsers: listUsers(getEndpoint().getIamClient(), exchange); break; case createGroup: createGroup(getEndpoint().getIamClient(), exchange); break; case deleteGroup: deleteGroup(getEndpoint().getIamClient(), exchange); break; case listGroups: listGroups(getEndpoint().getIamClient(), exchange); break; case addUserToGroup: addUserToGroup(getEndpoint().getIamClient(), exchange); break; case removeUserFromGroup: removeUserFromGroup(getEndpoint().getIamClient(), exchange); break; default: throw new IllegalArgumentException("Unsupported operation"); } } private IAM2Operations determineOperation(Exchange exchange) { IAM2Operations operation = exchange.getIn().getHeader(IAM2Constants.OPERATION, IAM2Operations.class); if (operation == null) { operation = getConfiguration().getOperation(); } return operation; } protected IAM2Configuration getConfiguration() { return getEndpoint().getConfiguration(); } @Override public String toString() { if (iamProducerToString == null) { iamProducerToString = "IAMProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]"; } return iamProducerToString; } @Override public IAM2Endpoint getEndpoint() { return (IAM2Endpoint) super.getEndpoint(); } private void listAccessKeys(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof ListAccessKeysRequest) { ListAccessKeysResponse response; try { response = iamClient.listAccessKeys((ListAccessKeysRequest) payload); } catch (AwsServiceException ase) { LOG.trace("List Access Keys command returned the error code {}", ase.getMessage()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(response); } } else { ListAccessKeysResponse response; try { response = iamClient.listAccessKeys(); } catch (AwsServiceException ase) { LOG.trace("List Access Keys command returned the error code {}", ase.getMessage()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(response); } } private void createUser(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof CreateUserRequest) { CreateUserResponse result; try { result = iamClient.createUser((CreateUserRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Create user command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { CreateUserRequest.Builder builder = CreateUserRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } else { throw new IllegalArgumentException("User Name must be specified"); } CreateUserResponse result; try { result = iamClient.createUser(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Create user command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void deleteUser(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof DeleteUserRequest) { DeleteUserResponse result; try { result = iamClient.deleteUser((DeleteUserRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Delete user command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { DeleteUserRequest.Builder builder = DeleteUserRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } else { throw new IllegalArgumentException("User Name must be specified"); } DeleteUserResponse result; try { result = iamClient.deleteUser(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Delete user command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void getUser(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof GetUserRequest) { GetUserResponse result; try { result = iamClient.getUser((GetUserRequest) payload); } catch (AwsServiceException ase) { LOG.trace("get user command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { GetUserRequest.Builder builder = GetUserRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } else { throw new IllegalArgumentException("User Name must be specified"); } GetUserResponse result; try { result = iamClient.getUser(builder.build()); } catch (AwsServiceException ase) { LOG.trace("get user command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void listUsers(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof ListUsersRequest) { ListUsersResponse result; try { result = iamClient.listUsers((ListUsersRequest) payload); } catch (AwsServiceException ase) { LOG.trace("List users command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { ListUsersResponse result; try { result = iamClient.listUsers(); } catch (AwsServiceException ase) { LOG.trace("List users command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void createAccessKey(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof CreateAccessKeyRequest) { CreateAccessKeyResponse result; try { result = iamClient.createAccessKey((CreateAccessKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Create Access Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { CreateAccessKeyRequest.Builder builder = CreateAccessKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } CreateAccessKeyResponse result; try { result = iamClient.createAccessKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Create Access Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void deleteAccessKey(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof DeleteAccessKeyRequest) { DeleteAccessKeyResponse result; try { result = iamClient.deleteAccessKey((DeleteAccessKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Delete Access Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { DeleteAccessKeyRequest.Builder builder = DeleteAccessKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_ID))) { String accessKeyId = exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_ID, String.class); builder.accessKeyId(accessKeyId); } else { throw new IllegalArgumentException("Key Id must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } DeleteAccessKeyResponse result; try { result = iamClient.deleteAccessKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Delete Access Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void updateAccessKey(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof UpdateAccessKeyRequest) { UpdateAccessKeyResponse result; try { result = iamClient.updateAccessKey((UpdateAccessKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Update Access Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { UpdateAccessKeyRequest.Builder builder = UpdateAccessKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_ID))) { String accessKeyId = exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_ID, String.class); builder.accessKeyId(accessKeyId); } else { throw new IllegalArgumentException("Key Id must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_STATUS))) { String status = exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_STATUS, String.class); builder.status(StatusType.fromValue(status)); } else { throw new IllegalArgumentException("Access Key status must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } UpdateAccessKeyResponse result; try { result = iamClient.updateAccessKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Update Access Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void createGroup(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof CreateGroupRequest) { CreateGroupResponse result; try { result = iamClient.createGroup((CreateGroupRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Create Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { CreateGroupRequest.Builder builder = CreateGroupRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.GROUP_NAME))) { String groupName = exchange.getIn().getHeader(IAM2Constants.GROUP_NAME, String.class); builder.groupName(groupName); } else { throw new IllegalArgumentException("Group Name must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.GROUP_PATH))) { String groupPath = exchange.getIn().getHeader(IAM2Constants.GROUP_PATH, String.class); builder.path(groupPath); } CreateGroupResponse result; try { result = iamClient.createGroup(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Create Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void deleteGroup(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof CreateGroupRequest) { DeleteGroupResponse result; try { result = iamClient.deleteGroup((DeleteGroupRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Delete Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { DeleteGroupRequest.Builder builder = DeleteGroupRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.GROUP_NAME))) { String groupName = exchange.getIn().getHeader(IAM2Constants.GROUP_NAME, String.class); builder.groupName(groupName); } else { throw new IllegalArgumentException("Group Name must be specified"); } DeleteGroupResponse result; try { result = iamClient.deleteGroup(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Delete Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void listGroups(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof ListGroupsRequest) { ListGroupsResponse result; try { result = iamClient.listGroups((ListGroupsRequest) payload); } catch (AwsServiceException ase) { LOG.trace("List Groups command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { ListGroupsResponse result; try { result = iamClient.listGroups(); } catch (AwsServiceException ase) { LOG.trace("List Groups command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void addUserToGroup(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof AddUserToGroupRequest) { AddUserToGroupResponse result; try { result = iamClient.addUserToGroup((AddUserToGroupRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Add User To Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { AddUserToGroupRequest.Builder builder = AddUserToGroupRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.GROUP_NAME))) { String groupName = exchange.getIn().getHeader(IAM2Constants.GROUP_NAME, String.class); builder.groupName(groupName); } else { throw new IllegalArgumentException("Group Name must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } else { throw new IllegalArgumentException("User Name must be specified"); } AddUserToGroupResponse result; try { result = iamClient.addUserToGroup(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Add User To Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void removeUserFromGroup(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof RemoveUserFromGroupRequest) { RemoveUserFromGroupResponse result; try { result = iamClient.removeUserFromGroup((RemoveUserFromGroupRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Remove User From Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { RemoveUserFromGroupRequest.Builder builder = RemoveUserFromGroupRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.GROUP_NAME))) { String groupName = exchange.getIn().getHeader(IAM2Constants.GROUP_NAME, String.class); builder.groupName(groupName); } else { throw new IllegalArgumentException("Group Name must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } else { throw new IllegalArgumentException("User Name must be specified"); } RemoveUserFromGroupResponse result; try { result = iamClient.removeUserFromGroup(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Remove User From Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } public static Message getMessageForResponse(final Exchange exchange) { return exchange.getMessage(); } }
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.store; import java.io.File; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Iterator; import org.neo4j.helpers.Pair; import org.neo4j.io.pagecache.PageCache; import org.neo4j.kernel.IdGeneratorFactory; import org.neo4j.kernel.IdType; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.impl.store.record.DynamicRecord; import org.neo4j.kernel.impl.util.Bits; import org.neo4j.logging.LogProvider; import static java.lang.System.arraycopy; /** * Dynamic store that stores strings. */ public class DynamicArrayStore extends AbstractDynamicStore { public static final int NUMBER_HEADER_SIZE = 3; public static final int STRING_HEADER_SIZE = 5; // store version, each store ends with this string (byte encoded) public static final String TYPE_DESCRIPTOR = "ArrayPropertyStore"; public DynamicArrayStore( File fileName, Config configuration, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, int blockSize ) { super( fileName, configuration, idType, idGeneratorFactory, pageCache, logProvider, blockSize ); } @Override public <FAILURE extends Exception> void accept( RecordStore.Processor<FAILURE> processor, DynamicRecord record ) throws FAILURE { processor.processArray( this, record ); } @Override public String getTypeDescriptor() { return TYPE_DESCRIPTOR; } public static void allocateFromNumbers( Collection<DynamicRecord> target, Object array, Iterator<DynamicRecord> recordsToUseFirst, DynamicRecordAllocator recordAllocator ) { Class<?> componentType = array.getClass().getComponentType(); boolean isPrimitiveByteArray = componentType.equals( Byte.TYPE ); boolean isByteArray = componentType.equals( Byte.class ) || isPrimitiveByteArray; ShortArray type = ShortArray.typeOf( array ); if ( type == null ) { throw new IllegalArgumentException( array + " not a valid array type." ); } int arrayLength = Array.getLength( array ); int requiredBits = isByteArray ? Byte.SIZE : type.calculateRequiredBitsForArray( array, arrayLength); int totalBits = requiredBits*arrayLength; int numberOfBytes = (totalBits-1)/8+1; int bitsUsedInLastByte = totalBits%8; bitsUsedInLastByte = bitsUsedInLastByte == 0 ? 8 : bitsUsedInLastByte; numberOfBytes += NUMBER_HEADER_SIZE; // type + rest + requiredBits header. TODO no need to use full bytes byte[] bytes; if ( isByteArray ) { bytes = new byte[NUMBER_HEADER_SIZE+ arrayLength]; bytes[0] = (byte) type.intValue(); bytes[1] = (byte) bitsUsedInLastByte; bytes[2] = (byte) requiredBits; if ( isPrimitiveByteArray ) { arraycopy( array, 0, bytes, NUMBER_HEADER_SIZE, arrayLength ); } else { Byte[] source = (Byte[]) array; for ( int i = 0; i < source.length; i++ ) { bytes[NUMBER_HEADER_SIZE+i] = source[i]; } } } else { Bits bits = Bits.bits( numberOfBytes ); bits.put( (byte)type.intValue() ); bits.put( (byte)bitsUsedInLastByte ); bits.put( (byte)requiredBits ); type.writeAll(array, arrayLength,requiredBits,bits); bytes = bits.asBytes(); } allocateRecordsFromBytes( target, bytes, recordsToUseFirst, recordAllocator ); } private static void allocateFromString( Collection<DynamicRecord> target, String[] array, Iterator<DynamicRecord> recordsToUseFirst, DynamicRecordAllocator recordAllocator ) { byte[][] stringsAsBytes = new byte[array.length][]; int totalBytesRequired = STRING_HEADER_SIZE; // 1b type + 4b array length for ( int i = 0; i < array.length; i++ ) { String string = array[i]; byte[] bytes = PropertyStore.encodeString( string ); stringsAsBytes[i] = bytes; totalBytesRequired += 4/*byte[].length*/ + bytes.length; } ByteBuffer buf = ByteBuffer.allocate( totalBytesRequired ); buf.put( PropertyType.STRING.byteValue() ); buf.putInt( array.length ); for ( byte[] stringAsBytes : stringsAsBytes ) { buf.putInt( stringAsBytes.length ); buf.put( stringAsBytes ); } allocateRecordsFromBytes( target, buf.array(), recordsToUseFirst, recordAllocator ); } public void allocateRecords( Collection<DynamicRecord> target, Object array, Iterator<DynamicRecord> recordsToUseFirst ) { allocateRecords( target, array, recordsToUseFirst, this ); } public static void allocateRecords( Collection<DynamicRecord> target, Object array, Iterator<DynamicRecord> recordsToUseFirst, DynamicRecordAllocator recordAllocator ) { if ( !array.getClass().isArray() ) { throw new IllegalArgumentException( array + " not an array" ); } Class<?> type = array.getClass().getComponentType(); if ( type.equals( String.class ) ) { allocateFromString( target, (String[]) array, recordsToUseFirst, recordAllocator ); } else { allocateFromNumbers( target, array, recordsToUseFirst, recordAllocator ); } } public static Object getRightArray( Pair<byte[],byte[]> data ) { byte[] header = data.first(); byte[] bArray = data.other(); byte typeId = header[0]; if ( typeId == PropertyType.STRING.intValue() ) { ByteBuffer headerBuffer = ByteBuffer.wrap( header, 1/*skip the type*/, header.length-1 ); int arrayLength = headerBuffer.getInt(); String[] result = new String[arrayLength]; ByteBuffer dataBuffer = ByteBuffer.wrap( bArray ); for ( int i = 0; i < arrayLength; i++ ) { int byteLength = dataBuffer.getInt(); byte[] stringByteArray = new byte[byteLength]; dataBuffer.get( stringByteArray ); result[i] = PropertyStore.decodeString( stringByteArray ); } return result; } else { ShortArray type = ShortArray.typeOf( typeId ); int bitsUsedInLastByte = header[1]; int requiredBits = header[2]; if ( requiredBits == 0 ) { return type.createEmptyArray(); } Object result; if ( type == ShortArray.BYTE && requiredBits == Byte.SIZE ) { // Optimization for byte arrays (probably large ones) result = bArray; } else { // Fallback to the generic approach, which is a slower Bits bits = Bits.bitsFromBytes( bArray ); int length = (bArray.length*8-(8-bitsUsedInLastByte))/requiredBits; result = type.createArray(length, bits, requiredBits); } return result; } } public Object getArrayFor( Iterable<DynamicRecord> records ) { return getRightArray( readFullByteArray( records, PropertyType.ARRAY ) ); } }
import org.lwjgl.*; import org.lwjgl.glfw.*; import org.lwjgl.opengl.*; import org.lwjgl.system.*; import stolen.Matrix; import java.io.DataInputStream; import java.io.InputStream; import java.nio.*; import java.util.Arrays; import java.util.concurrent.TimeUnit; import static org.lwjgl.glfw.Callbacks.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.ARBComputeShader.glDispatchCompute; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL13.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.glBindFragDataLocation; import static org.lwjgl.opengl.GL30.glBindVertexArray; import static org.lwjgl.opengl.GL30.glGenVertexArrays; import static org.lwjgl.opengl.GL42.glBindImageTexture; import static org.lwjgl.opengl.GL42.glMemoryBarrier; import static org.lwjgl.opengl.GL43.*; import static org.lwjgl.stb.STBImage.stbi_failure_reason; import static org.lwjgl.stb.STBImage.stbi_load; import static org.lwjgl.stb.STBImage.stbi_set_flip_vertically_on_load; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.opengl.GL20.glCreateProgram; public class ShadersPreview { public static final float AMENDMENT_STEP = 0.05f; public static final int WINDOW_WIDTH = 568; public static final int WINDOW_HEIGHT = 320; public static final float ROTATION_STEP_ANGLE = 1.0f; // The window handle private long window; private int drawProgramID, computeProgramID, clearProgramID; private int fullScreenVao; public static final int IMAGES_COUNT = 2; private int[] depthTexturesID = new int[IMAGES_COUNT]; private int[] resultTexturesID = new int[IMAGES_COUNT]; private int[] imageTexturesID = new int[IMAGES_COUNT]; private float[] mViewMatrix = new float[16]; private int workgroupSize; private static final int WIDTH = 640; private static final int HEIGHT = 480; private static final String S_COMP_SHADER_HEADER = "#version 310 es\n#define LOCAL_SIZE %d\n"; private float distanceAmendment = 0f; private float horizontalShift; private float horizontalAngleRotation = 0; private float angleDiff = 65.0f; float mix = 0; private void finalDraw(float[] mixer) { glUseProgram(drawProgramID); glBindVertexArray(fullScreenVao); int mMixerHandle = glGetUniformLocation(drawProgramID, "uMixer"); glUniform4fv(mMixerHandle, mixer); for (int i = 0; i < IMAGES_COUNT; i ++) { glActiveTexture(GL_TEXTURE0 + i * 2); glBindTexture(GL_TEXTURE_2D, resultTexturesID[i]); glActiveTexture(GL_TEXTURE0 + i* 2 + 1); glBindTexture(GL_TEXTURE_2D, imageTexturesID[i]); } glDrawArrays(GL_TRIANGLES, 0, 6); } private void runClearShaders() { glUseProgram(clearProgramID); for (int i = 0; i < IMAGES_COUNT; i ++) { glBindImageTexture(1, resultTexturesID[i], 0, false, 0, GL_READ_WRITE, GL_RGBA8); glDispatchCompute(WIDTH / workgroupSize, HEIGHT / workgroupSize, 1); glMemoryBarrier(GL_COMPUTE_SHADER_BIT); } } private void runComputeShader(int i, float[] mMVPMatrix) { glUseProgram(computeProgramID); glBindImageTexture(0, depthTexturesID[i], 0, false, 0, GL_READ_ONLY, GL_RGBA8); glBindImageTexture(1, resultTexturesID[i], 0, false, 0, GL_READ_WRITE, GL_RGBA8); int mMVPMatrixHandle = glGetUniformLocation(computeProgramID, "u_MVPMatrix"); glUniformMatrix4fv(mMVPMatrixHandle,false, mMVPMatrix); glDispatchCompute(WIDTH / workgroupSize, HEIGHT / workgroupSize, 1); // GL_COMPUTE_SHADER_BIT is the same as GL_SHADER_IMAGE_ ACCESS_BARRIER_BIT glMemoryBarrier(GL_COMPUTE_SHADER_BIT); } // draws each frame private void drawFrame() { runClearShaders(); // long time = System.currentTimeMillis() % 6000L - 3000L; float angleInDegrees = 0; // (-90.0f / 10000.0f) * ((int) time); float[] mMVPMatrix; mix = (float) Math.sin(horizontalAngleRotation * 3.14/ (2 * angleDiff)); mix = mix * mix; mix = Math.max(Math.min(mix, 1.0f), 0.0f); mMVPMatrix = getMVPMatrix(angleInDegrees, 0.0f, ( mix) * 0); runComputeShader(0, mMVPMatrix); mMVPMatrix = getMVPMatrix( - angleDiff,-0.0f, - (1 - mix) * 0); runComputeShader(1, mMVPMatrix); // System.out.println("mi x" + mix); // float[] mixer = {0.5f, 0.5f, 0f, 0f}; float[] mixer = {1.0f - mix, mix, 0f, 0f}; finalDraw(mixer); } private float[] getMVPMatrix(float angleInDegrees, float translateX, float xa) { float[] mModelMatrix= new float[16];; float[] mMVPMatrix=new float[16]; float[] mProjectionMatrix=new float[16];; // System.out.println("Angel " + angleInDegrees); mModelMatrix = Matrix.setIdentityM(mModelMatrix, 0); mModelMatrix = Matrix.rotateM(mModelMatrix, 0, xa, 1.0f, 0.0f, 0.0f); mModelMatrix = Matrix.rotateM(mModelMatrix, 0, angleInDegrees + horizontalAngleRotation, 0.0f, 1.0f, 0.0f); mModelMatrix = Matrix.translateM(mModelMatrix, 0, translateX + horizontalShift, 0, 2.1f); // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix // (which currently contains model * view). mMVPMatrix = Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0); mProjectionMatrix = Matrix.frustumM(mProjectionMatrix, 0, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f + distanceAmendment, 40.0f); // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix // (which now contains model * view * projection). mMVPMatrix = Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0); return mMVPMatrix; } private int createQuadFullScreenVao() { int vao = glGenVertexArrays(); int vbo = glGenBuffers(); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); ByteBuffer bb = BufferUtils.createByteBuffer(2 * 6); bb.put((byte) -1).put((byte) -1); bb.put((byte) 1).put((byte) -1); bb.put((byte) 1).put((byte) 1); bb.put((byte) 1).put((byte) 1); bb.put((byte) -1).put((byte) 1); bb.put((byte) -1).put((byte) -1); bb.flip(); glBufferData(GL_ARRAY_BUFFER, bb, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_BYTE, false, 0, 0L); glBindVertexArray(0); return vao; } private void initVars() { // config opengl glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // draw texture directly drawProgramID = glCreateProgram(); int drawVertID = createShader("draw.vert", GL_VERTEX_SHADER); int drawFragID = createShader("draw.frag", GL_FRAGMENT_SHADER); glAttachShader(drawProgramID, drawVertID); glAttachShader(drawProgramID, drawFragID); glLinkProgram(drawProgramID); checkProgramStatus(drawProgramID); clearProgramID = glCreateProgram(); int clearCompID = createShader("clear.comp", GL_COMPUTE_SHADER); glAttachShader(clearProgramID, clearCompID); glLinkProgram(clearProgramID); checkProgramStatus(clearProgramID); computeProgramID = glCreateProgram(); int computeCompID = createShader("draw.comp", GL_COMPUTE_SHADER); glAttachShader(computeProgramID, computeCompID); glLinkProgram(computeProgramID); checkProgramStatus(computeProgramID); // we tell how this called in shaders glBindAttribLocation(drawProgramID, 0, "vertex"); glBindFragDataLocation(drawProgramID, 0, "color"); fullScreenVao = createQuadFullScreenVao(); glUseProgram(drawProgramID); // Set sampler2d in GLSL fragment shader to texture unit 0 glUniform1i(glGetUniformLocation(drawProgramID, "uResult0Tex"), 0); glUniform1i(glGetUniformLocation(drawProgramID, "uImage0Tex"), 1); glUniform1i(glGetUniformLocation(drawProgramID, "uResult1Tex"), 2); glUniform1i(glGetUniformLocation(drawProgramID, "uImage1Tex"), 3); glUseProgram(computeProgramID); // Set sampler2d in GLSL fragment shader to texture unit 0 glUniform1i(glGetUniformLocation(computeProgramID, "inputImage"), 0); glUniform1i(glGetUniformLocation(computeProgramID, "resultImage"), 1); //TODO no idea what is this workgroupSize = 16; System.out.println("Work group size = " + workgroupSize); String[] images = {"040407","040507"}; for (int i = 0; i < IMAGES_COUNT; i ++) { imageTexturesID[i] = loadTexture("src/main/resources/" + images[i] + "_color.png"); depthTexturesID[i] = loadTexture("src/main/resources/" + images[i] + "_depth.png"); resultTexturesID[i] = createFramebufferTexture(); } } public static CharSequence getShaderCode(String name) { InputStream is = ShadersPreview.class.getResourceAsStream(name); final DataInputStream dataStream = new DataInputStream(is); byte[] shaderCode; try { shaderCode = new byte[dataStream.available()]; dataStream.readFully(shaderCode); is.close(); } catch (Throwable e) { return ""; } return new String(shaderCode); } private int createFramebufferTexture() { int tex = glGenTextures(); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); ByteBuffer black = null; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, WIDTH, HEIGHT, 0, GL_RGBA, GL_INT, black); glBindTexture(GL_TEXTURE_2D, 0); return tex; } private int createShader(String name, int type) { int shaderID = glCreateShader(type); glShaderSource(shaderID, getShaderCode(name)); glCompileShader(shaderID); checkShaderStatus(name, shaderID); return shaderID; } public void checkProgramStatus(int programID) { int status = glGetProgrami(programID, GL_LINK_STATUS); if (status != GL_TRUE) { System.err.println(glGetProgramInfoLog(programID)); } } private void checkShaderStatus(String name, int shaderID) { int status = glGetShaderi(shaderID, GL_COMPILE_STATUS); if (status != GL_TRUE) { System.err.println(name); System.err.println(glGetShaderInfoLog(shaderID)); } } public static int loadTexture(String path) { ByteBuffer image; int width, height; try (MemoryStack stack = MemoryStack.stackPush()) { /* Prepare image buffers */ IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); IntBuffer comp = stack.mallocInt(1); /* Load image */ stbi_set_flip_vertically_on_load(true); image = stbi_load(path, w, h, comp, 4); if (image == null) { throw new RuntimeException("Failed to load a texture file!("+path+")" + System.lineSeparator() + stbi_failure_reason()); } /* Get width and height of image */ width = w.get(); height = h.get(); } // create texture int textureID = glGenTextures(); glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); return textureID; } /** * have not touched rest of file */ public void run() { System.out.println("LWJGL version " + Version.getVersion()); init(); loop(); // Free the window callbacks and destroy the window glfwFreeCallbacks(window); glfwDestroyWindow(window); // Terminate GLFW and free the error callback glfwTerminate(); glfwSetErrorCallback(null).free(); } private void init() { // Setup an error callback. The default implementation // will print the error message in System.err. GLFWErrorCallback.createPrint(System.err).set(); // Initialize GLFW. Most GLFW functions will not work before doing this. if ( !glfwInit() ) throw new IllegalStateException("Unable to initialize GLFW"); // Configure GLFW glfwDefaultWindowHints(); // optional, the current window hints are already the default glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Create the window window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Shaders Preview", NULL, NULL); if ( window == NULL ) throw new RuntimeException("Failed to create the GLFW window"); // Setup a key callback. It will be called every time a key is pressed, repeated or released. glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> { if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE ) { glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop }else if (key == GLFW_KEY_LEFT||key == GLFW_KEY_RIGHT){ // System.out.println("Direction button pressed:"+key); horizontalAngleRotation = (key == GLFW_KEY_LEFT )? horizontalAngleRotation - ROTATION_STEP_ANGLE :horizontalAngleRotation+ROTATION_STEP_ANGLE; } }); glfwSetScrollCallback(window, (window, xoffset, yoffset)->{ if(yoffset>=0){ distanceAmendment += AMENDMENT_STEP; }else{ distanceAmendment -= AMENDMENT_STEP; } }); glfwSetCursorPosCallback(window, (window, xpos, ypos)->{ horizontalShift = (float)xpos/(WINDOW_HEIGHT/2)-1; }); // Get the thread stack and push a new frame try ( MemoryStack stack = stackPush() ) { IntBuffer pWidth = stack.mallocInt(1); // int* IntBuffer pHeight = stack.mallocInt(1); // int* // Get the window size passed to glfwCreateWindow glfwGetWindowSize(window, pWidth, pHeight); // Get the resolution of the primary monitor GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); // Center the window glfwSetWindowPos( window, (vidmode.width() - pWidth.get(0)) / 2, (vidmode.height() - pHeight.get(0)) / 2 ); } // the stack frame is popped automatically // Make the OpenGL context current glfwMakeContextCurrent(window); // Enable v-sync glfwSwapInterval(1); // Make the window visible glfwShowWindow(window); GL.createCapabilities(); initVars(); initInitialView(); } private void initInitialView() { // init camera view // Position the eye behind the origin. final float eyeX = 0.0f; final float eyeY = 0.0f; final float eyeZ = 1.5f; // We are looking toward the distance final float lookX = 0.0f; final float lookY = 0.0f; final float lookZ = -3.0f; // Set our up vector. This is where our head would be pointing were we holding the camera. final float upX = 00f; final float upY = 1.0f; final float upZ = 0.0f; // Set the view matrix. This matrix can be said to represent the camera position. // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose. Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ); } private void loop() { // This line is critical for LWJGL's interoperation with GLFW's // OpenGL context, or any context that is managed externally. // LWJGL detects the context that is current in the current thread, // creates the GLCapabilities instance and makes the OpenGL // bindings available for use. GL.createCapabilities(); // Set the clear color // glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClearColor(170f / 256, 159f / 256, 182f / 256, 1.0f); // Run the rendering loop until the user has attempted to close // the window or has pressed the ESCAPE key. while ( !glfwWindowShouldClose(window) ) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer drawFrame(); glfwSwapBuffers(window); // swap the color buffers // Poll for window events. The key callback above will only be // invoked during this call. glfwPollEvents(); } } public static void main(String[] args) { new ShadersPreview().run(); } }
package wordsegm; import java.util.ArrayList; import java.util.HashMap; public class WordSegm { private HashMap<String, Integer> wordFreq = null; private HashMap<String, HashMap<String, Integer>> markovChain = null; private int maxWordSize = 6; int base = 33000; double weight = 0.9; int lastPlus = 55000; int engPlus = 100000; boolean debug = true; public WordSegm(HashMap<String, Integer> wordFreq, HashMap<String, HashMap<String, Integer>> markovChain) { super(); this.wordFreq = wordFreq; this.markovChain = markovChain; } public ArrayList<String> segment(String str) { ArrayList<String> result = new ArrayList<String>(); Pretreatment pretreatment = new Pretreatment(); ArrayList<String> pretreatLsit = new ArrayList<String>(); int localMaxWordSize = pretreatment.preprocess(str, maxWordSize, pretreatLsit); int resLocalMaxWordSize = localMaxWordSize; String predecessor = null; for (int index = 0; index < pretreatLsit.size();) { int ind = index; if (predecessor == null || (predecessor != null && !wordFreq .containsKey(predecessor))) { ind = feedbackWordFreqSegment(index, localMaxWordSize, resLocalMaxWordSize, pretreatLsit); } else { HashMap<String, Integer> succeeds = markovChain .get(predecessor); boolean flag = false; for (int count = 0; count < localMaxWordSize; count++) { if (succeeds.containsKey(pretreatLsit.get(index + count))) { flag = true; } } if (flag) { ind = feedbackMarkovSegment(index, localMaxWordSize, resLocalMaxWordSize, succeeds, pretreatLsit); } else { ind = feedbackWordFreqSegment(index, localMaxWordSize, resLocalMaxWordSize, pretreatLsit); } } result.add(pretreatLsit.get(ind)); predecessor = pretreatLsit.get(ind); int count = ind - index + 1; if (localMaxWordSize == resLocalMaxWordSize) { int i = 0; for (; i < count; i++) { index += resLocalMaxWordSize; if (index == pretreatLsit.size() - (resLocalMaxWordSize * (resLocalMaxWordSize - 1)) / 2) { localMaxWordSize--; i++; break; } } for (; i < count; i++) { index += localMaxWordSize; localMaxWordSize--; } } else { for (int i = 0; i < count; i++) { index += localMaxWordSize; localMaxWordSize--; } } } return result; } public int feedbackMarkovSegment(int index, int localMaxWordSize, int resLocalMaxWordSize, HashMap<String, Integer> succeeds, ArrayList<String> pretreatLsit) { double score = 0, maxScore = 1; int border = index; for (int count = 0; count < localMaxWordSize; count++) { if (succeeds.containsKey(pretreatLsit.get(index + count))) { score = succeeds.get(pretreatLsit.get(index + count)) * Math.pow(base, count); } else { if (wordFreq.containsKey(pretreatLsit.get(index + count))) { score = wordFreq.get(pretreatLsit.get(index + count)) / Math.pow(weight, count); } else score = 1; } if (count == 0 && pretreatLsit.get(index).matches("[a-zA-Z]+")) { score = score + engPlus; } int tempIndex = index; int tempLocalMaxWordSize = localMaxWordSize; if (tempLocalMaxWordSize == resLocalMaxWordSize) { int i = 0; for (; i < count + 1; i++) { tempIndex += resLocalMaxWordSize; if (tempIndex == pretreatLsit.size() - (resLocalMaxWordSize * (resLocalMaxWordSize - 1)) / 2) { tempLocalMaxWordSize--; i++; break; } } for (; i < count + 1; i++) { tempIndex += tempLocalMaxWordSize; tempLocalMaxWordSize--; } } else { for (int i = 0; i < count + 1; i++) { tempIndex += tempLocalMaxWordSize; tempLocalMaxWordSize--; } } boolean exist = wordFreq.containsKey(pretreatLsit .get(index + count)); if (exist && tempLocalMaxWordSize == 0) { score = score + lastPlus; } double localMax = 1; double temp = 0; if (exist) { HashMap<String, Integer> tempSucceeds = markovChain .get(pretreatLsit.get(index + count)); for (int i = 0; i < tempLocalMaxWordSize; i++) { String word = pretreatLsit.get(tempIndex + i); if (tempSucceeds.containsKey(word)) { temp = tempSucceeds.get(word) * Math.pow(base, count); } if (temp > localMax) { localMax = temp; } } } else { for (int i = 0; i < tempLocalMaxWordSize; i++) { String word = pretreatLsit.get(tempIndex + i); if (wordFreq.containsKey(word)) { temp = wordFreq.get(word) / Math.pow(base, count); if (temp > localMax) { localMax = temp; } } } } score = score + localMax; if (score > maxScore) { maxScore = score; border = index + count; } } return border; } public int feedbackWordFreqSegment(int index, int localMaxWordSize, int resLocalMaxWordSize, ArrayList<String> pretreatLsit) { double score = 0, maxScore = 1; int border = index; for (int count = 0; count < localMaxWordSize; count++) { boolean exist = true; if (wordFreq.containsKey(pretreatLsit.get(index + count))) { if (count < 2) { score = wordFreq.get(pretreatLsit.get(index + count)) * Math.pow(base, count + weight); } else score = wordFreq.get(pretreatLsit.get(index + count)) * Math.pow(base, count); } else { score = 1; exist = false; } if (count == 0 && pretreatLsit.get(index).matches("[a-zA-Z]+")) { score = score + engPlus; } int tempIndex = index; int tempLocalMaxWordSize = localMaxWordSize; if (tempLocalMaxWordSize == resLocalMaxWordSize) { int i = 0; for (; i < count + 1; i++) { tempIndex += resLocalMaxWordSize; if (tempIndex == pretreatLsit.size() - (resLocalMaxWordSize * (resLocalMaxWordSize - 1)) / 2) { tempLocalMaxWordSize--; i++; break; } } for (; i < count + 1; i++) { tempIndex += tempLocalMaxWordSize; tempLocalMaxWordSize--; } } else { for (int i = 0; i < count + 1; i++) { tempIndex += tempLocalMaxWordSize; tempLocalMaxWordSize--; } } if (exist && tempLocalMaxWordSize == 0) { score = score + lastPlus; } double localMax = 1; double temp = 0; if (exist) { HashMap<String, Integer> tempSucceeds = markovChain .get(pretreatLsit.get(index + count)); for (int i = 0; i < tempLocalMaxWordSize; i++) { String word = pretreatLsit.get(tempIndex + i); if (tempSucceeds.containsKey(word)) { temp = tempSucceeds.get(word) * Math.pow(base, count); } if (temp > localMax) { localMax = temp; } } } else { for (int i = 0; i < tempLocalMaxWordSize; i++) { String word = pretreatLsit.get(tempIndex + i); if (wordFreq.containsKey(word)) { temp = wordFreq.get(word) / Math.pow(base, count); if (temp > localMax) { localMax = temp; } } } } score = score + localMax; if (score > maxScore) { maxScore = score; border = index + count; } } return border; } public String ArraytoString(ArrayList<String> words) { String result = ""; for (String s : words) { result += s + " | "; } return result; } }
/* * 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.simplesystemsmanagement.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/PutParameter" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PutParameterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The new version number of a parameter. If you edit a parameter value, Parameter Store automatically creates a new * version and assigns this new version a unique ID. You can reference a parameter version ID in API operations or * in Systems Manager documents (SSM documents). By default, if you don't specify a specific version, the system * returns the latest parameter value when a parameter is called. * </p> */ private Long version; /** * <p> * The tier assigned to the parameter. * </p> */ private String tier; /** * <p> * The new version number of a parameter. If you edit a parameter value, Parameter Store automatically creates a new * version and assigns this new version a unique ID. You can reference a parameter version ID in API operations or * in Systems Manager documents (SSM documents). By default, if you don't specify a specific version, the system * returns the latest parameter value when a parameter is called. * </p> * * @param version * The new version number of a parameter. If you edit a parameter value, Parameter Store automatically * creates a new version and assigns this new version a unique ID. You can reference a parameter version ID * in API operations or in Systems Manager documents (SSM documents). By default, if you don't specify a * specific version, the system returns the latest parameter value when a parameter is called. */ public void setVersion(Long version) { this.version = version; } /** * <p> * The new version number of a parameter. If you edit a parameter value, Parameter Store automatically creates a new * version and assigns this new version a unique ID. You can reference a parameter version ID in API operations or * in Systems Manager documents (SSM documents). By default, if you don't specify a specific version, the system * returns the latest parameter value when a parameter is called. * </p> * * @return The new version number of a parameter. If you edit a parameter value, Parameter Store automatically * creates a new version and assigns this new version a unique ID. You can reference a parameter version ID * in API operations or in Systems Manager documents (SSM documents). By default, if you don't specify a * specific version, the system returns the latest parameter value when a parameter is called. */ public Long getVersion() { return this.version; } /** * <p> * The new version number of a parameter. If you edit a parameter value, Parameter Store automatically creates a new * version and assigns this new version a unique ID. You can reference a parameter version ID in API operations or * in Systems Manager documents (SSM documents). By default, if you don't specify a specific version, the system * returns the latest parameter value when a parameter is called. * </p> * * @param version * The new version number of a parameter. If you edit a parameter value, Parameter Store automatically * creates a new version and assigns this new version a unique ID. You can reference a parameter version ID * in API operations or in Systems Manager documents (SSM documents). By default, if you don't specify a * specific version, the system returns the latest parameter value when a parameter is called. * @return Returns a reference to this object so that method calls can be chained together. */ public PutParameterResult withVersion(Long version) { setVersion(version); return this; } /** * <p> * The tier assigned to the parameter. * </p> * * @param tier * The tier assigned to the parameter. * @see ParameterTier */ public void setTier(String tier) { this.tier = tier; } /** * <p> * The tier assigned to the parameter. * </p> * * @return The tier assigned to the parameter. * @see ParameterTier */ public String getTier() { return this.tier; } /** * <p> * The tier assigned to the parameter. * </p> * * @param tier * The tier assigned to the parameter. * @return Returns a reference to this object so that method calls can be chained together. * @see ParameterTier */ public PutParameterResult withTier(String tier) { setTier(tier); return this; } /** * <p> * The tier assigned to the parameter. * </p> * * @param tier * The tier assigned to the parameter. * @return Returns a reference to this object so that method calls can be chained together. * @see ParameterTier */ public PutParameterResult withTier(ParameterTier tier) { this.tier = tier.toString(); 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 (getVersion() != null) sb.append("Version: ").append(getVersion()).append(","); if (getTier() != null) sb.append("Tier: ").append(getTier()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PutParameterResult == false) return false; PutParameterResult other = (PutParameterResult) obj; if (other.getVersion() == null ^ this.getVersion() == null) return false; if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false) return false; if (other.getTier() == null ^ this.getTier() == null) return false; if (other.getTier() != null && other.getTier().equals(this.getTier()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode()); hashCode = prime * hashCode + ((getTier() == null) ? 0 : getTier().hashCode()); return hashCode; } @Override public PutParameterResult clone() { try { return (PutParameterResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package com.example.app.ourapplication.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.example.app.ourapplication.Keys; import com.example.app.ourapplication.rest.model.response.Person; import com.example.app.ourapplication.rest.model.response.Subscriber; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by ROYSH on 6/8/2016. */ public class DBHelper extends SQLiteOpenHelper { private static final String TAG = DBHelper.class.getSimpleName(); private static final String MESSAGE_ID_COLUMN = "POSTID"; private static final String MESSAGE_COLUMN = "MESSAGE"; private static final String MESSAGE_USER_NAME_COLUMN = "USER_NAME"; private static final String MESSAGE_USER_ID_COLUMN = "USER_ID"; private static final String MESSAGE_IMAGE_COLUMN = "MESSAGE_IMAGE"; private static final String MESSAGE_TIME_COLUMN = "MESSAGETIME"; private static final String MESSAGE_LIKES_COLUMN = "LIKES"; private static final String PROFILE_IMAGE_COLUMN = "PROFILEIMAGE"; private static final String PROFILE_USER_COLUMN = "PROFILEUSER"; private static final String PROFILE_ID_COLUMN = "PROFILEID"; private static final String MESSAGE_PROTOCOL_COLUMN = "PROTOCOL"; private static final String SUBSCRIPTION_FLAG_COLUMN = "SUBSCRIPTION_FLAG"; private static final String SUBSCRIBER_ID_COLUMN = "SUBSCRIBER_ID"; private static final String USER_ID_COLUMN = "USER_ID"; private SQLiteDatabase mydatabase; public DBHelper(Context context) { super(context, "FEED", null, 32); //24 is the database version } @Override public void onCreate(SQLiteDatabase mydatabase) { // TODO Auto-generated method stub mydatabase.execSQL( "create table MESSAGE_DATA ("+MESSAGE_ID_COLUMN+" VARCHAR,"+ MESSAGE_USER_ID_COLUMN +" VARCHAR,"+ MESSAGE_USER_NAME_COLUMN+" VARCHAR,"+ MESSAGE_COLUMN+" VARCHAR,"+ PROFILE_IMAGE_COLUMN +" VARCHAR,"+ MESSAGE_IMAGE_COLUMN+" VARCHAR,"+ MESSAGE_TIME_COLUMN+" VARCHAR,"+ SUBSCRIPTION_FLAG_COLUMN+" VARCHAR,"+ MESSAGE_PROTOCOL_COLUMN+" VARCHAR)" ); mydatabase.execSQL( "create table COMMENT_DATA ("+MESSAGE_ID_COLUMN+" VARCHAR,"+ MESSAGE_USER_ID_COLUMN+" VARCHAR,"+ MESSAGE_USER_NAME_COLUMN+" VARCHAR,"+ MESSAGE_COLUMN+" VARCHAR,"+ PROFILE_IMAGE_COLUMN +" VARCHAR,"+ MESSAGE_TIME_COLUMN+" VARCHAR)" ); mydatabase.execSQL( "create table PROFILE_DATA (" + PROFILE_ID_COLUMN + " VARCHAR PRIMARY KEY," + PROFILE_USER_COLUMN + " VARCHAR ," + PROFILE_IMAGE_COLUMN + " VARCHAR )" //"CREATE TABLE IF NOT EXISTS DATA(FROM VARCHAR,TO VARCHAR,MESSAGE VARCHAR );" ); mydatabase.execSQL( "create table SUBSCRIBER_DATA (" + USER_ID_COLUMN + " VARCHAR," + SUBSCRIBER_ID_COLUMN + " VARCHAR," + "PRIMARY KEY(" + USER_ID_COLUMN + "," + SUBSCRIBER_ID_COLUMN + "))" //"CREATE TABLE IF NOT EXISTS DATA(FROM VARCHAR,TO VARCHAR,MESSAGE VARCHAR );" ); } @Override public void onUpgrade(SQLiteDatabase mydatabase, int oldVersion, int newVersion) { // TODO Auto-generated method stub mydatabase.execSQL("DROP TABLE IF EXISTS MESSAGE_DATA"); mydatabase.execSQL("DROP TABLE IF EXISTS PROFILE_DATA"); mydatabase.execSQL("DROP TABLE IF EXISTS COMMENT_DATA"); mydatabase.execSQL("DROP TABLE IF EXISTS SUBSCRIBER_DATA"); onCreate(mydatabase); } public boolean insertSubscriberData (Subscriber subscriber) { mydatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(USER_ID_COLUMN, subscriber.getUserId()); contentValues.put(SUBSCRIBER_ID_COLUMN, subscriber.getSubscriberId()); mydatabase.insert("SUBSCRIBER_DATA", null, contentValues); return true; } public ArrayList<Person> getFeedDataAll() { ArrayList<Person> array_list = new ArrayList<Person>(); SQLiteDatabase db = this.getReadableDatabase(); //Cursor msg_res = db.rawQuery( "select * from MESSAGE_DATA where " +MESSAGE_FROM_COLUMN+ " = \"" + id + "\" or " +MESSAGE_TO_COLUMN_NAME+ " = \""+id+"\" ORDER BY "+ MESSAGE_TIME_COLUMN_NAME+" DESC", null ); //Cursor msg_res = db.rawQuery("select * from MESSAGE_DATA where " + MESSAGE_PROTOCOL_COLUMN + " = \"HTTP\" ORDER BY " + MESSAGE_TIME_COLUMN + " DESC", null); Cursor msg_res = db.rawQuery("select * from MESSAGE_DATA ORDER BY " + MESSAGE_TIME_COLUMN + " DESC", null); msg_res.moveToFirst(); while(msg_res.isAfterLast() == false){ String column0 = msg_res.getString(0); String column1 = msg_res.getString(1); String column2 = msg_res.getString(2); String column3 = msg_res.getString(3); String column4 = msg_res.getString(4); String column5 = msg_res.getString(5); String column6 = msg_res.getString(6); String column7 = msg_res.getString(7); array_list.add(new Person("F",column0, column1 , column2 , column3, column4,column5,column6,column7 )); msg_res.moveToNext(); } return array_list; } public Person getFeedData(String id) { Person item; SQLiteDatabase db = this.getReadableDatabase(); //Cursor msg_res = db.rawQuery( "select * from MESSAGE_DATA where " +MESSAGE_FROM_COLUMN+ " = \"" + id + "\" or " +MESSAGE_TO_COLUMN_NAME+ " = \""+id+"\" ORDER BY "+ MESSAGE_TIME_COLUMN_NAME+" DESC", null ); // Cursor msg_res = db.rawQuery( "select * from MESSAGE_DATA where "+MESSAGE_ID_COLUMN+ " = \"" + id +"\" and " + MESSAGE_PROTOCOL_COLUMN + " = \"HTTP\" ORDER BY "+ MESSAGE_TIME_COLUMN+" DESC", null ); Cursor msg_res = db.rawQuery("select * from MESSAGE_DATA where "+MESSAGE_ID_COLUMN+ " = \"" + id + "\" ORDER BY " + MESSAGE_TIME_COLUMN + " DESC", null); msg_res.moveToFirst(); String column0 = msg_res.getString(0); String column1 = msg_res.getString(1); String column2 = msg_res.getString(2); String column3 = msg_res.getString(3); String column4 = msg_res.getString(4); String column5 = msg_res.getString(5); String column6 = msg_res.getString(6); String column7 = msg_res.getString(7); item = new Person("F",column0, column1 , column2 , column3, column4,column5,column6,column7); return item; } public String getUserSubscription(String id,String sid ) { String columndata; SQLiteDatabase db = this.getReadableDatabase(); Cursor msg_res = db.rawQuery("select SUBSCRIBER_ID from SUBSCRIBER_DATA where " + USER_ID_COLUMN + " = \"" + id + "\"" + " and " + SUBSCRIBER_ID_COLUMN + " = \"" + sid + "\"", null); msg_res.moveToFirst(); if (msg_res.getCount() != 0){ msg_res.moveToFirst(); columndata = msg_res.getString(0); Log.d(TAG, "getFeedDataColumn: " + columndata);} else{ columndata="nosubscription"; } return columndata; } public String getFeedDataColumn(String id, Integer columnnumber ) { String columndata; SQLiteDatabase db = this.getReadableDatabase(); Cursor msg_res = db.rawQuery("select * from MESSAGE_DATA where " + MESSAGE_ID_COLUMN + " = \"" + id + "\"", null); msg_res.moveToFirst(); if (msg_res.getCount() != 0){ msg_res.moveToFirst(); columndata = msg_res.getString(columnnumber); Log.d(TAG, "getFeedDataColumn: " + columndata);} else{ columndata="noimage"; } return columndata; } public String getProfileInfo(String id,Integer columnnumber) { String columndata; SQLiteDatabase db = this.getReadableDatabase(); //String Query = "SELECT * FROM PROFILE_DATA WHERE PROFILE_USER = 'Fiji' "; Cursor prof_res = db.rawQuery("SELECT * FROM PROFILE_DATA WHERE " + PROFILE_ID_COLUMN + " = \"" + id + "\"", null); Log.d(TAG, "getProfileInfoCount: " + prof_res.getCount()); Log.d(TAG, "getProfileInfoID: " + id); if (prof_res.getCount() != 0){ prof_res.moveToFirst(); columndata = prof_res.getString(columnnumber); // Log.d(TAG, "getProfileInfo: " + columndata); } else{ columndata="noimage"; } return columndata; } public ArrayList<Person> getCommentData(String id) { ArrayList<Person> array_list = new ArrayList<Person>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor msg_res = db.rawQuery( "select * from COMMENT_DATA where " +MESSAGE_ID_COLUMN+ " = \"" + id +"\" ORDER BY "+ MESSAGE_TIME_COLUMN+" ASC", null ); //Cursor res = db.rawQuery( "select * from MESSAGE_DATA" , null ); msg_res.moveToFirst(); while(msg_res.isAfterLast() == false){ String column0 = msg_res.getString(0); String column1 = msg_res.getString(1); String column2 = msg_res.getString(2); String column3 = msg_res.getString(3); String column4 = msg_res.getString(4); String column5 = msg_res.getString(5); array_list.add(new Person("C",column0, column1 , column2 ,column3,column4, "", column5,"" )); msg_res.moveToNext(); } return array_list; } public boolean updateProfile (String profile) { JSONObject msgObject = null; try { msgObject = new JSONObject(profile); } catch (JSONException e) { e.printStackTrace(); } mydatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); //contentValues.put(PROFILE_USER_COLUMN_NAME, msgObject.optString(Keys.KEY_NAME)); contentValues.put(msgObject.optString("columnname"), msgObject.optString("columndata")); mydatabase.update("PROFILE_DATA", contentValues, PROFILE_ID_COLUMN + "= \"" + msgObject.optString(Keys.KEY_USERID) + "\" ", null); return true; } public void RefreshUserSubscription() { SQLiteDatabase db = this.getWritableDatabase(); db.delete("SUBSCRIBER_DATA", null, null); } public boolean insertFeedData (Person message , String protocol) { /* JSONObject msgObject = null; try { msgObject = new JSONObject(message); Log.d(TAG, "Inserted"); } catch (JSONException e) { e.printStackTrace(); }*/ mydatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(MESSAGE_ID_COLUMN, message.getPostId()); contentValues.put(MESSAGE_USER_ID_COLUMN, message.getUserId()); contentValues.put(MESSAGE_USER_NAME_COLUMN, message.getSenderName()); contentValues.put(MESSAGE_COLUMN, message.getMessage()); contentValues.put(PROFILE_IMAGE_COLUMN, message.getPhotoId()); contentValues.put(MESSAGE_IMAGE_COLUMN, message.getPhotoMsg()); contentValues.put(MESSAGE_TIME_COLUMN, message.getTimeMsg()); contentValues.put(SUBSCRIPTION_FLAG_COLUMN, message.getSubscriptionFlag()); contentValues.put(MESSAGE_PROTOCOL_COLUMN, protocol); mydatabase.insert("MESSAGE_DATA", null, contentValues); return true; } public void deleteFeedData() { SQLiteDatabase db = this.getWritableDatabase(); db.delete("MESSAGE_DATA", null, null); } public boolean insertCommentData (Person message) { mydatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(MESSAGE_ID_COLUMN, message.getPostId()); contentValues.put(MESSAGE_USER_ID_COLUMN, message.getUserId()); contentValues.put(MESSAGE_USER_NAME_COLUMN, message.getSenderName()); contentValues.put(MESSAGE_COLUMN, message.getMessage()); contentValues.put(PROFILE_IMAGE_COLUMN, message.getPhotoId()); //contentValues.put(MESSAGE_IMAGE_COLUMN_NAME, msgObject.optString(Keys.KEY_IMAGE)); //contentValues.put(MESSAGE_LIKES_COLUMN_NAME, msgObject.optString(Keys.KEY_LIKES)); contentValues.put(MESSAGE_TIME_COLUMN, message.getTimeMsg()); mydatabase.insert("COMMENT_DATA", null, contentValues); return true; } public String getFeedDataLatestTime() { String columndata; SQLiteDatabase db = this.getReadableDatabase(); // Cursor msg_res = db.rawQuery( "select * from MESSAGE_DATA where " + MESSAGE_PROTOCOL_COLUMN + " = \"HTTP\" ORDER BY "+ MESSAGE_TIME_COLUMN+" DESC" , null ); Cursor msg_res = db.rawQuery( "select * from MESSAGE_DATA ORDER BY "+ MESSAGE_TIME_COLUMN+" DESC" , null ); msg_res.moveToFirst(); if (msg_res.getCount() != 0){ //msg_res.moveToFirst(); columndata = msg_res.getString(6); } else{ columndata="2000-12-31 12:00:00"; } Log.d(TAG, "getFeedDataLatestTime: " + columndata); return columndata; } public String getCommentDataLatestTime(String id) { String columndata; SQLiteDatabase db = this.getReadableDatabase(); Cursor msg_res = db.rawQuery( "select * from COMMENT_DATA where " +MESSAGE_ID_COLUMN+ " = \"" + id +"\" ORDER BY "+ MESSAGE_TIME_COLUMN+" DESC" , null ); msg_res.moveToFirst(); if (msg_res.getCount() != 0) { //msg_res.moveToFirst(); columndata = msg_res.getString(5); } else{ columndata="2000-12-31 12:00:00"; } Log.d(TAG, "getCommentDataColumn: " + columndata); return columndata; } }
/** * Copyright (C) [2013] [The FURTHeR Project] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.further.ds.api.request; import static edu.utah.further.ds.api.util.AttributeName.META_DATA; import static edu.utah.further.ds.api.util.AttributeName.QUERY_CONTEXT; import static edu.utah.further.ds.api.util.AttributeName.QUERY_RESULT; import static edu.utah.further.ds.api.util.AttributeName.SEARCH_QUERY; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.utah.further.core.api.chain.ChainRequest; import edu.utah.further.core.api.chain.RequestProcessor; import edu.utah.further.core.api.context.Labeled; import edu.utah.further.core.api.message.Severity; import edu.utah.further.core.api.message.SeverityMessage; import edu.utah.further.core.api.message.SeverityMessageContainer; import edu.utah.further.core.query.domain.SearchQuery; import edu.utah.further.ds.api.util.AttributeName; import edu.utah.further.ds.api.util.StatusMetaDataUtil; import edu.utah.further.fqe.ds.api.domain.DsMetaData; import edu.utah.further.fqe.ds.api.domain.QueryContext; import edu.utah.further.fqe.ds.api.to.QueryContextToImpl; /** * A query execution request is a type which holds inputs and outputs of a query * execution. A {@link QueryExecutionRequest} uses the Decorator and Delegation patterns * to enhance a {@link ChainRequest} while adding new standard methods for retrieving * typed attribute values, such as getResult(). * * The results of all {@link RequestProcessor} are stored and retrieved using * {@link QueryExecutionRequest#setResult(Object)} and * {@link QueryExecutionRequest#getResult()} * * Additionally, this class is <i>designed</i> to be subclassed with the Decorator and * Delegation patterns to provide typed retrieval and setting of inputs and outputs * instead of dealing directly with associated attribute map provided by * {@link ChainRequest} * * Typically request inputs and outputs will be grouped into one subclass of * {@link QueryExecutionRequest} and several {@link RequestProcessor}'s will operate with * this request subclass (see <code>HibernateExecReq</code> or * <code>WebserviceExecReq</code>). * * All subclasses must implement the constructor * {@link QueryExecutionRequest#QueryExecutionRequest(ChainRequest)} * <p> * -----------------------------------------------------------------------------------<br> * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <further@utah.edu>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author N. Dustin Schultz {@code <dustin.schultz@utah.edu>} * @version Sep 28, 2009 */ public class QueryExecutionRequest implements ChainRequest { // ========================= CONSTANTS ================================= /** * A logger that helps identify this class' printouts. */ private static final Logger log = LoggerFactory .getLogger(QueryExecutionRequest.class); // ========================= FIELDS ================================== /** * The wrapped chain request */ private final ChainRequest chainRequest; // ========================= CONSTRUCTORS ============================ /** * Constructor * * @param chainRequest * the chain request of this execution */ public QueryExecutionRequest(final ChainRequest chainRequest) { this.chainRequest = chainRequest; } // ============== IMPLEMENTATION: QueryExecutionRequest =============== /** * Gets the chain request associated with this execution * * @return the chainRequest */ public final ChainRequest getChainRequest() { return chainRequest; } /** * Gets the result of an execution * * @param <T> * the type of the result * @return the result of type T */ public final <T> T getResult() { // chainRequest.<T> required otherwise Sun javac complains, even though Eclipse // does not. // @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954 // @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=98379 return chainRequest.<T> getAttribute(QUERY_RESULT); } /** * Sets the result of an execution * * @param obj * the result */ public final void setResult(final Object obj) { chainRequest.setAttribute(QUERY_RESULT, obj); } /** * @return the searchQuery */ public final SearchQuery getSearchQuery() { return chainRequest.getAttribute(SEARCH_QUERY); } /** * @param searchQuery * the searchQuery to set */ public final void setSearchQuery(final SearchQuery searchQuery) { chainRequest.setAttribute(SEARCH_QUERY, searchQuery); } /** * Return the queryContext property. * * @return the queryContext */ public final QueryContext getQueryContext() { return chainRequest.getAttribute(AttributeName.QUERY_CONTEXT); } /** * Sets the status of the execution request. * * @param status * the status to set */ public final void setStatus(final String status) { final QueryContext queryContext = getQueryContext(); if (queryContext == null) { // This should only happen in isolated unit tests of executors where the full // query context is not available log.warn("QueryContext was not found in request, cannot set status. " + "If this isn't an isolated test, this is a bug"); return; } // Prepare new query context final QueryContext newQueryContext = QueryContextToImpl.newCopy(queryContext); final DsMetaData metaData = chainRequest.getAttribute(META_DATA); // Do not time execution processor here for now StatusMetaDataUtil.setCurrentStatus(newQueryContext, metaData.getName(), status, 0l); setQueryContext(queryContext); } // ============== IMPLEMENTATION: SeverityMessageContainer ============== /* * (non-Javadoc) * * @see * edu.utah.further.core.api.message.SeverityMessageContainer#addMessage(edu.utah. * further.core.api.message.Severity, java.lang.String) */ @Override public final void addMessage(final Severity severity, final String text) { chainRequest.addMessage(severity, text); } /* * (non-Javadoc) * * @see * edu.utah.further.core.api.message.SeverityMessageContainer#addMessages(edu.utah * .further.core.api.message.SeverityMessageContainer) */ @Override public final void addMessages(final SeverityMessageContainer other) { chainRequest.addMessages(other); } /* * (non-Javadoc) * * @see * edu.utah.further.core.api.message.SeverityMessageContainer#getMessages(edu.utah * .further.core.api.message.Severity) */ @Override public final Set<SeverityMessage> getMessages(final Severity severity) { return chainRequest.getMessages(severity); } // ============== IMPLEMENTATION: MessageContainer=============== /* * (non-Javadoc) * * @see * edu.utah.further.core.api.message.MessageContainer#addMessage(java.lang.Object) */ @Override public final void addMessage(final SeverityMessage message) { chainRequest.addMessage(message); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.message.MessageContainer#clearMessages() */ @Override public final void clearMessages() { chainRequest.clearMessages(); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.message.MessageContainer#getAsList() */ @Override public final List<SeverityMessage> getAsList() { return chainRequest.getAsList(); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.message.MessageContainer#getSize() */ @Override public final int getSize() { return chainRequest.getSize(); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.message.MessageContainer#isEmpty() */ @Override public final boolean isEmpty() { return chainRequest.isEmpty(); } /* * (non-Javadoc) * * @see * edu.utah.further.core.api.message.MessageContainer#removeMessage(java.lang.Object) */ @Override public final void removeMessage(final SeverityMessage uuid) { chainRequest.removeMessage(uuid); } // ============== IMPLEMENTATION: Iterable ======================== /* * (non-Javadoc) * * @see java.lang.Iterable#iterator() */ @Override public final Iterator<SeverityMessage> iterator() { return chainRequest.iterator(); } // ============== IMPLEMENTATION: AttributeContainer =============== /* * chainRequest.<T> required otherwise Sun javac complains, however, Eclipse does not. * * @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954 * * @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=98379 * * (non-Javadoc) * * @see * edu.utah.further.core.api.chain.AttributeContainer#getAttribute(java.lang.String) */ @Override public final <T> T getAttribute(final String name) { return chainRequest.<T> getAttribute(name); } /** * @param <T> * @param label * @return * @see edu.utah.further.core.api.chain.AttributeContainer#getAttribute(edu.utah.further.core.api.context.Labeled) */ @Override public final <T> T getAttribute(final Labeled label) { return chainRequest.<T> getAttribute(label); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.AttributeContainer#getAttributeNames() */ @Override public final Set<String> getAttributeNames() { return chainRequest.getAttributeNames(); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.AttributeContainer#getAttributes() */ @Override public final Map<String, Object> getAttributes() { return chainRequest.getAttributes(); } /** * @param attributes * @see edu.utah.further.core.api.chain.AttributeContainer#setAttributes(java.util.Map) */ @Override public final void setAttributes(final Map<String, ?> attributes) { chainRequest.setAttributes(attributes); } /** * @param map * @see edu.utah.further.core.api.chain.AttributeContainer#addAttributes(java.util.Map) */ @Override public void addAttributes(final Map<String, ?> map) { chainRequest.addAttributes(map); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.AttributeContainer#removeAllAttributes() */ @Override public void removeAllAttributes() { chainRequest.removeAllAttributes(); } /* * (non-Javadoc) * * @see * edu.utah.further.core.api.chain.AttributeContainer#removeAttribute(java.lang.String * ) */ @Override public final void removeAttribute(final String key) { chainRequest.removeAttribute(key); } /* * (non-Javadoc) * * @see * edu.utah.further.core.api.chain.AttributeContainer#setAttribute(java.lang.String, * java.lang.Object) */ @Override public final void setAttribute(final String key, final Object value) { chainRequest.setAttribute(key, value); } /** * @param label * @param value * @see edu.utah.further.core.api.chain.AttributeContainer#setAttribute(edu.utah.further.core.api.context.Labeled, * java.lang.Object) */ @Override public final void setAttribute(final Labeled label, final Object value) { chainRequest.setAttribute(label, value); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.ChainRequest#setException(java.lang.Throwable) */ @Override public final void setException(final Throwable throwable) { // Exception handling not yet supported in QueryExecutionRequest } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.ChainRequest#getException() */ @Override public Throwable getException() { // Exception handling not yet supported in QueryExecutionRequest return null; } /** * @return * @see edu.utah.further.core.api.chain.ChainRequest#hasException() */ @Override public boolean hasException() { return getException() != null; } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.ChainRequest#cancel() */ @Override public void cancel() { throw new UnsupportedOperationException( "Canceling a QueryExecutionRequest is not supported"); } /* * (non-Javadoc) * * @see edu.utah.further.core.api.chain.ChainRequest#isCanceled() */ @Override public boolean isCanceled() { log.warn("Canceling a QueryExecutionRequest is not supported"); return false; } // ============== PRIVATE METHODS ================================= /** * @param queryContext */ private void setQueryContext(final QueryContext queryContext) { chainRequest.setAttribute(QUERY_CONTEXT, queryContext); } }
/** * 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.hive.ql.udf.generic; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.util.JavaDataModel; import org.apache.hadoop.hive.serde2.io.DoubleWritable; import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.DoubleObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; /** * Computes an approximate histogram of a numerical column using a user-specified number of bins. * * The output is an array of (x,y) pairs as Hive struct objects that represents the histogram's * bin centers and heights. */ @Description(name = "histogram_numeric", value = "_FUNC_(expr, nb) - Computes a histogram on numeric 'expr' using nb bins.", extended = "Example:\n" + "> SELECT histogram_numeric(val, 3) FROM src;\n" + "[{\"x\":100,\"y\":14.0},{\"x\":200,\"y\":22.0},{\"x\":290.5,\"y\":11.0}]\n" + "The return value is an array of (x,y) pairs representing the centers of the " + "histogram's bins. As the value of 'nb' is increased, the histogram approximation" + "gets finer-grained, but may yield artifacts around outliers. In practice, 20-40 " + "histogram bins appear to work well, with more bins being required for skewed or " + "smaller datasets. Note that this function creates a histogram with non-uniform " + "bin widths. It offers no guarantees in terms of the mean-squared-error of the " + "histogram, but in practice is comparable to the histograms produced by the R/S-Plus" + "statistical computing packages.") public class GenericUDAFHistogramNumeric extends AbstractGenericUDAFResolver { // class static variables static final Logger LOG = LoggerFactory.getLogger(GenericUDAFHistogramNumeric.class.getName()); @Override public GenericUDAFEvaluator getEvaluator(TypeInfo[] parameters) throws SemanticException { if (parameters.length != 2) { throw new UDFArgumentTypeException(parameters.length - 1, "Please specify exactly two arguments."); } // validate the first parameter, which is the expression to compute over if (parameters[0].getCategory() != ObjectInspector.Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "Only primitive type arguments are accepted but " + parameters[0].getTypeName() + " was passed as parameter 1."); } switch (((PrimitiveTypeInfo) parameters[0]).getPrimitiveCategory()) { case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: case TIMESTAMP: case DECIMAL: break; case STRING: case BOOLEAN: case DATE: default: throw new UDFArgumentTypeException(0, "Only numeric type arguments are accepted but " + parameters[0].getTypeName() + " was passed as parameter 1."); } // validate the second parameter, which is the number of histogram bins if (parameters[1].getCategory() != ObjectInspector.Category.PRIMITIVE) { throw new UDFArgumentTypeException(1, "Only primitive type arguments are accepted but " + parameters[1].getTypeName() + " was passed as parameter 2."); } if( ((PrimitiveTypeInfo) parameters[1]).getPrimitiveCategory() != PrimitiveObjectInspector.PrimitiveCategory.INT) { throw new UDFArgumentTypeException(1, "Only an integer argument is accepted as parameter 2, but " + parameters[1].getTypeName() + " was passed instead."); } return new GenericUDAFHistogramNumericEvaluator(); } /** * Construct a histogram using an algorithm described by Ben-Haim and Tom-Tov. * * The algorithm is a heuristic adapted from the following paper: * Yael Ben-Haim and Elad Tom-Tov, "A streaming parallel decision tree algorithm", * J. Machine Learning Research 11 (2010), pp. 849--872. Although there are no approximation * guarantees, it appears to work well with adequate data and a large (e.g., 20-80) number * of histogram bins. */ public static class GenericUDAFHistogramNumericEvaluator extends GenericUDAFEvaluator { // For PARTIAL1 and COMPLETE: ObjectInspectors for original data private PrimitiveObjectInspector inputOI; private transient PrimitiveObjectInspector nbinsOI; // For PARTIAL2 and FINAL: ObjectInspectors for partial aggregations (list of doubles) private transient ListObjectInspector loi; @Override public ObjectInspector init(Mode m, ObjectInspector[] parameters) throws HiveException { super.init(m, parameters); // init input object inspectors if (m == Mode.PARTIAL1 || m == Mode.COMPLETE) { assert(parameters.length == 2); inputOI = (PrimitiveObjectInspector) parameters[0]; nbinsOI = (PrimitiveObjectInspector) parameters[1]; } else { loi = (ListObjectInspector) parameters[0]; } // init output object inspectors if (m == Mode.PARTIAL1 || m == Mode.PARTIAL2) { // The output of a partial aggregation is a list of doubles representing the // histogram being constructed. The first element in the list is the user-specified // number of bins in the histogram, and the histogram itself is represented as (x,y) // pairs following the first element, so the list length should *always* be odd. return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } else { // The output of FINAL and COMPLETE is a full aggregation, which is a // list of DoubleWritable structs that represent the final histogram as // (x,y) pairs of bin centers and heights. ArrayList<ObjectInspector> foi = new ArrayList<ObjectInspector>(); foi.add(PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); foi.add(PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); ArrayList<String> fname = new ArrayList<String>(); fname.add("x"); fname.add("y"); return ObjectInspectorFactory.getStandardListObjectInspector( ObjectInspectorFactory.getStandardStructObjectInspector(fname, foi) ); } } @Override public Object terminatePartial(AggregationBuffer agg) throws HiveException { // Return a single ArrayList where the first element is the number of histogram bins, // and subsequent elements represent histogram (x,y) pairs. StdAgg myagg = (StdAgg) agg; return myagg.histogram.serialize(); } @Override public Object terminate(AggregationBuffer agg) throws HiveException { StdAgg myagg = (StdAgg) agg; if (myagg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { ArrayList<DoubleWritable[]> result = new ArrayList<DoubleWritable[]>(); for(int i = 0; i < myagg.histogram.getUsedBins(); i++) { DoubleWritable[] bin = new DoubleWritable[2]; bin[0] = new DoubleWritable(myagg.histogram.getBin(i).x); bin[1] = new DoubleWritable(myagg.histogram.getBin(i).y); result.add(bin); } return result; } } @Override public void merge(AggregationBuffer agg, Object partial) throws HiveException { if(partial == null) { return; } List<DoubleWritable> partialHistogram = (List<DoubleWritable>) loi.getList(partial); DoubleObjectInspector doi = (DoubleObjectInspector)loi.getListElementObjectInspector(); StdAgg myagg = (StdAgg) agg; myagg.histogram.merge(partialHistogram, doi); } @Override public void iterate(AggregationBuffer agg, Object[] parameters) throws HiveException { assert (parameters.length == 2); if(parameters[0] == null || parameters[1] == null) { return; } StdAgg myagg = (StdAgg) agg; // Parse out the number of histogram bins only once, if we haven't already done // so before. We need at least 2 bins; otherwise, there is no point in creating // a histogram. if(!myagg.histogram.isReady()) { int nbins = PrimitiveObjectInspectorUtils.getInt(parameters[1], nbinsOI); if(nbins < 2) { throw new HiveException(getClass().getSimpleName() + " needs nbins to be at least 2," + " but you supplied " + nbins + "."); } // allocate memory for the histogram bins myagg.histogram.allocate(nbins); } // Process the current data point double v = PrimitiveObjectInspectorUtils.getDouble(parameters[0], inputOI); myagg.histogram.add(v); } // Aggregation buffer definition and manipulation methods @AggregationType(estimable = true) static class StdAgg extends AbstractAggregationBuffer { NumericHistogram histogram; // the histogram object @Override public int estimate() { return histogram.lengthFor(JavaDataModel.get()); } }; @Override public AggregationBuffer getNewAggregationBuffer() throws HiveException { StdAgg result = new StdAgg(); reset(result); return result; } @Override public void reset(AggregationBuffer agg) throws HiveException { StdAgg myagg = (StdAgg) agg; myagg.histogram = new NumericHistogram(); myagg.histogram.reset(); } } }
package org.tolweb.treegrow.page; import java.io.*; import java.util.*; import org.tolweb.treegrow.main.*; /** * AccessoryPage holds the data for an accessory page */ public class AccessoryPage extends OrderedObject implements Comparable, Serializable, AuxiliaryChangedFromServerProvider { /** * */ private static final long serialVersionUID = -3367444982771396618L; public static final byte RESTRICTED_USE = 0; public static final byte TOL_USE = 1; public static final byte EVERYWHERE_USE = 2; private static ArrayList legalStatuses ; private SortedSet internetLinks; private int contributorId; private boolean isArticle; /** * Used for permission awareness on the client-side (cached from the server-provided info) */ private boolean isEditable; /** * Holds the list of authors and thier details */ private Vector contributorList = null; /** * Holds the menu for this accessory page */ private String menu = null; /** * Holds the menu for this accessory page as it exists on the server * (will differ from "menu" if menu has changed or if this acc_page * is a new one). Updated after each upload */ private String menuOnServer = null; /** * Holds the page title for this accessory page */ private String pageTitle = null; /** * Holds the copyright information for this accessory page */ private String copyright = null; /** * Holds the author information for this accessory page */ private String authors = null; /** * Holds the text information for this accessory page */ private String text = null; /** * Holds the references for this accessory page */ private String references = null; /** * Holds the page status of the accessory page */ private String status = null; /** * Determines whether to use the linkedAccessoryPageID or the the * data entered for the given accessory page. */ private boolean useContent; /** * Whether the accessory page actually shows up on the menu */ private boolean showOnMenu; /** * Holds the order in which the menu of this accessory page is displayed */ private int order ; /** * Holds information as to whether the details of this accessory page has been changed or not. * true - change has been made. * false - no change has been made. */ private boolean changed = false; /** * Additional boolean to check whether the actual text of the accessory * page has changed. This is needed in order to determine whether we * send up the text to the server (because it could possibly be a lot * of text and could seriously affect upload times. */ private boolean textChanged; /** * Additional boolean to check whether the references of the accessory * page has changed. Same idea as textChanged */ private boolean referencesChanged; private Page page; private String copyrightYear; private String acknowledgements; private String notes; /** * The id for an accessory page owned by some other page. This is used * when one accessory page is linked to by multiple branch pages. The * root-most page gets ownership of the accessory page, and others point * down the tree to that page's acc_page */ private AccessoryPage linkedAccessoryPage; /** * Same as above but in this case it isn't an actual accessory page * object since it is pointing to something that wasn't downloaded in * current tree. */ private Ancestor.AncestorAccPage linkedAncestorAccessoryPage; private byte usePermission; private int id = -1; private boolean isSubmitted; private boolean isTreehouse; static { legalStatuses = new ArrayList( Arrays.asList( new String[] { XMLConstants.SKELETAL, XMLConstants.UNDER_CONSTRUCTION, XMLConstants.COMPLETE, XMLConstants.PEER_REVIEWED}) ); } public AccessoryPage() { } /** * Sets the values of this object to be equal to the AccessoryPage passed-in * @param other The other accessory page to copy the values from */ public void copyValues(AccessoryPage other) { setNotes(other.getNotes()); setAcknowledgements(other.getAcknowledgements()); setCopyright(other.getCopyright()); setIsSubmitted(other.getIsSubmitted()); setIsTreehouse(other.getIsTreehouse()); setUsePermission(other.getUsePermission()); setPageTitle(other.getPageTitle()); setMenu(other.getMenu()); setReferences(other.getReferences()); setStatus(other.getStatus()); setContributorId(other.getContributorId()); setCopyrightYear(other.getCopyrightYear()); setText(other.getText()); SortedSet links = new TreeSet(); Iterator it = other.getInternetLinks().iterator(); while (it.hasNext()) { InternetLink link = (InternetLink) it.next(); links.add(link.clone()); } setInternetLinks(links); } /** * empty constructor. */ public AccessoryPage(Page p) { contributorList = new Vector(); page = p; menu = "<< New Accessory Page >>"; status = XMLConstants.SKELETAL; useContent = true; } public Page getPage() { return page; } public void setIsSubmitted(boolean value) { isSubmitted = value; } /** * @hibernate.property column="is_submitted" * @return */ public boolean getIsSubmitted() { return isSubmitted; } public void setIsTreehouse(boolean value) { isTreehouse = value; } /** * @hibernate.property column="is_treehouse" * @return */ public boolean getIsTreehouse() { return isTreehouse; } /** * gets the menu heading of this accessory page * * @hibernate.property * * @return menu heading of this accessory page */ public String getMenu(){ if (useContent()) { return menu; } else { if (linkedAccessoryPage != null) { return linkedAccessoryPage.getMenu(); } else if (linkedAncestorAccessoryPage != null) { return linkedAncestorAccessoryPage.getMenu(); } else { return menu; } } } /** * sets the menu heading of this accessory page * * @param value menu heading for this accessory page */ public void setMenu(String value){ menu = value; } /** * gets the menu heading of this accessory page, as it exists on the * server * * @return server's menu heading of this accessory page */ public String getMenuOnServer(){ return menuOnServer; } /** * sets the menu heading of this accessory page, as it exists on the * server * * @param server's menu heading for this accessory page */ public void setMenuOnServer(String value){ menuOnServer = value; } /** * gets the page title of this accessory page * @hibernate.property column="page_title" * @return page title of this accessory page */ public String getPageTitle(){ return pageTitle; } /** * sets the page title of this accessory page * * @param value page title for this accessory page * @return */ public void setPageTitle(String value) { pageTitle = value; } /** * gets the copyright information of this accessory page * @hibernate.property column="page_copyrightholder" * @param * @return copyright information of this accessory page */ public String getCopyright(){ return copyright; } /** * sets the copyright information of this accessory page * * @param value copyright information for this accessory page * @return */ public void setCopyright(String value){ copyright = value; } public void setCopyrightYear(String value) { copyrightYear = value; } /** * @hibernate.property column="page_copyrightdate" * @return */ public String getCopyrightYear() { return copyrightYear; } /** * gets the author information of this accessory page * * @param * @return author information of this accessory page */ public String getAuthor(){ return authors; } /** * sets the author information of this accessory page * * @param value author information for this accessory page * @return */ public void setAuthor(String value) { authors = value; } /** * gets the text of this accessory page * * @hibernate.property column="main_text" * @return text of this accessory page */ public String getText() { return text; } /** * sets the text of this accessory page * * @param value text of this accessory page */ public void setText(String value) { text = value; } /** * gets the reference information of this accessory page * * @hibernate.property column="refs" * @return reference information of this accessory page */ public String getReferences() { return references; } /** * sets the reference information of this accessory page * * @param value reference information for this accessory page * @return */ public void setReferences(String value) { references = value; } /** * Returns the separate changed value for the references. This is * maintained separately because the references don't get uploaded * unless they have changed from the server * * @return Whether the references have been changed from the server */ public boolean referencesChanged() { return referencesChanged; } public void setReferencesChanged(boolean value) { referencesChanged = value; } /** * gets the page status of this accessory page * * @hibernate.property * @return page status of this accessory page */ public String getStatus(){ return status; } /** * sets the page status of this accessory page * * @param value page status of this accessory page * @return */ public void setStatus(String value) { status = value; if ( !legalStatuses.contains(status) ) { status = XMLConstants.SKELETAL; } } /** * Returns the linked accessory page. This will be null unless this * accessory page links to another one in the currently downloaded tree * * @return The linked accessory page */ public AccessoryPage getLinkedAccPage() { return linkedAccessoryPage; } public void setLinkedAccPage(AccessoryPage page) { linkedAccessoryPage = page; } /** * Returns the linked ancestor accessory page. This will be null unless * the accessory page links to another one not in the currently * downloaded tree * * @return The linked accessory page */ public Ancestor.AncestorAccPage getLinkedAncestorAccPage() { return linkedAncestorAccessoryPage; } public void setLinkedAncestorAccPage(Ancestor.AncestorAccPage value) { linkedAncestorAccessoryPage = value; } /** * Returns a boolean indicating whether this accessory page has its own * content or whether it links to another page * * @return A boolean indicating whether content is used */ public boolean useContent() { return useContent; } public void setUseContent(boolean value) { useContent = value; } /** * @hibernate.property column="use_content" * @return */ public boolean getUseContent() { return useContent(); } public boolean showOnMenu() { return showOnMenu; } public void setShowOnMenu(boolean value) { showOnMenu = value; } /** * gets the author information for this page as a vector of Author Objects. * * @param * @return the author information for this page */ public Vector getContributorList() { return contributorList; } public void setContributorList(Vector value) { contributorList = value; } /** * @hibernate.set table="InternetLinks" lazy="false" order-by="link_order asc" sort="natural" cascade="all" * @hibernate.collection-composite-element class="org.tolweb.treegrow.page.InternetLink" * @hibernate.collection-key column="acc_page_id" * @hibernate.collection-cache usage="nonstrict-read-write" */ public SortedSet getInternetLinks() { if (internetLinks == null) { internetLinks = new TreeSet(); } return internetLinks; } public void setInternetLinks(SortedSet value) { internetLinks = value; } public void addToInternetLinks(InternetLink value) { value.setOrder(getInternetLinks().size()); getInternetLinks().add(value); } public void removeFromInternetLinks(InternetLink value) { getInternetLinks().remove(value); } public boolean getHasInternetLinks() { Iterator it = getInternetLinks().iterator(); while (it.hasNext()) { InternetLink link = (InternetLink) it.next(); if (StringUtils.notEmpty(link.getUrl())) { return true; } } return false; } public boolean getHasReferences() { return StringUtils.notEmpty(getReferences()); } /** * Returns the id of the contributor who actually created this AccessoryPage * @hibernate.property column="contributor_id" * @return */ public int getContributorId() { return contributorId; } public void setContributorId(int value) { contributorId = value; } public void setUsePermission(byte value) { usePermission = value; } /** * @hibernate.property column="use_permission" * @return */ public byte getUsePermission() { return usePermission; } public int getId() { return id; } public void setId(int value) { id = value; } /** * Returns whether the page object that this accessory page is * attached to thinks that any of its accessory pages have changed * * @return Whether any of the pages accs have changed */ public boolean auxiliaryChangedFromServer() { return page.getAccessoriesChanged(); } /** * Sets the page object's accessorieschanged variable * * @param new value for the page object's accessorieschanged */ public void setAuxiliaryChangedFromServer(boolean value) { page.setAccessoriesChanged(value); } /** * Returns whether or not anything has changed on the accessory page * * @return Whether or not anything has changed on the accessory page */ public boolean changedFromServer() { return changed; } public void setChangedFromServer(boolean value) { changed = value; if (!value) { textChanged = false; referencesChanged = false; } } /** * Returns whether or not the text has changed. This is maintained * separately since text sections don't get sent up to the server * unless they change * * @return Whether or not the page text has changed */ public boolean textChanged() { return textChanged; } public void setTextChanged(boolean value) { textChanged = value; } /** * @hibernate.property */ public String getAcknowledgements() { return acknowledgements; } public void setAcknowledgements(String value) { acknowledgements = value; } /** * @hibernate.property * @return */ public String getNotes() { return notes; } public void setNotes(String value) { notes = value; } /** * @hibernate.property column="is_article" * @return */ public boolean getIsArticle() { return isArticle; } public void setIsArticle(boolean isArticle) { this.isArticle = isArticle; } /** * @return Returns the isEditable. */ public boolean getIsEditable() { return isEditable; } /** * @param isEditable The isEditable to set. */ public void setIsEditable(boolean isEditable) { this.isEditable = isEditable; } }
package com.ext.portlet.epsos.consent; import gnomon.util.GnPropsUtil; import java.util.Vector; import javax.portlet.PortletRequest; import javax.portlet.RenderRequest; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.ext.portlet.epsos.EpsosHelperService; import com.ext.portlet.epsos.demo.PatientSearchForm; import com.ext.sql.StrutsFormFields; import com.ext.util.CommonDefs; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portlet.ActionRequestImpl; import com.liferay.portlet.RenderRequestImpl; public class PatientConsentForm extends org.apache.struts.validator.ValidatorForm { private static final long serialVersionUID = 1L; public String consentid; public String patID; public String country; public String[] countryIds; public String[] countryNames; public String creationDate; public String validFrom; public String validTo; public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = super.validate(mapping,request); return errors; } public final void prepareFormFields(PortletRequest request) { if (request instanceof RenderRequest) this.prepareFormFields(((RenderRequestImpl)request).getHttpServletRequest()); else this.prepareFormFields(((ActionRequestImpl)request).getHttpServletRequest()); } public void prepareFormFields(HttpServletRequest request) { //this.countryIds = GetterUtil.getString(GnPropsUtil.get("portalb", "epsos.search.countries.supported"), "GR,UK").split(","); //this.countryNames = GetterUtil.getString(GnPropsUtil.get("portalb", "epsos.search.countries.supported"), "GR,UK").split(","); this.countryIds = EpsosHelperService.getInstance().getCountriesFromCS().split(","); this.countryNames = EpsosHelperService.getInstance().getCountriesFromCS().split(","); StrutsFormFields new_field=null; Vector<StrutsFormFields> fields = new Vector<StrutsFormFields>(); String loadaction = request.getParameter("loadaction"); boolean readOnly = false; if (loadaction == null || loadaction.equals("view") || loadaction.equals("delete")) readOnly = true; new_field = new StrutsFormFields("country","epsos.consent.country","select",false, readOnly); new_field.setCollectionProperty("countryIds"); new_field.setCollectionLabel("countryNames"); new_field.setOnChange("countrySelectionChanged()"); fields.addElement(new_field); fields.addElement(new StrutsFormFields("consentid","consentid","text",true,true)); fields.addElement(new StrutsFormFields("patID","patID","text",true,true)); fields.addElement(new StrutsFormFields("creationDate","epsos.consent.creationDate","text",false,true)); fields.addElement(new StrutsFormFields("validFrom","epsos.consent.validFrom","date",false, readOnly, true)); fields.addElement(new StrutsFormFields("validTo","epsos.consent.validTo","date",false, readOnly, true)); request.setAttribute(CommonDefs.ATTR_FORM_FIELDS, fields); } public void reset(ActionMapping mapping, HttpServletRequest request) { this.clear(); } public void clear() { // this.date1 = null; } public String getConsentid() { return consentid; } public void setConsentid(String consentid) { this.consentid = consentid; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String[] getCountryIds() { return countryIds; } public void setCountryIds(String[] countryIds) { this.countryIds = countryIds; } public String[] getCountryNames() { return countryNames; } public void setCountryNames(String[] countryNames) { this.countryNames = countryNames; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getValidFrom() { return validFrom; } public void setValidFrom(String validFrom) { this.validFrom = validFrom; } public String getValidTo() { return validTo; } public void setValidTo(String validTo) { this.validTo = validTo; } public void populateFormFromObject(PatientConsentObject obj) { this.consentid = obj.getConsentid(); this.patID = obj.getPatientId(); this.country = obj.getCountry(); if (obj.getCreationDate() != null) this.creationDate = EpsosHelperService.dateTimeFormat.format(obj.getCreationDate()); if (obj.getValidFrom() != null) this.validFrom = EpsosHelperService.dateFormat.format(obj.getValidFrom()); if (obj.getValidTo() != null) this.validTo = EpsosHelperService.dateFormat.format(obj.getValidTo()); } public void populateObjectFromForm(PatientConsentObject obj) { obj.setConsentid(this.consentid); obj.setPatientId(this.patID); obj.setCountry(this.country); try { obj.setCreationDate(EpsosHelperService.dateTimeFormat.parse(this.creationDate)); } catch (Exception e1) {} try { obj.setValidFrom(EpsosHelperService.dateFormat.parse(this.validFrom)); } catch (Exception e1) {} try { obj.setValidTo(EpsosHelperService.dateFormat.parse(this.validTo)); } catch (Exception e1) {} } public String getPatID() { return patID; } public void setPatID(String patID) { this.patID = patID; } }
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.project; import com.google.common.collect.Iterables; import com.google.gerrit.common.data.AccessSection; import com.google.gerrit.common.data.GlobalCapability; import com.google.gerrit.common.data.GroupDescription; import com.google.gerrit.common.data.GroupReference; import com.google.gerrit.common.data.Permission; import com.google.gerrit.common.data.PermissionRule; import com.google.gerrit.common.errors.InvalidNameException; import com.google.gerrit.extensions.api.access.AccessSectionInfo; import com.google.gerrit.extensions.api.access.PermissionInfo; import com.google.gerrit.extensions.api.access.PermissionRuleInfo; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.config.AllUsersName; import com.google.gerrit.server.git.ProjectConfig; import com.google.gerrit.server.group.GroupsCollection; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @Singleton public class SetAccessUtil { private final GroupsCollection groupsCollection; private final AllProjectsName allProjects; private final AllUsersName allUsers; private final Provider<SetParent> setParent; @Inject private SetAccessUtil( GroupsCollection groupsCollection, AllProjectsName allProjects, AllUsersName allUsers, Provider<SetParent> setParent) { this.groupsCollection = groupsCollection; this.allProjects = allProjects; this.allUsers = allUsers; this.setParent = setParent; } List<AccessSection> getAccessSections(Map<String, AccessSectionInfo> sectionInfos) throws UnprocessableEntityException { if (sectionInfos == null) { return Collections.emptyList(); } List<AccessSection> sections = new ArrayList<>(sectionInfos.size()); for (Map.Entry<String, AccessSectionInfo> entry : sectionInfos.entrySet()) { if (entry.getValue().permissions == null) { continue; } AccessSection accessSection = new AccessSection(entry.getKey()); for (Map.Entry<String, PermissionInfo> permissionEntry : entry.getValue().permissions.entrySet()) { if (permissionEntry.getValue().rules == null) { continue; } Permission p = new Permission(permissionEntry.getKey()); if (permissionEntry.getValue().exclusive != null) { p.setExclusiveGroup(permissionEntry.getValue().exclusive); } for (Map.Entry<String, PermissionRuleInfo> permissionRuleInfoEntry : permissionEntry.getValue().rules.entrySet()) { GroupDescription.Basic group = groupsCollection.parseId(permissionRuleInfoEntry.getKey()); if (group == null) { throw new UnprocessableEntityException( permissionRuleInfoEntry.getKey() + " is not a valid group ID"); } PermissionRuleInfo pri = permissionRuleInfoEntry.getValue(); PermissionRule r = new PermissionRule(GroupReference.forGroup(group)); if (pri != null) { if (pri.max != null) { r.setMax(pri.max); } if (pri.min != null) { r.setMin(pri.min); } r.setAction(GetAccess.ACTION_TYPE.inverse().get(pri.action)); if (pri.force != null) { r.setForce(pri.force); } } p.add(r); } accessSection.getPermissions().add(p); } sections.add(accessSection); } return sections; } /** * Checks that the removals and additions are logically valid, but doesn't check current user's * permission. In addition, checks that no Gerrit-managed permissions are added or removed. */ void validateChanges( ProjectConfig config, List<AccessSection> removals, List<AccessSection> additions) throws BadRequestException, InvalidNameException { // Perform permission checks for (AccessSection section : Iterables.concat(additions, removals)) { boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(section.getName()); if (isGlobalCapabilities) { if (!allProjects.equals(config.getName())) { throw new BadRequestException( "Cannot edit global capabilities for projects other than " + allProjects.get()); } } if (isGroupsMutationDisallowed(config.getName()) && section.getName().startsWith(RefNames.REFS_GROUPS)) { throw new BadRequestException( String.format( "permissions on %s are managed by gerrit and cannot be modified", RefNames.REFS_GROUPS)); } } // Perform addition checks for (AccessSection section : additions) { String name = section.getName(); boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(name); if (!isGlobalCapabilities) { if (!AccessSection.isValid(name)) { throw new BadRequestException("invalid section name"); } RefPattern.validate(name); } else { // Check all permissions for soundness for (Permission p : section.getPermissions()) { if (!GlobalCapability.isCapability(p.getName())) { throw new BadRequestException( "Cannot add non-global capability " + p.getName() + " to global capabilities"); } } } } } void applyChanges( ProjectConfig config, List<AccessSection> removals, List<AccessSection> additions) { // Apply removals for (AccessSection section : removals) { if (section.getPermissions().isEmpty()) { // Remove entire section config.remove(config.getAccessSection(section.getName())); continue; } // Remove specific permissions for (Permission p : section.getPermissions()) { if (p.getRules().isEmpty()) { config.remove(config.getAccessSection(section.getName()), p); } else { for (PermissionRule r : p.getRules()) { config.remove(config.getAccessSection(section.getName()), p, r); } } } } // Apply additions for (AccessSection section : additions) { AccessSection currentAccessSection = config.getAccessSection(section.getName()); if (currentAccessSection == null) { // Add AccessSection config.replace(section); } else { for (Permission p : section.getPermissions()) { Permission currentPermission = currentAccessSection.getPermission(p.getName()); if (currentPermission == null) { // Add Permission currentAccessSection.addPermission(p); } else { for (PermissionRule r : p.getRules()) { // AddPermissionRule currentPermission.add(r); } } } } } } public void setParentName( IdentifiedUser identifiedUser, ProjectConfig config, Project.NameKey projectName, Project.NameKey newParentProjectName, boolean checkAdmin) throws ResourceConflictException, AuthException, PermissionBackendException, BadRequestException { if (newParentProjectName != null && !config.getProject().getNameKey().equals(allProjects) && !config.getProject().getParent(allProjects).equals(newParentProjectName)) { try { setParent .get() .validateParentUpdate( projectName, identifiedUser, newParentProjectName.get(), checkAdmin); } catch (UnprocessableEntityException e) { throw new ResourceConflictException(e.getMessage(), e); } config.getProject().setParentName(newParentProjectName); } } private boolean isGroupsMutationDisallowed(Project.NameKey project) { return allProjects.equals(project) || allUsers.equals(project); } }
/* Copyright (C) 2016 Electronic Arts Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of Electronic Arts, Inc. ("EA") 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 ELECTRONIC ARTS AND ITS 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 ELECTRONIC ARTS OR ITS 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 cloud.orbit.actors; import com.ea.async.Async; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cloud.orbit.actors.annotation.StatelessWorker; import cloud.orbit.actors.annotation.StorageExtension; import cloud.orbit.actors.cloner.ExecutionObjectCloner; import cloud.orbit.actors.cluster.ClusterPeer; import cloud.orbit.actors.cluster.NodeAddress; import cloud.orbit.actors.concurrent.MultiExecutionSerializer; import cloud.orbit.actors.concurrent.WaitFreeMultiExecutionSerializer; import cloud.orbit.actors.extensions.ActorClassFinder; import cloud.orbit.actors.extensions.ActorConstructionExtension; import cloud.orbit.actors.extensions.ActorDeactivationExtension; import cloud.orbit.actors.extensions.ActorExtension; import cloud.orbit.actors.extensions.DefaultLoggerExtension; import cloud.orbit.actors.extensions.LifetimeExtension; import cloud.orbit.actors.extensions.LoggerExtension; import cloud.orbit.actors.extensions.MessageSerializer; import cloud.orbit.actors.extensions.NodeSelectorExtension; import cloud.orbit.actors.extensions.PipelineExtension; import cloud.orbit.actors.extensions.ResponseCachingExtension; import cloud.orbit.actors.extensions.StreamProvider; import cloud.orbit.actors.net.DefaultPipeline; import cloud.orbit.actors.net.Pipeline; import cloud.orbit.actors.runtime.AbstractActor; import cloud.orbit.actors.runtime.ActorBaseEntry; import cloud.orbit.actors.runtime.ActorEntry; import cloud.orbit.actors.runtime.ActorRuntime; import cloud.orbit.actors.runtime.ActorTaskContext; import cloud.orbit.actors.runtime.AsyncStreamReference; import cloud.orbit.actors.runtime.BasicRuntime; import cloud.orbit.actors.runtime.ClusterHandler; import cloud.orbit.actors.runtime.DefaultActorConstructionExtension; import cloud.orbit.actors.runtime.DefaultDescriptorFactory; import cloud.orbit.actors.runtime.DefaultHandlers; import cloud.orbit.actors.runtime.DefaultInvocationHandler; import cloud.orbit.actors.runtime.DefaultLifetimeExtension; import cloud.orbit.actors.runtime.DefaultLocalObjectsCleaner; import cloud.orbit.actors.runtime.Execution; import cloud.orbit.actors.runtime.FastActorClassFinder; import cloud.orbit.actors.runtime.Hosting; import cloud.orbit.actors.runtime.InternalUtils; import cloud.orbit.actors.runtime.Invocation; import cloud.orbit.actors.runtime.InvocationHandler; import cloud.orbit.actors.runtime.KryoSerializer; import cloud.orbit.actors.runtime.LazyActorClassFinder; import cloud.orbit.actors.runtime.LocalObjects; import cloud.orbit.actors.runtime.LocalObjectsCleaner; import cloud.orbit.actors.runtime.MessageLoopback; import cloud.orbit.actors.runtime.Messaging; import cloud.orbit.actors.runtime.NodeCapabilities; import cloud.orbit.actors.runtime.ObserverEntry; import cloud.orbit.actors.runtime.RandomSelectorExtension; import cloud.orbit.actors.runtime.Registration; import cloud.orbit.actors.runtime.ReminderController; import cloud.orbit.actors.runtime.RemoteReference; import cloud.orbit.actors.runtime.DefaultResponseCachingExtension; import cloud.orbit.actors.runtime.RuntimeActions; import cloud.orbit.actors.runtime.SerializationHandler; import cloud.orbit.actors.runtime.ShardedReminderController; import cloud.orbit.actors.runtime.StatelessActorEntry; import cloud.orbit.actors.streams.AsyncObserver; import cloud.orbit.actors.streams.AsyncStream; import cloud.orbit.actors.streams.StreamSequenceToken; import cloud.orbit.actors.streams.StreamSubscriptionHandle; import cloud.orbit.actors.streams.simple.SimpleStreamExtension; import cloud.orbit.actors.util.IdUtils; import cloud.orbit.annotation.Config; import cloud.orbit.concurrent.ExecutorUtils; import cloud.orbit.concurrent.Task; import cloud.orbit.exception.UncheckedException; import cloud.orbit.lifecycle.Startable; import cloud.orbit.util.StringUtils; import javax.inject.Singleton; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.time.Clock; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import static com.ea.async.Async.await; @Singleton public class Stage implements Startable, ActorRuntime, RuntimeActions { private Logger logger = LoggerFactory.getLogger(Stage.class); private static final int DEFAULT_EXECUTION_POOL_SIZE = 32; private static final int DEFAULT_LOCAL_ADDRESS_CACHE_MAXIMUM_SIZE = 10_000; private final String runtimeIdentity = "Orbit[" + IdUtils.urlSafeString(128) + "]"; private final WeakReference<ActorRuntime> cachedRef = new WeakReference<>(this); private final LocalObjects objects = new LocalObjects() { @Override protected <T> LocalObjectEntry createLocalObjectEntry(final RemoteReference<T> reference, final T object) { return Stage.this.createLocalObjectEntry(reference, object); } }; private final Executor shutdownExecutor = Executors.newSingleThreadExecutor(runnable -> { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setName("OrbitShutdownThread"); thread.setDaemon(true); return thread; }); @Config("orbit.actors.clusterName") private String clusterName; @Config("orbit.actors.placementGroup") private String placementGroup; @Config("orbit.actors.nodeName") private String nodeName; @Config("orbit.actors.stageMode") private StageMode mode = StageMode.HOST; @Config("orbit.actors.executionPoolSize") private int executionPoolSize = DEFAULT_EXECUTION_POOL_SIZE; @Config("orbit.actors.localAddressCacheMaximumSize") private int localAddressCacheMaximumSize = DEFAULT_LOCAL_ADDRESS_CACHE_MAXIMUM_SIZE; @Config("orbit.actors.extensions") private List<ActorExtension> extensions = new CopyOnWriteArrayList<>(); @Config("orbit.actors.stickyHeaders") private Set<String> stickyHeaders = new HashSet<>(); @Config("orbit.actors.basePackages") private List<String> basePackages = new ArrayList<>(); @Config("orbit.actors.pulseInterval") private long pulseIntervalMillis = TimeUnit.SECONDS.toMillis(10); @Config("orbit.actors.concurrentDeactivations") private int concurrentDeactivations = 16; @Config("orbit.actors.defaultActorTTL") private long defaultActorTTL = TimeUnit.MINUTES.toMillis(10); @Config("orbit.actors.deactivationTimeoutMillis") private long deactivationTimeoutMillis = TimeUnit.SECONDS.toMillis(10); @Config("orbit.actors.localAddressCacheTTL") private long localAddressCacheTTL = defaultActorTTL + deactivationTimeoutMillis; @Config("orbit.actors.numReminderControllers") private int numReminderControllers = 1; @Config("orbit.actors.broadcastActorDeactivations") private boolean broadcastActorDeactivations = true; private boolean enableMessageLoopback = true; private volatile NodeCapabilities.NodeState state; private ClusterPeer clusterPeer; private Messaging messaging; private InvocationHandler invocationHandler; private Execution execution; private Hosting hosting; private boolean startCalled; private Clock clock; private ExecutorService executionPool; private ExecutionObjectCloner objectCloner; private ExecutionObjectCloner messageLoopbackObjectCloner; private MessageSerializer messageSerializer; private LocalObjectsCleaner localObjectsCleaner; private MultiExecutionSerializer<Object> executionSerializer; private ActorClassFinder finder; private LoggerExtension loggerExtension; private Timer timer; private Pipeline pipeline; private final Task<Void> startPromise = new Task<>(); private Thread shutdownHook = null; private final Object shutdownLock = new Object(); public enum StageMode { CLIENT, // no activations HOST // allows activations } static { // this is here to help people testing the orbit source code. // because Async.init is removed by the build time bytecode instrumentation. Async.init(); } public static class Builder { private Clock clock; private ExecutorService executionPool; private ExecutionObjectCloner objectCloner; private ExecutionObjectCloner messageLoopbackObjectCloner; private MessageSerializer messageSerializer; private ClusterPeer clusterPeer; private Messaging messaging; private InvocationHandler invocationHandler; private Execution execution; private LocalObjectsCleaner localObjectsCleaner; private String clusterName; private String placementGroup; private String nodeName; private StageMode mode = StageMode.HOST; private int executionPoolSize = DEFAULT_EXECUTION_POOL_SIZE; private int localAddressCacheMaximumSize = DEFAULT_LOCAL_ADDRESS_CACHE_MAXIMUM_SIZE; private List<ActorExtension> extensions = new ArrayList<>(); private Set<String> stickyHeaders = new HashSet<>(); private List<String> basePackages = new ArrayList<>(); private Long actorTTLMillis = null; private Long localAddressCacheTTLMillis = null; private Integer numReminderControllers = null; private Boolean broadcastActorDeactivations = null; private Long deactivationTimeoutMillis; private Integer concurrentDeactivations; private Boolean enableShutdownHook = null; private Boolean enableMessageLoopback; private Timer timer; public Builder clock(Clock clock) { this.clock = clock; return this; } public Builder enableMessageLoopback(Boolean enableMessageLoopback) { this.enableMessageLoopback = enableMessageLoopback; return this; } public Builder executionPool(ExecutorService executionPool) { this.executionPool = executionPool; return this; } public Builder executionPoolSize(int executionPoolSize) { this.executionPoolSize = executionPoolSize; return this; } public Builder localAddressCacheMaximumSize(int localAddressCacheMaximumSize) { this.localAddressCacheMaximumSize = localAddressCacheMaximumSize; return this; } public Builder execution(Execution execution) { this.execution = execution; return this; } public Builder localObjectsCleaner(LocalObjectsCleaner localObjectsCleaner) { this.localObjectsCleaner = localObjectsCleaner; return this; } public Builder clusterPeer(ClusterPeer clusterPeer) { this.clusterPeer = clusterPeer; return this; } public Builder objectCloner(ExecutionObjectCloner objectCloner) { this.objectCloner = objectCloner; return this; } public Builder messageSerializer(MessageSerializer messageSerializer) { this.messageSerializer = messageSerializer; return this; } public Builder messageLoopbackObjectCloner(ExecutionObjectCloner messageLoopbackObjectCloner) { this.messageLoopbackObjectCloner = messageLoopbackObjectCloner; return this; } public Builder messaging(Messaging messaging) { this.messaging = messaging; return this; } public Builder invocationHandler(InvocationHandler invocationHandler) { this.invocationHandler = invocationHandler; return this; } public Builder clusterName(String clusterName) { this.clusterName = clusterName; return this; } public Builder placementGroup(String placementGroup) { this.placementGroup = placementGroup; return this; } public Builder nodeName(String nodeName) { this.nodeName = nodeName; return this; } public Builder mode(StageMode mode) { this.mode = mode; return this; } public Builder extensions(Collection<ActorExtension> extensions) { this.extensions.addAll(extensions); return this; } public Builder extensions(ActorExtension... extensions) { Collections.addAll(this.extensions, extensions); return this; } public Builder stickyHeaders(String... stickyHeaders) { Collections.addAll(this.stickyHeaders, stickyHeaders); return this; } public Builder basePackages(String... basePackages) { Collections.addAll(this.basePackages, basePackages); return this; } public Builder basePackages(Collection<String> basePackages) { this.basePackages.addAll(basePackages); return this; } public Builder timer(Timer timer) { this.timer = timer; return this; } public Builder actorTTL(final long duration, final TimeUnit timeUnit) { this.actorTTLMillis = timeUnit.toMillis(duration); return this; } public Builder localAddressCacheTTL(final long duration, final TimeUnit timeUnit) { this.localAddressCacheTTLMillis = timeUnit.toMillis(duration); return this; } public Builder numReminderControllers(final int numReminderControllers) { if(numReminderControllers < 1) { throw new IllegalArgumentException("Must specify at least 1 reminder controller"); } this.numReminderControllers = numReminderControllers; return this; } public Builder deactivationTimeout(final long duration, final TimeUnit timeUnit) { this.deactivationTimeoutMillis = timeUnit.toMillis(duration); return this; } public Builder concurrentDeactivations(final int concurrentDeactivations) { this.concurrentDeactivations = concurrentDeactivations; return this; } public Builder broadcastActorDeactivations(final boolean broadcastActorDeactivations) { this.broadcastActorDeactivations = broadcastActorDeactivations; return this; } public Builder enableShutdownHook(final boolean enableShutdownHook) { this.enableShutdownHook = enableShutdownHook; return this; } public Stage build() { final Stage stage = new Stage(); stage.setClock(clock); stage.setExecutionPool(executionPool); stage.setExecution(execution); stage.setObjectCloner(objectCloner); stage.setMessageLoopbackObjectCloner(messageLoopbackObjectCloner); stage.setMessageSerializer(messageSerializer); stage.setClusterName(clusterName); stage.setPlacementGroup(placementGroup); stage.setClusterPeer(clusterPeer); stage.setNodeName(nodeName); stage.setMode(mode); stage.setExecutionPoolSize(executionPoolSize); stage.setLocalAddressCacheMaximumSize(localAddressCacheMaximumSize); stage.setLocalObjectsCleaner(localObjectsCleaner); stage.setTimer(timer); extensions.forEach(stage::addExtension); stage.setInvocationHandler(invocationHandler); stage.setMessaging(messaging); stage.addStickyHeaders(stickyHeaders); stage.addBasePackages(basePackages); if(actorTTLMillis != null) stage.setDefaultActorTTL(actorTTLMillis); if(localAddressCacheTTLMillis != null) stage.setLocalAddressCacheTTL(localAddressCacheTTLMillis); if(numReminderControllers != null) stage.setNumReminderControllers(numReminderControllers); if(deactivationTimeoutMillis != null) stage.setDeactivationTimeout(deactivationTimeoutMillis); if(concurrentDeactivations != null) stage.setConcurrentDeactivations(concurrentDeactivations); if(broadcastActorDeactivations != null) stage.setBroadcastActorDeactivations(broadcastActorDeactivations); if(enableShutdownHook != null) stage.setEnableShutdownHook(enableShutdownHook); if(enableMessageLoopback != null) stage.setEnableMessageLoopback(enableMessageLoopback); return stage; } } public Stage() { ActorRuntime.setRuntime(cachedRef); } public void addStickyHeaders(Collection<String> stickyHeaders) { this.stickyHeaders.addAll(stickyHeaders); } public void addBasePackages(final List<String> basePackages) { this.basePackages.addAll(basePackages); } public void setClock(final Clock clock) { this.clock = clock; } public void setMessaging(final Messaging messaging) { this.messaging = messaging; } public void setInvocationHandler(final InvocationHandler invocationHandler) { this.invocationHandler = invocationHandler; } public void setExecutionPool(final ExecutorService executionPool) { this.executionPool = executionPool; } public ExecutorService getExecutionPool() { return executionPool; } public int getExecutionPoolSize() { return executionPoolSize; } public void setExecutionPoolSize(int defaultPoolSize) { this.executionPoolSize = defaultPoolSize; } public void setLocalAddressCacheMaximumSize(final int localAddressCacheMaximumSize) { this.localAddressCacheMaximumSize = localAddressCacheMaximumSize; } public Execution getExecution() { return execution; } public void setExecution(Execution execution) { this.execution = execution; } public void setLocalObjectsCleaner(final LocalObjectsCleaner localObjectsCleaner) { this.localObjectsCleaner = localObjectsCleaner; } public LocalObjectsCleaner getLocalObjectsCleaner() { return localObjectsCleaner; } public ExecutionObjectCloner getObjectCloner() { return objectCloner; } public void setMessageLoopbackObjectCloner(final ExecutionObjectCloner messageLoopbackObjectCloner) { this.messageLoopbackObjectCloner = messageLoopbackObjectCloner; } public void setObjectCloner(final ExecutionObjectCloner objectCloner) { this.objectCloner = objectCloner; } @SuppressWarnings("unused") public long getLocalObjectCount() { return objects.getLocalObjectCount(); } public String getClusterName() { return clusterName; } public void setClusterName(final String clusterName) { this.clusterName = clusterName; } public String getPlacementGroup() { return placementGroup; } public void setPlacementGroup(final String placementGroup) { this.placementGroup = placementGroup; } public String getNodeName() { return nodeName; } public void setNodeName(final String nodeName) { this.nodeName = nodeName; } public StageMode getMode() { return mode; } public void setMode(final StageMode mode) { if (startCalled) { throw new IllegalStateException("Stage mode cannot be changed after startup. " + this.toString()); } this.mode = mode; } public void setTimer(final Timer timer) { this.timer = timer; } public Task<Void> getStartPromise() { return startPromise; } public void setConcurrentDeactivations(int concurrentDeactivations) { this.concurrentDeactivations = concurrentDeactivations; } public void setDefaultActorTTL(long defaultActorTTLMs) { this.defaultActorTTL = defaultActorTTLMs; } public void setLocalAddressCacheTTL(final long localAddressCacheTTL) { this.localAddressCacheTTL = localAddressCacheTTL; } public void setNumReminderControllers(final int numReminderControllers) { if(numReminderControllers < 1) { throw new IllegalArgumentException("Must specify at least 1 reminder controller shard"); } this.numReminderControllers = numReminderControllers; } public void setDeactivationTimeout(long deactivationTimeoutMs) { this.deactivationTimeoutMillis = deactivationTimeoutMs; } public boolean getBroadcastActorDeactivations() { return broadcastActorDeactivations; } public void setBroadcastActorDeactivations(boolean broadcastActorDeactivation) { this.broadcastActorDeactivations = broadcastActorDeactivation; } public void setEnableShutdownHook(boolean enableShutdownHook) { // TODO: Reenable shutdown hook // This is currently disabled due to https://github.com/orbit/orbit/issues/301 if(enableShutdownHook) { logger.warn("Shutdown hook can not currently be enabled. See https://github.com/orbit/orbit/issues/301."); } } public void setEnableMessageLoopback(final boolean enableMessageLoopback) { this.enableMessageLoopback = enableMessageLoopback; } @Override public Task<?> start() { logger.info("Starting Orbit Stage..."); extensions = new ArrayList<>(extensions); startCalled = true; if (state != null) { throw new IllegalStateException("Can't start the stage in this state. " + this.toString()); } state = NodeCapabilities.NodeState.RUNNING; if (timer == null) { timer = new Timer("OrbitTimer", true); } if (loggerExtension == null) { loggerExtension = getFirstExtension(LoggerExtension.class); if (loggerExtension == null) { loggerExtension = new DefaultLoggerExtension(); } } logger = loggerExtension.getLogger(this); if (clusterName == null || clusterName.isEmpty()) { setClusterName("orbit-cluster"); } if (placementGroup == null || placementGroup.isEmpty()) { setPlacementGroup("default"); } if (nodeName == null || nodeName.isEmpty()) { setNodeName(getClusterName()); } if (executionPool == null) { executionPool = ExecutorUtils.newScalingThreadPool(executionPoolSize); } executionSerializer = new WaitFreeMultiExecutionSerializer<>(executionPool); if (hosting == null) { hosting = new Hosting(localAddressCacheMaximumSize, localAddressCacheTTL); } if (messaging == null) { messaging = new Messaging(); } if (execution == null) { execution = new Execution(); } if(invocationHandler == null) { invocationHandler = new DefaultInvocationHandler(); } if (messageSerializer == null) { messageSerializer = new KryoSerializer(); } if (clusterPeer == null) { clusterPeer = constructDefaultClusterPeer(); } if (clock == null) { clock = Clock.systemUTC(); } if (objectCloner == null) { objectCloner = new KryoSerializer(); } if (localObjectsCleaner == null) { localObjectsCleaner = new DefaultLocalObjectsCleaner(hosting, clock, executionPool, objects, defaultActorTTL, concurrentDeactivations, deactivationTimeoutMillis); } // create pipeline before waiting for ActorClassFinder as stop might be invoked before it is complete pipeline = new DefaultPipeline(); finder = getFirstExtension(ActorClassFinder.class); if (finder == null) { if(!basePackages.isEmpty()) { final String[] basePackagesArray = basePackages.toArray(new String[0]); finder = new FastActorClassFinder(basePackagesArray); } else { finder = new LazyActorClassFinder(); } } await(finder.start()); localObjectsCleaner.setActorDeactivationExtensions(getAllExtensions(ActorDeactivationExtension.class)); final List<ResponseCachingExtension> cacheExtensions = getAllExtensions(ResponseCachingExtension.class); if(cacheExtensions.size() > 1) { throw new IllegalArgumentException("Only one cache extension may be configured"); } final ResponseCachingExtension cacheManager = cacheExtensions .stream() .findFirst() .orElseGet(() -> { final DefaultResponseCachingExtension responseCaching = new DefaultResponseCachingExtension(); responseCaching.setObjectCloner(objectCloner); responseCaching.setRuntime(this); responseCaching.setMessageSerializer(messageSerializer); return responseCaching; }); hosting.setNodeType(mode == StageMode.HOST ? NodeCapabilities.NodeTypeEnum.SERVER : NodeCapabilities.NodeTypeEnum.CLIENT); execution.setRuntime(this); execution.setObjects(objects); execution.setExecutionSerializer(executionSerializer); execution.setInvocationHandler(invocationHandler); messaging.setRuntime(this); hosting.setStage(this); hosting.setClusterPeer(clusterPeer); final NodeSelectorExtension nodeSelector = getAllExtensions(NodeSelectorExtension.class) .stream() .findFirst() .orElse(new RandomSelectorExtension()); hosting.setNodeSelector(nodeSelector); hosting.setTargetPlacementGroups(Collections.singleton(placementGroup)); // caches responses pipeline.addLast(DefaultHandlers.CACHING, cacheManager); pipeline.addLast(DefaultHandlers.EXECUTION, execution); // handles invocation messages and request-response matching pipeline.addLast(DefaultHandlers.HOSTING, hosting); // handles invocation messages and request-response matching pipeline.addLast(DefaultHandlers.MESSAGING, messaging); if (enableMessageLoopback) { final MessageLoopback messageLoopback = new MessageLoopback(); messageLoopback.setCloner(messageLoopbackObjectCloner != null ? messageLoopbackObjectCloner : new KryoSerializer()); messageLoopback.setRuntime(this); pipeline.addLast(messageLoopback.getName(), messageLoopback); } // message serializer handler pipeline.addLast(DefaultHandlers.SERIALIZATION, new SerializationHandler(this, messageSerializer)); // cluster peer handler pipeline.addLast(DefaultHandlers.NETWORK, new ClusterHandler(clusterPeer, clusterName, nodeName)); extensions.stream().filter(extension -> extension instanceof PipelineExtension) .map(extension -> (PipelineExtension) extension) .forEach(extension -> { if (extension.getBeforeHandlerName() != null) { pipeline.addHandlerBefore(extension.getBeforeHandlerName(), extension.getName(), extension); } else if (extension.getAfterHandlerName() != null) { pipeline.addHandlerAfter(extension.getAfterHandlerName(), extension.getName(), extension); } else { pipeline.addFirst(extension.getName(), extension); } }); StreamProvider defaultStreamProvider = extensions.stream() .filter(p -> p instanceof StreamProvider) .map(p -> (StreamProvider) p) .filter(p -> StringUtils.equals(p.getName(), AsyncStream.DEFAULT_PROVIDER)).findFirst().orElse(null); if (defaultStreamProvider == null) { defaultStreamProvider = new SimpleStreamExtension(AsyncStream.DEFAULT_PROVIDER); extensions.add(defaultStreamProvider); } if (extensions.stream().noneMatch(p -> p instanceof LifetimeExtension)) { extensions.add(new DefaultLifetimeExtension()); } if (extensions.stream().noneMatch(p -> p instanceof ActorConstructionExtension)) { extensions.add(new DefaultActorConstructionExtension()); } logger.debug("Starting messaging..."); messaging.start(); logger.debug("Starting hosting..."); hosting.start(); logger.debug("Starting execution..."); execution.start(); logger.debug("Starting extensions..."); await(Task.allOf(extensions.stream().map(Startable::start))); Task<Void> future = pipeline.connect(null); future = future.thenRun(() -> { bind(); registerObserver(RuntimeActions.class, "", this); // schedules the pulse timer.schedule(new TimerTask() { @Override public void run() { try { if (state == NodeCapabilities.NodeState.RUNNING) { ForkJoinTask.adapt(() -> pulse().join()).fork(); } } catch (Exception e) { logger.error("Failed executing timer task", e); } } }, pulseIntervalMillis, pulseIntervalMillis); if (mode == StageMode.HOST) { startReminderController(); } }); future.whenComplete((r, e) -> { if (e != null) { startPromise.completeExceptionally(e); } else { startPromise.complete(r); } }); await(startPromise); logger.info("Orbit Stage started."); logger.info("Orbit Cluster Name: {}", clusterName); logger.info("Orbit Node Name: {}", nodeName); logger.info("Orbit Node ID: {}", clusterPeer.localAddress().toString()); logger.info("Orbit Runtime ID: {}", runtimeIdentity()); return Task.done(); } private void startReminderController() { if(useReminderShards()) { IntStream.range(0, numReminderControllers).forEach(i -> Actor.getReference(ShardedReminderController.class, Integer.toString(i)).ensureStart()); } else { Actor.getReference(ReminderController.class).ensureStart(); } } private boolean useReminderShards() { return numReminderControllers > 1; } public String getReminderControllerIdentity(final String reminderName) { return Integer.toString((Math.abs(reminderName.hashCode())) % numReminderControllers); } public void setClusterPeer(final ClusterPeer clusterPeer) { this.clusterPeer = clusterPeer; } /** * Installs extensions to the stage. * <p> * Example: * <pre> * stage.addExtension(new MongoDbProvider(...)); * </pre> * * @param extension Actor Extensions instance. */ public void addExtension(final ActorExtension extension) { this.extensions.add(extension); } @Override public Task<?> stop() { return doStop(); } private Task<?> doStop() { if (getState() != NodeCapabilities.NodeState.RUNNING) { throw new IllegalStateException("Stage node state is not running, state: " + getState()); } state = NodeCapabilities.NodeState.STOPPING; // * refuse new actor activations // first notify other nodes // * deactivate all actors // * notify rest of the cluster (no more observer messages) // * finalize all timers // * stop processing new received messages // * wait pending tasks execution // * stop the network logger.debug("Start stopping pipeline"); // shutdown must continue in non-execution pool thread to prevent thread waiting for itself when checking executionSerializer is busy await(hosting.notifyStateChange().whenCompleteAsync((r, e) -> {}, shutdownExecutor)); logger.debug("Stopping actors"); await(stopActors().whenCompleteAsync((r, e) -> {}, shutdownExecutor)); logger.debug("Stopping timers"); await(stopTimers()); do { InternalUtils.sleep(250); } while (executionSerializer.isBusy()); logger.debug("Closing pipeline"); await(pipeline.close()); logger.debug("Stopping execution serializer"); executionSerializer.shutdown(); logger.debug("Stopping extensions"); await(stopExtensions()); state = NodeCapabilities.NodeState.STOPPED; logger.debug("Stop done"); return Task.done(); } private Task<Void> stopActors() { return localObjectsCleaner.shutdown(); } private Task<Void> stopTimers() { try { timer.cancel(); } catch (final Throwable ex) { logger.error("Error stopping timers", ex); } return Task.done(); } private Task<Void> stopExtensions() { for (final ActorExtension e : getExtensions()) { try { await(e.stop()); } catch (final Throwable ex) { logger.error("Error stopping extension: " + e); } } return Task.done(); } public Hosting getHosting() { return hosting; } public ClusterPeer getClusterPeer() { return clusterPeer != null ? clusterPeer : (clusterPeer = constructDefaultClusterPeer()); } public Task pulse() { if (mode == StageMode.HOST) { startReminderController(); } await(clusterPeer.pulse()); return cleanup(); } public Task cleanup() { await(execution.cleanup()); await(localObjectsCleaner.cleanup()); await(messaging.cleanup()); return Task.done(); } /** * Binds this stage to the current thread. * This tells ungrounded references to use this stage to call remote methods. * <p> * An ungrounded reference is a reference created with {@code Actor.getRemoteReference} and used outside of an actor method. * <p> * This is only necessary when there are <i>two or more</i> OrbitStages active in the same virtual machine and * remote calls need to be issued from outside an actor. * This method was created to help with test cases. * <p> * A normal application will have a single stage and should have no reason to call this method. * <p> * This method writes a weak reference to the runtime in a thread local. * No cleanup is necessary, so none is available. */ @Override public void bind() { ActorRuntime.setRuntime(this.cachedRef); } private ClusterPeer constructDefaultClusterPeer() { try { final Class jGroupsClusterPeer = Class.forName("cloud.orbit.actors.cluster.JGroupsClusterPeer"); return (ClusterPeer) jGroupsClusterPeer.getConstructors()[0].newInstance(); } catch(Exception e) { throw new UncheckedException(e); } } @Override public List<NodeAddress> getAllNodes() { if (hosting == null) { return Collections.emptyList(); } return hosting.getAllNodes(); } public List<NodeAddress> getServerNodes() { if (hosting == null) { return Collections.emptyList(); } return hosting.getServerNodes(); } public NodeCapabilities.NodeState getState() { return state; } public ActorRuntime getRuntime() { return this; } public MessageSerializer getMessageSerializer() { return messageSerializer; } public void setMessageSerializer(final MessageSerializer messageSerializer) { this.messageSerializer = messageSerializer; } @Override public Task<?> invoke(final RemoteReference toReference, final Method m, final boolean oneWay, final int methodId, final Object[] params) { if (state == NodeCapabilities.NodeState.STOPPED) { throw new IllegalStateException("Stage is stopped. " + this.toString()); } final Invocation invocation = new Invocation(toReference, m, oneWay, methodId, params, null); // copy stick context valued to the message headers headers final ActorTaskContext context = ActorTaskContext.current(); if (context != null) { Map<String, Object> headers = null; for (final String key : stickyHeaders) { final Object value = context.getProperty(key); if (value != null) { if (headers == null) { headers = new HashMap<>(); } headers.put(key, value); } } invocation.setHeaders(headers); } final Task<Void> result = pipeline.write(invocation); return result; } @Override public Registration registerTimer(final AbstractActor<?> actor, final Callable<Task<?>> taskCallable, final long dueTime, final long period, final TimeUnit timeUnit) { final Object key = actor.getClass().isAnnotationPresent(StatelessWorker.class) ? actor : RemoteReference.from(actor); final ActorEntry localActor = (ActorEntry) objects.findLocalActor((Actor) actor); if (localActor == null || localActor.isDeactivated()) { throw new IllegalStateException("Actor is deactivated"); } class MyRegistration implements Registration { TimerTask task; @Override public void dispose() { if (task != null) { task.cancel(); } task = null; } } final TimerTask timerTask = new TimerTask() { boolean canceled; @Override public void run() { try { if (localActor.isDeactivated() || state == NodeCapabilities.NodeState.STOPPED) { cancel(); return; } executionSerializer.offerJob(key, () -> { if (localActor.isDeactivated() || state == NodeCapabilities.NodeState.STOPPED) { cancel(); } else { try { if (!canceled) { return (Task) taskCallable.call(); } } catch (final Exception ex) { logger.warn("Error calling timer", ex); } } return (Task) Task.done(); }, 10000); } catch (Exception e) { logger.error("Failed executing timer task", e); } } @Override public boolean cancel() { canceled = true; return super.cancel(); } }; final MyRegistration registration = new MyRegistration(); registration.task = timerTask; // this ensures that the timers get removed during deactivation localActor.addTimer(registration); if (period > 0) { timer.schedule(timerTask, timeUnit.toMillis(dueTime), timeUnit.toMillis(period)); } else { timer.schedule(timerTask, timeUnit.toMillis(dueTime)); } return registration; } @Override public Clock clock() { return clock; } @Override public Task<?> registerReminder(final Remindable actor, final String reminderName, final long dueTime, final long period, final TimeUnit timeUnit) { final Date date = new Date(clock.millis() + timeUnit.toMillis(dueTime)); if(useReminderShards()) { final String id = getReminderControllerIdentity(reminderName); return Actor.getReference(ShardedReminderController.class, id).registerOrUpdateReminder(actor, reminderName, date, period, timeUnit); } return Actor.getReference(ReminderController.class).registerOrUpdateReminder(actor, reminderName, date, period, timeUnit); } @Override public Task<?> unregisterReminder(final Remindable actor, final String reminderName) { if(useReminderShards()) { final String id = getReminderControllerIdentity(reminderName); return Actor.getReference(ShardedReminderController.class, id).unregisterReminder(actor, reminderName); } return Actor.getReference(ReminderController.class).unregisterReminder(actor, reminderName); } @Override public String runtimeIdentity() { return runtimeIdentity; } @Override public Task<NodeAddress> locateActor(final Addressable actorReference, final boolean forceActivation) { return hosting.locateActor((RemoteReference<?>) actorReference, forceActivation); } @Override public NodeAddress getLocalAddress() { return hosting.getNodeAddress(); } @Override public <T extends ActorObserver> T registerObserver(Class<T> iClass, String id, final T observer) { final RemoteReference<T> reference = objects.getOrAddLocalObjectReference(hosting.getNodeAddress(), iClass, id, observer); RemoteReference.setRuntime(reference, this); //noinspection unchecked return iClass != null ? iClass.cast(reference) : (T) reference; } @Override public <T> T getReference(BasicRuntime runtime, NodeAddress address, Class<T> iClass, Object id) { return DefaultDescriptorFactory.get().getReference(this, address, iClass, id); } @Override public StreamProvider getStreamProvider(final String providerName) { final StreamProvider streamProvider = getAllExtensions(StreamProvider.class).stream() .filter(p -> StringUtils.equals(p.getName(), providerName)) .findFirst().orElseThrow(() -> new UncheckedException(String.format("Provider: %s not found", providerName))); final AbstractActor<?> actor = ActorTaskContext.currentActor(); if (actor != null) { @SuppressWarnings("unchecked") final ActorEntry<AbstractActor> actorEntry = (ActorEntry<AbstractActor>) objects.findLocalActor((Actor) actor); // wraps the stream provider to ensure sequential execution return new StreamProvider() { @Override public <T> AsyncStream<T> getStream(final Class<T> dataClass, final String id) { final AsyncStream<T> stream = streamProvider.getStream(dataClass, id); return new AsyncStreamReference<>(providerName, dataClass, id, new AsyncStream<T>() { @Override public Task<Void> unsubscribe(final StreamSubscriptionHandle<T> handle) { // removes the subscription reminder from the actor entry. actorEntry.removeStreamSubscription(handle, stream); return stream.unsubscribe(handle); } @Override public Task<StreamSubscriptionHandle<T>> subscribe(final AsyncObserver<T> observer, StreamSequenceToken sequenceToken) { final Task<StreamSubscriptionHandle<T>> subscriptionTask = stream.subscribe(new AsyncObserver<T>() { @Override public Task<Void> onNext(final T data, final StreamSequenceToken sequenceToken) { // runs with the actor execution serialization concerns return actorEntry.run(entry -> observer.onNext(data, null)); } @Override public Task<Void> onError(final Exception ex) { // runs with the actor execution serialization concerns return actorEntry.run(entry -> observer.onError(ex)); } }, sequenceToken); // this allows the actor to unsubscribe automatically on deactivation actorEntry.addStreamSubscription(await(subscriptionTask), stream); return subscriptionTask; } @Override public Task<Void> publish(final T data) { return stream.publish(data); } }); } @Override public String getName() { return streamProvider.getName(); } }; } return streamProvider; } @Override public <T> AsyncStream<T> getStream(final String provider, final Class<T> dataClass, final String id) { return getStreamProvider(provider).getStream(dataClass, id); } @Override public List<ActorExtension> getExtensions() { return extensions; } <T> LocalObjects.LocalObjectEntry createLocalObjectEntry(final RemoteReference<T> reference, final T object) { final Class<T> interfaceClass = RemoteReference.getInterfaceClass(reference); if (Actor.class.isAssignableFrom(interfaceClass)) { final ActorBaseEntry actorEntry; if (interfaceClass.isAnnotationPresent(StatelessWorker.class)) { actorEntry = new StatelessActorEntry<>(objects, reference); } else { actorEntry = new ActorEntry<>(reference); } actorEntry.setExecutionSerializer(executionSerializer); actorEntry.setLoggerExtension(loggerExtension); actorEntry.setRuntime(this); final Class actorImplementation = finder.findActorImplementation((Class) interfaceClass); actorEntry.setConcreteClass(actorImplementation); actorEntry.setStorageExtension(getStorageExtensionFor(actorImplementation)); return actorEntry; } if (ActorObserver.class.isAssignableFrom(interfaceClass)) { final ObserverEntry observerEntry = new ObserverEntry(reference, object); observerEntry.setExecutionSerializer(executionSerializer); return observerEntry; } throw new IllegalArgumentException("Invalid object type: " + object.getClass()); } @Override public Task deactivateActor(Actor actor) { return localObjectsCleaner.deactivateActor(actor); } @Override public Task<Long> getActorCount() { return Task.fromValue(objects.getLocalActorCount()); } @SuppressWarnings("unchecked") public <T extends ActorExtension> T getStorageExtensionFor(Class actorClass) { if (extensions == null) { return null; } final Annotation annotation = actorClass.getAnnotation(StorageExtension.class); StorageExtension ann = (StorageExtension) annotation; String extensionName = ann == null ? "default" : ann.value(); // selects the fist provider with the right name return (T) extensions.stream() .filter(p -> (p instanceof cloud.orbit.actors.extensions.StorageExtension) && extensionName.equals(((cloud.orbit.actors.extensions.StorageExtension) p).getName())) .findFirst() .orElse(null); } public boolean canActivateActor(final String interfaceName) { if (getState() != NodeCapabilities.NodeState.RUNNING) { // todo, improve this if (hosting.getServerNodes().size() > 1) { return false; } } Class<Actor> aInterface = InternalUtils.classForName(interfaceName, true); if (aInterface == null) { return false; } final Class<?> concreteClass = finder.findActorImplementation(aInterface); return concreteClass != null; } public Pipeline getPipeline() { return pipeline; } @Override public Logger getLogger(Object object) { return loggerExtension.getLogger(object); } public Set<String> getStickyHeaders() { return stickyHeaders; } @Override public String toString() { return "Stage{" + "state=" + state + ", runtimeIdentity='" + runtimeIdentity + '\'' + '}'; } }
/** * 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.stratos.load.balancer.conf.structure; import org.apache.commons.lang.builder.HashCodeBuilder; import java.io.Serializable; import java.util.*; import java.util.Map.Entry; /** * This is the basic data structure which holds a <i>Nginx</i> formatted configuration file. */ public class Node implements Serializable { private static final long serialVersionUID = 4071569903421115370L; /** * Name of this Node element */ private String name; /** * Every node can have 0..n child nodes. * They are kept in a List. */ private List<Node> childNodes = new ArrayList<Node>(); /** * Every node can have 0..n properties. * They are kept in a Map, in the order they appear. * Key: property name * Value: property value */ private Map<String, String> properties = new LinkedHashMap<String, String>(); public void setChildNodes(List<Node> childNodes) { this.childNodes = childNodes; } public void setProperties(Map<String, String> properties) { this.properties = properties; } /** * This will convert each child Node of this Node to a String. * * @return a string which represents child nodes of this node. */ public String childNodesToString(int indentation) { StringBuilder childNodesString = new StringBuilder(); indentation++; for (Node node : childNodes) { childNodesString.append(node.toString(indentation) + "\n"); } return childNodesString.toString(); } /** * This will try to find a child Node of this Node, which has the given name. * * @param name name of the child node to find. * @return child Node object if found or else <code>null</code>. */ public Node findChildNodeByName(String name) { for (Node aNode : childNodes) { if (aNode.getName().equals(name)) { return aNode; } } return null; } /** * Returns the name of this Node. * * @return name of the node. */ public String getName() { return name; } /** * Returns child nodes List of this Node. * * @return List of Node */ public List<Node> getChildNodes() { return childNodes; } /** * Returns properties Map of this Node. * * @return Map whose keys and values are String. */ public Map<String, String> getProperties() { return properties; } /** * Returns the value of a given property. * * @param key name of a property. * @return trimmed value if the property is found in this Node, or else <code>null</code>. */ public String getProperty(String key) { if (properties.get(key) == null) { return null; } return properties.get(key).trim(); } /** * Returns all the properties of this Node as a String. * Key and value of the property is separated by a tab (\t) character and * each property is separated by a new line character. * * @param indentation relative number of tabs * @return properties of this node as a String. */ public String propertiesToString(int indentation) { String indent = getIndentation(indentation); StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : properties.entrySet()) { // hack to get a quick fix in. if (!"tenant_id".equals(entry.getKey()) && !"alias".equals(entry.getKey())) { sb.append(indent + entry.getKey() + "\t" + entry.getValue() + ";\n"); } } return sb.toString(); } /** * Removes the first occurrence of a node having the given name * and returns the removed {@link org.apache.stratos.load.balancer.conf.structure.Node}. * * @param name name of the child node to be removed. * @return removed {@link org.apache.stratos.load.balancer.conf.structure.Node} or else <code>null</code>. */ public Node removeChildNode(String name) { Node aNode = findChildNodeByName(name); if (aNode != null) { if (childNodes.remove(aNode)) { return aNode; } } return null; } /** * Removes the first occurrence of a node equals to the given node. * * @param node {@link org.apache.stratos.load.balancer.conf.structure.Node} to be removed. * @return whether the removal is successful or not. */ public boolean removeChildNode(Node node) { return childNodes.remove(node); } /** * Sets the name of this Node. * * @param name String to be set as the name. */ public void setName(String name) { this.name = name; } /** * Appends a child node at the end of the List of child nodes of this Node, if * a similar node is not already present as a child node. * * @param aNode child Node to be appended. */ public void appendChild(Node aNode) { if (aNode != null && !nodeAlreadyPresent(aNode)) { childNodes.add(aNode); } } /** * Adds a new property to properties Map of this Node if and only if * key is not <code>null</code>. * * @param key name of the property to be added. * @param value value of the property to be added. */ public void addProperty(String key, String value) { if (key != null) { properties.put(key, value); } } /** * Convert this Node to a String which is in <i>Nginx</i> format. * <br/> * Sample: * <br></br> * <code> * ij { * <br/> * klm n; * <br/> * pq { * <br/> * rst u; * <br/> * } * <br/> * } * <br/> * </code> */ public String toString() { String nodeString = getName() + " {\n" + (propertiesToString(1)) + (childNodesToString(1)) + "}"; return nodeString; } public boolean equals(Object node) { if (node instanceof Node) { return this.getName().equals(((Node) node).getName()) && isIdenticalProperties(this.getProperties(), ((Node) node).getProperties()) && isIdenticalChildren(this.getChildNodes(), ((Node) node).getChildNodes()); } return false; } public int hashCode() { return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers append(name). append(properties). append(childNodes). toHashCode(); } private boolean isIdenticalChildren(List<Node> childNodes1, List<Node> childNodes2) { if (childNodes1.size() != childNodes2.size()) { return false; } for (Node node1 : childNodes1) { int i = 0; for (Node node2 : childNodes2) { i++; if (node1.equals(node2)) { break; } if (i == childNodes1.size()) { return false; } } } return true; } private boolean nodeAlreadyPresent(Node aNode) { for (Node node : this.childNodes) { if (node.equals(aNode)) { return true; } } return false; } private boolean isIdenticalProperties(Map<String, String> map1, Map<String, String> map2) { if (map1.size() != map2.size()) { return false; } for (Iterator<Entry<String, String>> iterator1 = map1.entrySet().iterator(); iterator1.hasNext(); ) { Entry<String, String> entry1 = (Entry<String, String>) iterator1.next(); int i = 0; for (Iterator<Entry<String, String>> iterator2 = map2.entrySet().iterator(); iterator2.hasNext(); ) { Entry<String, String> entry2 = (Entry<String, String>) iterator2.next(); i++; if ((entry1.getKey().equals(entry2.getKey()) && entry1.getValue().equals(entry2.getValue()))) { break; } if (i == map1.size()) { return false; } } } return true; } private String toString(int indentation) { String indent = getIndentation(indentation - 1); String nodeString = indent + getName() + " {\n" + (propertiesToString(indentation)) + (childNodesToString(indentation)) + indent + "}"; return nodeString; } private String getIndentation(int tabs) { StringBuilder indent = new StringBuilder(""); for (int i = 0; i < tabs; i++) { indent.append("\t"); } return indent.toString(); } }
// Copyright 2013 The Flutter 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 io.flutter.embedding.engine; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.FlutterInjector; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint; import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.PluginRegistry; import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface; import io.flutter.embedding.engine.plugins.broadcastreceiver.BroadcastReceiverControlSurface; import io.flutter.embedding.engine.plugins.contentprovider.ContentProviderControlSurface; import io.flutter.embedding.engine.plugins.service.ServiceControlSurface; import io.flutter.embedding.engine.plugins.util.GeneratedPluginRegister; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.renderer.RenderSurface; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.embedding.engine.systemchannels.DeferredComponentChannel; import io.flutter.embedding.engine.systemchannels.KeyEventChannel; import io.flutter.embedding.engine.systemchannels.LifecycleChannel; import io.flutter.embedding.engine.systemchannels.LocalizationChannel; import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; import io.flutter.embedding.engine.systemchannels.NavigationChannel; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.embedding.engine.systemchannels.RestorationChannel; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.embedding.engine.systemchannels.SystemChannel; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.plugin.platform.PlatformViewsController; import java.util.HashSet; import java.util.Set; /** * A single Flutter execution environment. * * <p>The {@code FlutterEngine} is the container through which Dart code can be run in an Android * application. * * <p>Dart code in a {@code FlutterEngine} can execute in the background, or it can be render to the * screen by using the accompanying {@link FlutterRenderer} and Dart code using the Flutter * framework on the Dart side. Rendering can be started and stopped, thus allowing a {@code * FlutterEngine} to move from UI interaction to data-only processing and then back to UI * interaction. * * <p>Multiple {@code FlutterEngine}s may exist, execute Dart code, and render UIs within a single * Android app. For better memory performance characteristics, construct multiple {@code * FlutterEngine}s via {@link io.flutter.embedding.engine.FlutterEngineGroup} rather than via {@code * FlutterEngine}'s constructor directly. * * <p>To start running Dart and/or Flutter within this {@code FlutterEngine}, get a reference to * this engine's {@link DartExecutor} and then use {@link * DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)}. The {@link * DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)} method must not be invoked twice * on the same {@code FlutterEngine}. * * <p>To start rendering Flutter content to the screen, use {@link #getRenderer()} to obtain a * {@link FlutterRenderer} and then attach a {@link RenderSurface}. Consider using a {@link * io.flutter.embedding.android.FlutterView} as a {@link RenderSurface}. * * <p>Instatiating the first {@code FlutterEngine} per process will also load the Flutter engine's * native library and start the Dart VM. Subsequent {@code FlutterEngine}s will run on the same VM * instance but will have their own Dart <a * href="https://api.dartlang.org/stable/dart-isolate/Isolate-class.html">Isolate</a> when the * {@link DartExecutor} is run. Each Isolate is a self-contained Dart environment and cannot * communicate with each other except via Isolate ports. */ public class FlutterEngine { private static final String TAG = "FlutterEngine"; @NonNull private final FlutterJNI flutterJNI; @NonNull private final FlutterRenderer renderer; @NonNull private final DartExecutor dartExecutor; @NonNull private final FlutterEngineConnectionRegistry pluginRegistry; @NonNull private final LocalizationPlugin localizationPlugin; // System channels. @NonNull private final AccessibilityChannel accessibilityChannel; @NonNull private final DeferredComponentChannel deferredComponentChannel; @NonNull private final KeyEventChannel keyEventChannel; @NonNull private final LifecycleChannel lifecycleChannel; @NonNull private final LocalizationChannel localizationChannel; @NonNull private final MouseCursorChannel mouseCursorChannel; @NonNull private final NavigationChannel navigationChannel; @NonNull private final RestorationChannel restorationChannel; @NonNull private final PlatformChannel platformChannel; @NonNull private final SettingsChannel settingsChannel; @NonNull private final SystemChannel systemChannel; @NonNull private final TextInputChannel textInputChannel; // Platform Views. @NonNull private final PlatformViewsController platformViewsController; // Engine Lifecycle. @NonNull private final Set<EngineLifecycleListener> engineLifecycleListeners = new HashSet<>(); @NonNull private final EngineLifecycleListener engineLifecycleListener = new EngineLifecycleListener() { @SuppressWarnings("unused") public void onPreEngineRestart() { Log.v(TAG, "onPreEngineRestart()"); for (EngineLifecycleListener lifecycleListener : engineLifecycleListeners) { lifecycleListener.onPreEngineRestart(); } platformViewsController.onPreEngineRestart(); restorationChannel.clearData(); } @Override public void onEngineWillDestroy() { // This inner implementation doesn't do anything since FlutterEngine sent this // notification in the first place. It's meant for external listeners. } }; /** * Constructs a new {@code FlutterEngine}. * * <p>A new {@code FlutterEngine} does not execute any Dart code automatically. See {@link * #getDartExecutor()} and {@link DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)} * to begin executing Dart code within this {@code FlutterEngine}. * * <p>A new {@code FlutterEngine} will not display any UI until a {@link RenderSurface} is * registered. See {@link #getRenderer()} and {@link * FlutterRenderer#startRenderingToSurface(Surface)}. * * <p>A new {@code FlutterEngine} automatically attaches all plugins. See {@link #getPlugins()}. * * <p>A new {@code FlutterEngine} does come with all default system channels attached. * * <p>The first {@code FlutterEngine} instance constructed per process will also load the Flutter * native library and start a Dart VM. * * <p>In order to pass Dart VM initialization arguments (see {@link * io.flutter.embedding.engine.FlutterShellArgs}) when creating the VM, manually set the * initialization arguments by calling {@link * io.flutter.embedding.engine.loader.FlutterLoader#startInitialization(Context)} and {@link * io.flutter.embedding.engine.loader.FlutterLoader#ensureInitializationComplete(Context, * String[])} before constructing the engine. */ public FlutterEngine(@NonNull Context context) { this(context, null); } /** * Same as {@link #FlutterEngine(Context)} with added support for passing Dart VM arguments. * * <p>If the Dart VM has already started, the given arguments will have no effect. */ public FlutterEngine(@NonNull Context context, @Nullable String[] dartVmArgs) { this(context, /* flutterLoader */ null, /* flutterJNI */ null, dartVmArgs, true); } /** * Same as {@link #FlutterEngine(Context)} with added support for passing Dart VM arguments and * avoiding automatic plugin registration. * * <p>If the Dart VM has already started, the given arguments will have no effect. */ public FlutterEngine( @NonNull Context context, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) { this( context, /* flutterLoader */ null, /* flutterJNI */ null, dartVmArgs, automaticallyRegisterPlugins); } /** * Same as {@link #FlutterEngine(Context, String[], boolean)} with added support for configuring * whether the engine will receive restoration data. * * <p>The {@code waitForRestorationData} flag controls whether the engine delays responding to * requests from the framework for restoration data until that data has been provided to the * engine via {@code RestorationChannel.setRestorationData(byte[] data)}. If the flag is false, * the framework may temporarily initialize itself to default values before the restoration data * has been made available to the engine. Setting {@code waitForRestorationData} to true avoids * this extra work by delaying initialization until the data is available. * * <p>When {@code waitForRestorationData} is set, {@code * RestorationChannel.setRestorationData(byte[] data)} must be called at a later point in time. If * it later turns out that no restoration data is available to restore the framework from, that * method must still be called with null as an argument to indicate "no data". * * <p>If the framework never requests the restoration data, this flag has no effect. */ public FlutterEngine( @NonNull Context context, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins, boolean waitForRestorationData) { this( context, /* flutterLoader */ null, /* flutterJNI */ null, new PlatformViewsController(), dartVmArgs, automaticallyRegisterPlugins, waitForRestorationData); } /** * Same as {@link #FlutterEngine(Context, FlutterLoader, FlutterJNI, String[], boolean)} but with * no Dart VM flags and automatically registers plugins. * * <p>{@code flutterJNI} should be a new instance that has never been attached to an engine * before. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI) { this(context, flutterLoader, flutterJNI, null, true); } /** * Same as {@link #FlutterEngine(Context, FlutterLoader, FlutterJNI)}, plus Dart VM flags in * {@code dartVmArgs}, and control over whether plugins are automatically registered with this * {@code FlutterEngine} in {@code automaticallyRegisterPlugins}. If plugins are automatically * registered, then they are registered during the execution of this constructor. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) { this( context, flutterLoader, flutterJNI, new PlatformViewsController(), dartVmArgs, automaticallyRegisterPlugins); } /** * Same as {@link #FlutterEngine(Context, FlutterLoader, FlutterJNI, String[], boolean)}, plus the * ability to provide a custom {@code PlatformViewsController}. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @NonNull PlatformViewsController platformViewsController, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) { this( context, flutterLoader, flutterJNI, platformViewsController, dartVmArgs, automaticallyRegisterPlugins, false); } /** Fully configurable {@code FlutterEngine} constructor. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @NonNull PlatformViewsController platformViewsController, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins, boolean waitForRestorationData) { AssetManager assetManager; try { assetManager = context.createPackageContext(context.getPackageName(), 0).getAssets(); } catch (NameNotFoundException e) { assetManager = context.getAssets(); } FlutterInjector injector = FlutterInjector.instance(); if (flutterJNI == null) { flutterJNI = injector.getFlutterJNIFactory().provideFlutterJNI(); } this.flutterJNI = flutterJNI; this.dartExecutor = new DartExecutor(flutterJNI, assetManager); this.dartExecutor.onAttachedToJNI(); DeferredComponentManager deferredComponentManager = FlutterInjector.instance().deferredComponentManager(); accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI); deferredComponentChannel = new DeferredComponentChannel(dartExecutor); keyEventChannel = new KeyEventChannel(dartExecutor); lifecycleChannel = new LifecycleChannel(dartExecutor); localizationChannel = new LocalizationChannel(dartExecutor); mouseCursorChannel = new MouseCursorChannel(dartExecutor); navigationChannel = new NavigationChannel(dartExecutor); platformChannel = new PlatformChannel(dartExecutor); restorationChannel = new RestorationChannel(dartExecutor, waitForRestorationData); settingsChannel = new SettingsChannel(dartExecutor); systemChannel = new SystemChannel(dartExecutor); textInputChannel = new TextInputChannel(dartExecutor); if (deferredComponentManager != null) { deferredComponentManager.setDeferredComponentChannel(deferredComponentChannel); } this.localizationPlugin = new LocalizationPlugin(context, localizationChannel); if (flutterLoader == null) { flutterLoader = injector.flutterLoader(); } if (!flutterJNI.isAttached()) { flutterLoader.startInitialization(context.getApplicationContext()); flutterLoader.ensureInitializationComplete(context, dartVmArgs); } flutterJNI.addEngineLifecycleListener(engineLifecycleListener); flutterJNI.setPlatformViewsController(platformViewsController); flutterJNI.setLocalizationPlugin(localizationPlugin); flutterJNI.setDeferredComponentManager(injector.deferredComponentManager()); // It should typically be a fresh, unattached JNI. But on a spawned engine, the JNI instance // is already attached to a native shell. In that case, the Java FlutterEngine is created around // an existing shell. if (!flutterJNI.isAttached()) { attachToJni(); } // TODO(mattcarroll): FlutterRenderer is temporally coupled to attach(). Remove that coupling if // possible. this.renderer = new FlutterRenderer(flutterJNI); this.platformViewsController = platformViewsController; this.platformViewsController.onAttachedToJNI(); this.pluginRegistry = new FlutterEngineConnectionRegistry(context.getApplicationContext(), this, flutterLoader); // Only automatically register plugins if both constructor parameter and // loaded AndroidManifest config turn this feature on. if (automaticallyRegisterPlugins && flutterLoader.automaticallyRegisterPlugins()) { GeneratedPluginRegister.registerGeneratedPlugins(this); } } private void attachToJni() { Log.v(TAG, "Attaching to JNI."); flutterJNI.attachToNative(); if (!isAttachedToJni()) { throw new RuntimeException("FlutterEngine failed to attach to its native Object reference."); } } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean isAttachedToJni() { return flutterJNI.isAttached(); } /** * Create a second {@link io.flutter.embedding.engine.FlutterEngine} based on this current one by * sharing as much resources together as possible to minimize startup latency and memory cost. * * @param context is a Context used to create the {@link * io.flutter.embedding.engine.FlutterEngine}. Could be the same Context as the current engine * or a different one. Generally, only an application Context is needed for the {@link * io.flutter.embedding.engine.FlutterEngine} and its dependencies. * @param dartEntrypoint specifies the {@link DartEntrypoint} the new engine should run. It * doesn't need to be the same entrypoint as the current engine but must be built in the same * AOT or snapshot. * @return a new {@link io.flutter.embedding.engine.FlutterEngine}. */ @NonNull /*package*/ FlutterEngine spawn( @NonNull Context context, @NonNull DartEntrypoint dartEntrypoint, @Nullable String initialRoute) { if (!isAttachedToJni()) { throw new IllegalStateException( "Spawn can only be called on a fully constructed FlutterEngine"); } FlutterJNI newFlutterJNI = flutterJNI.spawn( dartEntrypoint.dartEntrypointFunctionName, dartEntrypoint.dartEntrypointLibrary, initialRoute); return new FlutterEngine( context, // Context. null, // FlutterLoader. A null value passed here causes the constructor to get it from the // FlutterInjector. newFlutterJNI); // FlutterJNI. } /** * Cleans up all components within this {@code FlutterEngine} and destroys the associated Dart * Isolate. All state held by the Dart Isolate, such as the Flutter Elements tree, is lost. * * <p>This {@code FlutterEngine} instance should be discarded after invoking this method. */ public void destroy() { Log.v(TAG, "Destroying."); for (EngineLifecycleListener listener : engineLifecycleListeners) { listener.onEngineWillDestroy(); } // The order that these things are destroyed is important. pluginRegistry.destroy(); platformViewsController.onDetachedFromJNI(); dartExecutor.onDetachedFromJNI(); flutterJNI.removeEngineLifecycleListener(engineLifecycleListener); flutterJNI.setDeferredComponentManager(null); flutterJNI.detachFromNativeAndReleaseResources(); if (FlutterInjector.instance().deferredComponentManager() != null) { FlutterInjector.instance().deferredComponentManager().destroy(); deferredComponentChannel.setDeferredComponentManager(null); } } /** * Adds a {@code listener} to be notified of Flutter engine lifecycle events, e.g., {@code * onPreEngineStart()}. */ public void addEngineLifecycleListener(@NonNull EngineLifecycleListener listener) { engineLifecycleListeners.add(listener); } /** * Removes a {@code listener} that was previously added with {@link * #addEngineLifecycleListener(EngineLifecycleListener)}. */ public void removeEngineLifecycleListener(@NonNull EngineLifecycleListener listener) { engineLifecycleListeners.remove(listener); } /** * The Dart execution context associated with this {@code FlutterEngine}. * * <p>The {@link DartExecutor} can be used to start executing Dart code from a given entrypoint. * See {@link DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)}. * * <p>Use the {@link DartExecutor} to connect any desired message channels and method channels to * facilitate communication between Android and Dart/Flutter. */ @NonNull public DartExecutor getDartExecutor() { return dartExecutor; } /** * The rendering system associated with this {@code FlutterEngine}. * * <p>To render a Flutter UI that is produced by this {@code FlutterEngine}'s Dart code, attach a * {@link RenderSurface} to this {@link FlutterRenderer}. */ @NonNull public FlutterRenderer getRenderer() { return renderer; } /** System channel that sends accessibility requests and events from Flutter to Android. */ @NonNull public AccessibilityChannel getAccessibilityChannel() { return accessibilityChannel; } /** System channel that sends key events from Android to Flutter. */ @NonNull public KeyEventChannel getKeyEventChannel() { return keyEventChannel; } /** System channel that sends Android lifecycle events to Flutter. */ @NonNull public LifecycleChannel getLifecycleChannel() { return lifecycleChannel; } /** System channel that sends locale data from Android to Flutter. */ @NonNull public LocalizationChannel getLocalizationChannel() { return localizationChannel; } /** System channel that sends Flutter navigation commands from Android to Flutter. */ @NonNull public NavigationChannel getNavigationChannel() { return navigationChannel; } /** * System channel that sends platform-oriented requests and information to Flutter, e.g., requests * to play sounds, requests for haptics, system chrome settings, etc. */ @NonNull public PlatformChannel getPlatformChannel() { return platformChannel; } /** * System channel to exchange restoration data between framework and engine. * * <p>The engine can obtain the current restoration data from the framework via this channel to * store it on disk and - when the app is relaunched - provide the stored data back to the * framework to recreate the original state of the app. */ @NonNull public RestorationChannel getRestorationChannel() { return restorationChannel; } /** * System channel that sends platform/user settings from Android to Flutter, e.g., time format, * scale factor, etc. */ @NonNull public SettingsChannel getSettingsChannel() { return settingsChannel; } /** System channel that allows manual installation and state querying of deferred components. */ @NonNull public DeferredComponentChannel getDeferredComponentChannel() { return deferredComponentChannel; } /** System channel that sends memory pressure warnings from Android to Flutter. */ @NonNull public SystemChannel getSystemChannel() { return systemChannel; } /** System channel that sends and receives text input requests and state. */ @NonNull public MouseCursorChannel getMouseCursorChannel() { return mouseCursorChannel; } /** System channel that sends and receives text input requests and state. */ @NonNull public TextInputChannel getTextInputChannel() { return textInputChannel; } /** * Plugin registry, which registers plugins that want to be applied to this {@code FlutterEngine}. */ @NonNull public PluginRegistry getPlugins() { return pluginRegistry; } /** The LocalizationPlugin this FlutterEngine created. */ @NonNull public LocalizationPlugin getLocalizationPlugin() { return localizationPlugin; } /** * {@code PlatformViewsController}, which controls all platform views running within this {@code * FlutterEngine}. */ @NonNull public PlatformViewsController getPlatformViewsController() { return platformViewsController; } @NonNull public ActivityControlSurface getActivityControlSurface() { return pluginRegistry; } @NonNull public ServiceControlSurface getServiceControlSurface() { return pluginRegistry; } @NonNull public BroadcastReceiverControlSurface getBroadcastReceiverControlSurface() { return pluginRegistry; } @NonNull public ContentProviderControlSurface getContentProviderControlSurface() { return pluginRegistry; } /** Lifecycle callbacks for Flutter engine lifecycle events. */ public interface EngineLifecycleListener { /** Lifecycle callback invoked before a hot restart of the Flutter engine. */ void onPreEngineRestart(); /** * Lifecycle callback invoked before the Flutter engine is destroyed. * * <p>For the duration of the call, the Flutter engine is still valid. */ void onEngineWillDestroy(); } }
/* * Copyright 2016 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.workbench.common.stunner.bpmn.backend; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import bpsim.impl.BpsimPackageImpl; import org.eclipse.bpmn2.Bpmn2Package; import org.eclipse.bpmn2.Definitions; import org.eclipse.bpmn2.DocumentRoot; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.jboss.drools.DroolsPackage; import org.jboss.drools.impl.DroolsPackageImpl; import org.kie.workbench.common.stunner.bpmn.backend.legacy.profile.impl.DefaultProfileImpl; import org.kie.workbench.common.stunner.bpmn.backend.legacy.resource.JBPMBpmn2ResourceFactoryImpl; import org.kie.workbench.common.stunner.bpmn.backend.legacy.resource.JBPMBpmn2ResourceImpl; import org.kie.workbench.common.stunner.bpmn.backend.marshall.json.Bpmn2Marshaller; import org.kie.workbench.common.stunner.bpmn.backend.marshall.json.Bpmn2UnMarshaller; import org.kie.workbench.common.stunner.bpmn.backend.marshall.json.builder.GraphObjectBuilderFactory; import org.kie.workbench.common.stunner.bpmn.backend.marshall.json.oryx.OryxManager; import org.kie.workbench.common.stunner.bpmn.definition.BPMNDiagram; import org.kie.workbench.common.stunner.core.api.DefinitionManager; import org.kie.workbench.common.stunner.core.api.FactoryManager; import org.kie.workbench.common.stunner.core.backend.service.XMLEncoderDiagramMetadataMarshaller; import org.kie.workbench.common.stunner.core.definition.service.DiagramMarshaller; import org.kie.workbench.common.stunner.core.definition.service.DiagramMetadataMarshaller; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.kie.workbench.common.stunner.core.graph.Graph; import org.kie.workbench.common.stunner.core.graph.Node; import org.kie.workbench.common.stunner.core.graph.command.GraphCommandManager; import org.kie.workbench.common.stunner.core.graph.command.impl.GraphCommandFactory; import org.kie.workbench.common.stunner.core.graph.content.definition.Definition; import org.kie.workbench.common.stunner.core.graph.processing.index.GraphIndexBuilder; import org.kie.workbench.common.stunner.core.graph.util.GraphUtils; import org.kie.workbench.common.stunner.core.registry.impl.DefinitionsCacheRegistry; import org.kie.workbench.common.stunner.core.rule.RuleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class BaseDiagramMarshaller<D> implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { private static final Logger LOG = LoggerFactory.getLogger(BaseDiagramMarshaller.class); private final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller; private final GraphObjectBuilderFactory bpmnGraphBuilderFactory; private final GraphIndexBuilder<?> indexBuilder; private final FactoryManager factoryManager; private final DefinitionsCacheRegistry definitionsCacheRegistry; private final RuleManager rulesManager; private final GraphCommandManager graphCommandManager; private final GraphCommandFactory commandFactory; protected final DefinitionManager definitionManager; protected final OryxManager oryxManager; public BaseDiagramMarshaller(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final GraphObjectBuilderFactory bpmnGraphBuilderFactory, final DefinitionManager definitionManager, final GraphIndexBuilder<?> indexBuilder, final OryxManager oryxManager, final FactoryManager factoryManager, final DefinitionsCacheRegistry definitionsCacheRegistry, final RuleManager rulesManager, final GraphCommandManager graphCommandManager, final GraphCommandFactory commandFactory) { this.diagramMetadataMarshaller = diagramMetadataMarshaller; this.bpmnGraphBuilderFactory = bpmnGraphBuilderFactory; this.definitionManager = definitionManager; this.indexBuilder = indexBuilder; this.oryxManager = oryxManager; this.factoryManager = factoryManager; this.definitionsCacheRegistry = definitionsCacheRegistry; this.rulesManager = rulesManager; this.graphCommandManager = graphCommandManager; this.commandFactory = commandFactory; } @Override @SuppressWarnings("unchecked") public String marshall(final Diagram diagram) { LOG.debug("Starting diagram marshalling..."); final Bpmn2Marshaller marshaller = createBpmn2Marshaller(definitionManager, oryxManager); String result = null; try { // Marshall the diagram definition result = marshaller.marshall(diagram, getPreProcessingData(diagram.getMetadata())); // Update diagram's settings. updateRootUUID(diagram.getMetadata(), diagram.getGraph()); } catch (IOException e) { LOG.error("Error marshalling file.", e); } LOG.debug("Diagram marshalling finished successfully."); return result; } protected Bpmn2Marshaller createBpmn2Marshaller(DefinitionManager definitionManager, OryxManager oryxManager) { return new Bpmn2Marshaller(definitionManager, oryxManager); } protected abstract String getPreProcessingData(Metadata metadata); public JBPMBpmn2ResourceImpl marshallToBpmn2Resource(final Diagram<Graph, Metadata> diagram) throws IOException { final Bpmn2Marshaller marshaller = new Bpmn2Marshaller(definitionManager, oryxManager); return marshaller.marshallToBpmn2Resource(diagram, getPreProcessingData(diagram.getMetadata())); } @Override public Graph unmarshall(final Metadata metadata, final InputStream inputStream) { LOG.debug("Starting diagram unmarshalling..."); // No rule checking for marshalling/unmarshalling, current jbpm designer marshallers should do it for us. final Bpmn2UnMarshaller parser = createBpmn2UnMarshaller(bpmnGraphBuilderFactory, definitionManager, factoryManager, definitionsCacheRegistry, rulesManager, oryxManager, graphCommandManager, commandFactory, indexBuilder, getDiagramDefinitionSetClass(), getDiagramDefinitionClass()); Graph result = null; try { // Unmarshall the diagram definition final Definitions definitions = parseDefinitions(inputStream); parser.setProfile(new DefaultProfileImpl()); result = parser.unmarshall(definitions, getPreProcessingData(metadata)); // Update diagram's settings. updateRootUUID(metadata, result); } catch (IOException e) { LOG.error("Error unmarshalling file.", e); } LOG.debug("Diagram unmarshalling finished successfully."); return result; } protected Bpmn2UnMarshaller createBpmn2UnMarshaller(GraphObjectBuilderFactory elementBuilderFactory, DefinitionManager definitionManager, FactoryManager factoryManager, DefinitionsCacheRegistry definitionsCacheRegistry, RuleManager rulesManager, OryxManager oryxManager, GraphCommandManager commandManager, GraphCommandFactory commandFactory, GraphIndexBuilder<?> indexBuilder, Class<?> diagramDefinitionSetClass, Class<? extends BPMNDiagram> diagramDefinitionClass) { return new Bpmn2UnMarshaller(elementBuilderFactory, definitionManager, factoryManager, definitionsCacheRegistry, rulesManager, oryxManager, commandManager, commandFactory, indexBuilder, diagramDefinitionSetClass, diagramDefinitionClass); } public abstract Class<?> getDiagramDefinitionSetClass(); public abstract Class<? extends BPMNDiagram> getDiagramDefinitionClass(); public void updateRootUUID(final Metadata settings, final Graph graph) { // Update settings's root UUID. final String rootUUID = getRootUUID(graph); settings.setCanvasRootUUID(rootUUID); } public void updateTitle(final Metadata metadata, final Graph graph) { // Update metadata's title. final String title = getTitle(graph); metadata.setTitle(title); } private String getTitle(final Graph graph) { final Node<Definition<BPMNDiagram>, ?> diagramNode = getFirstDiagramNode(graph); final BPMNDiagram diagramBean = null != diagramNode ? (BPMNDiagram) ((Definition) diagramNode.getContent()).getDefinition() : null; if (diagramBean == null) { return null; } return getTitle(diagramBean); } private String getTitle(final BPMNDiagram diagram) { final String title = diagram != null ? diagram.getDiagramSet().getName().getValue() : null; return title != null && title.trim().length() > 0 ? title : "-- Untitled diagram --"; } @SuppressWarnings("unchecked") private Node<Definition<BPMNDiagram>, ?> getFirstDiagramNode(final Graph graph) { return GraphUtils.getFirstNode(graph, getDiagramDefinitionClass()); } private String getRootUUID(final Graph graph) { final Node diagramNode = getFirstDiagramNode(graph); return null != diagramNode ? diagramNode.getUUID() : null; } private Definitions parseDefinitions(final InputStream inputStream) throws IOException { try { DroolsPackageImpl.init(); BpsimPackageImpl.init(); final ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new JBPMBpmn2ResourceFactoryImpl()); resourceSet.getPackageRegistry().put("http://www.omg.org/spec/BPMN/20100524/MODEL", Bpmn2Package.eINSTANCE); resourceSet.getPackageRegistry().put("http://www.jboss.org/drools", DroolsPackage.eINSTANCE); final JBPMBpmn2ResourceImpl resource = (JBPMBpmn2ResourceImpl) resourceSet.createResource(URI.createURI("inputStream://dummyUriWithValidSuffix.xml")); resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); resource.setEncoding("UTF-8"); final Map<String, Object> options = new HashMap<>(); options.put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); options.put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, true); options.put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true); options.put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF, JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD); resource.load(inputStream, options); final DocumentRoot root = (DocumentRoot) resource.getContents().get(0); return root.getDefinitions(); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { inputStream.close(); } } return null; } @Override public DiagramMetadataMarshaller<Metadata> getMetadataMarshaller() { return diagramMetadataMarshaller; } }
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.classic.spi; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; import org.slf4j.MDC; import org.slf4j.Marker; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.util.LogbackMDCAdapter; import org.slf4j.spi.MDCAdapter; /** * The internal representation of logging events. When an affirmative decision * is made to log then a <code>LoggingEvent</code> instance is created. This * instance is passed around to the different logback-classic components. * <p/> * <p> * Writers of logback-classic components such as appenders should be aware of * that some of the LoggingEvent fields are initialized lazily. Therefore, an * appender wishing to output data to be later correctly read by a receiver, * must initialize "lazy" fields prior to writing them out. See the * {@link #prepareForDeferredProcessing()} method for the exact list. * </p> * * @author Ceki G&uuml;lc&uuml; * @author S&eacute;bastien Pennec */ public class LoggingEvent implements ILoggingEvent { /** * Fully qualified name of the calling Logger class. This field does not * survive serialization. * <p/> * <p/> * Note that the getCallerInformation() method relies on this fact. */ transient String fqnOfLoggerClass; /** * The name of thread in which this logging event was generated. */ private String threadName; private String loggerName; private LoggerContext loggerContext; private LoggerContextVO loggerContextVO; /** * Level of logging event. * <p/> * <p> * This field should not be accessed directly. You should use the * {@link #getLevel} method instead. * </p> */ private transient Level level; private String message; // we gain significant space at serialization time by marking // formattedMessage as transient and constructing it lazily in // getFormattedMessage() transient String formattedMessage; private transient Object[] argumentArray; private ThrowableProxy throwableProxy; private StackTraceElement[] callerDataArray; private Marker marker; private Map<String, String> mdcPropertyMap; private static final Map<String, String> CACHED_NULL_MAP = new HashMap<String, String>(); /** * The number of milliseconds elapsed from 1/1/1970 until logging event was * created. */ private long timeStamp; public LoggingEvent() { } public LoggingEvent(String fqcn, Logger logger, Level level, String message, Throwable throwable, Object[] argArray) { this.fqnOfLoggerClass = fqcn; this.loggerName = logger.getName(); this.loggerContext = logger.getLoggerContext(); this.loggerContextVO = loggerContext.getLoggerContextRemoteView(); this.level = level; this.message = message; this.argumentArray = argArray; if(throwable == null) { throwable = extractThrowableAnRearrangeArguments(argArray); } if (throwable != null) { this.throwableProxy = new ThrowableProxy(throwable); LoggerContext lc = logger.getLoggerContext(); if (lc.isPackagingDataEnabled()) { this.throwableProxy.calculatePackagingData(); } } timeStamp = System.currentTimeMillis(); } private Throwable extractThrowableAnRearrangeArguments(Object[] argArray) { Throwable extractedThrowable = EventArgUtil.extractThrowable(argArray); if(EventArgUtil.successfulExtraction(extractedThrowable)) { this.argumentArray = EventArgUtil.trimmedCopy(argArray); } return extractedThrowable; } public void setArgumentArray(Object[] argArray) { if (this.argumentArray != null) { throw new IllegalStateException("argArray has been already set"); } this.argumentArray = argArray; } public Object[] getArgumentArray() { return this.argumentArray; } public Level getLevel() { return level; } public String getLoggerName() { return loggerName; } public void setLoggerName(String loggerName) { this.loggerName = loggerName; } public String getThreadName() { if (threadName == null) { threadName = (Thread.currentThread()).getName(); } return threadName; } /** * @param threadName The threadName to set. * @throws IllegalStateException If threadName has been already set. */ public void setThreadName(String threadName) throws IllegalStateException { if (this.threadName != null) { throw new IllegalStateException("threadName has been already set"); } this.threadName = threadName; } /** * Returns the throwable information contained within this event. May be * <code>null</code> if there is no such information. */ public IThrowableProxy getThrowableProxy() { return throwableProxy; } /** * Set this event's throwable information. */ public void setThrowableProxy(ThrowableProxy tp) { if (throwableProxy != null) { throw new IllegalStateException("ThrowableProxy has been already set."); } else { throwableProxy = tp; } } /** * This method should be called prior to serializing an event. It should also * be called when using asynchronous or deferred logging. * <p/> * <p/> * Note that due to performance concerns, this method does NOT extract caller * data. It is the responsibility of the caller to extract caller information. */ public void prepareForDeferredProcessing() { this.getFormattedMessage(); this.getThreadName(); // fixes http://jira.qos.ch/browse/LBCLASSIC-104 this.getMDCPropertyMap(); } public LoggerContextVO getLoggerContextVO() { return loggerContextVO; } public void setLoggerContextRemoteView(LoggerContextVO loggerContextVO) { this.loggerContextVO = loggerContextVO; } public String getMessage() { return message; } public void setMessage(String message) { if (this.message != null) { throw new IllegalStateException( "The message for this event has been set already."); } this.message = message; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public void setLevel(Level level) { if (this.level != null) { throw new IllegalStateException( "The level has been already set for this event."); } this.level = level; } /** * Get the caller information for this logging event. If caller information is * null at the time of its invocation, this method extracts location * information. The collected information is cached for future use. * <p/> * <p> * Note that after serialization it is impossible to correctly extract caller * information. * </p> */ public StackTraceElement[] getCallerData() { if (callerDataArray == null) { callerDataArray = CallerData.extract(new Throwable(), fqnOfLoggerClass, loggerContext.getMaxCallerDataDepth(), loggerContext.getFrameworkPackages()); } return callerDataArray; } public boolean hasCallerData() { return (callerDataArray != null); } public void setCallerData(StackTraceElement[] callerDataArray) { this.callerDataArray = callerDataArray; } public Marker getMarker() { return marker; } public void setMarker(Marker marker) { if (this.marker != null) { throw new IllegalStateException( "The marker has been already set for this event."); } this.marker = marker; } public long getContextBirthTime() { return loggerContextVO.getBirthTime(); } // lazy computation as suggested in LOGBACK-495 public String getFormattedMessage() { if (formattedMessage != null) { return formattedMessage; } if (argumentArray != null) { formattedMessage = MessageFormatter.arrayFormat(message, argumentArray) .getMessage(); } else { formattedMessage = message; } return formattedMessage; } public Map<String, String> getMDCPropertyMap() { // populate mdcPropertyMap if null if (mdcPropertyMap == null) { MDCAdapter mdc = MDC.getMDCAdapter(); if (mdc instanceof LogbackMDCAdapter) mdcPropertyMap = ((LogbackMDCAdapter) mdc).getPropertyMap(); else mdcPropertyMap = mdc.getCopyOfContextMap(); } // mdcPropertyMap still null, use CACHED_NULL_MAP if (mdcPropertyMap == null) mdcPropertyMap = CACHED_NULL_MAP; return mdcPropertyMap; } /** * Set the MDC map for this event. * * @param map * @since 1.0.8 */ public void setMDCPropertyMap(Map<String, String> map) { if (mdcPropertyMap != null) { throw new IllegalStateException( "The MDCPropertyMap has been already set for this event."); } this.mdcPropertyMap = map; } /** * Synonym for [@link #getMDCPropertyMap}. * * @deprecated Replaced by [@link #getMDCPropertyMap} */ public Map<String, String> getMdc() { return getMDCPropertyMap(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); sb.append(level).append("] "); sb.append(getFormattedMessage()); return sb.toString(); } /** * LoggerEventVO instances should be used for serialization. Use * {@link LoggingEventVO#build(ILoggingEvent) build} method to create the LoggerEventVO instance. * * @since 1.0.11 */ private void writeObject(ObjectOutputStream out) throws IOException { throw new UnsupportedOperationException(this.getClass() + " does not support serialization. " + "Use LoggerEventVO instance instead. See also LoggerEventVO.build method."); } }
package fi.hut.cs.drumbeat.ifc.convert.ifc2rdf; import java.util.*; import java.util.regex.Matcher; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import fi.hut.cs.drumbeat.common.config.ConfigurationItemEx; import fi.hut.cs.drumbeat.common.config.document.ConfigurationParserException; import fi.hut.cs.drumbeat.common.config.document.ConverterPoolConfigurationSection; import fi.hut.cs.drumbeat.rdf.*; public class Ifc2RdfConversionContext extends OwlProfile { ///////////////////////// // STATIC MEMBERS ///////////////////////// public static final String CONFIGURATION_SECTION_CONVERTER_TYPE_NAME = "Ifc2Rdf"; private static final String CONFIGURATION_PROPERTY_OWL_PROFILE = "OwlProfile"; private static final String CONFIGURATION_PROPERTY_CONVERSION_OPTIONS_PREFIX = "Options."; private static final String CONFIGURATION_PROPERTY_ONTOLOGY_PREFIX = "Ontology.Prefix"; private static final String CONFIGURATION_PROPERTY_ONTOLOGY_NAMESPACE_FORMAT = "Ontology.NamespaceFormat"; private static final String CONFIGURATION_PROPERTY_MODEL_PREFIX = "Model.Prefix"; private static final String CONFIGURATION_PROPERTY_MODEL_NAMESPACE_FORMAT = "Model.NamespaceFormat"; private static final String CONFIGURATION_NAMESPACE_FORMAT_VARIABLE_SCHEMA_VERSION = Matcher.quoteReplacement("$Schema.Version$"); private static final String CONFIGURATION_VARIABLE_CONVERTER_CONTEXT_NAME = Matcher.quoteReplacement("$Converter.Context.Name$"); public static Ifc2RdfConversionContext loadFromConfigurationFile(String contextName) throws ConfigurationParserException { ConverterPoolConfigurationSection configurationSection = ConverterPoolConfigurationSection.getInstance(Ifc2RdfConversionContext.CONFIGURATION_SECTION_CONVERTER_TYPE_NAME); ConfigurationItemEx configuration; if (contextName != null) { configuration = configurationSection.getConfigurationPool().getByName(contextName); } else { configuration = configurationSection.getConfigurationPool().getDefault(); } Ifc2RdfConversionContext context = new Ifc2RdfConversionContext(configuration); return context; } ///////////////////////// // NON-STATIC MEMBERS ///////////////////////// private String name; private String ontologyPrefix; private String ontologyNamespaceFormat; private String modelPrefix; private String modelNamespaceFormat; private EnumSet<Ifc2RdfConversionOptionsEnum> conversionOptions; public Ifc2RdfConversionContext(ConfigurationItemEx configuration) { super(OwlProfileEnum.valueOf(configuration.getProperties().getProperty(CONFIGURATION_PROPERTY_OWL_PROFILE))); name = configuration.getName(); Properties properties = configuration.getProperties(); conversionOptions = EnumSet.noneOf(Ifc2RdfConversionOptionsEnum.class); for (String propertyName : properties.stringPropertyNames()) { if (propertyName.startsWith(CONFIGURATION_PROPERTY_CONVERSION_OPTIONS_PREFIX) && Boolean.parseBoolean(properties.getProperty(propertyName))) { String conversionOptionValue = propertyName.substring(CONFIGURATION_PROPERTY_CONVERSION_OPTIONS_PREFIX.length()); conversionOptions.add(Ifc2RdfConversionOptionsEnum.valueOf(conversionOptionValue)); } } ontologyPrefix = properties.getProperty(CONFIGURATION_PROPERTY_ONTOLOGY_PREFIX, Ifc2RdfVocabulary.DEFAULT_ONTOLOGY_PREFIX); ontologyNamespaceFormat = properties.getProperty(CONFIGURATION_PROPERTY_ONTOLOGY_NAMESPACE_FORMAT, Ifc2RdfVocabulary.DEFAULT_ONTOLOGY_NAMESPACE_FORMAT) .replaceAll(CONFIGURATION_NAMESPACE_FORMAT_VARIABLE_SCHEMA_VERSION, "%1s") .replaceAll(CONFIGURATION_VARIABLE_CONVERTER_CONTEXT_NAME, "%2s"); modelPrefix = properties.getProperty(CONFIGURATION_PROPERTY_MODEL_PREFIX, Ifc2RdfVocabulary.DEFAULT_MODEL_PREFIX); modelNamespaceFormat = properties.getProperty(CONFIGURATION_PROPERTY_MODEL_NAMESPACE_FORMAT, Ifc2RdfVocabulary.DEFAULT_MODEL_NAMESPACE_FORMAT) .replaceAll(CONFIGURATION_NAMESPACE_FORMAT_VARIABLE_SCHEMA_VERSION, "%1s") .replaceAll(CONFIGURATION_VARIABLE_CONVERTER_CONTEXT_NAME, "%2s"); } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @return the ontologyPrefix */ public String getOntologyPrefix() { return ontologyPrefix; } /** * @param ontologyPrefix the ontologyPrefix to set */ public void setOntologyPrefix(String ontologyPrefix) { this.ontologyPrefix = ontologyPrefix; } /** * @return the ontologyNamespaceFormat */ public String getOntologyNamespaceFormat() { return ontologyNamespaceFormat; } /** * @param ontologyNamespaceFormat the ontologyNamespaceFormat to set */ public void setOntologyNamespaceFormat(String ontologyNamespaceFormat) { this.ontologyNamespaceFormat = ontologyNamespaceFormat; } /** * @return the modelPrefix */ public String getModelPrefix() { return modelPrefix; } /** * @param modelPrefix the modelPrefix to set */ public void setModelPrefix(String modelPrefix) { this.modelPrefix = modelPrefix; } /** * @return the modelNamespaceFormat */ public String getModelNamespaceFormat() { return modelNamespaceFormat; } /** * @param modelNamespaceFormat the modelNamespaceFormat to set */ public void setModelNamespaceFormat(String modelNamespaceFormat) { this.modelNamespaceFormat = modelNamespaceFormat; } /** * @return the conversionOptions */ public EnumSet<Ifc2RdfConversionOptionsEnum> getConversionOptions() { return conversionOptions; } /** * @param conversionOptions the conversionOptions to set */ public void setConversionOptions(EnumSet<Ifc2RdfConversionOptionsEnum> conversionOptions) { this.conversionOptions = conversionOptions; } public boolean allowPrintingPropertyDomainAndRangeAsUnion() { return supportsRdfProperty(RDFS.domain, EnumSet.of(RdfTripleObjectTypeEnum.NonClassIdentifier)) && conversionOptions.contains(Ifc2RdfConversionOptionsEnum.PrintPropertyDomainAndRangeAsUnion); } @Override public boolean supportsRdfProperty(Resource property, EnumSet<RdfTripleObjectTypeEnum> tripleObjectType) { if (!super.supportsRdfProperty(property, tripleObjectType)) { return false; } if (property.equals(RdfVocabulary.OLO.index)) { return conversionOptions.contains(Ifc2RdfConversionOptionsEnum.ForceConvertRdfListToOloOrderedList); } return true; } public boolean isEnabledOption(Ifc2RdfConversionOptionsEnum conversionOption) { if (conversionOptions.contains(conversionOption)) { if (conversionOption == Ifc2RdfConversionOptionsEnum.PrintPropertyCardinality) { return supportsRdfProperty(OWL.cardinality, EnumSet.of(RdfTripleObjectTypeEnum.ZeroOrOne)); } return true; } else { if (conversionOption == Ifc2RdfConversionOptionsEnum.ForceConvertEnumerationValuesToString) { return !supportsRdfProperty(OWL.oneOf, RdfTripleObjectTypeEnum.ObjectList); } else if (conversionOption == Ifc2RdfConversionOptionsEnum.ForceConvertBooleanValuesToString) { return !supportXsdType(XSD.xboolean); } return false; } } }
/* Copyright (c) 2012-2016 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Johnathan Garrett (LMN Solutions) - initial implementation */ package org.locationtech.geogig.test.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.locationtech.geogig.model.ObjectId; import org.locationtech.geogig.model.Ref; import org.locationtech.geogig.model.RevCommit; import org.locationtech.geogig.model.SymRef; import org.locationtech.geogig.plumbing.RefParse; import org.locationtech.geogig.plumbing.UpdateRef; import org.locationtech.geogig.plumbing.UpdateSymRef; import org.locationtech.geogig.porcelain.BranchCreateOp; import org.locationtech.geogig.porcelain.CheckoutOp; import org.locationtech.geogig.porcelain.CloneOp; import org.locationtech.geogig.porcelain.CommitOp; import org.locationtech.geogig.porcelain.LogOp; import org.locationtech.geogig.porcelain.PullOp; import org.locationtech.geogig.remote.RemoteRepositoryTestCase; import com.google.common.base.Optional; public class PullOpTest extends RemoteRepositoryTestCase { @Rule public ExpectedException exception = ExpectedException.none(); private LinkedList<RevCommit> expectedMaster; private LinkedList<RevCommit> expectedBranch; @Override protected void setUpInternal() throws Exception { // Commit several features to the remote expectedMaster = new LinkedList<RevCommit>(); expectedBranch = new LinkedList<RevCommit>(); insertAndAdd(remoteGeogig.geogig, points1); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); expectedBranch.addFirst(commit); // Create and checkout branch1 remoteGeogig.geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("Branch1") .call(); // Commit some changes to branch1 insertAndAdd(remoteGeogig.geogig, points2); commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedBranch.addFirst(commit); insertAndAdd(remoteGeogig.geogig, points3); commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedBranch.addFirst(commit); // Make sure Branch1 has all of the commits Iterator<RevCommit> logs = remoteGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedBranch, logged); // Checkout master and commit some changes remoteGeogig.geogig.command(CheckoutOp.class).setSource("master").call(); insertAndAdd(remoteGeogig.geogig, lines1); commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); insertAndAdd(remoteGeogig.geogig, lines2); commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Make sure master has all of the commits logs = remoteGeogig.geogig.command(LogOp.class).call(); logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); // Make sure the local repository has no commits prior to clone logs = localGeogig.geogig.command(LogOp.class).call(); assertNotNull(logs); assertFalse(logs.hasNext()); // clone from the remote CloneOp clone = clone(); clone.setRepositoryURL(remoteGeogig.envHome.toURI().toString()).setBranch("Branch1").call(); // Make sure the local repository got all of the commits logs = localGeogig.geogig.command(LogOp.class).call(); logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedBranch, logged); // Make sure the local master matches the remote localGeogig.geogig.command(CheckoutOp.class).setSource("master").call(); logs = localGeogig.geogig.command(LogOp.class).call(); logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullRebase() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Pull the commit PullOp pull = pull(); pull.setRebase(true).setAll(true).call(); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullNullCurrentBranch() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); localGeogig.geogig.command(UpdateRef.class).setName("master").setNewValue(ObjectId.NULL) .call(); localGeogig.geogig.command(UpdateSymRef.class).setName(Ref.HEAD).setNewValue("master") .call(); // Pull the commit PullOp pull = pull(); pull.setRebase(true).call(); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullMerge() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Pull the commit PullOp pull = pull(); pull.setRemote("origin").call(); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullRefspecs() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Pull the commit PullOp pull = pull(); pull.addRefSpec("master:newbranch"); pull.setRebase(true).call(); final Optional<Ref> currHead = localGeogig.geogig.command(RefParse.class).setName(Ref.HEAD) .call(); assertTrue(currHead.isPresent()); assertTrue(currHead.get() instanceof SymRef); final SymRef headRef = (SymRef) currHead.get(); final String currentBranch = Ref.localName(headRef.getTarget()); assertEquals("newbranch", currentBranch); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullRefspecForce() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Pull the commit PullOp pull = pull(); pull.addRefSpec("+master:newbranch"); pull.setRebase(true).call(); final Optional<Ref> currHead = localGeogig.geogig.command(RefParse.class).setName(Ref.HEAD) .call(); assertTrue(currHead.isPresent()); assertTrue(currHead.get() instanceof SymRef); final SymRef headRef = (SymRef) currHead.get(); final String currentBranch = Ref.localName(headRef.getTarget()); assertEquals("newbranch", currentBranch); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullMultipleRefspecs() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Pull the commit PullOp pull = pull(); pull.addRefSpec("master:newbranch"); pull.addRefSpec("Branch1:newbranch2"); pull.setRebase(true).call(); final Optional<Ref> currHead = localGeogig.geogig.command(RefParse.class).setName(Ref.HEAD) .call(); assertTrue(currHead.isPresent()); assertTrue(currHead.get() instanceof SymRef); final SymRef headRef = (SymRef) currHead.get(); final String currentBranch = Ref.localName(headRef.getTarget()); assertEquals("newbranch2", currentBranch); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedBranch, logged); localGeogig.geogig.command(CheckoutOp.class).setSource("newbranch").call(); logs = localGeogig.geogig.command(LogOp.class).call(); logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } @Test public void testPullTooManyRefs() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Pull the commit PullOp pull = pull(); pull.addRefSpec("master:newbranch:newbranch2"); exception.expect(IllegalArgumentException.class); pull.setRebase(true).call(); } @Test public void testPullToCurrentBranch() throws Exception { // Add a commit to the remote insertAndAdd(remoteGeogig.geogig, lines3); RevCommit commit = remoteGeogig.geogig.command(CommitOp.class).call(); expectedMaster.addFirst(commit); // Make sure the local master matches the remote localGeogig.geogig.command(BranchCreateOp.class).setName("mynewbranch") .setAutoCheckout(true).call(); // Pull the commit PullOp pull = pull(); pull.addRefSpec("master"); pull.setRebase(true).call(); final Optional<Ref> currHead = localGeogig.geogig.command(RefParse.class).setName(Ref.HEAD) .call(); assertTrue(currHead.isPresent()); assertTrue(currHead.get() instanceof SymRef); final SymRef headRef = (SymRef) currHead.get(); final String currentBranch = Ref.localName(headRef.getTarget()); assertEquals("mynewbranch", currentBranch); Iterator<RevCommit> logs = localGeogig.geogig.command(LogOp.class).call(); List<RevCommit> logged = new ArrayList<RevCommit>(); for (; logs.hasNext();) { logged.add(logs.next()); } assertEquals(expectedMaster, logged); } }
package org.testng; import static org.testng.internal.Utils.isStringBlank; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.internal.Attributes; import org.testng.internal.IConfiguration; import org.testng.internal.IInvoker; import org.testng.internal.Utils; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.thread.ThreadUtil; import org.testng.reporters.JUnitXMLReporter; import org.testng.reporters.TestHTMLReporter; import org.testng.reporters.TextReporter; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import java.io.File; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.inject.Injector; /** * <CODE>SuiteRunner</CODE> is responsible for running all the tests included in one * suite. The test start is triggered by {@link #run()} method. * * @author Cedric Beust, Apr 26, 2004 */ public class SuiteRunner implements ISuite, Serializable, IInvokedMethodListener { /* generated */ private static final long serialVersionUID = 5284208932089503131L; private static final String DEFAULT_OUTPUT_DIR = "test-output"; private Map<String, ISuiteResult> m_suiteResults = Collections.synchronizedMap(Maps.<String, ISuiteResult>newLinkedHashMap()); transient private List<TestRunner> m_testRunners = Lists.newArrayList(); transient private Map<Class<? extends ISuiteListener>, ISuiteListener> m_listeners = Maps.newHashMap(); transient private TestListenerAdapter m_textReporter = new TestListenerAdapter(); private String m_outputDir; // DEFAULT_OUTPUT_DIR; private XmlSuite m_suite; private Injector m_parentInjector; transient private List<ITestListener> m_testListeners = Lists.newArrayList(); transient private ITestRunnerFactory m_tmpRunnerFactory; transient private ITestRunnerFactory m_runnerFactory; transient private boolean m_useDefaultListeners = true; // The remote host where this suite was run, or null if run locally private String m_host; // The configuration transient private IConfiguration m_configuration; transient private ITestObjectFactory m_objectFactory; transient private Boolean m_skipFailedInvocationCounts = Boolean.FALSE; transient private List<IMethodInterceptor> m_methodInterceptors; private Map<Class<? extends IInvokedMethodListener>, IInvokedMethodListener> m_invokedMethodListeners; /** The list of all the methods invoked during this run */ private List<IInvokedMethod> m_invokedMethods = Collections.synchronizedList(Lists.<IInvokedMethod>newArrayList()); private List<ITestNGMethod> m_allTestMethods = Lists.newArrayList(); // transient private IAnnotationTransformer m_annotationTransformer = null; public SuiteRunner(IConfiguration configuration, XmlSuite suite, String outputDir) { this(configuration, suite, outputDir, null); } public SuiteRunner(IConfiguration configuration, XmlSuite suite, String outputDir, ITestRunnerFactory runnerFactory) { this(configuration, suite, outputDir, runnerFactory, false); } public SuiteRunner(IConfiguration configuration, XmlSuite suite, String outputDir, ITestRunnerFactory runnerFactory, boolean useDefaultListeners) { this(configuration, suite, outputDir, runnerFactory, useDefaultListeners, new ArrayList<IMethodInterceptor>() /* method interceptor */, null /* invoked method listeners */, null /* test listeners */); } protected SuiteRunner(IConfiguration configuration, XmlSuite suite, String outputDir, ITestRunnerFactory runnerFactory, boolean useDefaultListeners, List<IMethodInterceptor> methodInterceptors, List<IInvokedMethodListener> invokedMethodListeners, List<ITestListener> testListeners) { init(configuration, suite, outputDir, runnerFactory, useDefaultListeners, methodInterceptors, invokedMethodListeners, testListeners); } private void init(IConfiguration configuration, XmlSuite suite, String outputDir, ITestRunnerFactory runnerFactory, boolean useDefaultListeners, List<IMethodInterceptor> methodInterceptors, List<IInvokedMethodListener> invokedMethodListener, List<ITestListener> testListeners) { m_configuration = configuration; m_suite = suite; m_useDefaultListeners = useDefaultListeners; m_tmpRunnerFactory= runnerFactory; m_methodInterceptors = methodInterceptors != null ? methodInterceptors : new ArrayList<IMethodInterceptor>(); setOutputDir(outputDir); m_objectFactory = m_configuration.getObjectFactory(); if(m_objectFactory == null) { m_objectFactory = suite.getObjectFactory(); } // Add our own IInvokedMethodListener m_invokedMethodListeners = Maps.newHashMap(); if (invokedMethodListener != null) { for (IInvokedMethodListener listener : invokedMethodListener) { m_invokedMethodListeners.put(listener.getClass(), listener); } } m_invokedMethodListeners.put(getClass(), this); m_skipFailedInvocationCounts = suite.skipFailedInvocationCounts(); if (null != testListeners) { m_testListeners.addAll(testListeners); } m_runnerFactory = buildRunnerFactory(); // Order the <test> tags based on their order of appearance in testng.xml List<XmlTest> xmlTests = m_suite.getTests(); Collections.sort(xmlTests, new Comparator<XmlTest>() { @Override public int compare(XmlTest arg0, XmlTest arg1) { return arg0.getIndex() - arg1.getIndex(); } }); for (XmlTest test : xmlTests) { TestRunner tr = m_runnerFactory.newTestRunner(this, test, m_invokedMethodListeners.values()); // // Install the method interceptor, if any was passed // for (IMethodInterceptor methodInterceptor : m_methodInterceptors) { tr.addMethodInterceptor(methodInterceptor); } // Reuse the same text reporter so we can accumulate all the results // (this is used to display the final suite report at the end) tr.addListener(m_textReporter); m_testRunners.add(tr); // Add the methods found in this test to our global count m_allTestMethods.addAll(Arrays.asList(tr.getAllTestMethods())); } } @Override public XmlSuite getXmlSuite() { return m_suite; } @Override public String getName() { return m_suite.getName(); } public void setObjectFactory(ITestObjectFactory objectFactory) { m_objectFactory = objectFactory; } public void setReportResults(boolean reportResults) { m_useDefaultListeners = reportResults; } private void invokeListeners(boolean start) { for (ISuiteListener sl : m_listeners.values()) { if (start) { sl.onStart(this); } else { sl.onFinish(this); } } } private void setOutputDir(String outputdir) { if (isStringBlank(outputdir) && m_useDefaultListeners) { outputdir = DEFAULT_OUTPUT_DIR; } m_outputDir = (null != outputdir) ? new File(outputdir).getAbsolutePath() : null; } private ITestRunnerFactory buildRunnerFactory() { ITestRunnerFactory factory = null; if (null == m_tmpRunnerFactory) { factory = new DefaultTestRunnerFactory(m_configuration, m_testListeners.toArray(new ITestListener[m_testListeners.size()]), m_useDefaultListeners, m_skipFailedInvocationCounts); } else { factory = new ProxyTestRunnerFactory( m_testListeners.toArray(new ITestListener[m_testListeners.size()]), m_tmpRunnerFactory); } return factory; } @Override public String getParallel() { return m_suite.getParallel().toString(); } public String getParentModule() { return m_suite.getParentModule(); } @Override public String getGuiceStage() { return m_suite.getGuiceStage(); } public Injector getParentInjector() { return m_parentInjector; } public void setParentInjector(Injector injector) { m_parentInjector = injector; } @Override public void run() { invokeListeners(true /* start */); try { privateRun(); } finally { invokeListeners(false /* stop */); } } private void privateRun() { // Map for unicity, Linked for guaranteed order Map<Method, ITestNGMethod> beforeSuiteMethods= new LinkedHashMap<>(); Map<Method, ITestNGMethod> afterSuiteMethods = new LinkedHashMap<>(); IInvoker invoker = null; // Get the invoker and find all the suite level methods for (TestRunner tr: m_testRunners) { // TODO: Code smell. Invoker should belong to SuiteRunner, not TestRunner // -- cbeust invoker = tr.getInvoker(); for (ITestNGMethod m : tr.getBeforeSuiteMethods()) { beforeSuiteMethods.put(m.getMethod(), m); } for (ITestNGMethod m : tr.getAfterSuiteMethods()) { afterSuiteMethods.put(m.getMethod(), m); } } // // Invoke beforeSuite methods (the invoker can be null // if the suite we are currently running only contains // a <file-suite> tag and no real tests) // if (invoker != null) { if(beforeSuiteMethods.values().size() > 0) { invoker.invokeConfigurations(null, beforeSuiteMethods.values().toArray(new ITestNGMethod[beforeSuiteMethods.size()]), m_suite, m_suite.getParameters(), null, /* no parameter values */ null /* instance */ ); } Utils.log("SuiteRunner", 3, "Created " + m_testRunners.size() + " TestRunners"); // // Run all the test runners // boolean testsInParallel = XmlSuite.ParallelMode.TESTS.equals(m_suite.getParallel()); if (!testsInParallel) { runSequentially(); } else { runInParallelTestMode(); } // SuitePlan sp = new SuitePlan(); // for (TestRunner tr : m_testRunners) { // sp.addTestPlan(tr.getTestPlan()); // } // sp.dump(); // // Invoke afterSuite methods // if (afterSuiteMethods.values().size() > 0) { invoker.invokeConfigurations(null, afterSuiteMethods.values().toArray(new ITestNGMethod[afterSuiteMethods.size()]), m_suite, m_suite.getAllParameters(), null, /* no parameter values */ null /* instance */); } } } private List<IReporter> m_reporters = Lists.newArrayList(); private void addReporter(IReporter listener) { m_reporters.add(listener); } void addConfigurationListener(IConfigurationListener listener) { m_configuration.addConfigurationListener(listener); } public List<IReporter> getReporters() { return m_reporters; } private void runSequentially() { for (TestRunner tr : m_testRunners) { runTest(tr); } } private void runTest(TestRunner tr) { tr.run(); ISuiteResult sr = new SuiteResult(m_suite, tr); m_suiteResults.put(tr.getName(), sr); } /** * Implement <suite parallel="tests">. * Since this kind of parallelism happens at the suite level, we need a special code path * to execute it. All the other parallelism strategies are implemented at the test level * in TestRunner#createParallelWorkers (but since this method deals with just one <test> * tag, it can't implement <suite parallel="tests">, which is why we're doing it here). */ private void runInParallelTestMode() { List<Runnable> tasks= Lists.newArrayList(m_testRunners.size()); for(TestRunner tr: m_testRunners) { tasks.add(new SuiteWorker(tr)); } ThreadUtil.execute(tasks, m_suite.getThreadCount(), m_suite.getTimeOut(XmlTest.DEFAULT_TIMEOUT_MS), false); } private class SuiteWorker implements Runnable { private TestRunner m_testRunner; public SuiteWorker(TestRunner tr) { m_testRunner = tr; } @Override public void run() { Utils.log("[SuiteWorker]", 4, "Running XML Test '" + m_testRunner.getTest().getName() + "' in Parallel"); runTest(m_testRunner); } } /** * Registers ISuiteListeners interested in reporting the result of the current * suite. * * @param reporter */ protected void addListener(ISuiteListener reporter) { m_listeners.put(reporter.getClass(), reporter); } @Override public void addListener(ITestNGListener listener) { if (listener instanceof IInvokedMethodListener) { IInvokedMethodListener invokedMethodListener = (IInvokedMethodListener) listener; m_invokedMethodListeners.put(invokedMethodListener.getClass(), invokedMethodListener); } if (listener instanceof ISuiteListener) { addListener((ISuiteListener) listener); } if (listener instanceof IReporter) { addReporter((IReporter) listener); } if (listener instanceof IConfigurationListener) { addConfigurationListener((IConfigurationListener) listener); } } @Override public String getOutputDirectory() { return m_outputDir + File.separatorChar + getName(); } @Override public Map<String, ISuiteResult> getResults() { return m_suiteResults; } /** * FIXME: should be removed? * * @see org.testng.ISuite#getParameter(java.lang.String) */ @Override public String getParameter(String parameterName) { return m_suite.getParameter(parameterName); } /** * @see org.testng.ISuite#getMethodsByGroups() */ @Override public Map<String, Collection<ITestNGMethod>> getMethodsByGroups() { Map<String, Collection<ITestNGMethod>> result = Maps.newHashMap(); for (TestRunner tr : m_testRunners) { ITestNGMethod[] methods = tr.getAllTestMethods(); for (ITestNGMethod m : methods) { String[] groups = m.getGroups(); for (String groupName : groups) { Collection<ITestNGMethod> testMethods = result.get(groupName); if (null == testMethods) { testMethods = Lists.newArrayList(); result.put(groupName, testMethods); } testMethods.add(m); } } } return result; } /** * @see org.testng.ISuite#getInvokedMethods() */ @Override public Collection<ITestNGMethod> getInvokedMethods() { return getIncludedOrExcludedMethods(true /* included */); } /** * @see org.testng.ISuite#getExcludedMethods() */ @Override public Collection<ITestNGMethod> getExcludedMethods() { return getIncludedOrExcludedMethods(false/* included */); } private Collection<ITestNGMethod> getIncludedOrExcludedMethods(boolean included) { List<ITestNGMethod> result= Lists.newArrayList(); for (TestRunner tr : m_testRunners) { Collection<ITestNGMethod> methods = included ? tr.getInvokedMethods() : tr.getExcludedMethods(); for (ITestNGMethod m : methods) { result.add(m); } } return result; } @Override public IObjectFactory getObjectFactory() { return m_objectFactory instanceof IObjectFactory ? (IObjectFactory) m_objectFactory : null; } @Override public IObjectFactory2 getObjectFactory2() { return m_objectFactory instanceof IObjectFactory2 ? (IObjectFactory2) m_objectFactory : null; } /** * Returns the annotation finder for the given annotation type. * @return the annotation finder for the given annotation type. */ @Override public IAnnotationFinder getAnnotationFinder() { return m_configuration.getAnnotationFinder(); } public static void ppp(String s) { System.out.println("[SuiteRunner] " + s); } /** * The default implementation of {@link ITestRunnerFactory}. */ private static class DefaultTestRunnerFactory implements ITestRunnerFactory { private ITestListener[] m_failureGenerators; private boolean m_useDefaultListeners; private boolean m_skipFailedInvocationCounts; private IConfiguration m_configuration; public DefaultTestRunnerFactory(IConfiguration configuration, ITestListener[] failureListeners, boolean useDefaultListeners, boolean skipFailedInvocationCounts) { m_configuration = configuration; m_failureGenerators = failureListeners; m_useDefaultListeners = useDefaultListeners; m_skipFailedInvocationCounts = skipFailedInvocationCounts; } @Override public TestRunner newTestRunner(ISuite suite, XmlTest test, Collection<IInvokedMethodListener> listeners) { boolean skip = m_skipFailedInvocationCounts; if (! skip) { skip = test.skipFailedInvocationCounts(); } TestRunner testRunner = new TestRunner(m_configuration, suite, test, suite.getOutputDirectory(), suite.getAnnotationFinder(), skip, listeners); if (m_useDefaultListeners) { testRunner.addListener(new TestHTMLReporter()); testRunner.addListener(new JUnitXMLReporter()); //TODO: Moved these here because maven2 has output reporters running //already, the output from these causes directories to be created with //files. This is not the desired behaviour of running tests in maven2. //Don't know what to do about this though, are people relying on these //to be added even with defaultListeners set to false? testRunner.addListener(new TextReporter(testRunner.getName(), TestRunner.getVerbose())); } for (ITestListener itl : m_failureGenerators) { testRunner.addListener(itl); } for (IConfigurationListener cl : m_configuration.getConfigurationListeners()) { testRunner.addConfigurationListener(cl); } return testRunner; } } private static class ProxyTestRunnerFactory implements ITestRunnerFactory { private ITestListener[] m_failureGenerators; private ITestRunnerFactory m_target; public ProxyTestRunnerFactory(ITestListener[] failureListeners, ITestRunnerFactory target) { m_failureGenerators = failureListeners; m_target= target; } @Override public TestRunner newTestRunner(ISuite suite, XmlTest test, Collection<IInvokedMethodListener> listeners) { TestRunner testRunner= m_target.newTestRunner(suite, test, listeners); testRunner.addListener(new TextReporter(testRunner.getName(), TestRunner.getVerbose())); for (ITestListener itl : m_failureGenerators) { testRunner.addListener(itl); } return testRunner; } } public void setHost(String host) { m_host = host; } @Override public String getHost() { return m_host; } private SuiteRunState m_suiteState= new SuiteRunState(); /** * @see org.testng.ISuite#getSuiteState() */ @Override public SuiteRunState getSuiteState() { return m_suiteState; } public void setSkipFailedInvocationCounts(Boolean skipFailedInvocationCounts) { if (skipFailedInvocationCounts != null) { m_skipFailedInvocationCounts = skipFailedInvocationCounts; } } private IAttributes m_attributes = new Attributes(); @Override public Object getAttribute(String name) { return m_attributes.getAttribute(name); } @Override public void setAttribute(String name, Object value) { m_attributes.setAttribute(name, value); } @Override public Set<String> getAttributeNames() { return m_attributes.getAttributeNames(); } @Override public Object removeAttribute(String name) { return m_attributes.removeAttribute(name); } ///// // implements IInvokedMethodListener // @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { if (method == null) { throw new NullPointerException("Method should not be null"); } m_invokedMethods.add(method); } // // implements IInvokedMethodListener ///// @Override public List<IInvokedMethod> getAllInvokedMethods() { return m_invokedMethods; } @Override public List<ITestNGMethod> getAllMethods() { return m_allTestMethods; } }
/* * Copyright (c) 2000-2017 TeamDev Ltd. All rights reserved. * Use is subject to Apache 2.0 license terms. */ package com.teamdev.jxmaps.examples; import com.teamdev.jxmaps.ControlPosition; import com.teamdev.jxmaps.GeocoderCallback; import com.teamdev.jxmaps.GeocoderRequest; import com.teamdev.jxmaps.GeocoderResult; import com.teamdev.jxmaps.GeocoderStatus; import com.teamdev.jxmaps.Icon; import com.teamdev.jxmaps.InfoWindow; import com.teamdev.jxmaps.LatLng; import com.teamdev.jxmaps.Map; import com.teamdev.jxmaps.MapEvent; import com.teamdev.jxmaps.MapOptions; import com.teamdev.jxmaps.MapReadyHandler; import com.teamdev.jxmaps.MapStatus; import com.teamdev.jxmaps.MapTypeControlOptions; import com.teamdev.jxmaps.MapViewOptions; import com.teamdev.jxmaps.Marker; import com.teamdev.jxmaps.PhotoOptions; import com.teamdev.jxmaps.PlaceDetailsCallback; import com.teamdev.jxmaps.PlaceDetailsRequest; import com.teamdev.jxmaps.PlaceNearbySearchCallback; import com.teamdev.jxmaps.PlacePhoto; import com.teamdev.jxmaps.PlaceResult; import com.teamdev.jxmaps.PlaceSearchPagination; import com.teamdev.jxmaps.PlaceSearchRequest; import com.teamdev.jxmaps.PlacesService; import com.teamdev.jxmaps.PlacesServiceStatus; import com.teamdev.jxmaps.swing.MapView; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.xml.bind.DatatypeConverter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.ByteArrayOutputStream; import java.io.InputStream; /** * This example demonstrates how to find places on the map. * Also it demonstrates how to get details about selected place. * * @author Vitaly Eremenko * @author Sergei Piletsky */ public class PlacesSearchExample extends MapView implements EditableTextControlPanel { static final MapViewOptions mapOptions; static { // initializing a map view options mapOptions = new MapViewOptions(); // enabling usage of places library mapOptions.importPlaces(); } private final boolean standalone; static final Icon restarantIcon = new Icon(); static final Icon barIcon = new Icon(); static final Icon hotelIcon = new Icon(); static final Icon restarantIconHover = new Icon(); static final Icon barIconHover = new Icon(); static final Icon hotelIconHover = new Icon(); private OptionsWindow optionsWindow; private JTextField addressEdit; private JList placesList; private ExtendedMarker[] markers; private Marker mainMarker; private JPanel controlPanel; static class ExtendedMarker extends Marker { private Icon hoverIcon; private Icon normalIcon; private final Map map; private final PlacesService placesService; public void setPlaceId(String placeId) { this.placeId = placeId; } private String placeId; public ExtendedMarker(Map map, PlacesService placesService) { super(map); this.map = map; this.placesService = placesService; addEventListener("mouseover", new MapEvent() { @Override public void onEvent() { if (hoverIcon != null) { setIcon(hoverIcon); } } }); addEventListener("mouseout", new MapEvent() { @Override public void onEvent() { if (normalIcon != null) { setIcon(normalIcon); } } }); addEventListener("click", new MapEvent() { @Override public void onEvent() { showInfoWindow(); } }); } /** * Showing info window for certain place */ private void showInfoWindow() { // Checking if placeId value is set if (placeId != null) { // Creating place details request PlaceDetailsRequest request = new PlaceDetailsRequest(); // Setting placeId to search request request.setPlaceId(placeId); // Requesting details for the place by provided placeId placesService.getDetails(request, new PlaceDetailsCallback(map) { @Override public void onComplete (PlaceResult result, PlacesServiceStatus status){ // Checking operation status if (status == PlacesServiceStatus.OK) { // Creating a info window InfoWindow window = new InfoWindow(map); // Getting details from result and setting it as info window context window.setContent(getContentByResult(result)); // Setting info window position window.setPosition(getPosition()); // Showing information about place window.open(map, this); } } } ); } } private String getContentByResult(PlaceResult result) { String textContent = "<p><b>" + result.getName() + "</b></p>"; textContent += "<p>" + result.getFormattedAddress() + "</p>"; // Creating a photo options object PhotoOptions option = new PhotoOptions(); // Setting maximum photo height option.setMaxHeight(64); // Setting maximum photo width option.setMaxWidth(64); // Getting photos from result PlacePhoto[] photos = result.getPhotos(); if ((photos != null) && (photos.length > 0)) { PlacePhoto photo = photos[0]; String imageContent = "<table cellspacing=\"0\" cellpadding=\"5\"><tr><td><img src=\"" + photo.getUrl(option); imageContent += "\" /></td><td>"; textContent = imageContent + textContent; textContent += "</td></tr></table>"; } return textContent; } public void setIcons(Icon normalIcon, Icon hoverIcon) { this.normalIcon = normalIcon; this.hoverIcon = hoverIcon; setIcon(this.normalIcon); } } public PlacesSearchExample() { this(false); } public PlacesSearchExample(boolean standalone) { super(mapOptions); this.standalone = standalone; restarantIcon.loadFromStream(PlacesSearchExample.class.getResourceAsStream("res/restaurants_for_map.png"), "png"); barIcon.loadFromStream(PlacesSearchExample.class.getResourceAsStream("res/bars_and_pubs_for_map.png"), "png"); hotelIcon.loadFromStream(PlacesSearchExample.class.getResourceAsStream("res/hotels_for_map.png"), "png"); restarantIconHover.loadFromStream(PlacesSearchExample.class.getResourceAsStream("res/restaurants_for_map.png"), "png"); barIconHover.loadFromStream(PlacesSearchExample.class.getResourceAsStream("res/bars_and_pubs_for_map.png"), "png"); hotelIconHover.loadFromStream(PlacesSearchExample.class.getResourceAsStream("res/hotels_for_map.png"), "png"); // Setting of a ready handler to MapView object. onMapReady will be called when map initialization is done and // the map object is ready to use. Current implementation of onMapReady customizes the map object. setOnMapReadyHandler(new MapReadyHandler() { @Override public void onMapReady(MapStatus status) { // Check if the map is loaded correctly if (status == MapStatus.MAP_STATUS_OK) { init(); } } }); controlPanel = new JPanel(); addressEdit = new JTextField("London, Baker str., 221b"); addressEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { geocodePlace(addressEdit.getText()); } }); placesList = new JList<String>(new String[]{"Restaurants", "Hotels", "Bars and pubs"}); placesList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { findPlaces(); } }); configureControlPanel(); } @Override public JComponent getControlPanel() { return controlPanel; } @Override public int getPreferredHeight() { return 233; } class PlaceOption { final ImageIcon icon; final String name; public PlaceOption(ImageIcon icon, String name) { this.icon = icon; this.name = name; } public ImageIcon getIcon() { return icon; } public String getName() { return name; } } class PlaceOptionsRenderer extends JPanel implements ListCellRenderer { private final Color SELECTION_BACKGROUND = new Color(0xFA, 0xFA, 0xFA); private final JLabel imageLabel; private final JLabel text; public PlaceOptionsRenderer() { setLayout(new GridBagLayout()); imageLabel = new JLabel(); imageLabel.setPreferredSize(new Dimension(18, 18)); text = new JLabel(); Font robotoPlain13 = new Font("Roboto", 0, 13); text.setFont(robotoPlain13); text.setForeground(new Color(0x21, 0x21, 0x21)); add(imageLabel, new GridBagConstraints(0, 0, 1, 3, 0.0, 0.0 , GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(20, 22, 20, 22), 0, 0)); add(text, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0 , GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(20, 8, 20, 22), 0, 0)); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(SELECTION_BACKGROUND); } else { setBackground(list.getBackground()); } PlaceOption placeOption = (PlaceOption) value; imageLabel.setIcon(placeOption.getIcon()); text.setText(placeOption.getName()); return this; } } @Override public void configureControlPanel() { controlPanel.removeAll(); controlPanel.setBackground(Color.white); controlPanel.setLayout(new BorderLayout()); placesList = new JList<PlaceOption>(new PlaceOption[]{ new PlaceOption(new ImageIcon(PlacesSearchExample.class.getResource("res/restaurants.png")), "Restaurants"), new PlaceOption(new ImageIcon(PlacesSearchExample.class.getResource("res/hotels.png")), "Hotels"), new PlaceOption(new ImageIcon(PlacesSearchExample.class.getResource("res/bars_and_pubs.png")), "Bars and pubs"), }); placesList.setCellRenderer(new PlaceOptionsRenderer()); placesList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { findPlaces(); } }); placesList.setOpaque(false); placesList.setCursor(new Cursor(Cursor.HAND_CURSOR)); if (standalone) { controlPanel.add(addressEdit, BorderLayout.NORTH); } controlPanel.add(placesList, BorderLayout.CENTER); } @Override public void onTextEntered(String value) { geocodePlace(value); } @Override public String getInitialText() { return addressEdit.getText(); } private void findPlaces() { if (placesList.getSelectedIndex() < 0) return; // Getting the associated map object final Map map = getMap(); // Creating places search request final PlaceSearchRequest request = new PlaceSearchRequest(); // Setting start point for places search request.setLocation(map.getCenter()); // Setting radius for places search request.setRadius(500.0); final int imageType = placesList.getSelectedIndex(); final Icon iconUrl[] = new Icon[2]; switch (imageType) { case 0: iconUrl[0] = restarantIcon; iconUrl[1] = restarantIconHover; request.setTypes(new String[]{"restaurant"}); break; case 1: iconUrl[0] = hotelIcon; iconUrl[1] = hotelIconHover; request.setTypes(new String[]{"hotels"}); break; case 2: iconUrl[0] = barIcon; iconUrl[1] = barIconHover; request.setTypes(new String[]{"bar"}); break; } // Searching places near specified location getServices().getPlacesService().nearbySearch(request, new PlaceNearbySearchCallback(map) { @Override public void onComplete(PlaceResult[] results, PlacesServiceStatus status, PlaceSearchPagination pagination) { // Checking operation status if (status == PlacesServiceStatus.OK) { clearMarkers(); // Creating markers for each place markers = new ExtendedMarker[results.length]; for (int i=0; i< results.length; ++i) { PlaceResult result = results[i]; // Creating a marker for place found markers[i] = new ExtendedMarker(map, getServices().getPlacesService()); // Associating the marker with placeId (will be used on place details search) markers[i].setPlaceId(result.getPlaceId()); // Moving the marker to place location LatLng location = result.getGeometry() != null ? result.getGeometry().getLocation() : null; // Setting icons for the marker markers[i].setIcons(iconUrl[0],iconUrl[1]); if (location != null) // Setting the marker position markers[i].setPosition(location); } } } }); } private void geocodePlace(String address) { if (mainMarker != null) mainMarker.setVisible(false); mainMarker = null; clearMarkers(); // Getting the associated map object final Map map = getMap(); // Creating geocoder request GeocoderRequest request = new GeocoderRequest(); // Set address for request request.setAddress(address); // Geocoding a position by address getServices().getGeocoder().geocode(request, new GeocoderCallback(map) { @Override public void onComplete(GeocoderResult[] results, GeocoderStatus status) { // Checking operation status if ((status == GeocoderStatus.OK) && (results.length > 0)) { // Getting first result GeocoderResult result = results[0]; // Getting location (coords) LatLng location = result.getGeometry().getLocation(); // Centering map to result location map.setCenter(location); // Initializing main marker mainMarker = new Marker(map); // Moving marker to result location mainMarker.setPosition(location); // Showing marker on map mainMarker.setVisible(true); findPlaces(); } } }); } private void clearMarkers() { if (markers == null) return; for (Marker marker : markers) { marker.setVisible(false); } markers = null; } private void init() { // Getting the associated map object final Map map = getMap(); // Creating a map options object MapOptions options = new MapOptions(); // Creating a map type control options object MapTypeControlOptions controlOptions = new MapTypeControlOptions(); // Changing position of the map type control controlOptions.setPosition(ControlPosition.TOP_RIGHT); // Setting map type control options options.setMapTypeControlOptions(controlOptions); // Setting map options map.setOptions(options); // Setting initial zoom value map.setZoom(15.0); geocodePlace(addressEdit.getText()); } private static void loadAndRegisterCustomFonts() { try { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, PlacesSearchExample.class.getResourceAsStream("res/Roboto-Bold.ttf"))); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, PlacesSearchExample.class.getResourceAsStream("res/Roboto-Medium.ttf"))); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, PlacesSearchExample.class.getResourceAsStream("res/Roboto-Regular.ttf"))); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, PlacesSearchExample.class.getResourceAsStream("res/Roboto-Thin.ttf"))); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, PlacesSearchExample.class.getResourceAsStream("res/Roboto-Light.ttf"))); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { loadAndRegisterCustomFonts(); final PlacesSearchExample sample = new PlacesSearchExample(true); JFrame frame = new JFrame("Places Search"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(sample, BorderLayout.CENTER); frame.setSize(700, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); new OptionsWindow(sample, new Dimension(350, 200)) { @Override public void initContent(JWindow contentWindow) { contentWindow.add(sample.controlPanel); } }; } }
/* * Copyright (c) 2007, intarsys consulting GmbH * * 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 intarsys 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 OWNER 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 de.intarsys.tools.randomaccess; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Logger; /** * Implements random access to a file. */ public class RandomAccessFile extends AbstractRandomAccess { /** The logger to be used in this package */ private static Logger Log = PACKAGE.Log; /** * The wrapped RandomAccessFile of the java library */ private java.io.RandomAccessFile fileAccess; /** * Flag if this is used read only */ private boolean readOnly = false; /** * @param file * to open for random access * @throws FileNotFoundException * if file was not found or the file is locked by a different * process */ public RandomAccessFile(File file) throws IOException { this(file, true); } /** * @param file * to open for random access * @throws FileNotFoundException * if file was not found or the file is locked by a different * process */ public RandomAccessFile(File file, boolean create) throws IOException { if (create && !file.exists()) { File dir = file.getParentFile(); if ((dir != null) && !dir.exists()) { dir.mkdirs(); } file.createNewFile(); } if (!file.exists()) { throw new FileNotFoundException( "file does not exist or can't be created"); } if (file.canWrite()) { try { fileAccess = new java.io.RandomAccessFile(file, "rw"); return; } catch (IOException e) { // canWrite() doesn't check for user permissions // try again with readonly } } fileAccess = new java.io.RandomAccessFile(file, "r"); readOnly = true; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#close() */ public void close() throws IOException { if (fileAccess != null) { fileAccess.close(); } } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#flush() */ public void flush() throws IOException { fileAccess.getChannel().force(true); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getLength() */ public long getLength() throws IOException { return fileAccess.length(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getOffset() */ public long getOffset() throws IOException { return fileAccess.getFilePointer(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#isReadOnly() */ public boolean isReadOnly() { return readOnly; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read() */ public int read() throws IOException { return fileAccess.read(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[]) */ public int read(byte[] buffer) throws IOException { return fileAccess.read(buffer); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[], int, * int) */ public int read(byte[] buffer, int start, int numBytes) throws IOException { return fileAccess.read(buffer, start, numBytes); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#seek(long) */ public void seek(long offset) throws IOException { fileAccess.seek(offset); } public void seekBy(long delta) throws IOException { seek(fileAccess.getFilePointer() + delta); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#setLength(int) */ public void setLength(long newLength) throws IOException { fileAccess.setLength(newLength); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[]) */ public void write(byte[] buffer) throws IOException { fileAccess.write(buffer); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[], int, * int) */ public void write(byte[] buffer, int start, int numBytes) throws IOException { fileAccess.write(buffer, start, numBytes); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(int) */ public void write(int b) throws IOException { fileAccess.write(b); } }
package egovframework.com.ext.jfile.org.json; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. * @author JSON.org * @version 2008-09-18 */ public class JSONTokener { private int index; private Reader reader; private char lastChar; private boolean useLastChar; /** * Construct a JSONTokener from a string. * * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.useLastChar = false; this.index = 0; } /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { if (useLastChar || index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } index -= 1; useLastChar = true; } /** * Get the hex value of a character (base16). * @param c A character between '0' and '9' or between 'A' and 'F' or * between 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } /** * Determine if the source string still contains characters that next() * can consume. * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { char nextChar = next(); if (nextChar == 0) { return false; } back(); return true; } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() throws JSONException { if (this.useLastChar) { this.useLastChar = false; if (this.lastChar != 0) { this.index += 1; } return this.lastChar; } int c; try { c = this.reader.read(); } catch (IOException exc) { throw new JSONException(exc); } if (c <= 0) { // End of stream this.lastChar = 0; return 0; } this.index += 1; this.lastChar = (char) c; return this.lastChar; } /** * Consume the next character, and check that it matches a specified * character. * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next(char c) throws JSONException { char n = next(); if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException * Substring bounds error if there are not * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { return ""; } char[] buffer = new char[n]; int pos = 0; if (this.useLastChar) { this.useLastChar = false; buffer[0] = this.lastChar; pos = 1; } try { int len; while ((pos < n) && ((len = reader.read(buffer, pos, n - pos)) != -1)) { pos += len; } } catch (IOException exc) { throw new JSONException(exc); } this.index += pos; if (pos < n) { throw syntaxError("Substring bounds error"); } this.lastChar = buffer[n - 1]; return new String(buffer); } /** * Get the next char in the string, skipping whitespace. * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { char c = next(); if (c == 0 || c > ' ') { return c; } } } /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. * @param quote The quoting character, either * <code>"</code>&nbsp;<small>(double quote)</small> or * <code>'</code>&nbsp;<small>(single quote)</small>. * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); switch (c) { case 0: case '\n': case '\r': throw syntaxError("Unterminated string"); case '\\': c = next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(next(4), 16)); break; case '"': case '\'': case '\\': case '/': sb.append(c); break; default: throw syntaxError("Illegal escape."); } break; default: if (c == quote) { return sb.toString(); } sb.append(c); } } } /** * Get the text up but not including the specified character or the * end of line, whichever comes first. * @param d A delimiter character. * @return A string. */ public String nextTo(char d) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (c == d || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo(String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object. */ public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); } /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ public char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; reader.mark(Integer.MAX_VALUE); do { c = next(); if (c == 0) { reader.reset(); this.index = startIndex; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + toString()); } /** * Make a printable string of this JSONTokener. * * @return " at character [this.index]" */ public String toString() { return " at character " + 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apach3.http.impl.nio.reactor; import java.io.InterruptedIOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apach3.http.annotation.ThreadSafe; import org.apach3.http.nio.reactor.EventMask; import org.apach3.http.nio.reactor.IOEventDispatch; import org.apach3.http.nio.reactor.IOReactor; import org.apach3.http.nio.reactor.IOReactorException; import org.apach3.http.nio.reactor.IOReactorExceptionHandler; import org.apach3.http.nio.reactor.IOSession; /** * Default implementation of {@link AbstractIOReactor} that serves as a base * for more advanced {@link IOReactor} implementations. This class adds * support for the I/O event dispatching using {@link IOEventDispatch}, * management of buffering sessions, and session timeout handling. * * @since 4.0 */ @ThreadSafe // public methods only public class BaseIOReactor extends AbstractIOReactor { private final long timeoutCheckInterval; private final Set<IOSession> bufferingSessions; private long lastTimeoutCheck; private IOReactorExceptionHandler exceptionHandler = null; private IOEventDispatch eventDispatch = null; /** * Creates new BaseIOReactor instance. * * @param selectTimeout the select timeout. * @throws IOReactorException in case if a non-recoverable I/O error. */ public BaseIOReactor(long selectTimeout) throws IOReactorException { this(selectTimeout, false); } /** * Creates new BaseIOReactor instance. * * @param selectTimeout the select timeout. * @param interestOpsQueueing Ops queueing flag. * * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.1 */ public BaseIOReactor( long selectTimeout, boolean interestOpsQueueing) throws IOReactorException { super(selectTimeout, interestOpsQueueing); this.bufferingSessions = new HashSet<IOSession>(); this.timeoutCheckInterval = selectTimeout; this.lastTimeoutCheck = System.currentTimeMillis(); } /** * Activates the I/O reactor. The I/O reactor will start reacting to I/O * events and dispatch I/O event notifications to the given * {@link IOEventDispatch}. * * @throws InterruptedIOException if the dispatch thread is interrupted. * @throws IOReactorException in case if a non-recoverable I/O error. */ public void execute( final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException { if (eventDispatch == null) { throw new IllegalArgumentException("Event dispatcher may not be null"); } this.eventDispatch = eventDispatch; execute(); } /** * Sets exception handler for this I/O reactor. * * @param exceptionHandler the exception handler. */ public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; } /** * Handles the given {@link RuntimeException}. This method delegates * handling of the exception to the {@link IOReactorExceptionHandler}, * if available. * * @param ex the runtime exception. */ protected void handleRuntimeException(final RuntimeException ex) { if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) { throw ex; } } /** * This I/O reactor implementation does not react to the * {@link SelectionKey#OP_ACCEPT} event. * <p> * Super-classes can override this method to react to the event. */ @Override protected void acceptable(final SelectionKey key) { } /** * This I/O reactor implementation does not react to the * {@link SelectionKey#OP_CONNECT} event. * <p> * Super-classes can override this method to react to the event. */ @Override protected void connectable(final SelectionKey key) { } /** * Processes {@link SelectionKey#OP_READ} event on the given selection key. * This method dispatches the event notification to the * {@link IOEventDispatch#inputReady(IOSession)} method. */ @Override protected void readable(final SelectionKey key) { IOSession session = getSession(key); try { this.eventDispatch.inputReady(session); if (session.hasBufferedInput()) { this.bufferingSessions.add(session); } } catch (CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } catch (RuntimeException ex) { handleRuntimeException(ex); } } /** * Processes {@link SelectionKey#OP_WRITE} event on the given selection key. * This method dispatches the event notification to the * {@link IOEventDispatch#outputReady(IOSession)} method. */ @Override protected void writable(final SelectionKey key) { IOSession session = getSession(key); try { this.eventDispatch.outputReady(session); } catch (CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } catch (RuntimeException ex) { handleRuntimeException(ex); } } /** * Verifies whether any of the sessions associated with the given selection * keys timed out by invoking the {@link #timeoutCheck(SelectionKey, long)} * method. * <p> * This method will also invoke the * {@link IOEventDispatch#inputReady(IOSession)} method on all sessions * that have buffered input data. */ @Override protected void validate(final Set<SelectionKey> keys) { long currentTime = System.currentTimeMillis(); if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) { this.lastTimeoutCheck = currentTime; if (keys != null) { for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) { SelectionKey key = it.next(); timeoutCheck(key, currentTime); } } } if (!this.bufferingSessions.isEmpty()) { for (Iterator<IOSession> it = this.bufferingSessions.iterator(); it.hasNext(); ) { IOSession session = it.next(); if (!session.hasBufferedInput()) { it.remove(); continue; } try { if ((session.getEventMask() & EventMask.READ) > 0) { this.eventDispatch.inputReady(session); if (!session.hasBufferedInput()) { it.remove(); } } } catch (CancelledKeyException ex) { it.remove(); queueClosedSession(session); } catch (RuntimeException ex) { handleRuntimeException(ex); } } } } /** * Processes newly created I/O session. This method dispatches the event * notification to the {@link IOEventDispatch#connected(IOSession)} method. */ @Override protected void sessionCreated(final SelectionKey key, final IOSession session) { try { this.eventDispatch.connected(session); } catch (CancelledKeyException ex) { queueClosedSession(session); } catch (RuntimeException ex) { handleRuntimeException(ex); } } /** * Processes timed out I/O session. This method dispatches the event * notification to the {@link IOEventDispatch#timeout(IOSession)} method. */ @Override protected void sessionTimedOut(final IOSession session) { try { this.eventDispatch.timeout(session); } catch (CancelledKeyException ex) { queueClosedSession(session); } catch (RuntimeException ex) { handleRuntimeException(ex); } } /** * Processes closed I/O session. This method dispatches the event * notification to the {@link IOEventDispatch#disconnected(IOSession)} * method. */ @Override protected void sessionClosed(final IOSession session) { try { this.eventDispatch.disconnected(session); } catch (CancelledKeyException ex) { // ignore } catch (RuntimeException ex) { handleRuntimeException(ex); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import static org.apache.hadoop.hdfs.server.namenode.NNStorage.getFinalizedEditsFileName; import static org.apache.hadoop.hdfs.server.namenode.NNStorage.getImageFileName; import static org.apache.hadoop.hdfs.server.namenode.NNStorage.getInProgressEditsFileName; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.cli.CLITestCmdDFS; import org.apache.hadoop.cli.util.CLICommandDFSAdmin; import org.apache.hadoop.cli.util.CommandExecutor; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory; import org.apache.hadoop.hdfs.server.namenode.JournalSet.JournalAndStream; import org.apache.hadoop.util.Shell; import org.junit.Before; import org.junit.Test; import org.apache.hadoop.thirdparty.com.google.common.collect.ImmutableSet; /** * Startup and checkpoint tests * */ public class TestStorageRestore { public static final String NAME_NODE_HOST = "localhost:"; public static final String NAME_NODE_HTTP_HOST = "0.0.0.0:"; private static final Logger LOG = LoggerFactory.getLogger(TestStorageRestore.class.getName()); private Configuration config; private File hdfsDir=null; static final long seed = 0xAAAAEEFL; static final int blockSize = 4096; static final int fileSize = 8192; private File path1, path2, path3; private MiniDFSCluster cluster; @Before public void setUpNameDirs() throws Exception { config = new HdfsConfiguration(); hdfsDir = new File(MiniDFSCluster.getBaseDirectory()).getCanonicalFile(); if ( hdfsDir.exists() && !FileUtil.fullyDelete(hdfsDir) ) { throw new IOException("Could not delete hdfs directory '" + hdfsDir + "'"); } hdfsDir.mkdirs(); path1 = new File(hdfsDir, "name1"); path2 = new File(hdfsDir, "name2"); path3 = new File(hdfsDir, "name3"); path1.mkdir(); path2.mkdir(); path3.mkdir(); if(!path2.exists() || !path3.exists() || !path1.exists()) { throw new IOException("Couldn't create dfs.name dirs in " + hdfsDir.getAbsolutePath()); } String dfs_name_dir = new String(path1.getPath() + "," + path2.getPath()); System.out.println("configuring hdfsdir is " + hdfsDir.getAbsolutePath() + "; dfs_name_dir = "+ dfs_name_dir + ";dfs_name_edits_dir(only)=" + path3.getPath()); config.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, dfs_name_dir); config.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, dfs_name_dir + "," + path3.getPath()); config.set(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_DIR_KEY,new File(hdfsDir, "secondary").getPath()); FileSystem.setDefaultUri(config, "hdfs://"+NAME_NODE_HOST + "0"); config.set(DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY, "0.0.0.0:0"); // set the restore feature on config.setBoolean(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_RESTORE_KEY, true); } /** * invalidate storage by removing the second and third storage directories */ public void invalidateStorage(FSImage fi, Set<File> filesToInvalidate) throws IOException { ArrayList<StorageDirectory> al = new ArrayList<StorageDirectory>(2); Iterator<StorageDirectory> it = fi.getStorage().dirIterator(); while(it.hasNext()) { StorageDirectory sd = it.next(); if(filesToInvalidate.contains(sd.getRoot())) { LOG.info("causing IO error on " + sd.getRoot()); al.add(sd); } } // simulate an error fi.getStorage().reportErrorsOnDirectories(al); for (JournalAndStream j : fi.getEditLog().getJournals()) { if (j.getManager() instanceof FileJournalManager) { FileJournalManager fm = (FileJournalManager)j.getManager(); if (fm.getStorageDirectory().getRoot().equals(path2) || fm.getStorageDirectory().getRoot().equals(path3)) { EditLogOutputStream mockStream = spy(j.getCurrentStream()); j.setCurrentStreamForTests(mockStream); doThrow(new IOException("Injected fault: write")). when(mockStream).write(any()); } } } } /** * test */ private void printStorages(FSImage image) { FSImageTestUtil.logStorageContents(LOG, image.getStorage()); } /** * test * 1. create DFS cluster with 3 storage directories - 2 EDITS_IMAGE, 1 EDITS * 2. create a cluster and write a file * 3. corrupt/disable one storage (or two) by removing * 4. run doCheckpoint - it will fail on removed dirs (which * will invalidate the storages) * 5. write another file * 6. check that edits and fsimage differ * 7. run doCheckpoint * 8. verify that all the image and edits files are the same. */ @Test public void testStorageRestore() throws Exception { int numDatanodes = 0; cluster = new MiniDFSCluster.Builder(config).numDataNodes(numDatanodes) .manageNameDfsDirs(false) .build(); cluster.waitActive(); SecondaryNameNode secondary = new SecondaryNameNode(config); System.out.println("****testStorageRestore: Cluster and SNN started"); printStorages(cluster.getNameNode().getFSImage()); FileSystem fs = cluster.getFileSystem(); Path path = new Path("/", "test"); assertTrue(fs.mkdirs(path)); System.out.println("****testStorageRestore: dir 'test' created, invalidating storage..."); invalidateStorage(cluster.getNameNode().getFSImage(), ImmutableSet.of(path2, path3)); printStorages(cluster.getNameNode().getFSImage()); System.out.println("****testStorageRestore: storage invalidated"); path = new Path("/", "test1"); assertTrue(fs.mkdirs(path)); System.out.println("****testStorageRestore: dir 'test1' created"); // We did another edit, so the still-active directory at 'path1' // should now differ from the others FSImageTestUtil.assertFileContentsDifferent(2, new File(path1, "current/" + getInProgressEditsFileName(1)), new File(path2, "current/" + getInProgressEditsFileName(1)), new File(path3, "current/" + getInProgressEditsFileName(1))); FSImageTestUtil.assertFileContentsSame( new File(path2, "current/" + getInProgressEditsFileName(1)), new File(path3, "current/" + getInProgressEditsFileName(1))); System.out.println("****testStorageRestore: checkfiles(false) run"); secondary.doCheckpoint(); ///should enable storage.. // We should have a checkpoint through txid 4 in the two image dirs // (txid=4 for BEGIN, mkdir, mkdir, END) FSImageTestUtil.assertFileContentsSame( new File(path1, "current/" + getImageFileName(4)), new File(path2, "current/" + getImageFileName(4))); assertFalse("Should not have any image in an edits-only directory", new File(path3, "current/" + getImageFileName(4)).exists()); // Should have finalized logs in the directory that didn't fail assertTrue("Should have finalized logs in the directory that didn't fail", new File(path1, "current/" + getFinalizedEditsFileName(1,4)).exists()); // Should not have finalized logs in the failed directories assertFalse("Should not have finalized logs in the failed directories", new File(path2, "current/" + getFinalizedEditsFileName(1,4)).exists()); assertFalse("Should not have finalized logs in the failed directories", new File(path3, "current/" + getFinalizedEditsFileName(1,4)).exists()); // The new log segment should be in all of the directories. FSImageTestUtil.assertFileContentsSame( new File(path1, "current/" + getInProgressEditsFileName(5)), new File(path2, "current/" + getInProgressEditsFileName(5)), new File(path3, "current/" + getInProgressEditsFileName(5))); String md5BeforeEdit = FSImageTestUtil.getFileMD5( new File(path1, "current/" + getInProgressEditsFileName(5))); // The original image should still be the previously failed image // directory after it got restored, since it's still useful for // a recovery! FSImageTestUtil.assertFileContentsSame( new File(path1, "current/" + getImageFileName(0)), new File(path2, "current/" + getImageFileName(0))); // Do another edit to verify that all the logs are active. path = new Path("/", "test2"); assertTrue(fs.mkdirs(path)); // Logs should be changed by the edit. String md5AfterEdit = FSImageTestUtil.getFileMD5( new File(path1, "current/" + getInProgressEditsFileName(5))); assertFalse(md5BeforeEdit.equals(md5AfterEdit)); // And all logs should be changed. FSImageTestUtil.assertFileContentsSame( new File(path1, "current/" + getInProgressEditsFileName(5)), new File(path2, "current/" + getInProgressEditsFileName(5)), new File(path3, "current/" + getInProgressEditsFileName(5))); secondary.shutdown(); cluster.shutdown(); // All logs should be finalized by clean shutdown FSImageTestUtil.assertFileContentsSame( new File(path1, "current/" + getFinalizedEditsFileName(5,7)), new File(path2, "current/" + getFinalizedEditsFileName(5,7)), new File(path3, "current/" + getFinalizedEditsFileName(5,7))); } /** * Test dfsadmin -restoreFailedStorage command * @throws Exception */ @Test public void testDfsAdminCmd() throws Exception { cluster = new MiniDFSCluster.Builder(config). numDataNodes(2). manageNameDfsDirs(false).build(); cluster.waitActive(); try { FSImage fsi = cluster.getNameNode().getFSImage(); // it is started with dfs.namenode.name.dir.restore set to true (in SetUp()) boolean restore = fsi.getStorage().getRestoreFailedStorage(); LOG.info("Restore is " + restore); assertEquals(restore, true); // now run DFSAdmnin command String cmd = "-fs NAMENODE -restoreFailedStorage false"; String namenode = config.get(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "file:///"); CommandExecutor executor = new CLITestCmdDFS(cmd, new CLICommandDFSAdmin()).getExecutor(namenode, config); executor.executeCommand(cmd); restore = fsi.getStorage().getRestoreFailedStorage(); assertFalse("After set true call restore is " + restore, restore); // run one more time - to set it to true again cmd = "-fs NAMENODE -restoreFailedStorage true"; executor.executeCommand(cmd); restore = fsi.getStorage().getRestoreFailedStorage(); assertTrue("After set false call restore is " + restore, restore); // run one more time - no change in value cmd = "-fs NAMENODE -restoreFailedStorage check"; CommandExecutor.Result cmdResult = executor.executeCommand(cmd); restore = fsi.getStorage().getRestoreFailedStorage(); assertTrue("After check call restore is " + restore, restore); String commandOutput = cmdResult.getCommandOutput(); assertTrue(commandOutput.contains("restoreFailedStorage is set to true")); } finally { cluster.shutdown(); } } /** * Test to simulate interleaved checkpointing by 2 2NNs after a storage * directory has been taken offline. The first will cause the directory to * come back online, but it won't have any valid contents. The second 2NN will * then try to perform a checkpoint. The NN should not serve up the image or * edits from the restored (empty) dir. */ @Test public void testMultipleSecondaryCheckpoint() throws IOException { SecondaryNameNode secondary = null; try { cluster = new MiniDFSCluster.Builder(config).numDataNodes(1) .manageNameDfsDirs(false).build(); cluster.waitActive(); secondary = new SecondaryNameNode(config); FSImage fsImage = cluster.getNameNode().getFSImage(); printStorages(fsImage); FileSystem fs = cluster.getFileSystem(); Path testPath = new Path("/", "test"); assertTrue(fs.mkdirs(testPath)); printStorages(fsImage); // Take name1 offline invalidateStorage(fsImage, ImmutableSet.of(path1)); // Simulate a 2NN beginning a checkpoint, but not finishing. This will // cause name1 to be restored. cluster.getNameNodeRpc().rollEditLog(); printStorages(fsImage); // Now another 2NN comes along to do a full checkpoint. secondary.doCheckpoint(); printStorages(fsImage); // The created file should still exist in the in-memory FS state after the // checkpoint. assertTrue("path exists before restart", fs.exists(testPath)); secondary.shutdown(); // Restart the NN so it reloads the edits from on-disk. cluster.restartNameNode(); // The created file should still exist after the restart. assertTrue("path should still exist after restart", fs.exists(testPath)); } finally { if (cluster != null) { cluster.shutdown(); } if (secondary != null) { secondary.shutdown(); } } } /** * 1. create DFS cluster with 3 storage directories * - 2 EDITS_IMAGE(name1, name2), 1 EDITS(name3) * 2. create a file * 3. corrupt/disable name2 and name3 by removing rwx permission * 4. run doCheckpoint * - will fail on removed dirs (which invalidates them) * 5. write another file * 6. check there is only one healthy storage dir * 7. run doCheckpoint - recover should fail but checkpoint should succeed * 8. check there is still only one healthy storage dir * 9. restore the access permission for name2 and name 3, run checkpoint again * 10.verify there are 3 healthy storage dirs. */ @Test public void testStorageRestoreFailure() throws Exception { SecondaryNameNode secondary = null; // On windows, revoking write+execute permission on name2 does not // prevent us from creating files in name2\current. Hence we revoke // permissions on name2\current for the test. String nameDir2 = Shell.WINDOWS ? (new File(path2, "current").getAbsolutePath()) : path2.toString(); String nameDir3 = Shell.WINDOWS ? (new File(path3, "current").getAbsolutePath()) : path3.toString(); try { cluster = new MiniDFSCluster.Builder(config) .numDataNodes(0) .manageNameDfsDirs(false).build(); cluster.waitActive(); secondary = new SecondaryNameNode(config); printStorages(cluster.getNameNode().getFSImage()); FileSystem fs = cluster.getFileSystem(); Path path = new Path("/", "test"); assertTrue(fs.mkdirs(path)); // invalidate storage by removing rwx permission from name2 and name3 assertTrue(FileUtil.chmod(nameDir2, "000") == 0); assertTrue(FileUtil.chmod(nameDir3, "000") == 0); secondary.doCheckpoint(); // should remove name2 and name3 printStorages(cluster.getNameNode().getFSImage()); path = new Path("/", "test1"); assertTrue(fs.mkdirs(path)); assert (cluster.getNameNode().getFSImage().getStorage() .getNumStorageDirs() == 1); secondary.doCheckpoint(); // shouldn't be able to restore name 2 and 3 assert (cluster.getNameNode().getFSImage().getStorage() .getNumStorageDirs() == 1); assertTrue(FileUtil.chmod(nameDir2, "755") == 0); assertTrue(FileUtil.chmod(nameDir3, "755") == 0); secondary.doCheckpoint(); // should restore name 2 and 3 assert (cluster.getNameNode().getFSImage().getStorage() .getNumStorageDirs() == 3); } finally { if (path2.exists()) { FileUtil.chmod(nameDir2, "755"); } if (path3.exists()) { FileUtil.chmod(nameDir3, "755"); } if (cluster != null) { cluster.shutdown(); } if (secondary != null) { secondary.shutdown(); } } } }
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. * <p> */ package org.olat.course.nodes.projectbroker; 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.junit.Assert.fail; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.UUID; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.olat.basesecurity.SecurityGroupImpl; import org.olat.core.CoreSpringFactory; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.gui.translator.PackageTranslator; import org.olat.core.id.Identity; import org.olat.course.nodes.projectbroker.datamodel.Project; import org.olat.course.nodes.projectbroker.datamodel.ProjectBroker; import org.olat.course.nodes.projectbroker.datamodel.ProjectEvent; import org.olat.course.nodes.projectbroker.service.ProjectBrokerManagerFactory; import org.olat.course.nodes.projectbroker.service.ProjectBrokerModuleConfiguration; import org.olat.group.BusinessGroup; import org.olat.group.BusinessGroupImpl; import org.olat.group.BusinessGroupService; import org.olat.modules.ModuleConfiguration; import org.olat.repository.RepositoryEntry; import org.olat.test.JunitTestHelper; import org.olat.test.OlatTestCase; /** * * @author Christian Guretzki */ public class ProjectBrokerManagerTest extends OlatTestCase { /* * ::Test Setup:: */ private static Identity id1 = null; private static Identity id2 = null; // private static Long resourceableId = null; /** * @see junit.framework.TestCase#setUp() */ @Before public void setup() throws Exception { System.out.println("ProjectBrokerManagerTest.setUp start..."); try { id1 = JunitTestHelper.createAndPersistIdentityAsUser("project-id1-" + UUID.randomUUID().toString()); id2 = JunitTestHelper.createAndPersistIdentityAsUser("project-id2-" + UUID.randomUUID().toString()); if (resourceableId == null) { RepositoryEntry repositoryEntry = JunitTestHelper.deployDemoCourse(); resourceableId = repositoryEntry.getOlatResource().getResourceableId(); System.out.println("Demo course imported - resourceableId: " + resourceableId); } DBFactory.getInstance().closeSession(); System.out.println("ProjectBrokerManagerTest.setUp finished"); } catch (Exception e) { System.out.println("ProjectBrokerManagerTest.setUp Exception=" + e.getMessage()); e.printStackTrace(); fail(e.getMessage()); } } /** * */ @Test public void testCreateListDeleteProjects() throws Exception { System.out.println("testCreateListDeleteProjects: start..."); // create ProjectBroker A + B ProjectBroker projectBrokerA = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBrokerA = projectBrokerA.getKey(); ProjectBroker projectBrokerB = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBrokerB = projectBrokerB.getKey(); // add project to ProjectBroker A createProject("thema A1", id1, idProjectBrokerA, resourceableId ); createProject("thema A2", id1, idProjectBrokerA, resourceableId ); // add project to ProjectBroker B createProject("thema B1", id1, idProjectBrokerB, resourceableId ); createProject("thema B2", id1, idProjectBrokerB, resourceableId ); DBFactory.getInstance().closeSession(); // get project list and check content List<Project> projectListA = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerA); assertEquals("Wrong projectList.size for project-broker A",2, projectListA.size()); assertTrue("Wrong thema in project list A, title must start with 'thema A'", projectListA.get(0).getTitle().startsWith("thema A")); assertTrue("Wrong thema in project list A, title must start with 'thema A'", projectListA.get(1).getTitle().startsWith("thema A")); List<Project> projectListB = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerB); assertEquals("Wrong projectList.size for project-broker B",2, projectListB.size()); assertTrue("Wrong thema in project list B, title must start with 'thema B'", projectListB.get(0).getTitle().startsWith("thema B")); assertTrue("Wrong thema in project list B, title must start with 'thema B'", projectListB.get(1).getTitle().startsWith("thema B")); if (projectListA.get(0).getTitle().equals("thema A1")) { assertTrue("Wrong thema in project list A, title must be 'thema A2'", projectListA.get(1).getTitle().equals("thema A2")); } else if (projectListA.get(0).getTitle().equals("thema A2")) { assertTrue("Wrong thema in project list A, title must be 'thema A1'", projectListA.get(1).getTitle().equals("thema A1")); } if (projectListB.get(0).getTitle().equals("thema B1")) { assertTrue("Wrong thema in project list B, title must be 'thema B2'", projectListB.get(1).getTitle().equals("thema B2")); } else if (projectListB.get(0).getTitle().equals("thema B2")) { assertTrue("Wrong thema in project list B, title must be 'thema B1'", projectListB.get(1).getTitle().equals("thema B1")); } // delete project long candiadteGroupKey = projectListA.get(0).getCandidateGroup().getKey(); long projectGroupKey = projectListA.get(0).getProjectGroup().getKey(); assertNotNull("CandidateGroup does not exist before delete project", DBFactory.getInstance().findObject(SecurityGroupImpl.class, candiadteGroupKey)); assertNotNull("ProjectGroup does not exist before delete project", DBFactory.getInstance().findObject(BusinessGroupImpl.class, projectGroupKey)); ProjectBrokerManagerFactory.getProjectBrokerManager().deleteProject(projectListA.get(0), true, null, null); assertNull("CandidateGroup still exists after delete project", DBFactory.getInstance().findObject(SecurityGroupImpl.class, candiadteGroupKey)); assertNull("ProjectGroup still exists after delete project", DBFactory.getInstance().findObject(BusinessGroupImpl.class, projectGroupKey)); // get project list and check content projectListA = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerA); projectListB = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerB); assertEquals("Wrong projectList.size for project-broker A after delete 'thema A1'",1, projectListA.size()); assertEquals("Wrong projectList.size for project-broker B after delete 'thema A1'",2, projectListB.size()); // delete project ProjectBrokerManagerFactory.getProjectBrokerManager().deleteProject(projectListB.get(1), true, null, null); // get project list and check content projectListA = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerA); projectListB = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerB); assertEquals("Wrong projectList.size for project-broker A after delete 'thema B2'",1, projectListA.size()); assertEquals("Wrong projectList.size for project-broker B after delete 'thema B2'",1, projectListB.size()); // delete project ProjectBrokerManagerFactory.getProjectBrokerManager().deleteProject(projectListA.get(0), true, null, null); projectListA = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerA); projectListB = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerB); System.out.println("testCreateListDeleteProjects: projectListA=" + projectListA); assertEquals("Wrong projectList.size for project-broker A after delete all thema",0, projectListA.size()); assertEquals("Wrong projectList.size for project-broker B after delete all thema",1, projectListB.size()); // cleanup System.out.println("testCreateListDeleteProjects: done"); } @Test public void testPerformanceGetProjectList() throws Exception { System.out.println("testPerformanceGetProjectList: start..."); int FIRST_ITERATION = 10; int SECOND_ITERATION = 90; int THIRD_ITERATION = 400; // create ProjectBroker C ProjectBroker projectBrokerC = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBrokerC = projectBrokerC.getKey(); DBFactory.getInstance().closeSession(); for (int i = 0; i < FIRST_ITERATION; i++) { createProject("thema C1_" + i, id1, idProjectBrokerC, resourceableId ); } DBFactory.getInstance().closeSession(); long startTime = System.currentTimeMillis(); List<Project> projectListC = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerC); long endTime = System.currentTimeMillis(); assertEquals("Wrong projectList.size for project-broker C after first iteration",FIRST_ITERATION, projectListC.size()); long duration = endTime - startTime; System.out.println("getProjectListBy takes " + duration + "ms with " + FIRST_ITERATION + " projects"); for (int i = 0; i < SECOND_ITERATION; i++) { createProject("thema C1_" + i, id1, idProjectBrokerC, resourceableId ); } DBFactory.getInstance().closeSession(); startTime = System.currentTimeMillis(); projectListC = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerC); endTime = System.currentTimeMillis(); int numberOfProjects = FIRST_ITERATION + SECOND_ITERATION; assertEquals("Wrong projectList.size for project-broker C", numberOfProjects, projectListC.size()); duration = endTime - startTime; System.out.println("getProjectListBy takes " + duration + "ms with " + numberOfProjects + " projects"); for (int i = 0; i < THIRD_ITERATION; i++) { createProject("thema C1_" + i, id1, idProjectBrokerC, resourceableId ); } DBFactory.getInstance().closeSession(); startTime = System.currentTimeMillis(); projectListC = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerC); endTime = System.currentTimeMillis(); numberOfProjects = FIRST_ITERATION + SECOND_ITERATION + THIRD_ITERATION; assertEquals("Wrong projectList.size for project-broker C", numberOfProjects, projectListC.size()); duration = endTime - startTime; System.out.println("getProjectListBy takes " + duration + "ms with " + numberOfProjects + " projects"); // cleanup System.out.println("testPerformance: done"); } @Test public void testPerformanceTableModel() throws Exception { int ITERATION = 300; int START_PAGE_INDEX = 100; int PAGE_SIZE = 20; PackageTranslator translator = new PackageTranslator(this.getClass().getPackage().getName(), Locale.GERMAN); ProjectBroker projectBrokerD = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBrokerD = projectBrokerD.getKey(); ProjectBrokerModuleConfiguration moduleConfig = new ProjectBrokerModuleConfiguration( new ModuleConfiguration() ); for (int i = 0; i < ITERATION; i++) { createProject("thema D1_" + i, id1, idProjectBrokerD, resourceableId ); } List<Project> projectListD = ProjectBrokerManagerFactory.getProjectBrokerManager().getProjectListBy(idProjectBrokerD); ProjectListTableModel tableModel = new ProjectListTableModel(projectListD, id1, translator, moduleConfig, 0, 0, 0, false); // loop over table like rendering loop long startTime = System.currentTimeMillis(); for (int row = START_PAGE_INDEX; row < START_PAGE_INDEX+PAGE_SIZE; row++) { for (int col = 0; col < tableModel.getColumnCount(); col++) { Object element = tableModel.getValueAt(row, col); Assert.assertNotNull(element); } } long endTime = System.currentTimeMillis(); long duration = endTime - startTime; System.out.println("tableModel.getValueAt(row, col) for " + PAGE_SIZE + "elements (of " + ITERATION + ") takes " + duration + "ms with " + ITERATION + " projects"); // cleanup } @Test public void testIsProjectManager() throws Exception { ProjectBroker projectBrokerD = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBrokerD = projectBrokerD.getKey(); Project testProjectA = createProject("thema A", id1, idProjectBrokerD, resourceableId ); List<Identity> projectManagerList = new ArrayList<Identity>(); projectManagerList.add(id1); Project testProjectB = createProject("thema B", id2, idProjectBrokerD, resourceableId ); // check project leader in ProjectA assertTrue("Must be project-leader of project A", ProjectBrokerManagerFactory.getProjectGroupManager().isProjectManager(id1, testProjectA)); assertFalse("Can not be project leader of project B",ProjectBrokerManagerFactory.getProjectGroupManager().isProjectManager(id1, testProjectB)); assertTrue("Must be project-leader of project A", ProjectBrokerManagerFactory.getProjectGroupManager().isProjectManager(id2, testProjectB)); CoreSpringFactory.getImpl(BusinessGroupService.class).removeOwners(id1, projectManagerList, testProjectA.getProjectGroup()); // check no project leader anymore assertFalse("Can not be project leader of project A",ProjectBrokerManagerFactory.getProjectGroupManager().isProjectManager(id1, testProjectA)); assertFalse("Can not be project leader of project B",ProjectBrokerManagerFactory.getProjectGroupManager().isProjectManager(id1, testProjectB)); // cleanup } @Test public void testExistsProject() throws Exception { // 1. test project does not exists assertFalse("Wrong return value true, project does not exist", ProjectBrokerManagerFactory.getProjectBrokerManager().existsProject(39927492743L)); // 2. test project exists ProjectBroker projectBrokerD = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBrokerD = projectBrokerD.getKey(); Project testProjectA = createProject("thema existsProject-Test", id1, idProjectBrokerD, resourceableId ); DBFactory.getInstance().closeSession(); assertTrue("Wrong return value false, project exists", ProjectBrokerManagerFactory.getProjectBrokerManager().existsProject(testProjectA.getKey())); } @Test public void testUpdateProject() throws Exception { ProjectBroker projectBroker = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectBroker(); Long idProjectBroker = projectBroker.getKey(); Project testProjectA = createProject("updateTest", id1, idProjectBroker, resourceableId ); DBFactory.getInstance().closeSession(); // testProjectA is now a detached-object // Update 1 String updateTitle = "thema updateProject-Test update1"; testProjectA.setTitle(updateTitle); String updateDescription = "description update1"; testProjectA.setDescription(updateDescription); String updateState = "state update1"; testProjectA.setState(updateState); ProjectBrokerManagerFactory.getProjectBrokerManager().updateProject(testProjectA); DBFactory.getInstance().closeSession(); // testProjectA is now a detached-object again Project reloadedProject = (Project) DBFactory.getInstance().loadObject(testProjectA, true); assertEquals("Wrong updated title 1",updateTitle,reloadedProject.getTitle()); // Update 2 String updateTitle2 = "thema updateProject-Test update2"; testProjectA.setTitle(updateTitle2); int updateMaxMembers = 3; testProjectA.setMaxMembers(updateMaxMembers); String updateAttachmentFileName = "attachmentFile.txt"; testProjectA.setAttachedFileName(updateAttachmentFileName); boolean updateMailNotification = Boolean.TRUE; testProjectA.setMailNotificationEnabled(updateMailNotification); String updateCustomField0 = "CustomField0"; testProjectA.setCustomFieldValue(0, updateCustomField0); String updateCustomField1 = "CustomField1"; testProjectA.setCustomFieldValue(1, updateCustomField1); ProjectBrokerManagerFactory.getProjectBrokerManager().updateProject(testProjectA); DBFactory.getInstance().closeSession(); // Update 3 Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2010, 11, 15, 15, 30, 45); Date startDate = cal.getTime(); cal.clear(); cal.set(2010, 11, 20, 15, 30, 45); Date endDate = cal.getTime(); ProjectEvent projectEventEnroll = new ProjectEvent(Project.EventType.ENROLLMENT_EVENT, startDate, endDate); testProjectA.setProjectEvent(projectEventEnroll); ProjectEvent projectEventHandout = new ProjectEvent(Project.EventType.HANDOUT_EVENT, startDate, endDate); testProjectA.setProjectEvent(projectEventHandout); DBFactory.getInstance().closeSession(); reloadedProject = (Project) DBFactory.getInstance().loadObject(testProjectA, true); assertEquals("Wrong updated title 2",updateTitle2,reloadedProject.getTitle()); assertEquals("Wrong description",updateDescription,reloadedProject.getDescription()); assertEquals("Wrong state",updateState,reloadedProject.getState()); assertEquals("Wrong maxMembers",updateMaxMembers,reloadedProject.getMaxMembers()); assertEquals("Wrong AttachmentFileName",updateAttachmentFileName,reloadedProject.getAttachmentFileName()); assertEquals("Wrong MailNotification",updateMailNotification,reloadedProject.isMailNotificationEnabled()); assertEquals("Wrong CustomField 0",updateCustomField0,reloadedProject.getCustomFieldValue(0)); assertEquals("Wrong CustomField 1",updateCustomField1,reloadedProject.getCustomFieldValue(1)); assertEquals("Wrong customField Size",2,reloadedProject.getCustomFieldSize()); assertEquals("Wrong event Type (Handout)",Project.EventType.HANDOUT_EVENT,reloadedProject.getProjectEvent(Project.EventType.HANDOUT_EVENT).getEventType()); assertEquals("Wrong event start-date (Handout)",startDate.getTime(),reloadedProject.getProjectEvent(Project.EventType.HANDOUT_EVENT).getStartDate().getTime()); assertEquals("Wrong event end-date (Handout)",endDate.getTime(),reloadedProject.getProjectEvent(Project.EventType.HANDOUT_EVENT).getEndDate().getTime()); assertEquals("Wrong event Type (Enroll)",Project.EventType.ENROLLMENT_EVENT,reloadedProject.getProjectEvent(Project.EventType.ENROLLMENT_EVENT).getEventType()); assertEquals("Wrong event start-date (Enroll)",startDate.getTime(),reloadedProject.getProjectEvent(Project.EventType.ENROLLMENT_EVENT).getStartDate().getTime()); assertEquals("Wrong event end-date (Enroll)",endDate.getTime(),reloadedProject.getProjectEvent(Project.EventType.ENROLLMENT_EVENT).getEndDate().getTime()); } private Project createProject(String name, Identity creator, Long projectBrokerId, Long courseId) { BusinessGroup projectGroup = ProjectBrokerManagerFactory.getProjectGroupManager().createProjectGroupFor(projectBrokerId, creator, name + "_Group", name + "GroupDescription", courseId); Project project = ProjectBrokerManagerFactory.getProjectBrokerManager().createAndSaveProjectFor(name + "title", name + "description1", projectBrokerId, projectGroup); return project; } }
package com.suscipio_solutions.consecro_mud.Commands; import java.util.Enumeration; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Commands.interfaces.Command; import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan; import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan.Function; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.CMParms; import com.suscipio_solutions.consecro_mud.core.CMStrings; import com.suscipio_solutions.consecro_mud.core.CMath; import com.suscipio_solutions.consecro_mud.core.collections.Pair; import com.suscipio_solutions.consecro_mud.core.collections.PairVector; @SuppressWarnings({"unchecked","rawtypes"}) public class ClanVote extends StdCommand { public ClanVote(){} private final String[] access=I(new String[]{"CLANVOTE"}); @Override public String[] getAccessWords(){return access;} @Override public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException { StringBuffer msg=new StringBuffer(""); String voteNumStr=(commands.size()>1)?(String)commands.get(commands.size()-1):""; String clanName=""; if(!CMath.isInteger(voteNumStr)) { clanName=(commands.size()>2)?CMParms.combine(commands,1,commands.size()):""; voteNumStr=""; } else clanName=(commands.size()>2)?CMParms.combine(commands,1,commands.size()-1):""; Clan C=null; Integer clanRole=null; for(final Pair<Clan,Integer> c : mob.clans()) if((clanName.length()==0)||(CMLib.english().containsString(c.first.getName(), clanName))) { C=c.first; clanRole=c.second; break; } if((C==null)||(clanRole==null)) { mob.tell(L("You can't vote for anything in @x1.",((clanName.length()==0)?"any clan":clanName))); return false; } else if(!mob.isMonster()) { final Vector votesForYou=new Vector(); for(final Enumeration e=C.votes();e.hasMoreElements();) { final Clan.ClanVote CV=(Clan.ClanVote)e.nextElement(); if(((CV.function==Clan.Function.ASSIGN.ordinal()) &&(C.getAuthority(clanRole.intValue(),Clan.Function.VOTE_ASSIGN)!=Clan.Authority.CAN_NOT_DO)) ||((CV.function!=Clan.Function.ASSIGN.ordinal()) &&(C.getAuthority(clanRole.intValue(),Clan.Function.VOTE_OTHER)!=Clan.Authority.CAN_NOT_DO))) votesForYou.addElement(CV); } if(voteNumStr.length()==0) { if(votesForYou.size()==0) msg.append(L("Your @x1 does not have anything up for your vote.",C.getGovernmentName())); else { msg.append(L(" @x1@x2Command to execute\n\r",CMStrings.padRight("#",3),CMStrings.padRight(L("Status"),15))); for(int v=0;v<votesForYou.size();v++) { final Clan.ClanVote CV=(Clan.ClanVote)votesForYou.elementAt(v); final boolean ivoted=((CV.votes!=null)&&(CV.votes.containsFirst(mob.Name()))); final int votesCast=(CV.votes!=null)?CV.votes.size():0; msg.append((ivoted?"*":" ") +CMStrings.padRight(""+(v+1),3) +CMStrings.padRight(((CV.voteStatus==Clan.VSTAT_STARTED)?(votesCast+" votes cast"):(Clan.VSTAT_DESCS[CV.voteStatus])),15) +CMStrings.padRight(CV.matter,55)+"\n\r"); } msg.append(L("\n\rEnter CLANVOTE [#] to see details or place your vote.")); } } else { final int which=CMath.s_int(voteNumStr)-1; Clan.ClanVote CV=null; if((which>=0)&&(which<votesForYou.size())) CV=(Clan.ClanVote)votesForYou.elementAt(which); if(CV==null) msg.append(L("That vote does not exist. Use CLANVOTE to see a list.")); else { int yeas=0; int nays=0; Boolean myVote=null; if(CV.votes!=null) for(int vs=0;vs<CV.votes.size();vs++) { if(CV.votes.getFirst(vs).equals(mob.Name())) myVote=CV.votes.getSecond(vs); if(CV.votes.getSecond(vs).booleanValue()) yeas++; else nays++; } msg.append(L("Vote : @x1\n\r",""+(which+1))); msg.append(L("Started by : @x1\n\r",CV.voteStarter)); if(CV.voteStatus==Clan.VSTAT_STARTED) msg.append(L("Started on : @x1\n\r",CMLib.time().date2String(CV.voteStarted))); else msg.append(L("Ended on : @x1\n\r",CMLib.time().date2String(CV.voteStarted))); msg.append(L("Status : @x1\n\r",Clan.VSTAT_DESCS[CV.voteStatus])); switch(CV.voteStatus) { case Clan.VSTAT_STARTED: msg.append(L("If passed, the following command would be executed:\n\r")); break; case Clan.VSTAT_PASSED: msg.append(L("Results : @x1 Yeas, @x2 Nays\n\r",""+yeas,""+nays)); msg.append(L("The following command has been executed:\n\r")); break; case Clan.VSTAT_FAILED: msg.append(L("Results : @x1 Yeas, @x2 Nays\n\r",""+yeas,""+nays)); msg.append(L("The following command will not be executed:\n\r")); break; } msg.append(CV.matter+"\n\r"); if((CV.voteStatus==Clan.VSTAT_STARTED)&&(myVote==null)) { mob.tell(msg.toString()); msg=new StringBuffer(""); final StringBuffer prompt=new StringBuffer(""); String choices=""; if(CV.votes==null) CV.votes=new PairVector<String,Boolean>(); prompt.append("Y)EA N)AY "); choices="YN"; if(CV.voteStarter.equals(mob.Name())) { prompt.append("C)ANCEL "); choices+="C"; } final String enterWhat="to skip"; //if(myVote!=null) enterWhat=("to keep ("+(myVote.booleanValue()?"Y":"N")+") "); // no revote boolean updateVote=false; if((prompt.length()>0)&&(mob.session()!=null)) { final String answer=mob.session().choose(L("Choices: @x1or ENTER @x2: ",prompt.toString(),enterWhat),choices,""); if(answer.length()>0) switch(answer.toUpperCase().charAt(0)) { case 'Y': msg.append(L("Your YEA vote is recorded.")); CV.votes.addElement(mob.Name(),Boolean.TRUE); updateVote=true; yeas++; break; case 'N': CV.votes.addElement(mob.Name(),Boolean.FALSE); msg.append(L("Your NAY vote is recorded.")); updateVote=true; nays++; break; case 'C': if((mob.session()!=null) &&(mob.session().confirm(L("This will cancel this entire vote, are you sure (N/y)?"),L("N")))) { C.delVote(CV); CMLib.clans().clanAnnounce(mob,L("A prior vote for @x1 @x2 has been deleted.",C.getGovernmentName(),C.clanID())); msg.append(L("The vote has been deleted.")); updateVote=true; } break; } } final int numVotes=C.getNumVoters(Function.values()[CV.function]); if(numVotes<=(yeas+nays)) { updateVote=true; if(yeas<=nays) CV.voteStatus=Clan.VSTAT_FAILED; else { CV.voteStatus=Clan.VSTAT_PASSED; final MOB mob2=CMClass.getFactoryMOB(); mob2.setName(C.clanID()); mob2.setClan(C.clanID(),C.getTopRankedRoles(Function.ASSIGN).get(0).intValue()); mob2.basePhyStats().setLevel(1000); if(mob2.location()==null) { mob2.setLocation(mob2.getStartRoom()); if(mob2.location()==null) mob2.setLocation(CMLib.map().getRandomRoom()); } final Vector<String> V=CMParms.parse(CV.matter); mob2.doCommand(V,metaFlags|Command.METAFLAG_FORCED); mob2.destroy(); } } if(updateVote) C.updateVotes(); } } } } mob.tell(msg.toString()); return false; } @Override public boolean canBeOrdered(){return false;} }
/* * The MIT License * * Copyright (c) 2015 Petar Petrov * * 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 net.vexelon.bgrates.ui.activities; import java.util.Calendar; import java.util.Locale; import android.app.ActionBar; import android.app.Activity; import android.app.AlarmManager; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v13.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import net.vexelon.bgrates.Defs; import net.vexelon.bgrates.R; import net.vexelon.bgrates.services.RateService; import net.vexelon.bgrates.ui.events.Notifications; import net.vexelon.bgrates.ui.events.NotificationsListener; import net.vexelon.bgrates.ui.fragments.AbstractFragment; import net.vexelon.bgrates.ui.fragments.ConvertFragment; import net.vexelon.bgrates.ui.fragments.CurrenciesFragment; public class MainActivity extends Activity implements ActionBar.TabListener, NotificationsListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a {@link FragmentPagerAdapter} * derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v13.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; private PendingIntent pendingIntent;// // /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; Menu mMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayShowHomeEnabled(false); actionBar.setTitle(R.string.app_name_pure); // actionBar.setDisplayUseLogoEnabled(true); // actionBar.setLogo(R.drawable.icon); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this)); } // load default values PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Start Service startService(); } public void startService() { Intent myIntent = new Intent(MainActivity.this, RateService.class); pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 30); long initialStartTimeout = calendar.getTimeInMillis(); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, initialStartTimeout, Defs.NOTIFY_INTERVAL, pendingIntent); } public void cancelService() { AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.cancel(pendingIntent); } @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); mMenu = 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(); if (id == R.id.action_settings) { Intent intent = new Intent(this, PrefsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onNotification(Notifications event) { switch (event) { case UPDATE_RATES_DONE: // setRefreshActionButtonState(false); break; } } private Fragment getCurrentFragment() { String fragmentName = "android:switcher:" + mViewPager.getId() + ":" + mViewPager.getCurrentItem(); return getFragmentManager().findFragmentByTag(fragmentName); } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class // below). Fragment fragment = PlaceholderFragment.newInstance(position + 1); // ((AbstractFragment) fragment).addListener(MainActivity.this); return fragment; } @Override public int getCount() { // Show 2 total pages. return 2; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.tab_title_currencies).toUpperCase(l); case 1: return getString(R.string.tab_title_convert).toUpperCase(l); } return null; } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static Fragment newInstance(int sectionNumber) { AbstractFragment fragment = null; switch (sectionNumber) { case 1: fragment = new CurrenciesFragment(); break; case 2: fragment = new ConvertFragment(); break; } if (fragment != null) { Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); } return fragment; } } }
package ethanjones.cubes.graphics.rendering; import ethanjones.cubes.core.performance.Performance; import ethanjones.cubes.core.platform.Compatibility; import ethanjones.cubes.core.settings.Keybinds; import ethanjones.cubes.core.settings.Settings; import ethanjones.cubes.core.util.Toggle; import ethanjones.cubes.graphics.assets.Assets; import ethanjones.cubes.graphics.hud.ChatActor; import ethanjones.cubes.graphics.hud.FrametimeGraph; import ethanjones.cubes.graphics.hud.ImageButtons; import ethanjones.cubes.graphics.hud.inv.*; import ethanjones.cubes.graphics.menu.Fonts; import ethanjones.cubes.graphics.menu.MenuTools; import ethanjones.cubes.networking.NetworkingManager; import ethanjones.cubes.networking.packets.PacketChat; import ethanjones.cubes.side.client.ClientDebug; import ethanjones.cubes.side.common.Cubes; import ethanjones.cubes.world.save.Gamemode; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.badlogic.gdx.utils.Disposable; import static ethanjones.cubes.graphics.Graphics.*; import static ethanjones.cubes.graphics.hud.inv.HotbarActor.scroll; import static ethanjones.cubes.graphics.menu.Menu.skin; public class GuiRenderer implements Disposable { Stage stage; TextField chat; ChatActor chatLog; Touchpad touchpad; ImageButton jumpButton; ImageButton descendButton; ImageButton debugButton; ImageButton chatButton; ImageButton blockSelectorButton; public ImageButton inventoryModifierButton; public InventoryActor playerInv; public HotbarActor hotbar; Texture crosshair; public Toggle chatToggle = new Toggle() { @Override public void doEnable() { stage.addActor(chat); stage.setKeyboardFocus(chat); chatLog.open.enable(); hotbar.remove(); } @Override public void doDisable() { stage.setKeyboardFocus(null); stage.getRoot().removeActor(chat); chatLog.open.disable(); stage.addActor(hotbar); } }; public boolean debugEnabled; public boolean hideGuiEnabled; public GuiRenderer() { stage = new Stage(screenViewport, spriteBatch); final Input input = new Input(); Cubes.getClient().inputChain.stageHud = stage; Cubes.getClient().inputChain.hud = input; stage.addListener(scroll); InventoryManager.setup(stage); final TextField.TextFieldStyle defaultStyle = skin.get("default", TextField.TextFieldStyle.class); final TextField.TextFieldStyle chatStyle = new TextField.TextFieldStyle(defaultStyle); chatStyle.font = Fonts.hud; chatStyle.background = new TextureRegionDrawable(Assets.getTextureRegion("core:hud/ChatBackground.png")); chat = new TextField("", chatStyle) { protected InputListener createInputListener() { return new TextFieldClickListener() { @Override public boolean keyDown(InputEvent event, int keycode) { return input.functionKeys(keycode) || super.keyDown(event, keycode); } }; } }; chat.setTextFieldListener(new TextField.TextFieldListener() { @Override public void keyTyped(TextField textField, char c) { if (c == '\n' || c == '\r') { String msg = chat.getText().trim(); if (!msg.isEmpty()) { PacketChat packetChat = new PacketChat(); packetChat.msg = msg; NetworkingManager.sendPacketToServer(packetChat); } chat.setText(""); chatToggle.disable(); } } }); chatLog = new ChatActor(); stage.addActor(chatLog); if (Compatibility.get().isTouchScreen()) { touchpad = new Touchpad(0, skin); jumpButton = new ImageButton(ImageButtons.jumpButton()); descendButton = new ImageButton(ImageButtons.descendButton()); Cubes.getClient().inputChain.cameraController.touchpad = touchpad; Cubes.getClient().inputChain.cameraController.jumpButton = jumpButton; Cubes.getClient().inputChain.cameraController.descendButton = descendButton; debugButton = new ImageButton(ImageButtons.debugButton()); debugButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (Compatibility.get().functionModifier()) { Performance.toggleTracking(); } else { debugEnabled = !debugEnabled; } } }); chatButton = new ImageButton(ImageButtons.chatButton()); chatButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { chatToggle.toggle(); } }); blockSelectorButton = new ImageButton(ImageButtons.blocksButton()); blockSelectorButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { toggleInventory(); } }); inventoryModifierButton = new ImageButton(ImageButtons.inventoryModifierButton()); InventoryManager.GROUP_HIDDEN.addActor(touchpad); InventoryManager.GROUP_HIDDEN.addActor(jumpButton); InventoryManager.GROUP_HIDDEN.addActor(debugButton); InventoryManager.GROUP_HIDDEN.addActor(chatButton); InventoryManager.GROUP_HIDDEN.addActor(descendButton); stage.addActor(blockSelectorButton); InventoryManager.GROUP_SHOWN.addActor(inventoryModifierButton); } crosshair = Assets.getTexture("core:hud/Crosshair.png"); } public void playerCreated() { playerInv = new InventoryActor(Cubes.getClient().player.getInventory()); hotbar = new HotbarActor(Cubes.getClient().player.getInventory()); InventoryManager.GROUP_HIDDEN.addActor(hotbar); } public void render() { FrametimeGraph.update(); if (descendButton != null) descendButton.setVisible(Cubes.getClient().gamemode == Gamemode.creative || Cubes.getClient().player.noClip()); hotbar.setVisible(!hideGuiEnabled); stage.act(); stage.draw(); spriteBatch.setProjectionMatrix(screenViewport.getCamera().combined); spriteBatch.begin(); float crosshairSize = 10f; if (!hideGuiEnabled) { if (!InventoryManager.isInventoryOpen()) spriteBatch.draw(crosshair, (GUI_WIDTH / 2) - crosshairSize, (GUI_HEIGHT / 2) - crosshairSize, crosshairSize * 2, crosshairSize * 2); } if (debugEnabled) { FrametimeGraph.drawLines(spriteBatch); Fonts.debug.draw(spriteBatch, ClientDebug.getDebugString(), 5f, GUI_HEIGHT - 5); } spriteBatch.end(); if (debugEnabled) { FrametimeGraph.drawPoints(); } } public void resize() { chat.setBounds(0, 0, GUI_WIDTH, chat.getStyle().font.getLineHeight() * 1.5f); chatLog.setBounds(0, chat.getHeight(), GUI_WIDTH, chatLog.getPrefHeight()); if (touchpad != null) { float hbSize = 48; float padding = 10; float size = GUI_HEIGHT * Settings.getFloatSettingValue(Settings.INPUT_TOUCHPAD_SIZE); if (Settings.getBooleanSettingValue(Settings.INPUT_TOUCHPAD_LEFT)) { touchpad.setBounds(padding, hbSize + padding, size, size); jumpButton.setBounds(GUI_WIDTH - hbSize - padding, hbSize * 2 + padding, hbSize, hbSize); descendButton.setBounds(GUI_WIDTH - hbSize - padding, hbSize + padding, hbSize, hbSize); } else { touchpad.setBounds(GUI_WIDTH - size - padding, hbSize, size, size); jumpButton.setBounds(padding, hbSize * 2 + padding, hbSize, hbSize); descendButton.setBounds(padding, hbSize + padding, hbSize, hbSize); } } if (chatButton != null && debugButton != null && blockSelectorButton != null) { float width = blockSelectorButton.getPrefWidth() / 3 * 2; float height = blockSelectorButton.getPrefHeight() / 3 * 2; blockSelectorButton.setBounds(GUI_WIDTH - width, GUI_HEIGHT - height, width, height); chatButton.setBounds(GUI_WIDTH - width - width, GUI_HEIGHT - height, width, height); debugButton.setBounds(GUI_WIDTH - width - width - width, GUI_HEIGHT - height, width, height); inventoryModifierButton.setBounds(0, GUI_HEIGHT - height, width, height); } InventoryManager.resize(); MenuTools.center(hotbar); hotbar.setY(0); } public void newMessage(String string) { if (chatLog != null) chatLog.newMessage(string); } public void toggleInventory() { if (InventoryManager.isInventoryOpen()) { InventoryManager.hideInventory(); } else { if (Cubes.getClient().gamemode == Gamemode.creative) { InventoryManager.showInventory(new InventoryWindow(new DoubleInventory(new CreativeInventoryActor(), playerInv))); } else { InventoryManager.showInventory(new InventoryWindow(new DoubleInventory(new CraftingInventoryActor(), playerInv))); } } } @Override public void dispose() { stage.dispose(); } public boolean noCursorCatching() { return chatToggle.isEnabled() || InventoryManager.isInventoryOpen() || hideGuiEnabled; } private class Input extends InputAdapter { int hideGUI = Keybinds.getCode(Keybinds.KEYBIND_HIDEGUI); int debug = Keybinds.getCode(Keybinds.KEYBIND_DEBUG); int chat = Keybinds.getCode(Keybinds.KEYBIND_CHAT); int blocksMenu = Keybinds.getCode(Keybinds.KEYBIND_INVENTORY); private boolean functionKeys(int keycode) { if (keycode == hideGUI) { hideGuiEnabled = !hideGuiEnabled; return true; } if (keycode == debug) { if (Compatibility.get().functionModifier()) { Performance.toggleTracking(); } else { debugEnabled = !debugEnabled; } return true; } if (keycode == chat) { chatToggle.toggle(); return true; } return false; } @Override public boolean keyDown(int keycode) { if (functionKeys(keycode)) return true; if (keycode == blocksMenu) { toggleInventory(); return true; } int selected = -1; if (keycode == Keys.NUM_1) selected = 0; if (keycode == Keys.NUM_2) selected = 1; if (keycode == Keys.NUM_3) selected = 2; if (keycode == Keys.NUM_4) selected = 3; if (keycode == Keys.NUM_5) selected = 4; if (keycode == Keys.NUM_6) selected = 5; if (keycode == Keys.NUM_7) selected = 6; if (keycode == Keys.NUM_8) selected = 7; if (keycode == Keys.NUM_9) selected = 8; if (selected != -1) { Cubes.getClient().player.getInventory().hotbarSelected = selected; Cubes.getClient().player.getInventory().sync(); return true; } return false; } } }
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.MaturityLevel; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.BugPattern.Suppressibility; import com.google.errorprone.BugPatternValidator; import com.google.errorprone.ValidationException; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.matchers.Description; import com.sun.source.tree.Tree; import java.io.Serializable; import java.lang.annotation.Annotation; import java.util.Map; import java.util.Set; import javax.annotation.CheckReturnValue; /** * An accessor for information about a single bug checker, including the metadata in the check's * {@code @BugPattern} annotation and the class that implements the check. */ public class BugCheckerInfo implements Serializable { /** * The BugChecker class. */ private final Class<? extends BugChecker> checker; /** * The canonical name of this check. Corresponds to the {@code name} attribute from its * {@code BugPattern} annotation. */ private final String canonicalName; /** * Additional identifiers for this check, to be checked for in @SuppressWarnings annotations. * Corresponds to the canonical name plus all {@code altName}s from its {@code BugPattern} * annotation. */ private final ImmutableSet<String> allNames; /** * The error message to print in compiler diagnostics when this check triggers. Corresponds to the * {@code summary} attribute from its {@code BugPattern}. */ private final String message; /** * The default type of diagnostic (error or warning) to emit when this check triggers. */ private final SeverityLevel defaultSeverity; /** * The maturity of this checker. Used to decide whether to enable this check. Corresponds to the * {@code maturity} attribute from its {@code BugPattern}. */ private final MaturityLevel maturity; /** * The link URL to display in the diagnostic message when this check triggers. Computed from the * {@code link} and {@code linkType} attributes from its {@code BugPattern}. May be null if no * link should be displayed. */ private final String linkUrl; /** * Whether this check may be suppressed. Corresponds to the {@code suppressibility} attribute from * its {@code BugPattern}. */ private final Suppressibility suppressibility; /** * A custom suppression annotation for this check. Computed from the {@code suppressibility} and * {@code customSuppressionAnnotation} attributes from its {@code BugPattern}. May be null if * there is no custom suppression annotation for this check. */ private final Class<? extends Annotation> customSuppressionAnnotation; public static BugCheckerInfo create(Class<? extends BugChecker> checker) { BugPattern pattern = checkNotNull(checker.getAnnotation(BugPattern.class)); try { BugPatternValidator.validate(pattern); } catch (ValidationException e) { throw new IllegalStateException(e); } return new BugCheckerInfo(checker, pattern); } private BugCheckerInfo(Class<? extends BugChecker> checker, BugPattern pattern) { this.checker = checker; canonicalName = pattern.name(); allNames = ImmutableSet.<String>builder().add(canonicalName).add(pattern.altNames()).build(); message = pattern.summary(); maturity = pattern.maturity(); defaultSeverity = pattern.severity(); linkUrl = createLinkUrl(pattern); suppressibility = pattern.suppressibility(); if (suppressibility == Suppressibility.CUSTOM_ANNOTATION) { customSuppressionAnnotation = pattern.customSuppressionAnnotation(); } else { customSuppressionAnnotation = null; } } private static final String URL_FORMAT = "http://errorprone.info/bugpattern/%s"; private static String createLinkUrl(BugPattern pattern) { switch (pattern.linkType()) { case AUTOGENERATED: return String.format(URL_FORMAT, pattern.name()); case CUSTOM: // annotation.link() must be provided. if (pattern.link().isEmpty()) { throw new IllegalStateException( "If linkType element of @BugPattern is CUSTOM, " + "a link element must also be provided."); } return pattern.link(); case NONE: return null; default: throw new IllegalStateException( "Unexpected value for linkType element of @BugPattern: " + pattern.linkType()); } } /** * Returns a new builder for {@link Description}s. * * @param node the node where the error is * @param checker the {@code BugChecker} instance that is producing this {@code Description} */ @CheckReturnValue public static Description.Builder buildDescriptionFromChecker(Tree node, BugChecker checker) { return Description.builder( Preconditions.checkNotNull(node), checker.canonicalName(), checker.linkUrl(), checker.defaultSeverity(), checker.message()); } public String canonicalName() { return canonicalName; } public Set<String> allNames() { return allNames; } public String message() { return message; } public MaturityLevel maturity() { return maturity; } public SeverityLevel defaultSeverity() { return defaultSeverity; } public SeverityLevel severity(Map<String, SeverityLevel> severities) { return firstNonNull(severities.get(canonicalName), defaultSeverity); } public String linkUrl() { return linkUrl; } public Suppressibility suppressibility() { return suppressibility; } public Class<? extends Annotation> customSuppressionAnnotation() { return customSuppressionAnnotation; } public Class<? extends BugChecker> checkerClass() { return checker; } @Override public int hashCode() { return checker.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof BugCheckerInfo)) { return false; } return checker.equals(((BugCheckerInfo) o).checker); } @Override public String toString() { return canonicalName; } }
/* * Copyright (c) 2012, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software 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.cloudera.recordbreaker.fisheye; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.request.mapper.parameter.PageParameters; import java.util.List; import java.util.ArrayList; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import com.cloudera.recordbreaker.analyzer.TypeSummary; import com.cloudera.recordbreaker.analyzer.FileSummary; import com.cloudera.recordbreaker.analyzer.SchemaSummary; import com.cloudera.recordbreaker.analyzer.TypeGuessSummary; /** * The <code>FilesPage</code> renders information about all known files. */ public class FilesPage extends WebPage { final class DirLabelPair { volatile String label; volatile Path dir; public DirLabelPair(String label, Path dir) { this.label = label; this.dir = dir; } public String getLabel() { return label; } public Path getDir() { return dir; } } // // File listing for the current directory // final class FileListing extends WebMarkupContainer { String targetDir; public FileListing(String name, String targetDir) { super(name); this.targetDir = targetDir; FishEye fe = FishEye.getInstance(); final AccessController accessCtrl = fe.getAccessController(); if (fe.hasFSAndCrawl()) { // // I. Generate list of parent dirs for this directory // List<DirLabelPair> parentDirPairList = new ArrayList<DirLabelPair>(); List<FileSummary> parentDirList = fe.getDirParents(targetDir); FileSummary lastDir = null; if (parentDirList != null) { for (FileSummary curDirSummary: parentDirList) { Path curDir = curDirSummary.getPath(); String prefix = ""; if (lastDir != null) { prefix = lastDir.getPath().toString(); } String label = curDir.toString().substring(prefix.length()); // Check rights if (accessCtrl.hasReadAccess(curDirSummary)) { String dirUrl = urlFor(FilesPage.class, new PageParameters("targetdir=" + curDir.toString())).toString(); label = "<a href=\"" + dirUrl + "\">" + label + "</a>"; } parentDirPairList.add(new DirLabelPair(label, curDir)); lastDir = curDirSummary; } } String targetDirLabel = targetDir.substring(lastDir == null ? 0 : lastDir.getPath().toString().length()); parentDirPairList.add(new DirLabelPair(targetDirLabel, new Path(targetDir))); add(new Label("lastParentDirEntry", parentDirPairList.get(parentDirPairList.size()-1).getLabel())); parentDirPairList.remove(parentDirPairList.size()-1); add(new ListView<DirLabelPair>("parentdirlisting", parentDirPairList) { protected void populateItem(ListItem<DirLabelPair> item) { DirLabelPair pair = item.getModelObject(); item.add(new Label("dirlabel", pair.getLabel()).setEscapeModelStrings(false)); } }); // // II. Generate list of subdirs in the directory // final List<DirLabelPair> childDirPairList = new ArrayList<DirLabelPair>(); List<FileSummary> childDirList = fe.getDirChildren(targetDir); if (childDirList != null) { for (FileSummary curDirSummary: childDirList) { String label = curDirSummary.getFname(); if (accessCtrl.hasReadAccess(curDirSummary)) { String dirUrl = urlFor(FilesPage.class, new PageParameters("targetdir=" + curDirSummary.getPath().toString())).toString(); label = "<a href=\"" + dirUrl + "\">" + label + "</a>"; } childDirPairList.add(new DirLabelPair(label, curDirSummary.getPath())); } } add(new WebMarkupContainer("subdirbox") { { add(new ListView<DirLabelPair>("childdirlisting", childDirPairList) { protected void populateItem(ListItem<DirLabelPair> item) { DirLabelPair pair = item.getModelObject(); item.add(new Label("childdirlabel", pair.getLabel()).setEscapeModelStrings(false)); } }); setOutputMarkupPlaceholderTag(true); setVisibilityAllowed(false); } public void onConfigure() { setVisibilityAllowed(childDirPairList.size() > 0); } }); // // III. Generate list of files in the directory // List<FileSummary> filelist = FishEye.getInstance().getAnalyzer().getPrecachedFileSummariesInDir(false, targetDir); add(new Label("numFisheyeFiles", "" + filelist.size())); add(new ListView<FileSummary>("filelisting", filelist) { protected void populateItem(ListItem<FileSummary> item) { long start = System.currentTimeMillis(); FileSummary fs = item.getModelObject(); // 1. Filename. Link is conditional on having read access if (accessCtrl.hasReadAccess(fs)) { String fileUrl = urlFor(FilePage.class, new PageParameters("fid=" + fs.getFid())).toString(); item.add(new Label("filelabel", "<a href=\"" + fileUrl + "\">" + fs.getFname() + "</a>").setEscapeModelStrings(false)); } else { item.add(new Label("filelabel", fs.getFname())); } // 2-5. A bunch of fields that get added no matter what the user's access rights. item.add(new Label("sizelabel", "" + fs.getSize())); item.add(new Label("ownerlabel", fs.getOwner())); item.add(new Label("grouplabel", fs.getGroup())); item.add(new Label("permissionslabel", fs.getPermissions().toString())); // 6-7. Fields that have link conditional on read access AND the existence of relevant info. if (accessCtrl.hasReadAccess(fs)) { List<TypeGuessSummary> tgs = fs.getTypeGuesses(); if (tgs.size() > 0) { TypeSummary ts = tgs.get(0).getTypeSummary(); SchemaSummary ss = tgs.get(0).getSchemaSummary(); String typeUrl = urlFor(FiletypePage.class, new PageParameters("typeid=" + ts.getTypeId())).toString(); item.add(new Label("typelabel", "<a href=\"" + typeUrl + "\">" + ts.getLabel() + "</a>").setEscapeModelStrings(false)); String schemaUrl = urlFor(SchemaPage.class, new PageParameters("schemaid=" + ss.getSchemaId())).toString(); item.add(new Label("schemalabel", "<a href=\"" + schemaUrl + "\">" + "Schema" + "</a>").setEscapeModelStrings(false)); } else { item.add(new Label("typelabel", "")); item.add(new Label("schemalabel", "")); } } else { item.add(new Label("typelabel", "---")); item.add(new Label("schemalabel", "---")); } } }); } setOutputMarkupPlaceholderTag(true); setVisibilityAllowed(false); } public void onConfigure() { FishEye fe = FishEye.getInstance(); AccessController accessCtrl = fe.getAccessController(); FileSummary fileSummary = fe.getAnalyzer().getSingleFileSummary(targetDir); if (fileSummary != null) { setVisibilityAllowed(fe.hasFSAndCrawl() && accessCtrl.hasReadAccess(fileSummary)); } else { setVisibilityAllowed(false); } } } public FilesPage() { FishEye fe = FishEye.getInstance(); String targetDir = fe.getTopDir() != null ? fe.getTopDir() : "/"; add(new SettingsWarningBox()); add(new CrawlWarningBox()); add(new AccessControlWarningBox("accessControlWarningBox", targetDir)); add(new FileListing("currentDirListing", targetDir)); } public FilesPage(PageParameters params) { String targetDir = params.get("targetdir").toString(); add(new SettingsWarningBox()); add(new CrawlWarningBox()); add(new AccessControlWarningBox("accessControlWarningBox", targetDir)); add(new FileListing("currentDirListing", targetDir)); } }
/* * Copyright 2012-2016 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.boot.test.json; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Field; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.core.ResolvableType; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.util.FileCopyUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AbstractJsonMarshalTester}. * * @author Phillip Webb */ public abstract class AbstractJsonMarshalTesterTests { private static final String JSON = "{\"name\":\"Spring\",\"age\":123}"; private static final String MAP_JSON = "{\"a\":" + JSON + "}"; private static final String ARRAY_JSON = "[" + JSON + "]"; private static final ExampleObject OBJECT = createExampleObject("Spring", 123); private static final ResolvableType TYPE = ResolvableType .forClass(ExampleObject.class); @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void writeShouldReturnJsonContent() throws Exception { JsonContent<Object> content = createTester(TYPE).write(OBJECT); assertThat(content).isEqualToJson(JSON); } @Test public void writeListShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("listOfExampleObject"); List<ExampleObject> value = Collections.singletonList(OBJECT); JsonContent<Object> content = createTester(type).write(value); assertThat(content).isEqualToJson(ARRAY_JSON); } @Test public void writeArrayShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("arrayOfExampleObject"); ExampleObject[] value = new ExampleObject[] { OBJECT }; JsonContent<Object> content = createTester(type).write(value); assertThat(content).isEqualToJson(ARRAY_JSON); } @Test public void writeMapShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("mapOfExampleObject"); Map<String, Object> value = new LinkedHashMap<String, Object>(); value.put("a", OBJECT); JsonContent<Object> content = createTester(type).write(value); assertThat(content).isEqualToJson(MAP_JSON); } @Test public void createWhenResourceLoadClassIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ResourceLoadClass must not be null"); createTester(null, ResolvableType.forClass(ExampleObject.class)); } @Test public void createWhenTypeIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Type must not be null"); createTester(getClass(), null); } @Test public void parseBytesShouldReturnObject() throws Exception { AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.parse(JSON.getBytes())).isEqualTo(OBJECT); } @Test public void parseStringShouldReturnObject() throws Exception { AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.parse(JSON)).isEqualTo(OBJECT); } @Test public void readResourcePathShouldReturnObject() throws Exception { AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read("example.json")).isEqualTo(OBJECT); } @Test public void readFileShouldReturnObject() throws Exception { File file = this.temp.newFile("example.json"); FileCopyUtils.copy(JSON.getBytes(), file); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(file)).isEqualTo(OBJECT); } @Test public void readInputStreamShouldReturnObject() throws Exception { InputStream stream = new ByteArrayInputStream(JSON.getBytes()); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(stream)).isEqualTo(OBJECT); } @Test public void readResourceShouldReturnObject() throws Exception { Resource resource = new ByteArrayResource(JSON.getBytes()); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(resource)).isEqualTo(OBJECT); } @Test public void readReaderShouldReturnObject() throws Exception { Reader reader = new StringReader(JSON); AbstractJsonMarshalTester<Object> tester = createTester(TYPE); assertThat(tester.read(reader)).isEqualTo(OBJECT); } @Test public void parseListShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("listOfExampleObject"); AbstractJsonMarshalTester<Object> tester = createTester(type); assertThat(tester.parse(ARRAY_JSON)).asList().containsOnly(OBJECT); } @Test public void parseArrayShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("arrayOfExampleObject"); AbstractJsonMarshalTester<Object> tester = createTester(type); assertThat(tester.parse(ARRAY_JSON)).asArray().containsOnly(OBJECT); } @Test public void parseMapShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("mapOfExampleObject"); AbstractJsonMarshalTester<Object> tester = createTester(type); assertThat(tester.parse(MAP_JSON)).asMap().containsEntry("a", OBJECT); } protected static final ExampleObject createExampleObject(String name, int age) { ExampleObject exampleObject = new ExampleObject(); exampleObject.setName(name); exampleObject.setAge(age); return exampleObject; } protected final AbstractJsonMarshalTester<Object> createTester(ResolvableType type) { return createTester(AbstractJsonMarshalTesterTests.class, type); } protected abstract AbstractJsonMarshalTester<Object> createTester( Class<?> resourceLoadClass, ResolvableType type); /** * Access to field backed by {@link ResolvableType}. */ public static class ResolvableTypes { public List<ExampleObject> listOfExampleObject; public ExampleObject[] arrayOfExampleObject; public Map<String, ExampleObject> mapOfExampleObject; public static ResolvableType get(String name) { Field field = ReflectionUtils.findField(ResolvableTypes.class, name); return ResolvableType.forField(field); } } }
package org.dashbuilder.client.widgets.dataset.editor.workflow.edit; import java.util.List; import javax.validation.ConstraintViolation; import com.google.gwt.editor.client.SimpleBeanEditorDriver; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwtmockito.GwtMockitoTestRunner; import org.dashbuilder.client.widgets.dataset.editor.DataSetEditor; import org.dashbuilder.client.widgets.dataset.editor.workflow.AbstractDataSetWorkflowTest; import org.dashbuilder.client.widgets.dataset.editor.workflow.DataSetEditorWorkflow; import org.dashbuilder.client.widgets.dataset.event.CancelRequestEvent; import org.dashbuilder.client.widgets.dataset.event.SaveRequestEvent; import org.dashbuilder.client.widgets.dataset.event.TestDataSetRequestEvent; import org.dashbuilder.dataset.DataSet; import org.dashbuilder.dataset.DataSetLookup; import org.dashbuilder.dataset.client.DataSetClientServices; import org.dashbuilder.dataset.client.DataSetReadyCallback; import org.dashbuilder.dataset.client.editor.DataSetDefRefreshAttributesEditor; import org.dashbuilder.dataset.def.DataColumnDef; import org.dashbuilder.dataset.def.DataSetDef; import org.jboss.errai.ioc.client.container.SyncBeanDef; import org.jboss.errai.ioc.client.container.SyncBeanManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.uberfire.mocks.EventSourceMock; import org.uberfire.mvp.Command; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; @RunWith( GwtMockitoTestRunner.class ) public class DataSetEditWorkflowTest extends AbstractDataSetWorkflowTest { public static final String UUID = "uuid1"; public static final String NAME = "name1"; @Mock SyncBeanManager beanManager; @Mock EventSourceMock<SaveRequestEvent> saveRequestEvent; @Mock EventSourceMock<TestDataSetRequestEvent> testDataSetEvent; @Mock EventSourceMock<CancelRequestEvent> cancelRequestEvent; @Mock DataSetClientServices clientServices; @Mock DataSetDef dataSetDef; @Mock DataSet dataSet; @Mock DataSetEditorWorkflow.View view; @Mock DataSetDefRefreshAttributesEditor refreshEditor; @Mock SyncBeanDef<SimpleBeanEditorDriver> simpleBeanEditorDriverSyncBeanDef; @Mock SyncBeanDef<DataSetEditor> dataSetEditorSyncBeanDef; @Mock SimpleBeanEditorDriver driver; @Mock DataSetEditor editor; DataSetEditWorkflow presenter; @Before public void setup() throws Exception { super.setup(); when( dataSetDef.getUUID() ).thenReturn( UUID ); when( dataSetDef.getName() ).thenReturn( NAME ); when( dataSet.getUUID() ).thenReturn( UUID ); when( dataSet.getRowCount() ).thenReturn( 0 ); when( dataSetDef.clone() ).thenReturn( dataSetDef ); when( editor.refreshEditor() ).thenReturn( refreshEditor ); // Bean instantiation mocks. when( beanManager.lookupBean( SimpleBeanEditorDriver.class ) ).thenReturn( simpleBeanEditorDriverSyncBeanDef ); when( simpleBeanEditorDriverSyncBeanDef.newInstance() ).thenAnswer( new Answer<SimpleBeanEditorDriver>() { @Override public SimpleBeanEditorDriver answer( InvocationOnMock invocationOnMock ) throws Throwable { return driver; } } ); when( beanManager.lookupBean( DataSetEditor.class ) ).thenReturn( dataSetEditorSyncBeanDef ); when( dataSetEditorSyncBeanDef.newInstance() ).thenAnswer( new Answer<DataSetEditor>() { @Override public DataSetEditor answer( InvocationOnMock invocationOnMock ) throws Throwable { return editor; } } ); doAnswer( new Answer<Void>() { @Override public Void answer( final InvocationOnMock invocationOnMock ) throws Throwable { DataSetReadyCallback callback = (DataSetReadyCallback) invocationOnMock.getArguments()[2]; callback.callback( dataSet ); return null; } } ).when( clientServices ).lookupDataSet( any( dataSetDef.getClass() ), any( DataSetLookup.class ), any( DataSetReadyCallback.class ) ); presenter = new DataSetEditWorkflow( clientServices, validatorProvider, beanManager, saveRequestEvent, testDataSetEvent, cancelRequestEvent, view ) { @Override protected Class<? extends SimpleBeanEditorDriver> getDriverClass() { return SimpleBeanEditorDriver.class; } @Override protected Class getEditorClass() { return DataSetEditor.class; } @Override protected Iterable<ConstraintViolation<?>> validate( boolean isCacheEnabled, boolean isPushEnabled, boolean isRefreshEnabled ) { return null; } }; } @Test public void testEdit() { List<DataColumnDef> columnDefs = mock( List.class ); presenter.edit( dataSetDef, columnDefs ); assertEquals( editor, presenter.getEditor() ); verify( driver, times( 1 ) ).initialize( editor ); verify( editor, times( 1 ) ).setAcceptableValues( columnDefs ); verify( driver, times( 1 ) ).edit( dataSetDef ); verify( view, times( 2 ) ).clearView(); verify( view, times( 1 ) ).add( any( IsWidget.class ) ); verify( view, times( 0 ) ).init( presenter ); verify( view, times( 0 ) ).addButton( anyString(), anyString(), anyBoolean(), any( Command.class ) ); verify( view, times( 0 ) ).clearButtons(); } @Test public void testShowConfigurationTab() { presenter.editor = editor; presenter.showConfigurationTab(); verify( editor, times( 1 ) ).showConfigurationTab(); verify( editor, times( 0 ) ).showPreviewTab(); verify( editor, times( 0 ) ).showAdvancedTab(); verify( view, times( 0 ) ).clearView(); verify( view, times( 0 ) ).add( any( IsWidget.class ) ); verify( view, times( 0 ) ).init( presenter ); verify( view, times( 0 ) ).addButton( anyString(), anyString(), anyBoolean(), any( Command.class ) ); verify( view, times( 0 ) ).clearButtons(); } @Test public void testShowPreviewTab() { presenter.editor = editor; presenter.showPreviewTab(); verify( editor, times( 1 ) ).showPreviewTab(); verify( editor, times( 0 ) ).showConfigurationTab(); verify( editor, times( 0 ) ).showAdvancedTab(); verify( view, times( 0 ) ).clearView(); verify( view, times( 0 ) ).add( any( IsWidget.class ) ); verify( view, times( 0 ) ).init( presenter ); verify( view, times( 0 ) ).addButton( anyString(), anyString(), anyBoolean(), any( Command.class ) ); verify( view, times( 0 ) ).clearButtons(); } @Test public void testShowAdvancedTab() { presenter.editor = editor; presenter.showAdvancedTab(); verify( editor, times( 1 ) ).showAdvancedTab(); verify( editor, times( 0 ) ).showPreviewTab(); verify( editor, times( 0 ) ).showConfigurationTab(); verify( view, times( 0 ) ).clearView(); verify( view, times( 0 ) ).add( any( IsWidget.class ) ); verify( view, times( 0 ) ).init( presenter ); verify( view, times( 0 ) ).addButton( anyString(), anyString(), anyBoolean(), any( Command.class ) ); verify( view, times( 0 ) ).clearButtons(); } @Test public void testFlushDriverRefreshEnabled() throws Exception { presenter.editor = editor; when( refreshEditor.isRefreshEnabled() ).thenReturn( true ); presenter.afterFlush(); verify( dataSetDef, times( 0 ) ).setRefreshTime( null ); } @Test public void testFlushDriverRefreshDisabled() throws Exception { presenter.editor = editor; presenter._setDataSetDef( dataSetDef ); when( refreshEditor.isRefreshEnabled() ).thenReturn( false ); presenter.afterFlush(); verify( dataSetDef, times( 1 ) ).setRefreshTime( null ); } }
/* * Copyright (c) 2006-2017 DMDirc Developers * * 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.dmdirc.updater; import org.junit.Test; import static org.junit.Assert.*; public class VersionTest { @Test public void testConstructorWithNoArgsCreatesInvalidVersion() { assertFalse(new Version().isValid()); } @Test public void testToStringWhenGivenInt() { assertEquals("123", new Version(123).toString()); } @Test public void testIsValidWhenGivenInt() { assertTrue(new Version(123).isValid()); } @Test public void testToStringWhenGivenIntAsString() { assertEquals("123", new Version("123").toString()); } @Test public void testIsValidWhenGivenIntAsString() { assertTrue(new Version("123").isValid()); } @Test public void testToStringWhenGivenVersionString() { assertEquals("0.1.2rc3", new Version("0.1.2rc3").toString()); } @Test public void testIsValidWhenGivenVersionString() { assertTrue(new Version("0.1.2rc3").isValid()); } @Test public void testIsInvalidWhenGivenOtherString() { assertFalse(new Version("Hello!").isValid()); } @Test public void testIsInvalidWhenGivenInvalidGitHash() { assertFalse(new Version("0.1.3-12-gABCDEFG").isValid()); assertFalse(new Version("0.1.3-12-g123").isValid()); assertFalse(new Version("0.1.3-12-g123123123").isValid()); } @Test public void testInvalidVersionsAreEqual() { assertEquals(0, new Version().compareTo(new Version())); } @Test public void testEqualNumericalVersionsAreEqual() { assertEquals(0, new Version(123).compareTo(new Version(123))); } @Test public void testEqualNumericalAndStringVersionsAreEqual() { assertEquals(0, new Version(123).compareTo(new Version("123"))); } @Test public void testStringVersionsAreNewerThanNumericalVersions() { assertTrue(new Version(123).compareTo(new Version("0.1")) < 0); } @Test public void testNumericalVersionsAreOlderThanStringVersions() { assertTrue(new Version("0.1").compareTo(new Version(123)) > 0); } @Test public void testGreaterNumericalVersionIsNewer() { assertTrue(new Version(123).compareTo(new Version(124)) < 0); } @Test public void testLesserNumericalVersionIsOlder() { assertTrue(new Version(124).compareTo(new Version(123)) > 0); } @Test public void testEqualStringVersionsAreEqual() { assertEquals(0, new Version("1.2.3").compareTo(new Version("1.2.3"))); } @Test public void testLongerStringVersionsAreNewer() { assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3.1")) < 0); } @Test public void testHigherStringVersionsAreNewer() { assertTrue(new Version("1.2.3").compareTo(new Version("1.2.4")) < 0); assertTrue(new Version("1.2.3").compareTo(new Version("1.3.3")) < 0); assertTrue(new Version("1.2.3").compareTo(new Version("2.2.3")) < 0); assertTrue(new Version("1.2.3").compareTo(new Version("2.0")) < 0); } @Test public void testHigherStringVersionsAreNewerWithSuffixes() { assertTrue(new Version("1.2.3rc2").compareTo(new Version("1.2.4a1")) < 0); assertTrue(new Version("1.2.3b1").compareTo(new Version("1.3.3m8")) < 0); assertTrue(new Version("1.2.3m8").compareTo(new Version("2.2.3rc2")) < 0); assertTrue(new Version("1.2.3a6").compareTo(new Version("2.0b4")) < 0); } @Test public void testShorterStringVersionsAreOlder() { assertTrue(new Version("1.2.3.1").compareTo(new Version("1.2.3")) > 0); } @Test public void testLowerStringVersionsAreOlder() { assertTrue(new Version("1.2.4").compareTo(new Version("1.2.3")) > 0); assertTrue(new Version("1.3.3").compareTo(new Version("1.2.3")) > 0); assertTrue(new Version("2.2.3").compareTo(new Version("1.2.3")) > 0); assertTrue(new Version("2.0").compareTo(new Version("1.2.3")) > 0); } @Test public void testLowerStringVersionsAreOlderWithSuffixes() { assertTrue(new Version("1.2.4a1").compareTo(new Version("1.2.3rc2")) > 0); assertTrue(new Version("1.3.3m8").compareTo(new Version("1.2.3b1")) > 0); assertTrue(new Version("2.2.3rc2").compareTo(new Version("1.2.3m8")) > 0); assertTrue(new Version("2.0b4").compareTo(new Version("1.2.3a6")) > 0); } @Test public void testHigherGitSuffixesAreNewer() { assertTrue(new Version("1.2-17-gabcdeff").compareTo(new Version("1.2-18-gabcdeff")) < 0); } @Test public void testLowerGitSuffixesAreOlder() { assertTrue(new Version("1.2-18-gabcdeff").compareTo(new Version("1.2-17-gabcdeff")) > 0); } @Test public void testEqualVersionsWithDifferentGitHashesAreEqual() { assertEquals(0, new Version("1.2-17-g1234567").compareTo(new Version("1.2-17-gabcdeff"))); } @Test public void testHigherSuffixesAreNewer() { assertTrue(new Version("1.2.3rc1").compareTo(new Version("1.2.3rc2")) < 0); } @Test public void testBetasAreNewerThanAlphas() { assertTrue(new Version("1.2.3a8").compareTo(new Version("1.2.3b5")) < 0); } @Test public void testAlphasAreNewerThanMilestones() { assertTrue(new Version("1.2.3m8").compareTo(new Version("1.2.3a1")) < 0); } @Test public void testReleaseCandidatesAreNewerThanBetas() { assertTrue(new Version("1.2.3b8").compareTo(new Version("1.2.3rc1")) < 0); } @Test public void testReleasesAreNewerThanReleaseCandidates() { assertTrue(new Version("1.2.3rc8").compareTo(new Version("1.2.3")) < 0); } @Test public void testHigherSuffixesAreNewerWithMilestones() { assertTrue(new Version("1.2.3m1rc1").compareTo(new Version("1.2.3m1rc2")) < 0); } @Test public void testBetasAreNewerThanAlphasWithMilestones() { assertTrue(new Version("1.2.3m1a8").compareTo(new Version("1.2.3m1b5")) < 0); } @Test public void testReleaseCandidatesAreNewerThanBetasWithMilestones() { assertTrue(new Version("1.2.3m1b8").compareTo(new Version("1.2.3m1rc1")) < 0); } @Test public void testReleasesAreNewerThanReleaseCandidatesWithMilestones() { assertTrue(new Version("1.2.3m1rc8").compareTo(new Version("1.2.3m1")) < 0); } @Test public void testLowerSuffixesAreOlder() { assertTrue(new Version("1.2.3rc2").compareTo(new Version("1.2.3rc1")) > 0); } @Test public void testAlphasAreOlderThanBetas() { assertTrue(new Version("1.2.3b5").compareTo(new Version("1.2.3a8")) > 0); } @Test public void testMilestonesAreOlderThanAlphas() { assertTrue(new Version("1.2.3a1").compareTo(new Version("1.2.3m8")) > 0); } @Test public void testBetasAreOlderThanReleaseCandidates() { assertTrue(new Version("1.2.3rc1").compareTo(new Version("1.2.3b8")) > 0); } @Test public void testReleaseCandidatesAreOlderThanReleases() { assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3rc8")) > 0); } @Test public void testLowerSuffixesAreOlderWithMilestones() { assertTrue(new Version("1.2.3m1rc2").compareTo(new Version("1.2.3m1rc1")) > 0); } @Test public void testAlphasAreOlderThanBetasWithMilestones() { assertTrue(new Version("1.2.3m1b5").compareTo(new Version("1.2.3m1a8")) > 0); } @Test public void testBetasAreOlderThanReleaseCandidatesWithMilestones() { assertTrue(new Version("1.2.3m1rc1").compareTo(new Version("1.2.3m1b8")) > 0); } @Test public void testReleaseCandidatesAreOlderThanReleasesWithMilestones() { assertTrue(new Version("1.2.3m1").compareTo(new Version("1.2.3m1rc8")) > 0); } @Test public void testHashCodesEqualWhenIntVersionsEqual() { assertEquals(new Version(1).hashCode(), new Version(1).hashCode()); } @Test public void testHashCodesEqualWhenStringVersionsEqual() { assertEquals(new Version("0.1").hashCode(), new Version("0.1").hashCode()); } }
// 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.externalnav; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.provider.Browser; import android.webkit.WebView; import org.chromium.base.CommandLine; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.UrlUtilities; import org.chromium.chrome.browser.util.IntentUtils; import org.chromium.ui.base.PageTransition; import java.net.URI; import java.util.List; /** * Logic related to the URL overriding/intercepting functionality. * This feature allows Chrome to convert certain navigations to Android Intents allowing * applications like Youtube to direct users clicking on a http(s) link to their native app. */ public class ExternalNavigationHandler { private static final String TAG = "UrlHandler"; private static final String SCHEME_WTAI = "wtai://wp/"; private static final String SCHEME_WTAI_MC = "wtai://wp/mc;"; @VisibleForTesting public static final String EXTRA_BROWSER_FALLBACK_URL = "browser_fallback_url"; private final ExternalNavigationDelegate mDelegate; /** * Result types for checking if we should override URL loading. */ public enum OverrideUrlLoadingResult { /* We should override the URL loading and launch an intent. */ OVERRIDE_WITH_EXTERNAL_INTENT, /* We should override the URL loading and clobber the current tab. */ OVERRIDE_WITH_CLOBBERING_TAB, /* We should override the URL loading. The desired action will be determined * asynchronously (e.g. by requiring user confirmation). */ OVERRIDE_WITH_ASYNC_ACTION, /* We shouldn't override the URL loading. */ NO_OVERRIDE, } /** * A constructor for UrlHandler. * * @param activity The activity to launch an external intent from. */ public ExternalNavigationHandler(Activity activity) { this(new ExternalNavigationDelegateImpl(activity)); } @VisibleForTesting public ExternalNavigationHandler(ExternalNavigationDelegate delegate) { mDelegate = delegate; } /** * Determines whether the URL needs to be sent as an intent to the system, * and sends it, if appropriate. * @return Whether the URL generated an intent, caused a navigation in * current tab, or wasn't handled at all. */ public OverrideUrlLoadingResult shouldOverrideUrlLoading(ExternalNavigationParams params) { Intent intent; // Perform generic parsing of the URI to turn it into an Intent. try { intent = Intent.parseUri(params.getUrl(), Intent.URI_INTENT_SCHEME); } catch (Exception ex) { Log.w(TAG, "Bad URI " + params.getUrl(), ex); return OverrideUrlLoadingResult.NO_OVERRIDE; } boolean hasBrowserFallbackUrl = false; String browserFallbackUrl = IntentUtils.safeGetStringExtra(intent, EXTRA_BROWSER_FALLBACK_URL); if (browserFallbackUrl != null && UrlUtilities.isValidForIntentFallbackNavigation(browserFallbackUrl)) { hasBrowserFallbackUrl = true; } else { browserFallbackUrl = null; } OverrideUrlLoadingResult result = shouldOverrideUrlLoadingInternal( params, intent, hasBrowserFallbackUrl, browserFallbackUrl); if (result == OverrideUrlLoadingResult.NO_OVERRIDE && hasBrowserFallbackUrl && (params.getRedirectHandler() == null // For instance, if this is a chained fallback URL, we ignore it. || !params.getRedirectHandler().shouldNotOverrideUrlLoading())) { return clobberCurrentTabWithFallbackUrl(browserFallbackUrl, params); } return result; } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) private OverrideUrlLoadingResult shouldOverrideUrlLoadingInternal( ExternalNavigationParams params, Intent intent, boolean hasBrowserFallbackUrl, String browserFallbackUrl) { // http://crbug.com/441284 : Disallow firing external intent while Chrome is in the // background. if (params.isApplicationMustBeInForeground() && !mDelegate.isChromeAppInForeground()) { return OverrideUrlLoadingResult.NO_OVERRIDE; } // http://crbug.com/464669 : Disallow firing external intent from background tab. if (params.isBackgroundTabNavigation()) { return OverrideUrlLoadingResult.NO_OVERRIDE; } // pageTransition is a combination of an enumeration (core value) and bitmask. int pageTransitionCore = params.getPageTransition() & PageTransition.CORE_MASK; boolean isLink = pageTransitionCore == PageTransition.LINK; boolean isFormSubmit = pageTransitionCore == PageTransition.FORM_SUBMIT; boolean isFromIntent = (params.getPageTransition() & PageTransition.FROM_API) != 0; boolean isForwardBackNavigation = (params.getPageTransition() & PageTransition.FORWARD_BACK) != 0; boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(params.getUrl()); // http://crbug.com/169549 : If you type in a URL that then redirects in server side to an // link that cannot be rendered by the browser, we want to show the intent picker. boolean isTyped = pageTransitionCore == PageTransition.TYPED; boolean typedRedirectToExternalProtocol = isTyped && params.isRedirect() && isExternalProtocol; // We do not want to show the intent picker for core types typed, bookmarks, auto toplevel, // generated, keyword, keyword generated. See below for exception to typed URL and // redirects: // - http://crbug.com/143118 : URL intercepting should not be invoked on navigations // initiated by the user in the omnibox / NTP. // - http://crbug.com/159153 : Don't override http or https URLs from the NTP or bookmarks. // - http://crbug.com/162106: Intent picker should not be presented on returning to a page. // This should be covered by not showing the picker if the core type is reload. // http://crbug.com/164194 . A navigation forwards or backwards should never trigger // the intent picker. if (isForwardBackNavigation) { return OverrideUrlLoadingResult.NO_OVERRIDE; } // If accessing a file URL, ensure that the user has granted the necessary file access // to Chrome. This check should happen for reloads, navigations, etc..., which is why // it occurs before the subsequent blocks. if (params.getUrl().startsWith("file:") && mDelegate.shouldRequestFileAccess(params.getTab())) { mDelegate.startFileIntent( intent, params.getReferrerUrl(), params.getTab(), params.shouldCloseContentsOnOverrideUrlLoadingAndLaunchIntent()); return OverrideUrlLoadingResult.OVERRIDE_WITH_ASYNC_ACTION; } // http://crbug/331571 : Do not override a navigation started from user typing. // http://crbug/424029 : Need to stay in Chrome for an intent heading explicitly to Chrome. if (params.getRedirectHandler() != null) { if (params.getRedirectHandler().shouldStayInChrome() || params.getRedirectHandler().shouldNotOverrideUrlLoading()) { return OverrideUrlLoadingResult.NO_OVERRIDE; } } // http://crbug.com/149218: We want to show the intent picker for ordinary links, providing // the link is not an incoming intent from another application, unless it's a redirect (see // below). boolean linkNotFromIntent = isLink && !isFromIntent; boolean isOnEffectiveIntentRedirect = params.getRedirectHandler() == null ? false : params.getRedirectHandler().isOnEffectiveIntentRedirectChain(); // http://crbug.com/170925: We need to show the intent picker when we receive an intent from // another app that 30x redirects to a YouTube/Google Maps/Play Store/Google+ URL etc. boolean incomingIntentRedirect = (isLink && isFromIntent && params.isRedirect()) || isOnEffectiveIntentRedirect; // http://crbug.com/181186: We need to show the intent picker when we receive a redirect // following a form submit. boolean isRedirectFromFormSubmit = isFormSubmit && params.isRedirect(); if (!typedRedirectToExternalProtocol) { if (!linkNotFromIntent && !incomingIntentRedirect && !isRedirectFromFormSubmit) { return OverrideUrlLoadingResult.NO_OVERRIDE; } if (params.getRedirectHandler() != null && params.getRedirectHandler().isNavigationFromUserTyping()) { return OverrideUrlLoadingResult.NO_OVERRIDE; } } // Don't override navigation from a chrome:* url to http or https. For example, // when clicking a link in bookmarks or most visited. When navigating from such a // page, there is clear intent to complete the navigation in Chrome. if (params.getReferrerUrl() != null && params.getReferrerUrl().startsWith( UrlConstants.CHROME_SCHEME) && (params.getUrl().startsWith(UrlConstants.HTTP_SCHEME) || params.getUrl().startsWith(UrlConstants.HTTPS_SCHEME))) { return OverrideUrlLoadingResult.NO_OVERRIDE; } if (params.getUrl().startsWith(SCHEME_WTAI_MC)) { // wtai://wp/mc;number // number=string(phone-number) mDelegate.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + params.getUrl().substring(SCHEME_WTAI_MC.length())))); return OverrideUrlLoadingResult.OVERRIDE_WITH_EXTERNAL_INTENT; } else if (params.getUrl().startsWith(SCHEME_WTAI)) { // TODO: handle other WTAI schemes. return OverrideUrlLoadingResult.NO_OVERRIDE; } // The "about:", "chrome:", and "chrome-native:" schemes are internal to the browser; // don't want these to be dispatched to other apps. if (params.getUrl().startsWith("about:") || params.getUrl().startsWith("chrome:") || params.getUrl().startsWith("chrome-native:")) { return OverrideUrlLoadingResult.NO_OVERRIDE; } // The "content:" scheme is disabled in Clank. Do not try to start an activity. if (params.getUrl().startsWith("content:")) { return OverrideUrlLoadingResult.NO_OVERRIDE; } // Special case - It makes no sense to use an external application for a YouTube // pairing code URL, since these match the current tab with a device (Chromecast // or similar) it is supposed to be controlling. Using a different application // that isn't expecting this (in particular YouTube) doesn't work. if (params.getUrl().matches(".*youtube\\.com.*[?&]pairingCode=.*")) { return OverrideUrlLoadingResult.NO_OVERRIDE; } // TODO(changwan): check if we need to handle URL even when external intent is off. if (CommandLine.getInstance().hasSwitch( ChromeSwitches.DISABLE_EXTERNAL_INTENT_REQUESTS)) { Log.w(TAG, "External intent handling is disabled by a command-line flag."); return OverrideUrlLoadingResult.NO_OVERRIDE; } // check whether the intent can be resolved. If not, we will see // whether we can download it from the Market. if (!mDelegate.canResolveActivity(intent)) { if (hasBrowserFallbackUrl) { return clobberCurrentTabWithFallbackUrl(browserFallbackUrl, params); } String packagename = intent.getPackage(); if (packagename != null) { try { intent = new Intent(Intent.ACTION_VIEW, Uri.parse( "market://details?id=" + packagename + "&referrer=" + mDelegate.getPackageName())); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setPackage("com.android.vending"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mDelegate.startActivity(intent); return OverrideUrlLoadingResult.OVERRIDE_WITH_EXTERNAL_INTENT; } catch (ActivityNotFoundException ex) { // ignore the error on devices that does not have // play market installed. return OverrideUrlLoadingResult.NO_OVERRIDE; } } else { return OverrideUrlLoadingResult.NO_OVERRIDE; } } if (hasBrowserFallbackUrl) { intent.removeExtra(EXTRA_BROWSER_FALLBACK_URL); } // sanitize the Intent, ensuring web pages can not bypass browser // security (only access to BROWSABLE activities). intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setComponent(null); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { Intent selector = intent.getSelector(); if (selector != null) { selector.addCategory(Intent.CATEGORY_BROWSABLE); selector.setComponent(null); } } // Set the Browser application ID to us in case the user chooses Chrome // as the app. This will make sure the link is opened in the same tab // instead of making a new one. intent.putExtra(Browser.EXTRA_APPLICATION_ID, mDelegate.getPackageName()); if (params.isOpenInNewTab()) intent.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Make sure webkit can handle it internally before checking for specialized // handlers. If webkit can't handle it internally, we need to call // startActivityIfNeeded or startActivity. if (!isExternalProtocol) { if (!mDelegate.isSpecializedHandlerAvailable(intent)) { return OverrideUrlLoadingResult.NO_OVERRIDE; } else if (params.getReferrerUrl() != null && isLink) { // Current URL has at least one specialized handler available. For navigations // within the same host, keep the navigation inside the browser unless the set of // available apps to handle the new navigation is different. http://crbug.com/463138 URI currentUri; URI previousUri; try { currentUri = new URI(params.getUrl()); previousUri = new URI(params.getReferrerUrl()); } catch (Exception e) { currentUri = null; previousUri = null; } if (currentUri != null && previousUri != null && currentUri.getHost().equals(previousUri.getHost())) { Intent previousIntent; try { previousIntent = Intent.parseUri( params.getReferrerUrl(), Intent.URI_INTENT_SCHEME); } catch (Exception e) { previousIntent = null; } if (previousIntent != null) { List<ComponentName> currentHandlers = mDelegate.queryIntentActivities( intent); List<ComponentName> previousHandlers = mDelegate.queryIntentActivities( previousIntent); if (previousHandlers.containsAll(currentHandlers)) { return OverrideUrlLoadingResult.NO_OVERRIDE; } } } } } try { if (params.isIncognito() && !mDelegate.willChromeHandleIntent(intent)) { // This intent may leave Chrome. Warn the user that incognito does not carry over // to apps out side of Chrome. mDelegate.startIncognitoIntent(intent, params.getReferrerUrl(), hasBrowserFallbackUrl ? browserFallbackUrl : null, params.getTab(), params.shouldCloseContentsOnOverrideUrlLoadingAndLaunchIntent()); return OverrideUrlLoadingResult.OVERRIDE_WITH_ASYNC_ACTION; } else { if (params.getRedirectHandler() != null && incomingIntentRedirect) { if (!params.getRedirectHandler().hasNewResolver(intent)) { return OverrideUrlLoadingResult.NO_OVERRIDE; } } if (mDelegate.isDocumentMode() && params.getTransitionPageHelper() != null && params.getTransitionPageHelper().isTransitionStarting()) { // Use web to native app navigation transitions if there is exactly one // activity to handle the intent. List<ComponentName> list = mDelegate.queryIntentActivities(intent); if (list.size() == 1) { params.getTransitionPageHelper().transitionToNativeApp( params.getUrl(), intent); return OverrideUrlLoadingResult.OVERRIDE_WITH_EXTERNAL_INTENT; } } if (mDelegate.startActivityIfNeeded(intent)) { return OverrideUrlLoadingResult.OVERRIDE_WITH_EXTERNAL_INTENT; } else { return OverrideUrlLoadingResult.NO_OVERRIDE; } } } catch (ActivityNotFoundException ex) { // Ignore the error. If no application can handle the URL, // assume the browser can handle it. } return OverrideUrlLoadingResult.NO_OVERRIDE; } /** * Clobber the current tab with fallback URL. * * @param browserFallbackUrl The fallback URL. * @param params The external navigation params. * @return {@link OverrideUrlLoadingResult} if the tab was clobbered, or we launched an * intent. */ private OverrideUrlLoadingResult clobberCurrentTabWithFallbackUrl( String browserFallbackUrl, ExternalNavigationParams params) { if (!params.isMainFrame()) { // For subframes, we don't support fallback url for now. // http://crbug.com/364522. return OverrideUrlLoadingResult.NO_OVERRIDE; } // NOTE: any further redirection from fall-back URL should not override URL loading. // Otherwise, it can be used in chain for fingerprinting multiple app installation // status in one shot. In order to prevent this scenario, we notify redirection // handler that redirection from the current navigation should stay in Chrome. if (params.getRedirectHandler() != null) { params.getRedirectHandler().setShouldNotOverrideUrlLoadingUntilNewUrlLoading(); } return mDelegate.clobberCurrentTab( browserFallbackUrl, params.getReferrerUrl(), params.getTab()); } /** * @return Whether the |url| could be handled by an external application on the system. */ public boolean canExternalAppHandleUrl(String url) { if (url.startsWith(SCHEME_WTAI_MC)) return true; try { Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); return intent.getPackage() != null || mDelegate.canResolveActivity(intent); } catch (Exception ex) { // Ignore the error. Log.w(TAG, "Bad URI " + url, ex); } return false; } }
package uk.ac.ebi.spot.goci.curation.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm; import uk.ac.ebi.spot.goci.curation.model.SnpFormColumn; import uk.ac.ebi.spot.goci.curation.model.SnpMappingForm; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.Gene; import uk.ac.ebi.spot.goci.model.GenomicContext; import uk.ac.ebi.spot.goci.model.Location; import uk.ac.ebi.spot.goci.model.Locus; import uk.ac.ebi.spot.goci.model.RiskAllele; import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism; import uk.ac.ebi.spot.goci.repository.GenomicContextRepository; import uk.ac.ebi.spot.goci.service.LociAttributesService; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by emma on 20/05/2015. * * @author emma * <p> * Service class that creates an association or returns a view of an association, used by AssociationController. * Used only for SNP X SNP interaction associations */ @Service public class SnpInteractionAssociationService implements SnpAssociationFormService { // Repositories private GenomicContextRepository genomicContextRepository; // Services private LociAttributesService lociAttributesService; @Autowired public SnpInteractionAssociationService(GenomicContextRepository genomicContextRepository, LociAttributesService lociAttributesService) { this.genomicContextRepository = genomicContextRepository; this.lociAttributesService = lociAttributesService; } // Create a form to return to view from Association model object @Override public SnpAssociationForm createForm(Association association) { // Create form SnpAssociationInteractionForm form = new SnpAssociationInteractionForm(); // Set simple string and boolean values form.setAssociationId(association.getId()); form.setAssociationExtension(association.getAssociationExtension()); form.setPvalueDescription(association.getPvalueDescription()); form.setSnpType(association.getSnpType()); form.setSnpApproved(association.getSnpApproved()); form.setPvalueMantissa(association.getPvalueMantissa()); form.setPvalueExponent(association.getPvalueExponent()); form.setStandardError(association.getStandardError()); form.setRange(association.getRange()); form.setDescription(association.getDescription()); form.setRiskFrequency(association.getRiskFrequency()); // Set OR/Beta values form.setOrPerCopyNum(association.getOrPerCopyNum()); form.setOrPerCopyRecip(association.getOrPerCopyRecip()); form.setOrPerCopyRecipRange(association.getOrPerCopyRecipRange()); form.setBetaNum(association.getBetaNum()); form.setBetaUnit(association.getBetaUnit()); form.setBetaDirection(association.getBetaDirection()); // Add collection of Efo traits form.setEfoTraits(association.getEfoTraits()); // Create form columns List<SnpFormColumn> snpFormColumns = new ArrayList<>(); // For each locus get genes and risk alleles Collection<Locus> loci = association.getLoci(); Collection<GenomicContext> snpGenomicContexts = new ArrayList<GenomicContext>(); Collection<SingleNucleotidePolymorphism> snps = new ArrayList<SingleNucleotidePolymorphism>(); List<SnpMappingForm> snpMappingForms = new ArrayList<SnpMappingForm>(); // Create a column per locus if (loci != null && !loci.isEmpty()) { for (Locus locus : loci) { SnpFormColumn snpFormColumn = new SnpFormColumn(); // Set genes Collection<String> authorReportedGenes = new ArrayList<>(); for (Gene gene : locus.getAuthorReportedGenes()) { authorReportedGenes.add(gene.getGeneName()); } snpFormColumn.setAuthorReportedGenes(authorReportedGenes); // Set risk allele Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles(); String strongestRiskAllele = null; String snp = null; Collection<String> proxySnps = new ArrayList<>(); Boolean genomeWide = false; Boolean limitedList = false; String riskFrequency = null; // For snp x snp interaction studies should only have one risk allele per locus if (locusRiskAlleles != null && locusRiskAlleles.size() == 1) { for (RiskAllele riskAllele : locusRiskAlleles) { strongestRiskAllele = riskAllele.getRiskAlleleName(); snp = riskAllele.getSnp().getRsId(); SingleNucleotidePolymorphism snp_obj = riskAllele.getSnp(); snps.add(snp_obj); Collection<Location> locations = snp_obj.getLocations(); for (Location location : locations) { SnpMappingForm snpMappingForm = new SnpMappingForm(snp, location); snpMappingForms.add(snpMappingForm); } snpGenomicContexts.addAll(genomicContextRepository.findBySnpId(snp_obj.getId())); // Set proxy if (riskAllele.getProxySnps() != null) { for (SingleNucleotidePolymorphism riskAlleleProxySnp : riskAllele.getProxySnps()) { proxySnps.add(riskAlleleProxySnp.getRsId()); } } if (riskAllele.getGenomeWide() != null && riskAllele.getGenomeWide()) { genomeWide = true; } if (riskAllele.getLimitedList() != null && riskAllele.getLimitedList()) { limitedList = true; } riskFrequency = riskAllele.getRiskFrequency(); } } else { throw new RuntimeException( "More than one risk allele found for locus " + locus.getId() + ", this is not supported yet for SNP interaction associations" ); } // Set column attributes snpFormColumn.setStrongestRiskAllele(strongestRiskAllele); snpFormColumn.setSnp(snp); snpFormColumn.setProxySnps(proxySnps); snpFormColumn.setGenomeWide(genomeWide); snpFormColumn.setLimitedList(limitedList); snpFormColumn.setRiskFrequency(riskFrequency); snpFormColumns.add(snpFormColumn); } } form.setSnpMappingForms(snpMappingForms); form.setGenomicContexts(snpGenomicContexts); form.setSnps(snps); form.setSnpFormColumns(snpFormColumns); form.setNumOfInteractions(snpFormColumns.size()); return form; } public Association createAssociation(SnpAssociationInteractionForm form) { // Set simple string, boolean and float association attributes Association association = setCommonAssociationElements(form); // Set multi-snp and snp interaction checkboxes association.setMultiSnpHaplotype(false); association.setSnpInteraction(true); // For each column create a loci Collection<Locus> loci = new ArrayList<>(); for (SnpFormColumn col : form.getSnpFormColumns()) { Locus locus = new Locus(); locus.setDescription("SNP x SNP interaction"); // Set locus genes Collection<String> authorReportedGenes = col.getAuthorReportedGenes(); Collection<Gene> locusGenes = lociAttributesService.createGene(authorReportedGenes); locus.setAuthorReportedGenes(locusGenes); // Create SNP String curatorEnteredSNP = col.getSnp(); SingleNucleotidePolymorphism snp = lociAttributesService.createSnp(curatorEnteredSNP); // One risk allele per locus String curatorEnteredRiskAllele = col.getStrongestRiskAllele(); RiskAllele riskAllele = lociAttributesService.createRiskAllele(curatorEnteredRiskAllele, snp); Collection<RiskAllele> locusRiskAlleles = new ArrayList<>(); // Set risk allele attributes riskAllele.setGenomeWide(col.getGenomeWide()); riskAllele.setLimitedList(col.getLimitedList()); riskAllele.setRiskFrequency(col.getRiskFrequency()); // Check for a proxy and if we have one create a proxy snp Collection<String> curatorEnteredProxySnps = col.getProxySnps(); if (curatorEnteredProxySnps != null && !curatorEnteredProxySnps.isEmpty()) { Collection<SingleNucleotidePolymorphism> riskAlleleProxySnps = new ArrayList<>(); for (String curatorEnteredProxySnp : curatorEnteredProxySnps) { SingleNucleotidePolymorphism proxySnp = lociAttributesService.createSnp(curatorEnteredProxySnp); riskAlleleProxySnps.add(proxySnp); } riskAllele.setProxySnps(riskAlleleProxySnps); } // Link risk allele to locus locusRiskAlleles.add(riskAllele); locus.setStrongestRiskAlleles(locusRiskAlleles); // Add locus to collection and link to our association loci.add(locus); } association.setLoci(loci); return association; } }
package com.mopub.nativeads; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import com.mopub.common.AdFormat; import com.mopub.common.Constants; import com.mopub.common.Preconditions; import com.mopub.common.VisibleForTesting; import com.mopub.common.logging.MoPubLog; import com.mopub.common.util.DeviceUtils; import com.mopub.common.util.ManifestUtils; import com.mopub.mobileads.MoPubErrorCode; import com.mopub.network.AdRequest; import com.mopub.network.AdResponse; import com.mopub.network.MoPubNetworkError; import com.mopub.network.Networking; import com.mopub.volley.NetworkResponse; import com.mopub.volley.RequestQueue; import com.mopub.volley.VolleyError; import java.lang.ref.WeakReference; import java.util.Map; import java.util.TreeMap; import static com.mopub.common.GpsHelper.fetchAdvertisingInfoAsync; import static com.mopub.nativeads.CustomEventNative.CustomEventNativeListener; import static com.mopub.nativeads.NativeErrorCode.CONNECTION_ERROR; import static com.mopub.nativeads.NativeErrorCode.EMPTY_AD_RESPONSE; import static com.mopub.nativeads.NativeErrorCode.INVALID_JSON; import static com.mopub.nativeads.NativeErrorCode.INVALID_REQUEST_URL; import static com.mopub.nativeads.NativeErrorCode.SERVER_ERROR_RESPONSE_CODE; import static com.mopub.nativeads.NativeErrorCode.UNSPECIFIED; public class MoPubNative { public interface MoPubNativeNetworkListener { public void onNativeLoad(final NativeResponse nativeResponse); public void onNativeFail(final NativeErrorCode errorCode); } static final MoPubNativeNetworkListener EMPTY_NETWORK_LISTENER = new MoPubNativeNetworkListener() { @Override public void onNativeLoad(@NonNull final NativeResponse nativeResponse) { // If this listener is invoked, it means that MoPubNative instance has been destroyed // so destroy any leftover incoming NativeResponses nativeResponse.destroy(); } @Override public void onNativeFail(final NativeErrorCode errorCode) { } }; static final MoPubNativeEventListener EMPTY_EVENT_LISTENER = new MoPubNativeEventListener() { @Override public void onNativeImpression(@Nullable final View view) { } @Override public void onNativeClick(@Nullable final View view) { } }; public interface MoPubNativeEventListener { public void onNativeImpression(final View view); public void onNativeClick(final View view); } /** * @deprecated As of release 2.4, use {@link MoPubNativeEventListener} and * {@link MoPubNativeNetworkListener} instead. */ @Deprecated public interface MoPubNativeListener extends MoPubNativeNetworkListener, MoPubNativeEventListener { } // must be an activity context since 3rd party networks need it @NonNull private final WeakReference<Context> mContext; @NonNull private final String mAdUnitId; @NonNull private MoPubNativeNetworkListener mMoPubNativeNetworkListener; @NonNull private MoPubNativeEventListener mMoPubNativeEventListener; // For small sets TreeMap, takes up less memory than HashMap @NonNull private Map<String, Object> mLocalExtras = new TreeMap<String, Object>(); @NonNull private final AdRequest.Listener mVolleyListener; @Nullable private AdRequest mNativeRequest; /** * @deprecated As of release 2.4, use {@link MoPubNative(Context, String, * MoPubNativeNetworkListener)} and {@link #setNativeEventListener(MoPubNativeEventListener)} * instead. */ @Deprecated public MoPubNative(@NonNull final Context context, @NonNull final String adUnitId, @NonNull final MoPubNativeListener moPubNativeListener) { this(context, adUnitId, (MoPubNativeNetworkListener) moPubNativeListener); setNativeEventListener(moPubNativeListener); } public MoPubNative(@NonNull final Context context, @NonNull final String adUnitId, @NonNull final MoPubNativeNetworkListener moPubNativeNetworkListener) { Preconditions.checkNotNull(context, "Context may not be null."); Preconditions.checkNotNull(adUnitId, "AdUnitId may not be null."); Preconditions.checkNotNull(moPubNativeNetworkListener, "MoPubNativeNetworkListener may not be null."); ManifestUtils.checkNativeActivitiesDeclared(context); mContext = new WeakReference<Context>(context); mAdUnitId = adUnitId; mMoPubNativeNetworkListener = moPubNativeNetworkListener; mMoPubNativeEventListener = EMPTY_EVENT_LISTENER; mVolleyListener = new AdRequest.Listener() { @Override public void onSuccess(@NonNull final AdResponse response) { onAdLoad(response); } @Override public void onErrorResponse(@NonNull final VolleyError volleyError) { onAdError(volleyError); } }; // warm up cache for google play services info fetchAdvertisingInfoAsync(context, null); } public void setNativeEventListener(@Nullable final MoPubNativeEventListener nativeEventListener) { mMoPubNativeEventListener = (nativeEventListener == null) ? EMPTY_EVENT_LISTENER : nativeEventListener; } public void destroy() { mContext.clear(); if (mNativeRequest != null) { mNativeRequest.cancel(); mNativeRequest = null; } mMoPubNativeNetworkListener = EMPTY_NETWORK_LISTENER; mMoPubNativeEventListener = EMPTY_EVENT_LISTENER; } public void setLocalExtras(@Nullable final Map<String, Object> localExtras) { if (localExtras == null) { mLocalExtras = new TreeMap<String, Object>(); } else { mLocalExtras = new TreeMap<String, Object>(localExtras); } } public void makeRequest() { makeRequest((RequestParameters)null); } public void makeRequest(@Nullable final RequestParameters requestParameters) { makeRequest(requestParameters, null); } public void makeRequest(@Nullable final RequestParameters requestParameters, @Nullable Integer sequenceNumber) { final Context context = getContextOrDestroy(); if (context == null) { return; } if (!DeviceUtils.isNetworkAvailable(context)) { mMoPubNativeNetworkListener.onNativeFail(CONNECTION_ERROR); return; } loadNativeAd(requestParameters, sequenceNumber); } private void loadNativeAd( @Nullable final RequestParameters requestParameters, @Nullable final Integer sequenceNumber) { final Context context = getContextOrDestroy(); if (context == null) { return; } final NativeUrlGenerator generator = new NativeUrlGenerator(context) .withAdUnitId(mAdUnitId) .withRequest(requestParameters); if (sequenceNumber != null) { generator.withSequenceNumber(sequenceNumber); } final String endpointUrl = generator.generateUrlString(Constants.HOST); if (endpointUrl != null) { MoPubLog.d("Loading ad from: " + endpointUrl); } requestNativeAd(endpointUrl); } void requestNativeAd(@Nullable final String endpointUrl) { final Context context = getContextOrDestroy(); if (context == null) { return; } if (endpointUrl == null) { mMoPubNativeNetworkListener.onNativeFail(INVALID_REQUEST_URL); return; } mNativeRequest = new AdRequest(endpointUrl, AdFormat.NATIVE, mAdUnitId, context, mVolleyListener); RequestQueue requestQueue = Networking.getRequestQueue(context); requestQueue.add(mNativeRequest); } private void onAdLoad(@NonNull final AdResponse response) { final Context context = getContextOrDestroy(); if (context == null) { return; } final CustomEventNativeListener customEventNativeListener = new CustomEventNativeListener() { @Override public void onNativeAdLoaded(@NonNull final NativeAdInterface nativeAd) { final Context context = getContextOrDestroy(); if (context == null) { return; } mMoPubNativeNetworkListener.onNativeLoad(new NativeResponse(context, response.getImpressionTrackingUrl(), response.getClickTrackingUrl(), mAdUnitId, nativeAd, mMoPubNativeEventListener)); } @Override public void onNativeAdFailed(final NativeErrorCode errorCode) { requestNativeAd(response.getFailoverUrl()); } }; CustomEventNativeAdapter.loadNativeAd( context, mLocalExtras, response, customEventNativeListener ); } @VisibleForTesting void onAdError(@NonNull final VolleyError volleyError) { MoPubLog.d("Native ad request failed.", volleyError); if (volleyError instanceof MoPubNetworkError) { MoPubNetworkError error = (MoPubNetworkError) volleyError; switch (error.getReason()) { case BAD_BODY: mMoPubNativeNetworkListener.onNativeFail(INVALID_JSON); return; case BAD_HEADER_DATA: mMoPubNativeNetworkListener.onNativeFail(INVALID_JSON); return; case WARMING_UP: // Used for the sample app to signal a toast. // This is not customer-facing except in the sample app. MoPubLog.c(MoPubErrorCode.WARMUP.toString()); mMoPubNativeNetworkListener.onNativeFail(EMPTY_AD_RESPONSE); return; case NO_FILL: mMoPubNativeNetworkListener.onNativeFail(EMPTY_AD_RESPONSE); return; case UNSPECIFIED: default: mMoPubNativeNetworkListener.onNativeFail(UNSPECIFIED); return; } } else { // Process our other status code errors. NetworkResponse response = volleyError.networkResponse; if (response != null && response.statusCode >= 500 && response.statusCode < 600) { mMoPubNativeNetworkListener.onNativeFail(SERVER_ERROR_RESPONSE_CODE); } else if (response == null && !DeviceUtils.isNetworkAvailable(mContext.get())) { MoPubLog.c(String.valueOf(MoPubErrorCode.NO_CONNECTION.toString())); mMoPubNativeNetworkListener.onNativeFail(CONNECTION_ERROR); } else { mMoPubNativeNetworkListener.onNativeFail(UNSPECIFIED); } } } Context getContextOrDestroy() { final Context context = mContext.get(); if (context == null) { destroy(); MoPubLog.d("Weak reference to Activity Context in MoPubNative became null. This instance" + " of MoPubNative is destroyed and No more requests will be processed."); } return context; } @NonNull @VisibleForTesting @Deprecated MoPubNativeNetworkListener getMoPubNativeNetworkListener() { return mMoPubNativeNetworkListener; } @NonNull @VisibleForTesting @Deprecated MoPubNativeEventListener getMoPubNativeEventListener() { return mMoPubNativeEventListener; } }
/** * 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 java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger.AuditConstants; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerFinishedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerImpl; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; /** * Represents an application attempt from the viewpoint of the Fair Scheduler. */ @Private @Unstable public class FSAppAttempt extends SchedulerApplicationAttempt implements Schedulable { private static final Log LOG = LogFactory.getLog(FSAppAttempt.class); private static final DefaultResourceCalculator RESOURCE_CALCULATOR = new DefaultResourceCalculator(); private long startTime; private Priority priority; private ResourceWeights resourceWeights; private Resource demand = Resources.createResource(0); private FairScheduler scheduler; private Resource fairShare = Resources.createResource(0, 0); private Resource preemptedResources = Resources.createResource(0); private RMContainerComparator comparator = new RMContainerComparator(); private final Map<RMContainer, Long> preemptionMap = new HashMap<RMContainer, Long>(); /** * Delay scheduling: We often want to prioritize scheduling of node-local * containers over rack-local or off-switch containers. To acheive this * we first only allow node-local assigments for a given prioirty level, * then relax the locality threshold once we've had a long enough period * without succesfully scheduling. We measure both the number of "missed" * scheduling opportunities since the last container was scheduled * at the current allowed level and the time since the last container * was scheduled. Currently we use only the former. */ private final Map<Priority, NodeType> allowedLocalityLevel = new HashMap<Priority, NodeType>(); public FSAppAttempt(FairScheduler scheduler, ApplicationAttemptId applicationAttemptId, String user, FSLeafQueue queue, ActiveUsersManager activeUsersManager, RMContext rmContext) { super(applicationAttemptId, user, queue, activeUsersManager, rmContext); this.scheduler = scheduler; this.startTime = scheduler.getClock().getTime(); this.priority = Priority.newInstance(1); this.resourceWeights = new ResourceWeights(); } public ResourceWeights getResourceWeights() { return resourceWeights; } /** * Get metrics reference from containing queue. */ public QueueMetrics getMetrics() { return queue.getMetrics(); } synchronized public void containerCompleted(RMContainer rmContainer, ContainerStatus containerStatus, RMContainerEventType event) { Container container = rmContainer.getContainer(); ContainerId containerId = container.getId(); // Remove from the list of newly allocated containers if found newlyAllocatedContainers.remove(rmContainer); // Inform the container rmContainer.handle( new RMContainerFinishedEvent( containerId, containerStatus, event) ); LOG.info("Completed container: " + rmContainer.getContainerId() + " in state: " + rmContainer.getState() + " event:" + event); // Remove from the list of containers liveContainers.remove(rmContainer.getContainerId()); RMAuditLogger.logSuccess(getUser(), AuditConstants.RELEASE_CONTAINER, "SchedulerApp", getApplicationId(), containerId); // Update usage metrics Resource containerResource = rmContainer.getContainer().getResource(); queue.getMetrics().releaseResources(getUser(), 1, containerResource); Resources.subtractFrom(currentConsumption, containerResource); // remove from preemption map if it is completed preemptionMap.remove(rmContainer); // Clear resource utilization metrics cache. lastMemoryAggregateAllocationUpdateTime = -1; } private synchronized void unreserveInternal( Priority priority, FSSchedulerNode node) { Map<NodeId, RMContainer> reservedContainers = this.reservedContainers.get(priority); RMContainer reservedContainer = reservedContainers.remove(node.getNodeID()); if (reservedContainers.isEmpty()) { this.reservedContainers.remove(priority); } // Reset the re-reservation count resetReReservations(priority); Resource resource = reservedContainer.getContainer().getResource(); Resources.subtractFrom(currentReservation, resource); LOG.info("Application " + getApplicationId() + " unreserved " + " on node " + node + ", currently has " + reservedContainers.size() + " at priority " + priority + "; currentReservation " + currentReservation); } @Override public synchronized Resource getHeadroom() { final FSQueue queue = (FSQueue) this.queue; SchedulingPolicy policy = queue.getPolicy(); Resource queueFairShare = queue.getFairShare(); Resource queueUsage = queue.getResourceUsage(); Resource clusterResource = this.scheduler.getClusterResource(); Resource clusterUsage = this.scheduler.getRootQueueMetrics() .getAllocatedResources(); Resource clusterAvailableResource = Resources.subtract(clusterResource, clusterUsage); Resource headroom = policy.getHeadroom(queueFairShare, queueUsage, clusterAvailableResource); if (LOG.isDebugEnabled()) { LOG.debug("Headroom calculation for " + this.getName() + ":" + "Min(" + "(queueFairShare=" + queueFairShare + " - queueUsage=" + queueUsage + ")," + " clusterAvailableResource=" + clusterAvailableResource + "(clusterResource=" + clusterResource + " - clusterUsage=" + clusterUsage + ")" + "Headroom=" + headroom); } return headroom; } public synchronized float getLocalityWaitFactor( Priority priority, int clusterNodes) { // Estimate: Required unique resources (i.e. hosts + racks) int requiredResources = Math.max(this.getResourceRequests(priority).size() - 1, 0); // waitFactor can't be more than '1' // i.e. no point skipping more than clustersize opportunities return Math.min(((float)requiredResources / clusterNodes), 1.0f); } /** * Return the level at which we are allowed to schedule containers, given the * current size of the cluster and thresholds indicating how many nodes to * fail at (as a fraction of cluster size) before relaxing scheduling * constraints. */ public synchronized NodeType getAllowedLocalityLevel(Priority priority, int numNodes, double nodeLocalityThreshold, double rackLocalityThreshold) { // upper limit on threshold if (nodeLocalityThreshold > 1.0) { nodeLocalityThreshold = 1.0; } if (rackLocalityThreshold > 1.0) { rackLocalityThreshold = 1.0; } // If delay scheduling is not being used, can schedule anywhere if (nodeLocalityThreshold < 0.0 || rackLocalityThreshold < 0.0) { return NodeType.OFF_SWITCH; } // Default level is NODE_LOCAL if (!allowedLocalityLevel.containsKey(priority)) { allowedLocalityLevel.put(priority, NodeType.NODE_LOCAL); return NodeType.NODE_LOCAL; } NodeType allowed = allowedLocalityLevel.get(priority); // If level is already most liberal, we're done if (allowed.equals(NodeType.OFF_SWITCH)) return NodeType.OFF_SWITCH; double threshold = allowed.equals(NodeType.NODE_LOCAL) ? nodeLocalityThreshold : rackLocalityThreshold; // Relax locality constraints once we've surpassed threshold. if (getSchedulingOpportunities(priority) > (numNodes * threshold)) { if (allowed.equals(NodeType.NODE_LOCAL)) { allowedLocalityLevel.put(priority, NodeType.RACK_LOCAL); resetSchedulingOpportunities(priority); } else if (allowed.equals(NodeType.RACK_LOCAL)) { allowedLocalityLevel.put(priority, NodeType.OFF_SWITCH); resetSchedulingOpportunities(priority); } } return allowedLocalityLevel.get(priority); } /** * Return the level at which we are allowed to schedule containers. * Given the thresholds indicating how much time passed before relaxing * scheduling constraints. */ public synchronized NodeType getAllowedLocalityLevelByTime(Priority priority, long nodeLocalityDelayMs, long rackLocalityDelayMs, long currentTimeMs) { // if not being used, can schedule anywhere if (nodeLocalityDelayMs < 0 || rackLocalityDelayMs < 0) { return NodeType.OFF_SWITCH; } // default level is NODE_LOCAL if (! allowedLocalityLevel.containsKey(priority)) { allowedLocalityLevel.put(priority, NodeType.NODE_LOCAL); return NodeType.NODE_LOCAL; } NodeType allowed = allowedLocalityLevel.get(priority); // if level is already most liberal, we're done if (allowed.equals(NodeType.OFF_SWITCH)) { return NodeType.OFF_SWITCH; } // check waiting time long waitTime = currentTimeMs; if (lastScheduledContainer.containsKey(priority)) { waitTime -= lastScheduledContainer.get(priority); } else { waitTime -= getStartTime(); } long thresholdTime = allowed.equals(NodeType.NODE_LOCAL) ? nodeLocalityDelayMs : rackLocalityDelayMs; if (waitTime > thresholdTime) { if (allowed.equals(NodeType.NODE_LOCAL)) { allowedLocalityLevel.put(priority, NodeType.RACK_LOCAL); resetSchedulingOpportunities(priority, currentTimeMs); } else if (allowed.equals(NodeType.RACK_LOCAL)) { allowedLocalityLevel.put(priority, NodeType.OFF_SWITCH); resetSchedulingOpportunities(priority, currentTimeMs); } } return allowedLocalityLevel.get(priority); } synchronized public RMContainer allocate(NodeType type, FSSchedulerNode node, Priority priority, ResourceRequest request, Container container) { // Update allowed locality level NodeType allowed = allowedLocalityLevel.get(priority); if (allowed != null) { if (allowed.equals(NodeType.OFF_SWITCH) && (type.equals(NodeType.NODE_LOCAL) || type.equals(NodeType.RACK_LOCAL))) { this.resetAllowedLocalityLevel(priority, type); } else if (allowed.equals(NodeType.RACK_LOCAL) && type.equals(NodeType.NODE_LOCAL)) { this.resetAllowedLocalityLevel(priority, type); } } // Required sanity check - AM can call 'allocate' to update resource // request without locking the scheduler, hence we need to check if (getTotalRequiredResources(priority) <= 0) { return null; } // Create RMContainer RMContainer rmContainer = new RMContainerImpl(container, getApplicationAttemptId(), node.getNodeID(), appSchedulingInfo.getUser(), rmContext); // Add it to allContainers list. newlyAllocatedContainers.add(rmContainer); liveContainers.put(container.getId(), rmContainer); // Update consumption and track allocations List<ResourceRequest> resourceRequestList = appSchedulingInfo.allocate( type, node, priority, request, container); Resources.addTo(currentConsumption, container.getResource()); // Update resource requests related to "request" and store in RMContainer ((RMContainerImpl) rmContainer).setResourceRequests(resourceRequestList); // Inform the container rmContainer.handle( new RMContainerEvent(container.getId(), RMContainerEventType.START)); if (LOG.isDebugEnabled()) { LOG.debug("allocate: applicationAttemptId=" + container.getId().getApplicationAttemptId() + " container=" + container.getId() + " host=" + container.getNodeId().getHost() + " type=" + type); } RMAuditLogger.logSuccess(getUser(), AuditConstants.ALLOC_CONTAINER, "SchedulerApp", getApplicationId(), container.getId()); return rmContainer; } /** * Should be called when the scheduler assigns a container at a higher * degree of locality than the current threshold. Reset the allowed locality * level to a higher degree of locality. */ public synchronized void resetAllowedLocalityLevel(Priority priority, NodeType level) { NodeType old = allowedLocalityLevel.get(priority); LOG.info("Raising locality level from " + old + " to " + level + " at " + " priority " + priority); allowedLocalityLevel.put(priority, level); } // related methods public void addPreemption(RMContainer container, long time) { assert preemptionMap.get(container) == null; preemptionMap.put(container, time); Resources.addTo(preemptedResources, container.getAllocatedResource()); } public Long getContainerPreemptionTime(RMContainer container) { return preemptionMap.get(container); } public Set<RMContainer> getPreemptionContainers() { return preemptionMap.keySet(); } @Override public FSLeafQueue getQueue() { return (FSLeafQueue)super.getQueue(); } public Resource getPreemptedResources() { return preemptedResources; } public void resetPreemptedResources() { preemptedResources = Resources.createResource(0); for (RMContainer container : getPreemptionContainers()) { Resources.addTo(preemptedResources, container.getAllocatedResource()); } } public void clearPreemptedResources() { preemptedResources.setMemory(0); preemptedResources.setVirtualCores(0); } /** * Create and return a container object reflecting an allocation for the * given appliction on the given node with the given capability and * priority. */ public Container createContainer( FSSchedulerNode node, Resource capability, Priority priority) { NodeId nodeId = node.getRMNode().getNodeID(); ContainerId containerId = BuilderUtils.newContainerId( getApplicationAttemptId(), getNewContainerId()); // Create the container Container container = BuilderUtils.newContainer(containerId, nodeId, node.getRMNode() .getHttpAddress(), capability, priority, null); return container; } /** * Reserve a spot for {@code container} on this {@code node}. If * the container is {@code alreadyReserved} on the node, simply * update relevant bookeeping. This dispatches ro relevant handlers * in {@link FSSchedulerNode}.. */ private void reserve(Priority priority, FSSchedulerNode node, Container container, boolean alreadyReserved) { LOG.info("Making reservation: node=" + node.getNodeName() + " app_id=" + getApplicationId()); if (!alreadyReserved) { getMetrics().reserveResource(getUser(), container.getResource()); RMContainer rmContainer = super.reserve(node, priority, null, container); node.reserveResource(this, priority, rmContainer); } else { RMContainer rmContainer = node.getReservedContainer(); super.reserve(node, priority, rmContainer, container); node.reserveResource(this, priority, rmContainer); } } /** * Remove the reservation on {@code node} at the given {@link Priority}. * This dispatches SchedulerNode handlers as well. */ public void unreserve(Priority priority, FSSchedulerNode node) { RMContainer rmContainer = node.getReservedContainer(); unreserveInternal(priority, node); node.unreserveResource(this); getMetrics().unreserveResource( getUser(), rmContainer.getContainer().getResource()); } /** * Assign a container to this node to facilitate {@code request}. If node does * not have enough memory, create a reservation. This is called once we are * sure the particular request should be facilitated by this node. * * @param node * The node to try placing the container on. * @param request * The ResourceRequest we're trying to satisfy. * @param type * The locality of the assignment. * @param reserved * Whether there's already a container reserved for this app on the node. * @return * If an assignment was made, returns the resources allocated to the * container. If a reservation was made, returns * FairScheduler.CONTAINER_RESERVED. If no assignment or reservation was * made, returns an empty resource. */ private Resource assignContainer( FSSchedulerNode node, ResourceRequest request, NodeType type, boolean reserved) { // How much does this request need? Resource capability = request.getCapability(); // How much does the node have? Resource available = node.getAvailableResource(); Container container = null; if (reserved) { container = node.getReservedContainer().getContainer(); } else { container = createContainer(node, capability, request.getPriority()); } // Can we allocate a container on this node? if (Resources.fitsIn(capability, available)) { // Inform the application of the new container for this request RMContainer allocatedContainer = allocate(type, node, request.getPriority(), request, container); if (allocatedContainer == null) { // Did the application need this resource? if (reserved) { unreserve(request.getPriority(), node); } return Resources.none(); } // If we had previously made a reservation, delete it if (reserved) { unreserve(request.getPriority(), node); } // Inform the node node.allocateContainer(allocatedContainer); // If this container is used to run AM, update the leaf queue's AM usage if (getLiveContainers().size() == 1 && !getUnmanagedAM()) { getQueue().addAMResourceUsage(container.getResource()); setAmRunning(true); } return container.getResource(); } else { // The desired container won't fit here, so reserve reserve(request.getPriority(), node, container, reserved); return FairScheduler.CONTAINER_RESERVED; } } private Resource assignContainer(FSSchedulerNode node, boolean reserved) { if (LOG.isDebugEnabled()) { LOG.debug("Node offered to app: " + getName() + " reserved: " + reserved); } Collection<Priority> prioritiesToTry = (reserved) ? Arrays.asList(node.getReservedContainer().getReservedPriority()) : getPriorities(); // For each priority, see if we can schedule a node local, rack local // or off-switch request. Rack of off-switch requests may be delayed // (not scheduled) in order to promote better locality. synchronized (this) { for (Priority priority : prioritiesToTry) { if (getTotalRequiredResources(priority) <= 0 || !hasContainerForNode(priority, node)) { continue; } addSchedulingOpportunity(priority); // Check the AM resource usage for the leaf queue if (getLiveContainers().size() == 0 && !getUnmanagedAM()) { if (!getQueue().canRunAppAM(getAMResource())) { return Resources.none(); } } ResourceRequest rackLocalRequest = getResourceRequest(priority, node.getRackName()); ResourceRequest localRequest = getResourceRequest(priority, node.getNodeName()); if (localRequest != null && !localRequest.getRelaxLocality()) { LOG.warn("Relax locality off is not supported on local request: " + localRequest); } NodeType allowedLocality; if (scheduler.isContinuousSchedulingEnabled()) { allowedLocality = getAllowedLocalityLevelByTime(priority, scheduler.getNodeLocalityDelayMs(), scheduler.getRackLocalityDelayMs(), scheduler.getClock().getTime()); } else { allowedLocality = getAllowedLocalityLevel(priority, scheduler.getNumClusterNodes(), scheduler.getNodeLocalityThreshold(), scheduler.getRackLocalityThreshold()); } if (rackLocalRequest != null && rackLocalRequest.getNumContainers() != 0 && localRequest != null && localRequest.getNumContainers() != 0) { return assignContainer(node, localRequest, NodeType.NODE_LOCAL, reserved); } if (rackLocalRequest != null && !rackLocalRequest.getRelaxLocality()) { continue; } if (rackLocalRequest != null && rackLocalRequest.getNumContainers() != 0 && (allowedLocality.equals(NodeType.RACK_LOCAL) || allowedLocality.equals(NodeType.OFF_SWITCH))) { return assignContainer(node, rackLocalRequest, NodeType.RACK_LOCAL, reserved); } ResourceRequest offSwitchRequest = getResourceRequest(priority, ResourceRequest.ANY); if (offSwitchRequest != null && !offSwitchRequest.getRelaxLocality()) { continue; } if (offSwitchRequest != null && offSwitchRequest.getNumContainers() != 0 && allowedLocality.equals(NodeType.OFF_SWITCH)) { return assignContainer(node, offSwitchRequest, NodeType.OFF_SWITCH, reserved); } } } return Resources.none(); } /** * Called when this application already has an existing reservation on the * given node. Sees whether we can turn the reservation into an allocation. * Also checks whether the application needs the reservation anymore, and * releases it if not. * * @param node * Node that the application has an existing reservation on */ public Resource assignReservedContainer(FSSchedulerNode node) { RMContainer rmContainer = node.getReservedContainer(); Priority priority = rmContainer.getReservedPriority(); // Make sure the application still needs requests at this priority if (getTotalRequiredResources(priority) == 0) { unreserve(priority, node); return Resources.none(); } // Fail early if the reserved container won't fit. // Note that we have an assumption here that there's only one container size // per priority. if (!Resources.fitsIn(node.getReservedContainer().getReservedResource(), node.getAvailableResource())) { return Resources.none(); } return assignContainer(node, true); } /** * Whether this app has containers requests that could be satisfied on the * given node, if the node had full space. */ public boolean hasContainerForNode(Priority prio, FSSchedulerNode node) { ResourceRequest anyRequest = getResourceRequest(prio, ResourceRequest.ANY); ResourceRequest rackRequest = getResourceRequest(prio, node.getRackName()); ResourceRequest nodeRequest = getResourceRequest(prio, node.getNodeName()); return // There must be outstanding requests at the given priority: anyRequest != null && anyRequest.getNumContainers() > 0 && // If locality relaxation is turned off at *-level, there must be a // non-zero request for the node's rack: (anyRequest.getRelaxLocality() || (rackRequest != null && rackRequest.getNumContainers() > 0)) && // If locality relaxation is turned off at rack-level, there must be a // non-zero request at the node: (rackRequest == null || rackRequest.getRelaxLocality() || (nodeRequest != null && nodeRequest.getNumContainers() > 0)) && // The requested container must be able to fit on the node: Resources.lessThanOrEqual(RESOURCE_CALCULATOR, null, anyRequest.getCapability(), node.getRMNode().getTotalCapability()); } static class RMContainerComparator implements Comparator<RMContainer>, Serializable { @Override public int compare(RMContainer c1, RMContainer c2) { int ret = c1.getContainer().getPriority().compareTo( c2.getContainer().getPriority()); if (ret == 0) { return c2.getContainerId().compareTo(c1.getContainerId()); } return ret; } } /* Schedulable methods implementation */ @Override public String getName() { return getApplicationId().toString(); } @Override public Resource getDemand() { return demand; } @Override public long getStartTime() { return startTime; } @Override public Resource getMinShare() { return Resources.none(); } @Override public Resource getMaxShare() { return Resources.unbounded(); } @Override public Resource getResourceUsage() { // Here the getPreemptedResources() always return zero, except in // a preemption round return Resources.subtract(getCurrentConsumption(), getPreemptedResources()); } @Override public ResourceWeights getWeights() { return scheduler.getAppWeight(this); } @Override public Priority getPriority() { // Right now per-app priorities are not passed to scheduler, // so everyone has the same priority. return priority; } @Override public Resource getFairShare() { return this.fairShare; } @Override public void setFairShare(Resource fairShare) { this.fairShare = fairShare; } @Override public void updateDemand() { demand = Resources.createResource(0); // Demand is current consumption plus outstanding requests Resources.addTo(demand, getCurrentConsumption()); // Add up outstanding resource requests synchronized (this) { for (Priority p : getPriorities()) { for (ResourceRequest r : getResourceRequests(p).values()) { Resource total = Resources.multiply(r.getCapability(), r.getNumContainers()); Resources.addTo(demand, total); } } } } @Override public Resource assignContainer(FSSchedulerNode node) { return assignContainer(node, false); } /** * Preempt a running container according to the priority */ @Override public RMContainer preemptContainer() { if (LOG.isDebugEnabled()) { LOG.debug("App " + getName() + " is going to preempt a running " + "container"); } RMContainer toBePreempted = null; for (RMContainer container : getLiveContainers()) { if (!getPreemptionContainers().contains(container) && (toBePreempted == null || comparator.compare(toBePreempted, container) > 0)) { toBePreempted = container; } } return toBePreempted; } }
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2016 Groupon, Inc * Copyright 2014-2016 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.invoice.calculator; import java.math.BigDecimal; import java.util.Iterator; import javax.annotation.Nullable; import org.joda.time.DateTime; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.api.InvoiceItemType; import org.killbill.billing.invoice.api.InvoicePayment; import org.killbill.billing.invoice.api.InvoicePaymentType; import org.killbill.billing.util.currency.KillBillMoney; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; public abstract class InvoiceCalculatorUtils { public static boolean isInvoiceAdjustmentItem(final InvoiceItem invoiceItemToCheck, final Iterable<InvoiceItem> invoiceItems) { // Invoice level credit, i.e. credit adj, but NOT on its on own invoice return InvoiceItemType.CREDIT_ADJ.equals(invoiceItemToCheck.getInvoiceItemType()) && !isCreditInvoice(invoiceItems); } private static boolean isCreditInvoice(final Iterable<InvoiceItem> invoiceItems) { if (Iterables.size(invoiceItems) != 2) { return false; } final Iterator<InvoiceItem> itr = invoiceItems.iterator(); final InvoiceItem item1 = itr.next(); final InvoiceItem item2 = itr.next(); if (!InvoiceItemType.CREDIT_ADJ.equals(item1.getInvoiceItemType()) && !InvoiceItemType.CREDIT_ADJ.equals(item2.getInvoiceItemType())) { return false; } return ((InvoiceItemType.CREDIT_ADJ.equals(item1.getInvoiceItemType()) && isCbaAdjItemInCreditInvoice(item1, item2)) || (InvoiceItemType.CREDIT_ADJ.equals(item2.getInvoiceItemType()) && isCbaAdjItemInCreditInvoice(item2, item1))); } private static boolean isCbaAdjItemInCreditInvoice(final InvoiceItem creditAdjItem, final InvoiceItem itemToCheck) { return (InvoiceItemType.CBA_ADJ.equals(itemToCheck.getInvoiceItemType()) && itemToCheck.getInvoiceId().equals(creditAdjItem.getInvoiceId()) && itemToCheck.getAmount().compareTo(creditAdjItem.getAmount().negate()) == 0); } // Item adjustments public static boolean isInvoiceItemAdjustmentItem(final InvoiceItem invoiceItem) { return InvoiceItemType.ITEM_ADJ.equals(invoiceItem.getInvoiceItemType()) || InvoiceItemType.REPAIR_ADJ.equals(invoiceItem.getInvoiceItemType()); } // Account credits, gained or consumed public static boolean isAccountCreditItem(final InvoiceItem invoiceItem) { return InvoiceItemType.CBA_ADJ.equals(invoiceItem.getInvoiceItemType()); } // Item from Parent Invoice public static boolean isParentSummaryItem(final InvoiceItem invoiceItem) { return InvoiceItemType.PARENT_SUMMARY.equals(invoiceItem.getInvoiceItemType()); } // Regular line item (charges) public static boolean isCharge(final InvoiceItem invoiceItem) { return InvoiceItemType.TAX.equals(invoiceItem.getInvoiceItemType()) || InvoiceItemType.EXTERNAL_CHARGE.equals(invoiceItem.getInvoiceItemType()) || InvoiceItemType.FIXED.equals(invoiceItem.getInvoiceItemType()) || InvoiceItemType.USAGE.equals(invoiceItem.getInvoiceItemType()) || InvoiceItemType.RECURRING.equals(invoiceItem.getInvoiceItemType()); } public static BigDecimal computeRawInvoiceBalance(final Currency currency, @Nullable final Iterable<InvoiceItem> invoiceItems, @Nullable final Iterable<InvoicePayment> invoicePayments) { final BigDecimal amountPaid = computeInvoiceAmountPaid(currency, invoicePayments) .add(computeInvoiceAmountRefunded(currency, invoicePayments)); final BigDecimal chargedAmount = computeInvoiceAmountCharged(currency, invoiceItems) .add(computeInvoiceAmountCredited(currency, invoiceItems)) .add(computeInvoiceAmountAdjustedForAccountCredit(currency, invoiceItems)); final BigDecimal invoiceBalance = chargedAmount.add(amountPaid.negate()); return KillBillMoney.of(invoiceBalance, currency); } public static BigDecimal computeChildInvoiceAmount(final Currency currency, @Nullable final Iterable<InvoiceItem> invoiceItems) { if (invoiceItems == null) { return BigDecimal.ZERO; } final Iterable<InvoiceItem> chargeItems = Iterables.filter(invoiceItems, new Predicate<InvoiceItem>() { @Override public boolean apply(final InvoiceItem input) { return isCharge(input); } }); if (Iterables.isEmpty(chargeItems)) { // return only credit amount to be subtracted to parent item amount return computeInvoiceAmountCredited(currency, invoiceItems).negate(); } final BigDecimal chargedAmount = computeInvoiceAmountCharged(currency, invoiceItems) .add(computeInvoiceAmountCredited(currency, invoiceItems)) .add(computeInvoiceAmountAdjustedForAccountCredit(currency, invoiceItems)); return KillBillMoney.of(chargedAmount, currency); } // Snowflake for the CREDIT_ADJ on its own invoice private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit(final Currency currency, final Iterable<InvoiceItem> invoiceItems) { BigDecimal amountAdjusted = BigDecimal.ZERO; if (invoiceItems == null || !invoiceItems.iterator().hasNext()) { return KillBillMoney.of(amountAdjusted, currency); } if (isCreditInvoice(invoiceItems)) { //if the invoice corresponds to a CREDIT, include its amount Iterator<InvoiceItem> itr = invoiceItems.iterator(); InvoiceItem item1 = itr.next(); InvoiceItem item2 = itr.next(); if (InvoiceItemType.CREDIT_ADJ.equals(item1.getInvoiceItemType())) { amountAdjusted = amountAdjusted.add(item1.getAmount()); } else { // since the isCreditInvoice is already checked, this implies that item2 is of type CREDIT_ADJ amountAdjusted = amountAdjusted.add(item2.getAmount()); } } return KillBillMoney.of(amountAdjusted, currency); } public static BigDecimal computeInvoiceAmountCharged(final Currency currency, @Nullable final Iterable<InvoiceItem> invoiceItems) { BigDecimal amountCharged = BigDecimal.ZERO; if (invoiceItems == null || !invoiceItems.iterator().hasNext()) { return KillBillMoney.of(amountCharged, currency); } for (final InvoiceItem invoiceItem : invoiceItems) { if (isCharge(invoiceItem) || isInvoiceAdjustmentItem(invoiceItem, invoiceItems) || isInvoiceItemAdjustmentItem(invoiceItem) || isParentSummaryItem(invoiceItem)) { amountCharged = amountCharged.add(invoiceItem.getAmount()); } } return KillBillMoney.of(amountCharged, currency); } public static BigDecimal computeInvoiceOriginalAmountCharged(final DateTime invoiceCreatedDate, final Currency currency, @Nullable final Iterable<InvoiceItem> invoiceItems) { BigDecimal amountCharged = BigDecimal.ZERO; if (invoiceItems == null || !invoiceItems.iterator().hasNext()) { return KillBillMoney.of(amountCharged, currency); } for (final InvoiceItem invoiceItem : invoiceItems) { if (isCharge(invoiceItem) && (invoiceItem.getCreatedDate() != null && invoiceItem.getCreatedDate().equals(invoiceCreatedDate))) { amountCharged = amountCharged.add(invoiceItem.getAmount()); } } return KillBillMoney.of(amountCharged, currency); } public static BigDecimal computeInvoiceAmountCredited(final Currency currency, @Nullable final Iterable<InvoiceItem> invoiceItems) { BigDecimal amountCredited = BigDecimal.ZERO; if (invoiceItems == null || !invoiceItems.iterator().hasNext()) { return KillBillMoney.of(amountCredited, currency); } for (final InvoiceItem invoiceItem : invoiceItems) { if (isAccountCreditItem(invoiceItem)) { amountCredited = amountCredited.add(invoiceItem.getAmount()); } } return KillBillMoney.of(amountCredited, currency); } public static BigDecimal computeInvoiceAmountPaid(final Currency currency, @Nullable final Iterable<InvoicePayment> invoicePayments) { BigDecimal amountPaid = BigDecimal.ZERO; if (invoicePayments == null || !invoicePayments.iterator().hasNext()) { return KillBillMoney.of(amountPaid, currency); } for (final InvoicePayment invoicePayment : invoicePayments) { if (!invoicePayment.isSuccess()) { continue; } if (InvoicePaymentType.ATTEMPT.equals(invoicePayment.getType())) { amountPaid = amountPaid.add(invoicePayment.getAmount()); } } return KillBillMoney.of(amountPaid, currency); } public static BigDecimal computeInvoiceAmountRefunded(final Currency currency, @Nullable final Iterable<InvoicePayment> invoicePayments) { BigDecimal amountRefunded = BigDecimal.ZERO; if (invoicePayments == null || !invoicePayments.iterator().hasNext()) { return KillBillMoney.of(amountRefunded, currency); } for (final InvoicePayment invoicePayment : invoicePayments) { if (invoicePayment.isSuccess() == null || !invoicePayment.isSuccess()) { continue; } if (InvoicePaymentType.REFUND.equals(invoicePayment.getType()) || InvoicePaymentType.CHARGED_BACK.equals(invoicePayment.getType())) { amountRefunded = amountRefunded.add(invoicePayment.getAmount()); } } return KillBillMoney.of(amountRefunded, currency); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.io.util; import java.io.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.io.FSReadError; public class MmappedSegmentedFile extends SegmentedFile { private static final Logger logger = LoggerFactory.getLogger(MmappedSegmentedFile.class); // in a perfect world, MAX_SEGMENT_SIZE would be final, but we need to test with a smaller size to stay sane. public static long MAX_SEGMENT_SIZE = Integer.MAX_VALUE; /** * Sorted array of segment offsets and MappedByteBuffers for segments. If mmap is completely disabled, or if the * segment would be too long to mmap, the value for an offset will be null, indicating that we need to fall back * to a RandomAccessFile. */ private final Segment[] segments; public MmappedSegmentedFile(String path, long length, Segment[] segments) { super(path, length); this.segments = segments; } /** * @return The segment entry for the given position. */ private Segment floor(long position) { assert 0 <= position && position < length: position + " vs " + length; Segment seg = new Segment(position, null); int idx = Arrays.binarySearch(segments, seg); assert idx != -1 : "Bad position " + position + " in segments " + Arrays.toString(segments); if (idx < 0) // round down to entry at insertion point idx = -(idx + 2); return segments[idx]; } /** * @return The segment containing the given position: must be closed after use. */ public FileDataInput getSegment(long position) { Segment segment = floor(position); if (segment.right != null) { // segment is mmap'd return new MappedFileDataInput(segment.right, path, segment.left, (int) (position - segment.left)); } // not mmap'd: open a braf covering the segment // FIXME: brafs are unbounded, so this segment will cover the rest of the file, rather than just the row RandomAccessReader file = RandomAccessReader.open(new File(path)); file.seek(position); return file; } public void cleanup() { if (!FileUtils.isCleanerAvailable()) return; /* * Try forcing the unmapping of segments using undocumented unsafe sun APIs. * If this fails (non Sun JVM), we'll have to wait for the GC to finalize the mapping. * If this works and a thread tries to access any segment, hell will unleash on earth. */ try { for (Segment segment : segments) { if (segment.right == null) continue; FileUtils.clean(segment.right); } logger.debug("All segments have been unmapped successfully"); } catch (Exception e) { // This is not supposed to happen logger.error("Error while unmapping segments", e); } } /** * Overrides the default behaviour to create segments of a maximum size. */ static class Builder extends SegmentedFile.Builder { // planned segment boundaries private List<Long> boundaries; // offset of the open segment (first segment begins at 0). private long currentStart = 0; // current length of the open segment. // used to allow merging multiple too-large-to-mmap segments, into a single buffered segment. private long currentSize = 0; public Builder() { super(); boundaries = new ArrayList<Long>(); boundaries.add(0L); } public void addPotentialBoundary(long boundary) { if (boundary - currentStart <= MAX_SEGMENT_SIZE) { // boundary fits into current segment: expand it currentSize = boundary - currentStart; return; } // close the current segment to try and make room for the boundary if (currentSize > 0) { currentStart += currentSize; boundaries.add(currentStart); } currentSize = boundary - currentStart; // if we couldn't make room, the boundary needs its own segment if (currentSize > MAX_SEGMENT_SIZE) { currentStart = boundary; boundaries.add(currentStart); currentSize = 0; } } public SegmentedFile complete(String path) { long length = new File(path).length(); // add a sentinel value == length if (length != boundaries.get(boundaries.size() - 1)) boundaries.add(length); // create the segments return new MmappedSegmentedFile(path, length, createSegments(path)); } private Segment[] createSegments(String path) { int segcount = boundaries.size() - 1; Segment[] segments = new Segment[segcount]; RandomAccessFile raf; try { raf = new RandomAccessFile(path, "r"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { for (int i = 0; i < segcount; i++) { long start = boundaries.get(i); long size = boundaries.get(i + 1) - start; MappedByteBuffer segment = size <= MAX_SEGMENT_SIZE ? raf.getChannel().map(FileChannel.MapMode.READ_ONLY, start, size) : null; segments[i] = new Segment(start, segment); } } catch (IOException e) { throw new FSReadError(e, path); } finally { FileUtils.closeQuietly(raf); } return segments; } @Override public void serializeBounds(DataOutput out) throws IOException { super.serializeBounds(out); out.writeInt(boundaries.size()); for (long position: boundaries) out.writeLong(position); } @Override public void deserializeBounds(DataInput in) throws IOException { super.deserializeBounds(in); int size = in.readInt(); List<Long> temp = new ArrayList<Long>(size); for (int i = 0; i < size; i++) temp.add(in.readLong()); boundaries = temp; } } }
package it.unibz.inf.ontop.owlrefplatform.core.unfolding; /* * #%L * ontop-reformulation-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * 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 it.unibz.inf.ontop.model.DatatypeFactory; import it.unibz.inf.ontop.model.ExpressionOperation; import it.unibz.inf.ontop.model.Function; import it.unibz.inf.ontop.model.BNodePredicate; import it.unibz.inf.ontop.model.CQIE; import it.unibz.inf.ontop.model.Constant; import it.unibz.inf.ontop.model.DatalogProgram; import it.unibz.inf.ontop.model.Term; import it.unibz.inf.ontop.model.OBDADataFactory; import it.unibz.inf.ontop.model.Predicate; import it.unibz.inf.ontop.model.URITemplatePredicate; import it.unibz.inf.ontop.model.ValueConstant; import it.unibz.inf.ontop.model.Variable; import it.unibz.inf.ontop.model.Predicate.COL_TYPE; import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl; import it.unibz.inf.ontop.model.impl.OBDAVocabulary; import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.Substitution; import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.UnifierUtilities; import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.UriTemplateMatcher; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; public class ExpressionEvaluator { private final UriTemplateMatcher uriTemplateMatcher; private final OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); private final DatatypeFactory dtfac = OBDADataFactoryImpl.getInstance().getDatatypeFactory(); private boolean regexFlag = false; public ExpressionEvaluator(UriTemplateMatcher matcher) { uriTemplateMatcher = matcher; } public void evaluateExpressions(DatalogProgram p) { List<CQIE> toremove = new LinkedList<>(); for (CQIE q : p.getRules()) { setRegexFlag(false); // reset the ObjectConstant flag boolean empty = evaluateExpressions(q.getBody()); if (empty) toremove.add(q); } p.removeRules(toremove); } private boolean evaluateExpressions(List<Function> body) { for (int atomidx = 0; atomidx < body.size(); atomidx++) { Function atom = body.get(atomidx); Term newatom = eval(atom); if (newatom == OBDAVocabulary.TRUE) { body.remove(atomidx); atomidx -= 1; continue; } else if (newatom == OBDAVocabulary.FALSE) { return true; } body.set(atomidx, (Function)newatom); } return false; } private Term eval(Term expr) { if (expr instanceof Variable) return expr; else if (expr instanceof Constant) return expr; else if (expr instanceof Function) return eval((Function) expr); throw new RuntimeException("Invalid expression"); } private Term eval(Function expr) { Predicate p = expr.getFunctionSymbol(); if (expr.isAlgebraFunction()) { // p == OBDAVocabulary.SPARQL_JOIN || p == OBDAVocabulary.SPARQL_LEFTJOIN List<Term> terms = expr.getTerms(); for (int i=0; i<terms.size(); i++) { Term old = terms.get(i); if (old instanceof Function) { Term newterm = eval((Function)old); if (!newterm.equals(old)) if (newterm == OBDAVocabulary.FALSE) { // terms.set(i, fac.getTypedTerm(OBDAVocabulary.FALSE, COL_TYPE.BOOLEAN)); } else if (newterm == OBDAVocabulary.TRUE) { //remove terms.remove(i); i--; continue; } else { terms.set(i, newterm); } } } return expr; } else if (expr.isOperation()) { return evalOperation(expr); } else if (expr.isDataTypeFunction()) { Term t0 = expr.getTerm(0); if (t0 instanceof Constant) { ValueConstant value = (ValueConstant) t0; String valueString = value.getValue(); if (dtfac.isBoolean(p)) { // OBDAVocabulary.XSD_BOOLEAN if (valueString.equals("true") || valueString.equals("1")) { return OBDAVocabulary.TRUE; } else if (valueString.equals("false") || valueString.equals("0")) { return OBDAVocabulary.FALSE; } } else if (dtfac.isInteger(p)) { long valueInteger = Long.parseLong(valueString); return fac.getBooleanConstant(valueInteger != 0); } else if (dtfac.isFloat(p)) { double valueD = Double.parseDouble(valueString); return fac.getBooleanConstant(valueD > 0); } else if (dtfac.isString(p)) { // ROMAN (18 Dec 2015): toString() was wrong -- it contains "" and so is never empty return fac.getBooleanConstant(valueString.length() != 0); } else if (dtfac.isLiteral(p)) { // R: a bit wider than p == fac.getDataTypePredicateLiteral() // by taking LANG into account // ROMAN (18 Dec 2015): toString() was wrong -- it contains "" and so is never empty return fac.getBooleanConstant(valueString.length() != 0); } // TODO (R): year, date and time are not covered? } else if (t0 instanceof Variable) { return fac.getFunctionIsTrue(expr); } else { return expr; } } if (p.getName().toUpperCase().contains("QUEST_OBJECT_PROPERTY_ASSERTION")) { // ROMAN (26 Sep 2015): what exactly is the meaning of this check? setRegexFlag(true); } return expr; } private void setRegexFlag(boolean b) { regexFlag = b; } private boolean isObjectConstant() { return regexFlag; } private Term evalOperation(Function term) { Predicate pred = term.getFunctionSymbol(); if (pred == ExpressionOperation.AND) { return evalAnd(term.getTerm(0), term.getTerm(1)); } else if (pred == ExpressionOperation.OR) { return evalOr(term.getTerm(0), term.getTerm(1)); } else if (pred == ExpressionOperation.EQ) { return evalEqNeq(term, true); } else if (pred == ExpressionOperation.GT) { return term; } else if (pred == ExpressionOperation.GTE) { return term; } else if (pred == ExpressionOperation.IS_NOT_NULL) { return evalIsNullNotNull(term, false); } else if (pred == ExpressionOperation.IS_NULL) { return evalIsNullNotNull(term, true); } else if (pred == ExpressionOperation.LT) { return term; } else if (pred == ExpressionOperation.LTE) { return term; } else if (pred == ExpressionOperation.NEQ) { return evalEqNeq(term, false); } else if (pred == ExpressionOperation.NOT) { return evalNot(term); } else if (pred == ExpressionOperation.IS_TRUE) { return evalIsTrue(term); } else if (pred == ExpressionOperation.IS_LITERAL) { return evalIsLiteral(term); } else if (pred == ExpressionOperation.IS_BLANK) { return evalIsBlank(term); } else if (pred == ExpressionOperation.IS_IRI) { return evalIsIri(term); } else if (pred == ExpressionOperation.LANGMATCHES) { return evalLangMatches(term); } else if (pred == ExpressionOperation.REGEX) { return evalRegex(term); } else if (pred == ExpressionOperation.SQL_LIKE) { return term; } else if (pred == ExpressionOperation.STR_STARTS) { return term; } else if (pred == ExpressionOperation.STR_ENDS) { return term; } else if (pred == ExpressionOperation.CONTAINS) { return term; } else if (pred == ExpressionOperation.SPARQL_STR) { return evalStr(term); } else if (pred == ExpressionOperation.SPARQL_DATATYPE) { return evalDatatype(term); } else if (pred == ExpressionOperation.SPARQL_LANG) { return evalLang(term); } else if (pred == ExpressionOperation.ADD || pred == ExpressionOperation.SUBTRACT || pred == ExpressionOperation.MULTIPLY || pred == ExpressionOperation.DIVIDE) { Function returnedDatatype = getDatatype(term); if (returnedDatatype != null && isNumeric((ValueConstant) returnedDatatype.getTerm(0))) return term; else return OBDAVocabulary.FALSE; } else if (pred == ExpressionOperation.QUEST_CAST) { return term; } else { throw new RuntimeException( "Evaluation of expression not supported: " + term.toString()); } } /* * Expression evaluator for isLiteral() function */ private Term evalIsLiteral(Function term) { Term innerTerm = term.getTerm(0); if (innerTerm instanceof Function) { Function function = (Function) innerTerm; return fac.getBooleanConstant(function.isDataTypeFunction()); } else { return term; } } /* * Expression evaluator for isBlank() function */ private Term evalIsBlank(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function function = (Function) teval; Predicate predicate = function.getFunctionSymbol(); return fac.getBooleanConstant(predicate instanceof BNodePredicate); } return term; } /* * Expression evaluator for isURI() function */ private Term evalIsUri(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function function = (Function) teval; Predicate predicate = function.getFunctionSymbol(); return fac.getBooleanConstant(predicate instanceof URITemplatePredicate); } return term; } /* * Expression evaluator for isIRI() function */ private Term evalIsIri(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function function = (Function) teval; Predicate predicate = function.getFunctionSymbol(); return fac.getBooleanConstant(predicate instanceof URITemplatePredicate); } return term; } /* * Expression evaluator for str() function */ private Term evalStr(Function term) { Term innerTerm = term.getTerm(0); if (innerTerm instanceof Function) { Function function = (Function) innerTerm; Predicate predicate = function.getFunctionSymbol(); Term parameter = function.getTerm(0); if (function.isDataTypeFunction()) { if (dtfac.isLiteral(predicate)) { // R: was datatype.equals(OBDAVocabulary.RDFS_LITERAL_URI) return fac.getTypedTerm( fac.getVariable(parameter.toString()), COL_TYPE.LITERAL); } else if (dtfac.isString(predicate)) { // R: was datatype.equals(OBDAVocabulary.XSD_STRING_URI)) { return fac.getTypedTerm( fac.getVariable(parameter.toString()), COL_TYPE.LITERAL); } else { return fac.getTypedTerm( fac.getFunctionCast(fac.getVariable(parameter.toString()), fac.getConstantLiteral(dtfac.getDatatypeURI(COL_TYPE.LITERAL).stringValue())), COL_TYPE.LITERAL); } } else if (predicate instanceof URITemplatePredicate) { return fac.getTypedTerm(function.clone(), COL_TYPE.LITERAL); } else if (predicate instanceof BNodePredicate) { return OBDAVocabulary.NULL; } } return term; } /* * Expression evaluator for datatype() function */ private Term evalDatatype(Function term) { Term innerTerm = term.getTerm(0); if (innerTerm instanceof Function) { Function function = (Function) innerTerm; return getDatatype(function); } return term; } private Function getDatatype(Function function) { Predicate predicate = function.getFunctionSymbol(); if (function.isDataTypeFunction()) { return fac.getUriTemplateForDatatype(predicate.toString()); } else if (predicate instanceof BNodePredicate) { return null; } else if (predicate instanceof URITemplatePredicate) { return null; } else if (function.isAlgebraFunction()) { return fac.getUriTemplateForDatatype(dtfac.getDatatypeURI(COL_TYPE.BOOLEAN).stringValue()); } else if (predicate == ExpressionOperation.ADD || predicate == ExpressionOperation.SUBTRACT || predicate == ExpressionOperation.MULTIPLY || predicate == ExpressionOperation.DIVIDE) { //return numerical if arguments have same type Term arg1 = function.getTerm(0); Predicate pred1 = getDatatypePredicate(arg1); Term arg2 = function.getTerm(1); Predicate pred2 = getDatatypePredicate(arg2); if (pred1.equals(pred2) || (isDouble(pred1) && isNumeric(pred2))) { return fac.getUriTemplateForDatatype(pred1.toString()); } else if (isNumeric(pred1) && isDouble(pred2)) { return fac.getUriTemplateForDatatype(pred2.toString()); } else { return null; } } else if (function.isOperation()) { //return boolean uri return fac.getUriTemplateForDatatype(dtfac.getDatatypeURI(COL_TYPE.BOOLEAN).stringValue()); } return null; } private Predicate getDatatypePredicate(Term term) { if (term instanceof Function) { Function function = (Function) term; return function.getFunctionSymbol(); } else if (term instanceof Constant) { Constant constant = (Constant) term; COL_TYPE type = constant.getType(); Predicate pred = dtfac.getTypePredicate(type); if (pred == null) pred = dtfac.getTypePredicate(COL_TYPE.STRING); // .XSD_STRING; return pred; } else { throw new RuntimeException("Unknown term type"); } } private boolean isDouble(Predicate pred) { return (pred.equals(dtfac.getTypePredicate(COL_TYPE.DOUBLE)) || pred.equals(dtfac.getTypePredicate(COL_TYPE.FLOAT))); } private boolean isNumeric(Predicate pred) { return (dtfac.isInteger(pred) || dtfac.isFloat(pred)); } private boolean isNumeric(ValueConstant constant) { String constantValue = constant.getValue(); Predicate.COL_TYPE type = dtfac.getDatatype(constantValue); if (type != null) { Predicate p = dtfac.getTypePredicate(type); return isNumeric(p); } return false; } /* * Expression evaluator for lang() function */ private Term evalLang(Function term) { Term innerTerm = term.getTerm(0); // Create a default return constant: blank language with literal type. Term emptyconstant = fac.getTypedTerm(fac.getConstantLiteral("", COL_TYPE.LITERAL), COL_TYPE.LITERAL); if (!(innerTerm instanceof Function)) { return emptyconstant; } Function function = (Function) innerTerm; if (!function.isDataTypeFunction()) { return null; } Predicate predicate = function.getFunctionSymbol(); //String datatype = predicate.toString(); if (!dtfac.isLiteral(predicate)) { // (datatype.equals(OBDAVocabulary.RDFS_LITERAL_URI)) return emptyconstant; } if (function.getTerms().size() != 2) { return emptyconstant; } else { // rdfs:Literal(text, lang) Term parameter = function.getTerm(1); if (parameter instanceof Variable) { return fac.getTypedTerm(parameter.clone(), COL_TYPE.LITERAL); } else if (parameter instanceof Constant) { return fac.getTypedTerm( fac.getConstantLiteral(((Constant) parameter).getValue(),COL_TYPE.LITERAL), COL_TYPE.LITERAL); } } return term; } /* * Expression evaluator for langMatches() function */ private Term evalLangMatches(Function term) { final String SELECT_ALL = "*"; /* * Evaluate the first term */ Term teval1 = eval(term.getTerm(0)); if (teval1 == null) { return OBDAVocabulary.FALSE; } /* * Evaluate the second term */ Term innerTerm2 = term.getTerm(1); if (innerTerm2 == null) { return OBDAVocabulary.FALSE; } /* * Term checks */ if (teval1 instanceof Constant && innerTerm2 instanceof Constant) { String lang1 = ((Constant) teval1).getValue(); String lang2 = ((Constant) innerTerm2).getValue(); if (lang2.equals(SELECT_ALL)) { if (lang1.isEmpty()) return fac.getFunctionIsNull(teval1); else return fac.getFunctionIsNotNull(teval1); } else { return fac.getBooleanConstant(lang1.equals(lang2)); } } else if (teval1 instanceof Variable && innerTerm2 instanceof Constant) { Variable var = (Variable) teval1; Constant lang = (Constant) innerTerm2; if (lang.getValue().equals(SELECT_ALL)) { // The char * means to get all languages return fac.getFunctionIsNotNull(var); } else { return fac.getFunctionEQ(var, lang); } } else if (teval1 instanceof Function && innerTerm2 instanceof Function) { Function f1 = (Function) teval1; Function f2 = (Function) innerTerm2; return evalLangMatches(fac.getLANGMATCHESFunction(f1.getTerm(0), f2.getTerm(0))); } else { return term; } } private Term evalRegex(Function term) { Term innerTerm = term.getTerm(0); if (innerTerm instanceof Function) { Function f = (Function) innerTerm; Predicate functionSymbol = f.getFunctionSymbol(); if (isObjectConstant()) { setRegexFlag(false); return fac.getBooleanConstant(functionSymbol.equals(ExpressionOperation.SPARQL_STR)); } } return term; } private Term evalIsNullNotNull(Function term, boolean isnull) { Term innerTerm = term.getTerms().get(0); if (innerTerm instanceof Function) { Function f = (Function) innerTerm; if (f.isDataTypeFunction()) return innerTerm; } Term result = eval(innerTerm); if (result == OBDAVocabulary.NULL) { return fac.getBooleanConstant(isnull); } else if (result instanceof Constant) { return fac.getBooleanConstant(!isnull); } // TODO improve evaluation of is (not) null /* * This can be improved by evaluating some of the function, e.g,. URI * and Bnodes never return null */ if (isnull) { return fac.getFunctionIsNull(result); } else { return fac.getFunctionIsNotNull(result); } } private Term evalIsTrue(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function f = (Function) teval; Predicate predicate = f.getFunctionSymbol(); if (predicate == ExpressionOperation.IS_NOT_NULL) { return fac.getFunctionIsNotNull(f.getTerm(0)); } else if (predicate == ExpressionOperation.IS_NULL) { return fac.getFunctionIsNull(f.getTerm(0)); } else if (predicate == ExpressionOperation.NEQ) { return fac.getFunctionNEQ(f.getTerm(0), f.getTerm(1)); } else if (predicate == ExpressionOperation.EQ) { return fac.getFunctionEQ(f.getTerm(0), f.getTerm(1)); } } else if (teval instanceof Constant) { return teval; } return term; } private Term evalNot(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function f = (Function) teval; Predicate predicate = f.getFunctionSymbol(); if (predicate == ExpressionOperation.IS_NOT_NULL) { return fac.getFunctionIsNull(f.getTerm(0)); } else if (predicate == ExpressionOperation.IS_NULL) { return fac.getFunctionIsNotNull(f.getTerm(0)); } else if (predicate == ExpressionOperation.NEQ) { return fac.getFunctionEQ(f.getTerm(0), f.getTerm(1)); } else if (predicate == ExpressionOperation.EQ) { return fac.getFunctionNEQ(f.getTerm(0), f.getTerm(1)); } } else if (teval instanceof Constant) { return teval; } return term; } private Term evalEqNeq(Function term, boolean eq) { /* * Evaluate the first term */ // Do not eval if term is DataTypeFunction, e.g. integer(10) Term teval1; if (term.getTerm(0) instanceof Function) { Function t1 = (Function) term.getTerm(0); if (!(t1.isDataTypeFunction())) { teval1 = eval(term.getTerm(0)); if (teval1 == null) { return OBDAVocabulary.FALSE; } } else { teval1 = term.getTerm(0); } } else { teval1 = eval(term.getTerm(0)); } /* * Evaluate the second term */ Term teval2; if (term.getTerm(1) instanceof Function) { Function t2 = (Function) term.getTerm(1); Predicate p2 = t2.getFunctionSymbol(); if (!(t2.isDataTypeFunction())) { teval2 = eval(term.getTerm(1)); if (teval2 == null) { return OBDAVocabulary.FALSE; } } else { teval2 = term.getTerm(1); } } else { teval2 = eval(term.getTerm(1)); } /* * Normalizing the location of terms, functions first */ Term eval1 = teval1 instanceof Function ? teval1 : teval2; Term eval2 = teval1 instanceof Function ? teval2 : teval1; if (eval1 instanceof Variable || eval2 instanceof Variable) { // no - op } else if (eval1 instanceof Constant && eval2 instanceof Constant) { if (eval1.equals(eval2)) return fac.getBooleanConstant(eq); else return fac.getBooleanConstant(!eq); } else if (eval1 instanceof Function) { Function f1 = (Function) eval1; Predicate pred1 = f1.getFunctionSymbol(); if (f1.isDataTypeFunction()) { if (pred1.getType(0) == COL_TYPE.UNSUPPORTED) { throw new RuntimeException("Unsupported type: " + pred1); } } else if (f1.isOperation()) { return term; } /* * Evaluate the second term */ if (eval2 instanceof Function) { Function f2 = (Function) eval2; Predicate pred2 = f2.getFunctionSymbol(); if (pred2.getType(0) == COL_TYPE.UNSUPPORTED) { throw new RuntimeException("Unsupported type: " + pred2); } /* * Evaluate both terms by comparing their datatypes */ if (dtfac.isLiteral(pred1) && dtfac.isLiteral(pred2)) { // R: replaced incorrect check // pred1 == fac.getDataTypePredicateLiteral() // && pred2 == fac.getDataTypePredicateLiteral()) // which does not work for LITERAL_LANG /* * Special code to handle quality of Literals (plain, and * with language) */ if (f1.getTerms().size() != f2.getTerms().size()) { // case one is with language another without return fac.getBooleanConstant(!eq); } else if (f1.getTerms().size() == 2) { // SIZE == 2 // these are literals with languages, we need to // return the evaluation of the values and the // languages case literals without language, its // exactly as normal datatypes. // This is copy paste code if (eq) { Function eqValues = fac.getFunctionEQ(f1.getTerm(0), f2.getTerm(0)); Function eqLang = fac.getFunctionEQ(f1.getTerm(1), f2.getTerm(1)); return evalAnd(eqValues, eqLang); } Function eqValues = fac.getFunctionNEQ(f1.getTerm(0), f2.getTerm(0)); Function eqLang = fac.getFunctionNEQ(f1.getTerm(1), f2.getTerm(1)); return evalOr(eqValues, eqLang); } // case literals without language, its exactly as normal // datatypes // this is copy paste code if (eq) { Function neweq = fac.getFunctionEQ(f1.getTerm(0), f2.getTerm(0)); return evalEqNeq(neweq, true); } else { Function neweq = fac.getFunctionNEQ(f1.getTerm(0), f2.getTerm(0)); return evalEqNeq(neweq, false); } } else if (pred1.equals(pred2)) { if (pred1 instanceof URITemplatePredicate) { return evalUriTemplateEqNeq(f1, f2, eq); } else { if (eq) { Function neweq = fac.getFunctionEQ(f1.getTerm(0), f2.getTerm(0)); return evalEqNeq(neweq, true); } else { Function neweq = fac.getFunctionNEQ(f1.getTerm(0), f2.getTerm(0)); return evalEqNeq(neweq, false); } } } else if (!pred1.equals(pred2)) { return fac.getBooleanConstant(!eq); } else { return term; } } } /* eval2 is not a function */ if (eq) { return fac.getFunctionEQ(eval1, eval2); } else { return fac.getFunctionNEQ(eval1, eval2); } } private Term evalUriTemplateEqNeq(Function uriFunction1, Function uriFunction2, boolean isEqual) { int arityForFunction1 = uriFunction1.getArity(); int arityForFunction2 = uriFunction2.getArity(); if (arityForFunction1 == 1) { if (arityForFunction2 == 1) { return evalUriFunctionsWithSingleTerm(uriFunction1, uriFunction2, isEqual); } else if (arityForFunction2 > 1) { Function newUriFunction1 = getUriFunctionWithParameters(uriFunction1); return evalUriFunctionsWithMultipleTerms(newUriFunction1, uriFunction2, isEqual); } } else if (arityForFunction1 > 1) { if (arityForFunction2 == 1) { Function newUriFunction2 = getUriFunctionWithParameters(uriFunction2); return evalUriFunctionsWithMultipleTerms(newUriFunction2, uriFunction1, isEqual); } else if (arityForFunction2 > 1) { return evalUriFunctionsWithMultipleTerms(uriFunction1, uriFunction2, isEqual); } } return null; } private Term evalUriFunctionsWithSingleTerm(Function uriFunction1, Function uriFunction2, boolean isEqual) { Term term1 = uriFunction1.getTerm(0); Term term2 = uriFunction2.getTerm(0); // if (!(term1 instanceof ValueConstant)) { // return null; // } if (term2 instanceof Variable) { if (isEqual) { return fac.getFunctionEQ(term2, term1); } else { return fac.getFunctionNEQ(term2, term1); } } else if (term2 instanceof ValueConstant) { if (term1.equals(term2)) return fac.getBooleanConstant(isEqual); else return fac.getBooleanConstant(!isEqual); } return null; } private Term evalUriFunctionsWithMultipleTerms(Function uriFunction1, Function uriFunction2, boolean isEqual) { Substitution theta = UnifierUtilities.getMGU(uriFunction1, uriFunction2); if (theta == null) { return fac.getBooleanConstant(isEqual); } else { boolean isEmpty = theta.isEmpty(); if (isEmpty) { return fac.getBooleanConstant(!isEqual); } else { Function result = null; List<Function> temp = new ArrayList<>(); Set<Variable> keys = theta.getMap().keySet(); for (Variable var : keys) { if (isEqual) result = fac.getFunctionEQ(var, theta.get(var)); else result = fac.getFunctionNEQ(var, theta.get(var)); temp.add(result); if (temp.size() == 2) { result = fac.getFunctionAND(temp.get(0), temp.get(1)); temp.clear(); temp.add(result); } } return result; } } } private Function getUriFunctionWithParameters(Function uriFunction) { ValueConstant uriString = (ValueConstant) uriFunction.getTerm(0); return uriTemplateMatcher.generateURIFunction(uriString.getValue()); } private Term evalAnd(Term t1, Term t2) { Term e1 = eval(t1); Term e2 = eval(t2); if (e1 == OBDAVocabulary.FALSE || e2 == OBDAVocabulary.FALSE) return OBDAVocabulary.FALSE; if (e1 == OBDAVocabulary.TRUE) return e2; if (e2 == OBDAVocabulary.TRUE) return e1; return fac.getFunctionAND(e1, e2); } private Term evalOr(Term t1, Term t2) { Term e1 = eval(t1); Term e2 = eval(t2); if (e1 == OBDAVocabulary.TRUE || e2 == OBDAVocabulary.TRUE) return OBDAVocabulary.TRUE; if (e1 == OBDAVocabulary.FALSE) return e2; if (e2 == OBDAVocabulary.FALSE) return e1; return fac.getFunctionOR(e1, e2); } }
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.changes; import static com.google.gerrit.client.FormatUtil.shortFormat; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.ui.AccountLinkPanel; import com.google.gerrit.client.ui.BranchLink; import com.google.gerrit.client.ui.ChangeLink; import com.google.gerrit.client.ui.NavigationTable; import com.google.gerrit.client.ui.NeedsSignInKeyCommand; import com.google.gerrit.client.ui.ProjectLink; import com.google.gerrit.common.PageLinks; import com.google.gerrit.common.data.AccountInfoCache; import com.google.gerrit.common.data.ChangeInfo; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.HTMLTable.Cell; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ChangeTable extends NavigationTable<ChangeInfo> { private static final int C_STAR = 1; private static final int C_SUBJECT = 2; private static final int C_OWNER = 3; private static final int C_PROJECT = 4; private static final int C_BRANCH = 5; private static final int C_LAST_UPDATE = 6; private static final int COLUMNS = 7; private final List<Section> sections; private AccountInfoCache accountCache = AccountInfoCache.empty(); public ChangeTable() { super(Util.C.changeItemHelp()); if (Gerrit.isSignedIn()) { keysAction.add(new StarKeyCommand(0, 's', Util.C.changeTableStar())); } sections = new ArrayList<>(); table.setText(0, C_STAR, ""); table.setText(0, C_SUBJECT, Util.C.changeTableColumnSubject()); table.setText(0, C_OWNER, Util.C.changeTableColumnOwner()); table.setText(0, C_PROJECT, Util.C.changeTableColumnProject()); table.setText(0, C_BRANCH, Util.C.changeTableColumnBranch()); table.setText(0, C_LAST_UPDATE, Util.C.changeTableColumnLastUpdate()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(0, C_STAR, Gerrit.RESOURCES.css().iconHeader()); for (int i = C_SUBJECT; i < COLUMNS; i++) { fmt.addStyleName(0, i, Gerrit.RESOURCES.css().dataHeader()); } table.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final Cell cell = table.getCellForEvent(event); if (cell == null) { return; } if (cell.getCellIndex() == C_STAR) { // Don't do anything (handled by star itself). } else if (cell.getCellIndex() == C_OWNER) { // Don't do anything. } else if (getRowItem(cell.getRowIndex()) != null) { movePointerTo(cell.getRowIndex()); } } }); } protected void onStarClick(final int row) { final ChangeInfo c = getRowItem(row); if (c != null && Gerrit.isSignedIn()) { ((StarredChanges.Icon) table.getWidget(row, C_STAR)).toggleStar(); } } @Override protected Object getRowItemKey(final ChangeInfo item) { return item.getId(); } @Override protected void onOpenRow(final int row) { final ChangeInfo c = getRowItem(row); Gerrit.display(PageLinks.toChange(c), new ChangeScreen(c)); } private void insertNoneRow(final int row) { insertRow(row); table.setText(row, 0, Util.C.changeTableNone()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.setColSpan(row, 0, COLUMNS); fmt.setStyleName(row, 0, Gerrit.RESOURCES.css().emptySection()); } private void insertChangeRow(final int row) { insertRow(row); applyDataRowStyle(row); } @Override protected void applyDataRowStyle(final int row) { super.applyDataRowStyle(row); final CellFormatter fmt = table.getCellFormatter(); fmt.addStyleName(row, C_STAR, Gerrit.RESOURCES.css().iconCell()); for (int i = C_SUBJECT; i < COLUMNS; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().dataCell()); } fmt.addStyleName(row, C_SUBJECT, Gerrit.RESOURCES.css().cSUBJECT()); fmt.addStyleName(row, C_OWNER, Gerrit.RESOURCES.css().cOWNER()); fmt.addStyleName(row, C_LAST_UPDATE, Gerrit.RESOURCES.css().cLastUpdate()); } private void populateChangeRow(final int row, final ChangeInfo c, final ChangeRowFormatter changeRowFormatter) { ChangeCache cache = ChangeCache.get(c.getId()); cache.getChangeInfoCache().set(c); table.setWidget(row, C_ARROW, null); if (Gerrit.isSignedIn()) { table.setWidget(row, C_STAR, StarredChanges.createIcon(c.getId(), c.isStarred())); } String s = Util.cropSubject(c.getSubject()); if (c.getStatus() != null && c.getStatus() != Change.Status.NEW) { s += " (" + c.getStatus().name() + ")"; } if (changeRowFormatter != null) { removeChangeStyle(row, changeRowFormatter); final String rowStyle = changeRowFormatter.getRowStyle(c); if (rowStyle != null) { table.getRowFormatter().addStyleName(row, rowStyle); } s = changeRowFormatter.getDisplayText(c, s); } table.setWidget(row, C_SUBJECT, new TableChangeLink(s, c)); table.setWidget(row, C_OWNER, link(c.getOwner())); table.setWidget(row, C_PROJECT, new ProjectLink(c.getProject().getKey())); table.setWidget(row, C_BRANCH, new BranchLink(c.getProject().getKey(), c .getStatus(), c.getBranch(), c.getTopic())); table.setText(row, C_LAST_UPDATE, shortFormat(c.getLastUpdatedOn())); setRowItem(row, c); } private void removeChangeStyle(int row, final ChangeRowFormatter changeRowFormatter) { final ChangeInfo oldChange = getRowItem(row); if (oldChange == null) { return; } final String oldRowStyle = changeRowFormatter.getRowStyle(oldChange); if (oldRowStyle != null) { table.getRowFormatter().removeStyleName(row, oldRowStyle); } } private AccountLinkPanel link(final Account.Id id) { return AccountLinkPanel.link(accountCache, id); } public void addSection(final Section s) { assert s.parent == null; if (s.titleText != null) { s.titleRow = table.getRowCount(); table.setText(s.titleRow, 0, s.titleText); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.setColSpan(s.titleRow, 0, COLUMNS); fmt.addStyleName(s.titleRow, 0, Gerrit.RESOURCES.css().sectionHeader()); } else { s.titleRow = -1; } s.parent = this; s.dataBegin = table.getRowCount(); insertNoneRow(s.dataBegin); sections.add(s); } public void setAccountInfoCache(final AccountInfoCache aic) { assert aic != null; accountCache = aic; } private int insertRow(final int beforeRow) { for (final Section s : sections) { if (beforeRow <= s.titleRow) { s.titleRow++; } if (beforeRow < s.dataBegin) { s.dataBegin++; } } return table.insertRow(beforeRow); } private void removeRow(final int row) { for (final Section s : sections) { if (row < s.titleRow) { s.titleRow--; } if (row < s.dataBegin) { s.dataBegin--; } } table.removeRow(row); } public class StarKeyCommand extends NeedsSignInKeyCommand { public StarKeyCommand(int mask, char key, String help) { super(mask, key, help); } @Override public void onKeyPress(final KeyPressEvent event) { onStarClick(getCurrentRow()); } } private final class TableChangeLink extends ChangeLink { private TableChangeLink(final String text, final ChangeInfo c) { super(text, c); } @Override public void go() { movePointerTo(cid); super.go(); } } public static class Section { String titleText; ChangeTable parent; final Account.Id ownerId; int titleRow = -1; int dataBegin; int rows; private ChangeRowFormatter changeRowFormatter; public Section() { this(null, null); } public Section(final String titleText) { this(titleText, null); } public Section(final String titleText, final Account.Id owner) { setTitleText(titleText); ownerId = owner; } public void setTitleText(final String text) { titleText = text; if (titleRow >= 0) { parent.table.setText(titleRow, 0, titleText); } } public void setChangeRowFormatter(final ChangeRowFormatter changeRowFormatter) { this.changeRowFormatter = changeRowFormatter; } public void display(final List<ChangeInfo> changeList) { final int sz = changeList != null ? changeList.size() : 0; final boolean hadData = rows > 0; if (hadData) { while (sz < rows) { parent.removeRow(dataBegin); rows--; } } if (sz == 0) { if (hadData) { parent.insertNoneRow(dataBegin); } } else { Set<Change.Id> cids = new HashSet<>(); if (!hadData) { parent.removeRow(dataBegin); } while (rows < sz) { parent.insertChangeRow(dataBegin + rows); rows++; } for (int i = 0; i < sz; i++) { ChangeInfo c = changeList.get(i); parent.populateChangeRow(dataBegin + i, c, changeRowFormatter); cids.add(c.getId()); } } } } public static interface ChangeRowFormatter { /** * Returns the name of the CSS style that should be applied to the change * row. * * @param c the change for which the styling should be returned * @return the name of the CSS style that should be applied to the change * row */ String getRowStyle(ChangeInfo c); /** * Returns the text that should be displayed for the change. * * @param c the change for which the display text should be returned * @param displayText the current display text * @return the new display text */ String getDisplayText(ChangeInfo c, String displayText); } }
/* * 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.hive.ql.exec.vector; import org.apache.hive.common.util.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * This class supports string and binary data by value reference -- i.e. each field is * explicitly present, as opposed to provided by a dictionary reference. * In some cases, all the values will be in the same byte array to begin with, * but this need not be the case. If each value is in a separate byte * array to start with, or not all of the values are in the same original * byte array, you can still assign data by reference into this column vector. * This gives flexibility to use this in multiple situations. * <p> * When setting data by reference, the caller * is responsible for allocating the byte arrays used to hold the data. * You can also set data by value, as long as you call the initBuffer() method first. * You can mix "by value" and "by reference" in the same column vector, * though that use is probably not typical. */ public class BytesColumnVector extends ColumnVector { public byte[][] vector; public int[] start; // start offset of each field /* * The length of each field. If the value repeats for every entry, then it is stored * in vector[0] and isRepeating from the superclass is set to true. */ public int[] length; // A call to increaseBufferSpace() or ensureValPreallocated() will ensure that buffer[] points to // a byte[] with sufficient space for the specified size. private byte[] buffer; // optional buffer to use when actually copying in data private int nextFree; // next free position in buffer // Hang onto a byte array for holding smaller byte values private byte[] smallBuffer; private int smallBufferNextFree; private int bufferAllocationCount; // Estimate that there will be 16 bytes per entry static final int DEFAULT_BUFFER_SIZE = 16 * VectorizedRowBatch.DEFAULT_SIZE; // Proportion of extra space to provide when allocating more buffer space. static final float EXTRA_SPACE_FACTOR = (float) 1.2; // Largest size allowed in smallBuffer static final int MAX_SIZE_FOR_SMALL_BUFFER = 1024 * 1024; /** * Use this constructor for normal operation. * All column vectors should be the default size normally. */ public BytesColumnVector() { this(VectorizedRowBatch.DEFAULT_SIZE); } /** * Don't call this constructor except for testing purposes. * * @param size number of elements in the column vector */ public BytesColumnVector(int size) { super(Type.BYTES, size); vector = new byte[size][]; start = new int[size]; length = new int[size]; } /** * Additional reset work for BytesColumnVector (releasing scratch bytes for by value strings). */ @Override public void reset() { super.reset(); initBuffer(0); } /** * Set a field by reference. * * This is a FAST version that assumes the caller has checked to make sure the sourceBuf * is not null and elementNum is correctly adjusted for isRepeating. And, that the isNull entry * has been set. Only the output entry fields will be set by this method. * * @param elementNum index within column vector to set * @param sourceBuf container of source data * @param start start byte position within source * @param length length of source byte sequence */ public void setRef(int elementNum, byte[] sourceBuf, int start, int length) { vector[elementNum] = sourceBuf; this.start[elementNum] = start; this.length[elementNum] = length; } /** * You must call initBuffer first before using setVal(). * Provide the estimated number of bytes needed to hold * a full column vector worth of byte string data. * * @param estimatedValueSize Estimated size of buffer space needed */ public void initBuffer(int estimatedValueSize) { nextFree = 0; smallBufferNextFree = 0; // if buffer is already allocated, keep using it, don't re-allocate if (buffer != null) { // Free up any previously allocated buffers that are referenced by vector if (bufferAllocationCount > 0) { for (int idx = 0; idx < vector.length; ++idx) { vector[idx] = null; length[idx] = 0; } buffer = smallBuffer; // In case last row was a large bytes value } } else { // allocate a little extra space to limit need to re-allocate int bufferSize = this.vector.length * (int)(estimatedValueSize * EXTRA_SPACE_FACTOR); if (bufferSize < DEFAULT_BUFFER_SIZE) { bufferSize = DEFAULT_BUFFER_SIZE; } buffer = new byte[bufferSize]; smallBuffer = buffer; } bufferAllocationCount = 0; } /** * Initialize buffer to default size. */ public void initBuffer() { initBuffer(0); } /** * @return amount of buffer space currently allocated */ public int bufferSize() { if (buffer == null) { return 0; } return buffer.length; } /** * Set a field by actually copying in to a local buffer. * If you must actually copy data in to the array, use this method. * DO NOT USE this method unless it's not practical to set data by reference with setRef(). * Setting data by reference tends to run a lot faster than copying data in. * * This is a FAST version that assumes the caller has checked to make sure the sourceBuf * is not null and elementNum is correctly adjusted for isRepeating. And, that the isNull entry * has been set. Only the output entry fields will be set by this method. * * @param elementNum index within column vector to set * @param sourceBuf container of source data * @param start start byte position within source * @param length length of source byte sequence */ public void setVal(int elementNum, byte[] sourceBuf, int start, int length) { if ((nextFree + length) > buffer.length) { increaseBufferSpace(length); } if (length > 0) { System.arraycopy(sourceBuf, start, buffer, nextFree, length); } vector[elementNum] = buffer; this.start[elementNum] = nextFree; this.length[elementNum] = length; nextFree += length; } /** * Set a field by actually copying in to a local buffer. * If you must actually copy data in to the array, use this method. * DO NOT USE this method unless it's not practical to set data by reference with setRef(). * Setting data by reference tends to run a lot faster than copying data in. * * This is a FAST version that assumes the caller has checked to make sure the sourceBuf * is not null and elementNum is correctly adjusted for isRepeating. And, that the isNull entry * has been set. Only the output entry fields will be set by this method. * * @param elementNum index within column vector to set * @param sourceBuf container of source data */ public void setVal(int elementNum, byte[] sourceBuf) { setVal(elementNum, sourceBuf, 0, sourceBuf.length); } /** * Preallocate space in the local buffer so the caller can fill in the value bytes themselves. * * Always use with getValPreallocatedBytes, getValPreallocatedStart, and setValPreallocated. */ public void ensureValPreallocated(int length) { if ((nextFree + length) > buffer.length) { increaseBufferSpace(length); } } @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Expose internal rep for efficiency") public byte[] getValPreallocatedBytes() { return buffer; } public int getValPreallocatedStart() { return nextFree; } /** * Set the length of the preallocated values bytes used. * @param elementNum * @param length */ public void setValPreallocated(int elementNum, int length) { vector[elementNum] = buffer; this.start[elementNum] = nextFree; this.length[elementNum] = length; nextFree += length; } /** * Set a field to the concatenation of two string values. Result data is copied * into the internal buffer. * * @param elementNum index within column vector to set * @param leftSourceBuf container of left argument * @param leftStart start of left argument * @param leftLen length of left argument * @param rightSourceBuf container of right argument * @param rightStart start of right argument * @param rightLen length of right arugment */ public void setConcat(int elementNum, byte[] leftSourceBuf, int leftStart, int leftLen, byte[] rightSourceBuf, int rightStart, int rightLen) { int newLen = leftLen + rightLen; if ((nextFree + newLen) > buffer.length) { increaseBufferSpace(newLen); } vector[elementNum] = buffer; this.start[elementNum] = nextFree; this.length[elementNum] = newLen; System.arraycopy(leftSourceBuf, leftStart, buffer, nextFree, leftLen); nextFree += leftLen; System.arraycopy(rightSourceBuf, rightStart, buffer, nextFree, rightLen); nextFree += rightLen; } /** * Increase buffer space enough to accommodate next element. * This uses an exponential increase mechanism to rapidly * increase buffer size to enough to hold all data. * As batches get re-loaded, buffer space allocated will quickly * stabilize. * * @param nextElemLength size of next element to be added */ public void increaseBufferSpace(int nextElemLength) { // A call to increaseBufferSpace() or ensureValPreallocated() will ensure that buffer[] points to // a byte[] with sufficient space for the specified size. // This will either point to smallBuffer, or to a newly allocated byte array for larger values. if (nextElemLength > MAX_SIZE_FOR_SMALL_BUFFER) { // Larger allocations will be special-cased and will not use the normal buffer. // buffer/nextFree will be set to a newly allocated array just for the current row. // The next row will require another call to increaseBufferSpace() since this new buffer should be used up. byte[] newBuffer = new byte[nextElemLength]; ++bufferAllocationCount; // If the buffer was pointing to smallBuffer, then nextFree keeps track of the current state // of the free index for smallBuffer. We now need to save this value to smallBufferNextFree // so we don't lose this. A bit of a weird dance here. if (smallBuffer == buffer) { smallBufferNextFree = nextFree; } buffer = newBuffer; nextFree = 0; } else { // This value should go into smallBuffer. if (smallBuffer != buffer) { // Previous row was for a large bytes value ( > MAX_SIZE_FOR_SMALL_BUFFER). // Use smallBuffer if possible. buffer = smallBuffer; nextFree = smallBufferNextFree; } // smallBuffer might still be out of space if ((nextFree + nextElemLength) > buffer.length) { int newLength = smallBuffer.length * 2; while (newLength < nextElemLength) { if (newLength > 0) { newLength *= 2; } else { // integer overflow happened; maximize size of next smallBuffer newLength = Integer.MAX_VALUE; } } smallBuffer = new byte[newLength]; ++bufferAllocationCount; smallBufferNextFree = 0; // Update buffer buffer = smallBuffer; nextFree = 0; } } } /** Copy the current object contents into the output. Only copy selected entries, * as indicated by selectedInUse and the sel array. */ @Override public void copySelected( boolean selectedInUse, int[] sel, int size, ColumnVector outputColVector) { BytesColumnVector output = (BytesColumnVector) outputColVector; boolean[] outputIsNull = output.isNull; // We do not need to do a column reset since we are carefully changing the output. output.isRepeating = false; // Handle repeating case if (isRepeating) { if (noNulls || !isNull[0]) { outputIsNull[0] = false; output.setVal(0, vector[0], start[0], length[0]); } else { outputIsNull[0] = true; output.noNulls = false; } output.isRepeating = true; return; } // Handle normal case if (noNulls) { if (selectedInUse) { // CONSIDER: For large n, fill n or all of isNull array and use the tighter ELSE loop. if (!outputColVector.noNulls) { for(int j = 0; j != size; j++) { final int i = sel[j]; // Set isNull before call in case it changes it mind. outputIsNull[i] = false; output.setVal(i, vector[i], start[i], length[i]); } } else { for(int j = 0; j != size; j++) { final int i = sel[j]; output.setVal(i, vector[i], start[i], length[i]); } } } else { if (!outputColVector.noNulls) { // Assume it is almost always a performance win to fill all of isNull so we can // safely reset noNulls. Arrays.fill(outputIsNull, false); outputColVector.noNulls = true; } for(int i = 0; i != size; i++) { output.setVal(i, vector[i], start[i], length[i]); } } } else /* there are nulls in our column */ { // Carefully handle NULLs... if (selectedInUse) { for (int j = 0; j < size; j++) { int i = sel[j]; if (!isNull[i]) { output.isNull[i] = false; output.setVal(i, vector[i], start[i], length[i]); } else { output.isNull[i] = true; output.noNulls = false; } } } else { for (int i = 0; i < size; i++) { if (!isNull[i]) { output.isNull[i] = false; output.setVal(i, vector[i], start[i], length[i]); } else { output.isNull[i] = true; output.noNulls = false; } } } } } /** Simplify vector by brute-force flattening noNulls and isRepeating * This can be used to reduce combinatorial explosion of code paths in VectorExpressions * with many arguments, at the expense of loss of some performance. */ public void flatten(boolean selectedInUse, int[] sel, int size) { flattenPush(); if (isRepeating) { isRepeating = false; // setRef is used below and this is safe, because the reference // is to data owned by this column vector. If this column vector // gets re-used, the whole thing is re-used together so there // is no danger of a dangling reference. // Only copy data values if entry is not null. The string value // at position 0 is undefined if the position 0 value is null. if (noNulls || !isNull[0]) { if (selectedInUse) { for (int j = 0; j < size; j++) { int i = sel[j]; this.setRef(i, vector[0], start[0], length[0]); } } else { for (int i = 0; i < size; i++) { this.setRef(i, vector[0], start[0], length[0]); } } } flattenRepeatingNulls(selectedInUse, sel, size); } flattenNoNulls(selectedInUse, sel, size); } // Fill the all the vector entries with provided value public void fill(byte[] value) { isRepeating = true; isNull[0] = false; setVal(0, value, 0, value.length); } // Fill the column vector with nulls public void fillWithNulls() { noNulls = false; isRepeating = true; vector[0] = null; isNull[0] = true; } /** * Set the element in this column vector from the given input vector. * * The inputElementNum will be adjusted to 0 if the input column has isRepeating set. * * On the other hand, the outElementNum must have been adjusted to 0 in ADVANCE when the output * has isRepeating set. * * IMPORTANT: if the output entry is marked as NULL, this method will do NOTHING. This * supports the caller to do output NULL processing in advance that may cause the output results * operation to be ignored. Thus, make sure the output isNull entry is set in ADVANCE. * * The inputColVector noNulls and isNull entry will be examined. The output will only * be set if the input is NOT NULL. I.e. noNulls || !isNull[inputElementNum] where * inputElementNum may have been adjusted to 0 for isRepeating. * * If the input entry is NULL or out-of-range, the output will be marked as NULL. * I.e. set output noNull = false and isNull[outElementNum] = true. An example of out-of-range * is the DecimalColumnVector which can find the input decimal does not fit in the output * precision/scale. * * (Since we return immediately if the output entry is NULL, we have no need and do not mark * the output entry to NOT NULL). * */ @Override public void setElement(int outputElementNum, int inputElementNum, ColumnVector inputColVector) { // Invariants. if (isRepeating && outputElementNum != 0) { throw new AssertionError("Output column number expected to be 0 when isRepeating"); } if (inputColVector.isRepeating) { inputElementNum = 0; } // Do NOTHING if output is NULL. if (!noNulls && isNull[outputElementNum]) { return; } if (inputColVector.noNulls || !inputColVector.isNull[inputElementNum]) { BytesColumnVector in = (BytesColumnVector) inputColVector; setVal(outputElementNum, in.vector[inputElementNum], in.start[inputElementNum], in.length[inputElementNum]); } else { // Only mark output NULL when input is NULL. isNull[outputElementNum] = true; noNulls = false; } } @Override public void init() { initBuffer(0); } public String toString(int row) { if (isRepeating) { row = 0; } if (noNulls || !isNull[row]) { return new String(vector[row], start[row], length[row], StandardCharsets.UTF_8); } else { return null; } } @Override public void stringifyValue(StringBuilder buffer, int row) { if (isRepeating) { row = 0; } if (noNulls || !isNull[row]) { buffer.append('"'); buffer.append(new String(vector[row], start[row], length[row], StandardCharsets.UTF_8)); buffer.append('"'); } else { buffer.append("null"); } } @Override public void ensureSize(int size, boolean preserveData) { super.ensureSize(size, preserveData); if (size > vector.length) { int[] oldStart = start; start = new int[size]; int[] oldLength = length; length = new int[size]; byte[][] oldVector = vector; vector = new byte[size][]; if (preserveData) { if (isRepeating) { vector[0] = oldVector[0]; start[0] = oldStart[0]; length[0] = oldLength[0]; } else { System.arraycopy(oldVector, 0, vector, 0, oldVector.length); System.arraycopy(oldStart, 0, start, 0 , oldStart.length); System.arraycopy(oldLength, 0, length, 0, oldLength.length); } } } } @Override public void shallowCopyTo(ColumnVector otherCv) { BytesColumnVector other = (BytesColumnVector)otherCv; super.shallowCopyTo(other); other.nextFree = nextFree; other.vector = vector; other.start = start; other.length = length; other.buffer = buffer; } }
/** * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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. * <p> * Created on 18/12/17 */ package org.neo4j.jdbc.utils; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author Gianmarco Laggia @ Larus B.A. * @since 3.2.0 */ public class ObjectConverter { private static final Map<String, Method> CONVERTERS = new HashMap<>(); static { // Preload converters. Method[] methods = ObjectConverter.class.getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 1) { if (method.getParameterTypes()[0] == Object.class) { //generic method CONVERTERS.put("any_" + method.getReturnType().getName(), method); } else { // Converter should accept 1 argument. This skips the convert() method. CONVERTERS.put(method.getParameterTypes()[0].getName() + "_" + method.getReturnType().getName(), method); } } } } private ObjectConverter() { } // Action ------------------------------------------------------------------------------------- /** * Convert the given object value to the given class. * * @param <T> the destination type of the conversion * @param from The object value to be converted. * @param to The type class which the given object should be converted to. * @return The converted object value. * @throws NullPointerException If 'to' is null. * @throws UnsupportedOperationException If no suitable converter can be found. * @throws RuntimeException If conversion failed somehow. This can be caused by at least * an ExceptionInInitializerError, IllegalAccessException or InvocationTargetException. */ public static <T> T convert(Object from, Class<T> to) { // Null is just null. if (from == null) { return null; } // Can we cast? Then just do it. if (to.isAssignableFrom(from.getClass())) { return to.cast(from); } // Lookup the suitable converter. String converterId = from.getClass().getName() + "_" + to.getCanonicalName(); String genericConverterId = "any_" + to.getCanonicalName(); Method converter = CONVERTERS.get(converterId); if (converter == null) { converter = CONVERTERS.get(genericConverterId); } if (converter == null) { throw new UnsupportedOperationException("Cannot convert from " + from.getClass().getName() + " to " + to.getCanonicalName() + ". Requested converter does not exist."); } // Convert the value. try { return to.cast(converter.invoke(to, from)); } catch (Exception e) { throw new ClassCastException("Cannot convert from " + from.getClass().getName() + " to " + to.getName() + ". Conversion failed with " + e.getMessage()); } } // Converters --------------------------------------------------------------------------------- /** * Cast an object to a map * @param value the object to convert * @return the converted Map */ public static Map anyToMap(Object value) { return (Map) value; } /** * Converts Integer to Boolean. If integer value is 0, then return FALSE, else return TRUE. * * @param value The Integer to be converted. * @return The converted Boolean value. */ public static Boolean integerToBoolean(Integer value) { return value == 0 ? Boolean.FALSE : Boolean.TRUE; } /** * Converts Boolean to Integer. If boolean value is TRUE, then return 1, else return 0. * * @param value The Boolean to be converted. * @return The converted Integer value. */ public static Integer booleanToInteger(Boolean value) { return value ? 1 : 0; } /** * Converts Boolean to Short. If boolean value is TRUE, then return 1, else return 0. * * @param value The Boolean to be converted. * @return The converted Short value. */ public static Short booleanToShort(Boolean value) { return value ? (short) 1 : (short) 0; } /** * Converts Boolean to Double. If boolean value is TRUE, then return 1, else return 0. * * @param value The Boolean to be converted. * @return The converted Double value. */ public static Double booleanToDouble(Boolean value) { return value ? 1D : 0D; } /** * Converts Boolean to Float. If boolean value is TRUE, then return 1, else return 0. * * @param value The Boolean to be converted. * @return The converted Float value. */ public static Float booleanToFloat(Boolean value) { return value ? 1F : 0F; } /** * Converts Boolean to Long. If boolean value is TRUE, then return 1, else return 0. * * @param value The Boolean to be converted. * @return The converted Long value. */ public static Long booleanToLong(Boolean value) { return value ? 1L : 0L; } /** * Converts Integer to String. * * @param value The Integer to be converted. * @return The converted String value. */ public static String integerToString(Integer value) { return value.toString(); } /** * Converts Long to String. * * @param value The Long to be converted. * @return The converted String value. */ public static String longToString(Long value) { return value.toString(); } /** * Converts String to Integer. * * @param value The String to be converted. * @return The converted Integer value. */ public static Integer stringToInteger(String value) { return Integer.valueOf(value); } /** * Converts String to Long. * * @param value The String to be converted. * @return The converted Long value. */ public static Long stringToLong(String value) { return Long.valueOf(value); } /** * Converts Long to Float. * * @param value The Long to be converted. * @return The converted Float value. */ public static Float longToFloat(Long value) { return value.floatValue(); } /** * Converts Long to Short. * * @param value The Long to be converted. * @return The converted Short value. */ public static Short longToShort(Long value) { return value.shortValue(); } /** * Converts Long to Integer. * * @param value The Long to be converted. * @return The converted Integer value. */ public static Integer longToInteger(Long value) { return value.intValue(); } /** * Converts String to Float. * * @param value The String to be converted. * @return The converted Float value. */ public static Float stringToFloat(String value) { return Float.valueOf(value); } /** * Converts Boolean to String. * * @param value The Boolean to be converted. * @return The converted String value. */ public static String booleanToString(Boolean value) { return value.toString(); } /** * Converts String to Boolean. * * @param value The String to be converted. * @return The converted Boolean value. */ public static Boolean stringToBoolean(String value) { return Boolean.valueOf(value); } /** * Converts Long to Double. * * @param value The Long to be converted. * @return The converted Double value. */ public static Double longToDouble(Long value) { return value.doubleValue(); } /** * Converts String to Double. * * @param value The String to be converted. * @return The converted Double value. */ public static Double stringToDouble(String value) { return Double.valueOf(value); } /** * Converts String to Short. * * @param value The String to be converted. * @return The converted Short value. */ public static Short stringToShort(String value) { return Short.valueOf(value); } }
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.kms.model; import java.io.Serializable; /** * <p> * Contains information about an alias. * </p> */ public class AliasListEntry implements Serializable, Cloneable { /** * String that contains the alias. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * <b>Pattern: </b>^[a-zA-Z0-9:/_-]+$<br/> */ private String aliasName; /** * String that contains the key ARN. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>20 - 2048<br/> */ private String aliasArn; /** * String that contains the key identifier pointed to by the alias. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> */ private String targetKeyId; /** * String that contains the alias. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * <b>Pattern: </b>^[a-zA-Z0-9:/_-]+$<br/> * * @return String that contains the alias. */ public String getAliasName() { return aliasName; } /** * String that contains the alias. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * <b>Pattern: </b>^[a-zA-Z0-9:/_-]+$<br/> * * @param aliasName String that contains the alias. */ public void setAliasName(String aliasName) { this.aliasName = aliasName; } /** * String that contains the alias. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * <b>Pattern: </b>^[a-zA-Z0-9:/_-]+$<br/> * * @param aliasName String that contains the alias. * * @return A reference to this updated object so that method calls can be chained * together. */ public AliasListEntry withAliasName(String aliasName) { this.aliasName = aliasName; return this; } /** * String that contains the key ARN. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>20 - 2048<br/> * * @return String that contains the key ARN. */ public String getAliasArn() { return aliasArn; } /** * String that contains the key ARN. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>20 - 2048<br/> * * @param aliasArn String that contains the key ARN. */ public void setAliasArn(String aliasArn) { this.aliasArn = aliasArn; } /** * String that contains the key ARN. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>20 - 2048<br/> * * @param aliasArn String that contains the key ARN. * * @return A reference to this updated object so that method calls can be chained * together. */ public AliasListEntry withAliasArn(String aliasArn) { this.aliasArn = aliasArn; return this; } /** * String that contains the key identifier pointed to by the alias. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * * @return String that contains the key identifier pointed to by the alias. */ public String getTargetKeyId() { return targetKeyId; } /** * String that contains the key identifier pointed to by the alias. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * * @param targetKeyId String that contains the key identifier pointed to by the alias. */ public void setTargetKeyId(String targetKeyId) { this.targetKeyId = targetKeyId; } /** * String that contains the key identifier pointed to by the alias. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 256<br/> * * @param targetKeyId String that contains the key identifier pointed to by the alias. * * @return A reference to this updated object so that method calls can be chained * together. */ public AliasListEntry withTargetKeyId(String targetKeyId) { this.targetKeyId = targetKeyId; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAliasName() != null) sb.append("AliasName: " + getAliasName() + ","); if (getAliasArn() != null) sb.append("AliasArn: " + getAliasArn() + ","); if (getTargetKeyId() != null) sb.append("TargetKeyId: " + getTargetKeyId() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAliasName() == null) ? 0 : getAliasName().hashCode()); hashCode = prime * hashCode + ((getAliasArn() == null) ? 0 : getAliasArn().hashCode()); hashCode = prime * hashCode + ((getTargetKeyId() == null) ? 0 : getTargetKeyId().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AliasListEntry == false) return false; AliasListEntry other = (AliasListEntry)obj; if (other.getAliasName() == null ^ this.getAliasName() == null) return false; if (other.getAliasName() != null && other.getAliasName().equals(this.getAliasName()) == false) return false; if (other.getAliasArn() == null ^ this.getAliasArn() == null) return false; if (other.getAliasArn() != null && other.getAliasArn().equals(this.getAliasArn()) == false) return false; if (other.getTargetKeyId() == null ^ this.getTargetKeyId() == null) return false; if (other.getTargetKeyId() != null && other.getTargetKeyId().equals(this.getTargetKeyId()) == false) return false; return true; } @Override public AliasListEntry clone() { try { return (AliasListEntry) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * 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.fs.adl; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.microsoft.azure.datalake.store.ADLStoreClient; import com.microsoft.azure.datalake.store.ADLStoreOptions; import com.microsoft.azure.datalake.store.DirectoryEntry; import com.microsoft.azure.datalake.store.IfExists; import com.microsoft.azure.datalake.store.LatencyTracker; import com.microsoft.azure.datalake.store.UserGroupRepresentation; import com.microsoft.azure.datalake.store.oauth2.AccessTokenProvider; import com.microsoft.azure.datalake.store.oauth2.ClientCredsTokenProvider; import com.microsoft.azure.datalake.store.oauth2.DeviceCodeTokenProvider; import com.microsoft.azure.datalake.store.oauth2.MsiTokenProvider; import com.microsoft.azure.datalake.store.oauth2.RefreshTokenBasedTokenProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.ContentSummary.Builder; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.InvalidPathException; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Options.Rename; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.adl.oauth2.AzureADTokenProvider; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclStatus; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.ProviderUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Progressable; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.VersionInfo; import static org.apache.hadoop.fs.adl.AdlConfKeys.*; /** * A FileSystem to access Azure Data Lake Store. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class AdlFileSystem extends FileSystem { private static final Logger LOG = LoggerFactory.getLogger(AdlFileSystem.class); public static final String SCHEME = "adl"; static final int DEFAULT_PORT = 443; private URI uri; private String userName; private boolean overrideOwner; private ADLStoreClient adlClient; private Path workingDirectory; private boolean aclBitStatus; private UserGroupRepresentation oidOrUpn; // retained for tests private AccessTokenProvider tokenProvider; private AzureADTokenProvider azureTokenProvider; static { AdlConfKeys.addDeprecatedKeys(); } @Override public String getScheme() { return SCHEME; } public URI getUri() { return uri; } @Override public int getDefaultPort() { return DEFAULT_PORT; } @Override public boolean supportsSymlinks() { return false; } /** * Called after a new FileSystem instance is constructed. * * @param storeUri a uri whose authority section names the host, port, * etc. for this FileSystem * @param originalConf the configuration to use for the FS. The account- * specific options are patched over the base ones * before any use is made of the config. */ @Override public void initialize(URI storeUri, Configuration originalConf) throws IOException { String hostname = storeUri.getHost(); String accountName = getAccountNameFromFQDN(hostname); Configuration conf = propagateAccountOptions(originalConf, accountName); super.initialize(storeUri, conf); this.setConf(conf); this.uri = URI .create(storeUri.getScheme() + "://" + storeUri.getAuthority()); try { userName = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException e) { userName = "hadoop"; LOG.warn("Got exception when getting Hadoop user name." + " Set the user name to '" + userName + "'.", e); } this.setWorkingDirectory(getHomeDirectory()); overrideOwner = getConf().getBoolean(ADL_DEBUG_OVERRIDE_LOCAL_USER_AS_OWNER, ADL_DEBUG_SET_LOCAL_USER_AS_OWNER_DEFAULT); aclBitStatus = conf.getBoolean(ADL_SUPPORT_ACL_BIT_IN_FSPERMISSION, ADL_SUPPORT_ACL_BIT_IN_FSPERMISSION_DEFAULT); String accountFQDN = null; String mountPoint = null; if (!hostname.contains(".") && !hostname.equalsIgnoreCase( "localhost")) { // this is a symbolic name. Resolve it. String hostNameProperty = "dfs.adls." + hostname + ".hostname"; String mountPointProperty = "dfs.adls." + hostname + ".mountpoint"; accountFQDN = getNonEmptyVal(conf, hostNameProperty); mountPoint = getNonEmptyVal(conf, mountPointProperty); } else { accountFQDN = hostname; } if (storeUri.getPort() > 0) { accountFQDN = accountFQDN + ":" + storeUri.getPort(); } adlClient = ADLStoreClient .createClient(accountFQDN, getAccessTokenProvider(conf)); ADLStoreOptions options = new ADLStoreOptions(); options.enableThrowingRemoteExceptions(); if (getTransportScheme().equalsIgnoreCase(INSECURE_TRANSPORT_SCHEME)) { options.setInsecureTransport(); } if (mountPoint != null) { options.setFilePathPrefix(mountPoint); } String clusterName = conf.get(ADL_EVENTS_TRACKING_CLUSTERNAME, "UNKNOWN"); String clusterType = conf.get(ADL_EVENTS_TRACKING_CLUSTERTYPE, "UNKNOWN"); String clientVersion = ADL_HADOOP_CLIENT_NAME + (StringUtils .isEmpty(VersionInfo.getVersion().trim()) ? ADL_HADOOP_CLIENT_VERSION.trim() : VersionInfo.getVersion().trim()); options.setUserAgentSuffix(clientVersion + "/" + VersionInfo.getVersion().trim() + "/" + clusterName + "/" + clusterType); int timeout = conf.getInt(ADL_HTTP_TIMEOUT, -1); if (timeout > 0) { // only set timeout if specified in config. Otherwise use SDK default options.setDefaultTimeout(timeout); } else { LOG.info("No valid ADL SDK timeout configured: using SDK default."); } adlClient.setOptions(options); boolean trackLatency = conf .getBoolean(LATENCY_TRACKER_KEY, LATENCY_TRACKER_DEFAULT); if (!trackLatency) { LatencyTracker.disable(); } boolean enableUPN = conf.getBoolean(ADL_ENABLEUPN_FOR_OWNERGROUP_KEY, ADL_ENABLEUPN_FOR_OWNERGROUP_DEFAULT); oidOrUpn = enableUPN ? UserGroupRepresentation.UPN : UserGroupRepresentation.OID; } /** * This method is provided for convenience for derived classes to define * custom {@link AzureADTokenProvider} instance. * * In order to ensure secure hadoop infrastructure and user context for which * respective {@link AdlFileSystem} instance is initialized, * Loading {@link AzureADTokenProvider} is not sufficient. * * The order of loading {@link AzureADTokenProvider} is to first invoke * {@link #getCustomAccessTokenProvider(Configuration)}, If method return null * which means no implementation provided by derived classes, then * configuration object is loaded to retrieve token configuration as specified * is documentation. * * Custom token management takes the higher precedence during initialization. * * @param conf Configuration object * @return null if the no custom {@link AzureADTokenProvider} token management * is specified. * @throws IOException if failed to initialize token provider. */ protected synchronized AzureADTokenProvider getCustomAccessTokenProvider( Configuration conf) throws IOException { String className = getNonEmptyVal(conf, AZURE_AD_TOKEN_PROVIDER_CLASS_KEY); Class<? extends AzureADTokenProvider> azureADTokenProviderClass = conf.getClass(AZURE_AD_TOKEN_PROVIDER_CLASS_KEY, null, AzureADTokenProvider.class); if (azureADTokenProviderClass == null) { throw new IllegalArgumentException( "Configuration " + className + " " + "not defined/accessible."); } azureTokenProvider = ReflectionUtils .newInstance(azureADTokenProviderClass, conf); if (azureTokenProvider == null) { throw new IllegalArgumentException("Failed to initialize " + className); } azureTokenProvider.initialize(conf); return azureTokenProvider; } private AccessTokenProvider getAccessTokenProvider(Configuration config) throws IOException { Configuration conf = ProviderUtils.excludeIncompatibleCredentialProviders( config, AdlFileSystem.class); TokenProviderType type = conf.getEnum( AdlConfKeys.AZURE_AD_TOKEN_PROVIDER_TYPE_KEY, AdlConfKeys.AZURE_AD_TOKEN_PROVIDER_TYPE_DEFAULT); switch (type) { case RefreshToken: tokenProvider = getConfRefreshTokenBasedTokenProvider(conf); break; case ClientCredential: tokenProvider = getConfCredentialBasedTokenProvider(conf); break; case MSI: tokenProvider = getMsiBasedTokenProvider(conf); break; case DeviceCode: tokenProvider = getDeviceCodeTokenProvider(conf); break; case Custom: default: AzureADTokenProvider azureADTokenProvider = getCustomAccessTokenProvider( conf); tokenProvider = new SdkTokenProviderAdapter(azureADTokenProvider); break; } return tokenProvider; } private AccessTokenProvider getConfCredentialBasedTokenProvider( Configuration conf) throws IOException { String clientId = getPasswordString(conf, AZURE_AD_CLIENT_ID_KEY); String refreshUrl = getPasswordString(conf, AZURE_AD_REFRESH_URL_KEY); String clientSecret = getPasswordString(conf, AZURE_AD_CLIENT_SECRET_KEY); return new ClientCredsTokenProvider(refreshUrl, clientId, clientSecret); } private AccessTokenProvider getConfRefreshTokenBasedTokenProvider( Configuration conf) throws IOException { String clientId = getPasswordString(conf, AZURE_AD_CLIENT_ID_KEY); String refreshToken = getPasswordString(conf, AZURE_AD_REFRESH_TOKEN_KEY); return new RefreshTokenBasedTokenProvider(clientId, refreshToken); } private AccessTokenProvider getMsiBasedTokenProvider( Configuration conf) throws IOException { return new MsiTokenProvider(conf.getInt(MSI_PORT, -1)); } private AccessTokenProvider getDeviceCodeTokenProvider( Configuration conf) throws IOException { String clientAppId = getNonEmptyVal(conf, DEVICE_CODE_CLIENT_APP_ID); return new DeviceCodeTokenProvider(clientAppId); } @VisibleForTesting AccessTokenProvider getTokenProvider() { return tokenProvider; } @VisibleForTesting AzureADTokenProvider getAzureTokenProvider() { return azureTokenProvider; } @VisibleForTesting public ADLStoreClient getAdlClient() { return adlClient; } /** * Constructing home directory locally is fine as long as Hadoop * local user name and ADL user name relationship story is not fully baked * yet. * * @return Hadoop local user home directory. */ @Override public Path getHomeDirectory() { return makeQualified(new Path("/user/" + userName)); } /** * Create call semantic is handled differently in case of ADL. Create * semantics is translated to Create/Append * semantics. * 1. No dedicated connection to server. * 2. Buffering is locally done, Once buffer is full or flush is invoked on * the by the caller. All the pending * data is pushed to ADL as APPEND operation code. * 3. On close - Additional call is send to server to close the stream, and * release lock from the stream. * * Necessity of Create/Append semantics is * 1. ADL backend server does not allow idle connection for longer duration * . In case of slow writer scenario, * observed connection timeout/Connection reset causing occasional job * failures. * 2. Performance boost to jobs which are slow writer, avoided network latency * 3. ADL equally better performing with multiple of 4MB chunk as append * calls. * * @param f File path * @param permission Access permission for the newly created file * @param overwrite Remove existing file and recreate new one if true * otherwise throw error if file exist * @param bufferSize Buffer size, ADL backend does not honour * @param replication Replication count, ADL backend does not honour * @param blockSize Block size, ADL backend does not honour * @param progress Progress indicator * @return FSDataOutputStream OutputStream on which application can push * stream of bytes * @throws IOException when system error, internal server error or user error */ @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { statistics.incrementWriteOps(1); IfExists overwriteRule = overwrite ? IfExists.OVERWRITE : IfExists.FAIL; return new FSDataOutputStream(new AdlFsOutputStream(adlClient .createFile(toRelativeFilePath(f), overwriteRule, Integer.toOctalString(applyUMask(permission).toShort()), true), getConf()), this.statistics); } /** * Opens an FSDataOutputStream at the indicated Path with write-progress * reporting. Same as create(), except fails if parent directory doesn't * already exist. * * @param f the file name to open * @param permission Access permission for the newly created file * @param flags {@link CreateFlag}s to use for this stream. * @param bufferSize the size of the buffer to be used. ADL backend does * not honour * @param replication required block replication for the file. ADL backend * does not honour * @param blockSize Block size, ADL backend does not honour * @param progress Progress indicator * @throws IOException when system error, internal server error or user error * @see #setPermission(Path, FsPermission) * @deprecated API only for 0.20-append */ @Override public FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { statistics.incrementWriteOps(1); IfExists overwriteRule = IfExists.FAIL; for (CreateFlag flag : flags) { if (flag == CreateFlag.OVERWRITE) { overwriteRule = IfExists.OVERWRITE; break; } } return new FSDataOutputStream(new AdlFsOutputStream(adlClient .createFile(toRelativeFilePath(f), overwriteRule, Integer.toOctalString(applyUMask(permission).toShort()), false), getConf()), this.statistics); } /** * Append to an existing file (optional operation). * * @param f the existing file to be appended. * @param bufferSize the size of the buffer to be used. ADL backend does * not honour * @param progress Progress indicator * @throws IOException when system error, internal server error or user error */ @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { statistics.incrementWriteOps(1); return new FSDataOutputStream( new AdlFsOutputStream(adlClient.getAppendStream(toRelativeFilePath(f)), getConf()), this.statistics); } /** * Azure data lake does not support user configuration for data replication * hence not leaving system to query on * azure data lake. * * Stub implementation * * @param p Not honoured * @param replication Not honoured * @return True hard coded since ADL file system does not support * replication configuration * @throws IOException No exception would not thrown in this case however * aligning with parent api definition. */ @Override public boolean setReplication(final Path p, final short replication) throws IOException { statistics.incrementWriteOps(1); return true; } /** * Open call semantic is handled differently in case of ADL. Instead of * network stream is returned to the user, * Overridden FsInputStream is returned. * * @param f File path * @param buffersize Buffer size, Not honoured * @return FSDataInputStream InputStream on which application can read * stream of bytes * @throws IOException when system error, internal server error or user error */ @Override public FSDataInputStream open(final Path f, final int buffersize) throws IOException { statistics.incrementReadOps(1); return new FSDataInputStream( new AdlFsInputStream(adlClient.getReadStream(toRelativeFilePath(f)), statistics, getConf())); } /** * Return a file status object that represents the path. * * @param f The path we want information from * @return a FileStatus object * @throws IOException when the path does not exist or any other error; * IOException see specific implementation */ @Override public FileStatus getFileStatus(final Path f) throws IOException { statistics.incrementReadOps(1); DirectoryEntry entry = adlClient.getDirectoryEntry(toRelativeFilePath(f), oidOrUpn); return toFileStatus(entry, f); } /** * List the statuses of the files/directories in the given path if the path is * a directory. * * @param f given path * @return the statuses of the files/directories in the given patch * @throws IOException when the path does not exist or any other error; * IOException see specific implementation */ @Override public FileStatus[] listStatus(final Path f) throws IOException { statistics.incrementReadOps(1); List<DirectoryEntry> entries = adlClient.enumerateDirectory(toRelativeFilePath(f), oidOrUpn); return toFileStatuses(entries, f); } /** * Renames Path src to Path dst. Can take place on local fs * or remote DFS. * * ADLS support POSIX standard for rename operation. * * @param src path to be renamed * @param dst new path after rename * @return true if rename is successful * @throws IOException on failure */ @Override public boolean rename(final Path src, final Path dst) throws IOException { statistics.incrementWriteOps(1); if (toRelativeFilePath(src).equals("/")) { return false; } return adlClient.rename(toRelativeFilePath(src), toRelativeFilePath(dst)); } @Override @Deprecated public void rename(final Path src, final Path dst, final Options.Rename... options) throws IOException { statistics.incrementWriteOps(1); boolean overwrite = false; for (Rename renameOption : options) { if (renameOption == Rename.OVERWRITE) { overwrite = true; break; } } adlClient .rename(toRelativeFilePath(src), toRelativeFilePath(dst), overwrite); } /** * Concat existing files together. * * @param trg the path to the target destination. * @param srcs the paths to the sources to use for the concatenation. * @throws IOException when system error, internal server error or user error */ @Override public void concat(final Path trg, final Path[] srcs) throws IOException { statistics.incrementWriteOps(1); List<String> sourcesList = new ArrayList<String>(); for (Path entry : srcs) { sourcesList.add(toRelativeFilePath(entry)); } adlClient.concatenateFiles(toRelativeFilePath(trg), sourcesList); } /** * Delete a file. * * @param path the path to delete. * @param recursive if path is a directory and set to * true, the directory is deleted else throws an exception. * In case of a file the recursive can be set to either * true or false. * @return true if delete is successful else false. * @throws IOException when system error, internal server error or user error */ @Override public boolean delete(final Path path, final boolean recursive) throws IOException { statistics.incrementWriteOps(1); String relativePath = toRelativeFilePath(path); // Delete on root directory not supported. if (relativePath.equals("/")) { // This is important check after recent commit // HADOOP-12977 and HADOOP-13716 validates on root for // 1. if root is empty and non recursive delete then return false. // 2. if root is non empty and non recursive delete then throw exception. if (!recursive && adlClient.enumerateDirectory(toRelativeFilePath(path), 1).size() > 0) { throw new IOException("Delete on root is not supported."); } return false; } return recursive ? adlClient.deleteRecursive(relativePath) : adlClient.delete(relativePath); } /** * Make the given file and all non-existent parents into * directories. Has the semantics of Unix 'mkdir -p'. * Existence of the directory hierarchy is not an error. * * @param path path to create * @param permission to apply to path */ @Override public boolean mkdirs(final Path path, final FsPermission permission) throws IOException { statistics.incrementWriteOps(1); return adlClient.createDirectory(toRelativeFilePath(path), Integer.toOctalString(applyUMask(permission).toShort())); } private FileStatus[] toFileStatuses(final List<DirectoryEntry> entries, final Path parent) { FileStatus[] fileStatuses = new FileStatus[entries.size()]; int index = 0; for (DirectoryEntry entry : entries) { FileStatus status = toFileStatus(entry, parent); if (!(entry.name == null || entry.name == "")) { status.setPath( new Path(parent.makeQualified(uri, workingDirectory), entry.name)); } fileStatuses[index++] = status; } return fileStatuses; } private FsPermission applyUMask(FsPermission permission) { if (permission == null) { permission = FsPermission.getDefault(); } return permission.applyUMask(FsPermission.getUMask(getConf())); } private FileStatus toFileStatus(final DirectoryEntry entry, final Path f) { Path p = makeQualified(f); boolean aclBit = aclBitStatus ? entry.aclBit : false; if (overrideOwner) { return new AdlFileStatus(entry, p, userName, "hdfs", aclBit); } return new AdlFileStatus(entry, p, aclBit); } /** * Set owner of a path (i.e. a file or a directory). * The parameters owner and group cannot both be null. * * @param path The path * @param owner If it is null, the original username remains unchanged. * @param group If it is null, the original groupname remains unchanged. */ @Override public void setOwner(final Path path, final String owner, final String group) throws IOException { statistics.incrementWriteOps(1); adlClient.setOwner(toRelativeFilePath(path), owner, group); } /** * Set permission of a path. * * @param path The path * @param permission Access permission */ @Override public void setPermission(final Path path, final FsPermission permission) throws IOException { statistics.incrementWriteOps(1); adlClient.setPermission(toRelativeFilePath(path), Integer.toOctalString(permission.toShort())); } /** * Modifies ACL entries of files and directories. This method can add new ACL * entries or modify the permissions on existing ACL entries. All existing * ACL entries that are not specified in this call are retained without * changes. (Modifications are merged into the current ACL.) * * @param path Path to modify * @param aclSpec List of AclEntry describing modifications * @throws IOException if an ACL could not be modified */ @Override public void modifyAclEntries(final Path path, final List<AclEntry> aclSpec) throws IOException { statistics.incrementWriteOps(1); List<com.microsoft.azure.datalake.store.acl.AclEntry> msAclEntries = new ArrayList<com.microsoft.azure.datalake.store.acl.AclEntry>(); for (AclEntry aclEntry : aclSpec) { msAclEntries.add(com.microsoft.azure.datalake.store.acl.AclEntry .parseAclEntry(aclEntry.toString())); } adlClient.modifyAclEntries(toRelativeFilePath(path), msAclEntries); } /** * Removes ACL entries from files and directories. Other ACL entries are * retained. * * @param path Path to modify * @param aclSpec List of AclEntry describing entries to remove * @throws IOException if an ACL could not be modified */ @Override public void removeAclEntries(final Path path, final List<AclEntry> aclSpec) throws IOException { statistics.incrementWriteOps(1); List<com.microsoft.azure.datalake.store.acl.AclEntry> msAclEntries = new ArrayList<com.microsoft.azure.datalake.store.acl.AclEntry>(); for (AclEntry aclEntry : aclSpec) { msAclEntries.add(com.microsoft.azure.datalake.store.acl.AclEntry .parseAclEntry(aclEntry.toString(), true)); } adlClient.removeAclEntries(toRelativeFilePath(path), msAclEntries); } /** * Removes all default ACL entries from files and directories. * * @param path Path to modify * @throws IOException if an ACL could not be modified */ @Override public void removeDefaultAcl(final Path path) throws IOException { statistics.incrementWriteOps(1); adlClient.removeDefaultAcls(toRelativeFilePath(path)); } /** * Removes all but the base ACL entries of files and directories. The entries * for user, group, and others are retained for compatibility with permission * bits. * * @param path Path to modify * @throws IOException if an ACL could not be removed */ @Override public void removeAcl(final Path path) throws IOException { statistics.incrementWriteOps(1); adlClient.removeAllAcls(toRelativeFilePath(path)); } /** * Fully replaces ACL of files and directories, discarding all existing * entries. * * @param path Path to modify * @param aclSpec List of AclEntry describing modifications, must include * entries for user, group, and others for compatibility with * permission bits. * @throws IOException if an ACL could not be modified */ @Override public void setAcl(final Path path, final List<AclEntry> aclSpec) throws IOException { statistics.incrementWriteOps(1); List<com.microsoft.azure.datalake.store.acl.AclEntry> msAclEntries = new ArrayList<com.microsoft.azure.datalake.store.acl.AclEntry>(); for (AclEntry aclEntry : aclSpec) { msAclEntries.add(com.microsoft.azure.datalake.store.acl.AclEntry .parseAclEntry(aclEntry.toString())); } adlClient.setAcl(toRelativeFilePath(path), msAclEntries); } /** * Gets the ACL of a file or directory. * * @param path Path to get * @return AclStatus describing the ACL of the file or directory * @throws IOException if an ACL could not be read */ @Override public AclStatus getAclStatus(final Path path) throws IOException { statistics.incrementReadOps(1); com.microsoft.azure.datalake.store.acl.AclStatus adlStatus = adlClient.getAclStatus(toRelativeFilePath(path), oidOrUpn); AclStatus.Builder aclStatusBuilder = new AclStatus.Builder(); aclStatusBuilder.owner(adlStatus.owner); aclStatusBuilder.group(adlStatus.group); aclStatusBuilder.setPermission( new FsPermission(Short.valueOf(adlStatus.octalPermissions, 8))); aclStatusBuilder.stickyBit(adlStatus.stickyBit); String aclListString = com.microsoft.azure.datalake.store.acl.AclEntry .aclListToString(adlStatus.aclSpec); List<AclEntry> aclEntries = AclEntry.parseAclSpec(aclListString, true); aclStatusBuilder.addEntries(aclEntries); return aclStatusBuilder.build(); } /** * Checks if the user can access a path. The mode specifies which access * checks to perform. If the requested permissions are granted, then the * method returns normally. If access is denied, then the method throws an * {@link AccessControlException}. * * @param path Path to check * @param mode type of access to check * @throws AccessControlException if access is denied * @throws java.io.FileNotFoundException if the path does not exist * @throws IOException see specific implementation */ @Override public void access(final Path path, FsAction mode) throws IOException { statistics.incrementReadOps(1); if (!adlClient.checkAccess(toRelativeFilePath(path), mode.SYMBOL)) { throw new AccessControlException("Access Denied : " + path.toString()); } } /** * Return the {@link ContentSummary} of a given {@link Path}. * * @param f path to use */ @Override public ContentSummary getContentSummary(Path f) throws IOException { statistics.incrementReadOps(1); com.microsoft.azure.datalake.store.ContentSummary msSummary = adlClient .getContentSummary(toRelativeFilePath(f)); return new Builder().length(msSummary.length) .directoryCount(msSummary.directoryCount).fileCount(msSummary.fileCount) .spaceConsumed(msSummary.spaceConsumed).build(); } @VisibleForTesting protected String getTransportScheme() { return SECURE_TRANSPORT_SCHEME; } @VisibleForTesting String toRelativeFilePath(Path path) { return path.makeQualified(uri, workingDirectory).toUri().getPath(); } /** * Get the current working directory for the given file system. * * @return the directory pathname */ @Override public Path getWorkingDirectory() { return workingDirectory; } /** * Set the current working directory for the given file system. All relative * paths will be resolved relative to it. * * @param dir Working directory path. */ @Override public void setWorkingDirectory(final Path dir) { if (dir == null) { throw new InvalidPathException("Working directory cannot be set to NULL"); } /** * Do not validate the scheme and URI of the passsed parameter. When Adls * runs as additional file system, working directory set has the default * file system scheme and uri. * * Found a problem during PIG execution in * https://github.com/apache/pig/blob/branch-0 * .15/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer * /PigInputFormat.java#L235 * However similar problem would be present in other application so * defaulting to build working directory using relative path only. */ this.workingDirectory = this.makeAbsolute(dir); } /** * Return the number of bytes that large input files should be optimally * be split into to minimize i/o time. * * @deprecated use {@link #getDefaultBlockSize(Path)} instead */ @Deprecated public long getDefaultBlockSize() { return ADL_BLOCK_SIZE; } /** * Return the number of bytes that large input files should be optimally * be split into to minimize i/o time. The given path will be used to * locate the actual filesystem. The full path does not have to exist. * * @param f path of file * @return the default block size for the path's filesystem */ public long getDefaultBlockSize(Path f) { return getDefaultBlockSize(); } /** * Get the block size. * @param f the filename * @return the number of bytes in a block */ /** * @deprecated Use getFileStatus() instead */ @Deprecated public long getBlockSize(Path f) throws IOException { return ADL_BLOCK_SIZE; } /** * Get replication. * * @param src file name * @return file replication * @deprecated Use getFileStatus() instead */ @Deprecated public short getReplication(Path src) { return ADL_REPLICATION_FACTOR; } private Path makeAbsolute(Path path) { return path.isAbsolute() ? path : new Path(this.workingDirectory, path); } private static String getNonEmptyVal(Configuration conf, String key) { String value = conf.get(key); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException( "No value for " + key + " found in conf file."); } return value; } /** * A wrapper of {@link Configuration#getPassword(String)}. It returns * <code>String</code> instead of <code>char[]</code>. * * @param conf the configuration * @param key the property key * @return the password string * @throws IOException if the password was not found */ private static String getPasswordString(Configuration conf, String key) throws IOException { char[] passchars = conf.getPassword(key); if (passchars == null) { throw new IOException("Password " + key + " not found"); } return new String(passchars); } @VisibleForTesting public void setUserGroupRepresentationAsUPN(boolean enableUPN) { oidOrUpn = enableUPN ? UserGroupRepresentation.UPN : UserGroupRepresentation.OID; } /** * Gets ADL account name from ADL FQDN. * @param accountFQDN ADL account fqdn * @return ADL account name */ public static String getAccountNameFromFQDN(String accountFQDN) { return accountFQDN.contains(".") ? accountFQDN.substring(0, accountFQDN.indexOf(".")) : accountFQDN; } /** * Propagates account-specific settings into generic ADL configuration keys. * This is done by propagating the values of the form * {@code fs.adl.account.${account_name}.key} to * {@code fs.adl.key}, for all values of "key" * * The source of the updated property is set to the key name of the account * property, to aid in diagnostics of where things came from. * * Returns a new configuration. Why the clone? * You can use the same conf for different filesystems, and the original * values are not updated. * * * @param source Source Configuration object * @param accountName account name. Must not be empty * @return a (potentially) patched clone of the original */ public static Configuration propagateAccountOptions(Configuration source, String accountName) { Preconditions.checkArgument(StringUtils.isNotEmpty(accountName), "accountName"); final String accountPrefix = AZURE_AD_ACCOUNT_PREFIX + accountName +'.'; LOG.debug("Propagating entries under {}", accountPrefix); final Configuration dest = new Configuration(source); for (Map.Entry<String, String> entry : source) { final String key = entry.getKey(); // get the (unexpanded) value. final String value = entry.getValue(); if (!key.startsWith(accountPrefix) || accountPrefix.equals(key)) { continue; } // there's a account prefix, so strip it final String stripped = key.substring(accountPrefix.length()); // propagate the value, building a new origin field. // to track overwrites, the generic key is overwritten even if // already matches the new one. String origin = "[" + StringUtils.join( source.getPropertySources(key), ", ") +"]"; final String generic = AZURE_AD_PREFIX + stripped; LOG.debug("Updating {} from {}", generic, origin); dest.set(generic, value, key + " via " + origin); } return dest; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.test.streaming.runtime; import org.apache.flink.api.common.functions.CoGroupFunction; import org.apache.flink.api.common.functions.JoinFunction; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.streaming.api.datastream.CoGroupedStreams; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks; import org.apache.flink.streaming.api.functions.sink.SinkFunction; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.transformations.OneInputTransformation; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.util.KeyedOneInputStreamOperatorTestHarness; import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness; import org.apache.flink.test.util.AbstractTestBase; import org.apache.flink.util.Collector; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; /** * Integration tests for windowed join / coGroup operators. */ @SuppressWarnings("serial") public class CoGroupJoinITCase extends AbstractTestBase { private static List<String> testResults; @Test public void testCoGroup() throws Exception { testResults = new ArrayList<>(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); DataStream<Tuple2<String, Integer>> source1 = env.addSource(new SourceFunction<Tuple2<String, Integer>>() { private static final long serialVersionUID = 1L; @Override public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception { ctx.collect(Tuple2.of("a", 0)); ctx.collect(Tuple2.of("a", 1)); ctx.collect(Tuple2.of("a", 2)); ctx.collect(Tuple2.of("b", 3)); ctx.collect(Tuple2.of("b", 4)); ctx.collect(Tuple2.of("b", 5)); ctx.collect(Tuple2.of("a", 6)); ctx.collect(Tuple2.of("a", 7)); ctx.collect(Tuple2.of("a", 8)); // source is finite, so it will have an implicit MAX watermark when it finishes } @Override public void cancel() { } }).assignTimestampsAndWatermarks(new Tuple2TimestampExtractor()); DataStream<Tuple2<String, Integer>> source2 = env.addSource(new SourceFunction<Tuple2<String, Integer>>() { @Override public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception { ctx.collect(Tuple2.of("a", 0)); ctx.collect(Tuple2.of("a", 1)); ctx.collect(Tuple2.of("b", 3)); ctx.collect(Tuple2.of("c", 6)); ctx.collect(Tuple2.of("c", 7)); ctx.collect(Tuple2.of("c", 8)); // source is finite, so it will have an implicit MAX watermark when it finishes } @Override public void cancel() { } }).assignTimestampsAndWatermarks(new Tuple2TimestampExtractor()); source1.coGroup(source2) .where(new Tuple2KeyExtractor()) .equalTo(new Tuple2KeyExtractor()) .window(TumblingEventTimeWindows.of(Time.of(3, TimeUnit.MILLISECONDS))) .apply(new CoGroupFunction<Tuple2<String, Integer>, Tuple2<String, Integer>, String>() { @Override public void coGroup(Iterable<Tuple2<String, Integer>> first, Iterable<Tuple2<String, Integer>> second, Collector<String> out) throws Exception { StringBuilder result = new StringBuilder(); result.append("F:"); for (Tuple2<String, Integer> t: first) { result.append(t.toString()); } result.append(" S:"); for (Tuple2<String, Integer> t: second) { result.append(t.toString()); } out.collect(result.toString()); } }) .addSink(new SinkFunction<String>() { @Override public void invoke(String value) throws Exception { testResults.add(value); } }); env.execute("CoGroup Test"); List<String> expectedResult = Arrays.asList( "F:(a,0)(a,1)(a,2) S:(a,0)(a,1)", "F:(b,3)(b,4)(b,5) S:(b,3)", "F:(a,6)(a,7)(a,8) S:", "F: S:(c,6)(c,7)(c,8)"); Collections.sort(expectedResult); Collections.sort(testResults); Assert.assertEquals(expectedResult, testResults); } @Test public void testJoin() throws Exception { testResults = new ArrayList<>(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); DataStream<Tuple3<String, String, Integer>> source1 = env.addSource(new SourceFunction<Tuple3<String, String, Integer>>() { @Override public void run(SourceContext<Tuple3<String, String, Integer>> ctx) throws Exception { ctx.collect(Tuple3.of("a", "x", 0)); ctx.collect(Tuple3.of("a", "y", 1)); ctx.collect(Tuple3.of("a", "z", 2)); ctx.collect(Tuple3.of("b", "u", 3)); ctx.collect(Tuple3.of("b", "w", 5)); ctx.collect(Tuple3.of("a", "i", 6)); ctx.collect(Tuple3.of("a", "j", 7)); ctx.collect(Tuple3.of("a", "k", 8)); // source is finite, so it will have an implicit MAX watermark when it finishes } @Override public void cancel() {} }).assignTimestampsAndWatermarks(new Tuple3TimestampExtractor()); DataStream<Tuple3<String, String, Integer>> source2 = env.addSource(new SourceFunction<Tuple3<String, String, Integer>>() { @Override public void run(SourceContext<Tuple3<String, String, Integer>> ctx) throws Exception { ctx.collect(Tuple3.of("a", "u", 0)); ctx.collect(Tuple3.of("a", "w", 1)); ctx.collect(Tuple3.of("b", "i", 3)); ctx.collect(Tuple3.of("b", "k", 5)); ctx.collect(Tuple3.of("a", "x", 6)); ctx.collect(Tuple3.of("a", "z", 8)); // source is finite, so it will have an implicit MAX watermark when it finishes } @Override public void cancel() {} }).assignTimestampsAndWatermarks(new Tuple3TimestampExtractor()); source1.join(source2) .where(new Tuple3KeyExtractor()) .equalTo(new Tuple3KeyExtractor()) .window(TumblingEventTimeWindows.of(Time.of(3, TimeUnit.MILLISECONDS))) .apply(new JoinFunction<Tuple3<String, String, Integer>, Tuple3<String, String, Integer>, String>() { @Override public String join(Tuple3<String, String, Integer> first, Tuple3<String, String, Integer> second) throws Exception { return first + ":" + second; } }) .addSink(new SinkFunction<String>() { @Override public void invoke(String value) throws Exception { testResults.add(value); } }); env.execute("Join Test"); List<String> expectedResult = Arrays.asList( "(a,x,0):(a,u,0)", "(a,x,0):(a,w,1)", "(a,y,1):(a,u,0)", "(a,y,1):(a,w,1)", "(a,z,2):(a,u,0)", "(a,z,2):(a,w,1)", "(b,u,3):(b,i,3)", "(b,u,3):(b,k,5)", "(b,w,5):(b,i,3)", "(b,w,5):(b,k,5)", "(a,i,6):(a,x,6)", "(a,i,6):(a,z,8)", "(a,j,7):(a,x,6)", "(a,j,7):(a,z,8)", "(a,k,8):(a,x,6)", "(a,k,8):(a,z,8)"); Collections.sort(expectedResult); Collections.sort(testResults); Assert.assertEquals(expectedResult, testResults); } @Test public void testSelfJoin() throws Exception { testResults = new ArrayList<>(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); DataStream<Tuple3<String, String, Integer>> source1 = env.addSource(new SourceFunction<Tuple3<String, String, Integer>>() { private static final long serialVersionUID = 1L; @Override public void run(SourceContext<Tuple3<String, String, Integer>> ctx) throws Exception { ctx.collect(Tuple3.of("a", "x", 0)); ctx.collect(Tuple3.of("a", "y", 1)); ctx.collect(Tuple3.of("a", "z", 2)); ctx.collect(Tuple3.of("b", "u", 3)); ctx.collect(Tuple3.of("b", "w", 5)); ctx.collect(Tuple3.of("a", "i", 6)); ctx.collect(Tuple3.of("a", "j", 7)); ctx.collect(Tuple3.of("a", "k", 8)); // source is finite, so it will have an implicit MAX watermark when it finishes } @Override public void cancel() { } }).assignTimestampsAndWatermarks(new Tuple3TimestampExtractor()); source1.join(source1) .where(new Tuple3KeyExtractor()) .equalTo(new Tuple3KeyExtractor()) .window(TumblingEventTimeWindows.of(Time.of(3, TimeUnit.MILLISECONDS))) .apply(new JoinFunction<Tuple3<String, String, Integer>, Tuple3<String, String, Integer>, String>() { @Override public String join(Tuple3<String, String, Integer> first, Tuple3<String, String, Integer> second) throws Exception { return first + ":" + second; } }) .addSink(new SinkFunction<String>() { @Override public void invoke(String value) throws Exception { testResults.add(value); } }); env.execute("Self-Join Test"); List<String> expectedResult = Arrays.asList( "(a,x,0):(a,x,0)", "(a,x,0):(a,y,1)", "(a,x,0):(a,z,2)", "(a,y,1):(a,x,0)", "(a,y,1):(a,y,1)", "(a,y,1):(a,z,2)", "(a,z,2):(a,x,0)", "(a,z,2):(a,y,1)", "(a,z,2):(a,z,2)", "(b,u,3):(b,u,3)", "(b,u,3):(b,w,5)", "(b,w,5):(b,u,3)", "(b,w,5):(b,w,5)", "(a,i,6):(a,i,6)", "(a,i,6):(a,j,7)", "(a,i,6):(a,k,8)", "(a,j,7):(a,i,6)", "(a,j,7):(a,j,7)", "(a,j,7):(a,k,8)", "(a,k,8):(a,i,6)", "(a,k,8):(a,j,7)", "(a,k,8):(a,k,8)"); Collections.sort(expectedResult); Collections.sort(testResults); Assert.assertEquals(expectedResult, testResults); } /** * Verifies that pipelines including {@link CoGroupedStreams} can be checkpointed properly, * which includes snapshotting configurations of any involved serializers. * * @see <a href="https://issues.apache.org/jira/browse/FLINK-6808">FLINK-6808</a> */ @Test public void testCoGroupOperatorWithCheckpoint() throws Exception { // generate an operator for the co-group operation StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); DataStream<Tuple2<String, Integer>> source1 = env.fromElements(Tuple2.of("a", 0), Tuple2.of("b", 3)); DataStream<Tuple2<String, Integer>> source2 = env.fromElements(Tuple2.of("a", 1), Tuple2.of("b", 6)); DataStream<String> coGroupWindow = source1.coGroup(source2) .where(new Tuple2KeyExtractor()) .equalTo(new Tuple2KeyExtractor()) .window(TumblingEventTimeWindows.of(Time.of(3, TimeUnit.MILLISECONDS))) .apply(new CoGroupFunction<Tuple2<String, Integer>, Tuple2<String, Integer>, String>() { @Override public void coGroup(Iterable<Tuple2<String, Integer>> first, Iterable<Tuple2<String, Integer>> second, Collector<String> out) throws Exception { out.collect(first + ":" + second); } }); OneInputTransformation<Tuple2<String, Integer>, String> transform = (OneInputTransformation<Tuple2<String, Integer>, String>) coGroupWindow.getTransformation(); OneInputStreamOperator<Tuple2<String, Integer>, String> operator = transform.getOperator(); // wrap the operator in the test harness, and perform a snapshot OneInputStreamOperatorTestHarness<Tuple2<String, Integer>, String> testHarness = new KeyedOneInputStreamOperatorTestHarness<>(operator, new Tuple2KeyExtractor(), BasicTypeInfo.STRING_TYPE_INFO); testHarness.open(); testHarness.snapshot(0L, 0L); } private static class Tuple2TimestampExtractor implements AssignerWithPunctuatedWatermarks<Tuple2<String, Integer>> { @Override public long extractTimestamp(Tuple2<String, Integer> element, long previousTimestamp) { return element.f1; } @Override public Watermark checkAndGetNextWatermark(Tuple2<String, Integer> element, long extractedTimestamp) { return new Watermark(extractedTimestamp - 1); } } private static class Tuple3TimestampExtractor implements AssignerWithPunctuatedWatermarks<Tuple3<String, String, Integer>> { @Override public long extractTimestamp(Tuple3<String, String, Integer> element, long previousTimestamp) { return element.f2; } @Override public Watermark checkAndGetNextWatermark(Tuple3<String, String, Integer> lastElement, long extractedTimestamp) { return new Watermark(lastElement.f2 - 1); } } private static class Tuple2KeyExtractor implements KeySelector<Tuple2<String, Integer>, String> { @Override public String getKey(Tuple2<String, Integer> value) throws Exception { return value.f0; } } private static class Tuple3KeyExtractor implements KeySelector<Tuple3<String, String, Integer>, String> { @Override public String getKey(Tuple3<String, String, Integer> value) throws Exception { return value.f0; } } }
/* Copyright (C) 2005-2011 Fabio Riccardi */ package com.lightcrafts.image.metadata; import java.io.File; import java.io.IOException; import com.lightcrafts.image.BadImageFileException; import com.lightcrafts.image.ImageInfo; import com.lightcrafts.image.metadata.values.*; import com.lightcrafts.image.types.AdobeResourceParserEventHandler; import com.lightcrafts.image.types.JPEGAPPDParser; import com.lightcrafts.image.types.ImageType; import com.lightcrafts.image.types.JPEGImageType; import com.lightcrafts.utils.bytebuffer.LCByteBuffer; import static com.lightcrafts.image.metadata.IPTCConstants.*; import static com.lightcrafts.image.metadata.IPTCTags.*; import static com.lightcrafts.image.types.AdobeConstants.*; /** * An <code>IPTCMetadataReader</code> is-an {@link ImageMetadataReader} for * reading IPTC metadata. * * @author Paul J. Lucas [paul@lightcrafts.com] */ public final class IPTCMetadataReader extends ImageMetadataReader implements AdobeResourceParserEventHandler { ////////// public ///////////////////////////////////////////////////////// /** * Construct an <code>IPTCMetadataReader</code>. * * @param imageInfo The image to read the metadata from. * @param segBuf The {@link LCByteBuffer} containing the raw binary * metadata from the image file. For TIFF images, this is the IPTC * metadata directly; for JPEG images, it's a set of Adobe resource blocks, * one of which is the IPTC metadata. * @param fromType The type of image the IPTC metadata is being read from. */ public IPTCMetadataReader( ImageInfo imageInfo, LCByteBuffer segBuf, ImageType fromType ) { super( imageInfo, segBuf ); m_fromType = fromType; if ( !(fromType instanceof JPEGImageType) ) { // // For non-JPEG images, the entire contents of the buffer are the // IPTC metadata. // m_iptcStartPos = m_buf.position(); m_iptcLength = m_buf.remaining(); } } /** * {@inheritDoc} */ public boolean gotResource( int blockID, String name, int dataLength, File file, LCByteBuffer buf ) { if ( blockID == PHOTOSHOP_IPTC_RESOURCE_ID ) { // // We've found the IPTC resource block as one of the set of Adobe // resource blocks: note its start position and length. // m_iptcStartPos = m_buf.position(); m_iptcLength = dataLength; return false; } return true; } ////////// protected ////////////////////////////////////////////////////// /** * Read the metadata from all directories. */ protected void readAllDirectories() throws IOException { if ( m_iptcLength == 0 ) { // // We never found an IPTC resource block among the set of Adobe // resource blocks; hence the image has no IPTC metadata. // return; } final ImageMetadataDirectory dir = m_metadata.getDirectoryFor( IPTCDirectory.class, true ); // // IPTC metadata has only one directory. // readDirectory( m_iptcStartPos, dir ); } /** * Read the image header. */ protected void readHeader() throws BadImageFileException, IOException { if ( m_fromType instanceof JPEGImageType ) { // // We have to parse the APPD segment we were given that contains a // set of Adobe resource blocks, one of which may be an IPTC block. // JPEGAPPDParser.parse( this, m_imageInfo.getFile(), m_buf ); } else { // // For other image types, there is nothing to do since the buffer // contains the IPTC metadata directly with no header of any kind. // } } ////////// private //////////////////////////////////////////////////////// /** * Read the metadata from a single directory. * * @param offset The offset from the beginning of the file of the * directory. * @param dir The metadata is put here. */ private void readDirectory( int offset, ImageMetadataDirectory dir ) throws IOException { m_buf.position( offset ); while ( offset < m_buf.limit() ) { if ( !readDirectoryEntry( offset, dir ) ) break; offset = m_buf.position(); } } /** * Read the metadata from a single directory entry. * * @param offset The offset from the beginning of the file of the * directory entry. * @param dir The metadata is put here. * @return Returns <code>true</code> only if the entry was read * successfully. */ private boolean readDirectoryEntry( int offset, ImageMetadataDirectory dir ) throws IOException { m_buf.position( offset ); if ( m_buf.remaining() < IPTC_ENTRY_HEADER_SIZE ) { // // There needs to be at least 5 bytes remaining for a tag. // return false; } if ( m_buf.get() != IPTC_TAG_START_BYTE ) return false; final int tagID = m_buf.getUnsignedShort(); int byteCount = m_buf.getUnsignedShort(); if ( (byteCount & 0x8000) != 0 ) { // // Handle the "Extended DataSet Tag." // int byteCountLength = byteCount & 0x7FFF; byteCount = 0; while ( byteCountLength-- > 0 ) byteCount = (byteCount << 8) | m_buf.getUnsignedByte(); } if ( byteCount > m_buf.remaining() ) { logBadImageMetadata(); return false; } final ImageMetaValue value = readValue( dir, tagID, byteCount ); if ( value != null ) try { dir.putValue( tagID, value ); } catch ( IllegalArgumentException e ) { logBadImageMetadata(); } return true; } /** * Read a value (or values) for a given IPTC tag. * * @param dir The {@link ImageMetadataDirectory} to read a value for. * @param tagID The ID of the tag that &quot;owns&quot; this value. * @param byteCount The number of bytes in the value. */ private ImageMetaValue readValue( ImageMetadataDirectory dir, int tagID, int byteCount ) throws IOException { switch ( tagID ) { case IPTC_RECORD_VERSION: final short value = (short)(m_buf.get() << 8 | m_buf.get()); return new UnsignedShortMetaValue( value ); case IPTC_URGENCY: return new UnsignedByteMetaValue( m_buf.get() ); case IPTC_DATE_CREATED: case IPTC_DATE_SENT: case IPTC_DIGITAL_CREATION_DATE: case IPTC_EXPIRATION_DATE: case IPTC_RELEASE_DATE: if ( byteCount >= IPTC_DATE_SIZE ) { final String s = m_buf.getString( byteCount, "UTF-8" ); return new DateMetaValue( s ); } break; case IPTC_DIGITAL_CREATION_TIME: case IPTC_EXPIRATION_TIME: case IPTC_RELEASE_TIME: case IPTC_TIME_CREATED: case IPTC_TIME_SENT: // no break; default: if ( byteCount < 1 ) break; String c = "ISO-8859-1"; final ImageMetaValue oldCharset = dir.getValue( IPTC_CODED_CHARACTER_SET ); if ( oldCharset != null ) { byte[] utf8 = {0x1B, 0x25, 0x47}; // ESC, "%", "G" if ( oldCharset.getStringValue().getBytes() == utf8 ) c = "UTF-8"; } String s = m_buf.getString( byteCount, c ); final int nullByte = s.indexOf( '\0' ); if ( nullByte >= 0 ) { s = s.substring( 0, nullByte ); if ( s.length() == 0 ) break; } final ImageMetaValue oldValue = dir.getValue( tagID ); if ( oldValue == null ) return new StringMetaValue( s ); final boolean old = oldValue.setIsChangeable( true ); oldValue.appendValue( s ); oldValue.setIsChangeable( old ); return oldValue; } return null; } /** * The type of image we're parsing IPTC metadata from. */ private final ImageType m_fromType; private int m_iptcStartPos; private int m_iptcLength; } /* vim:set et sw=4 ts=4: */
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.10.21 at 11:22:17 AM HST // package org.w3._2005.atom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; /** * * The Atom source construct is defined in section 4.2.11 of the format spec. * * * <p>Java class for sourceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="sourceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded"> * &lt;element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="generator" type="{http://www.w3.org/2005/Atom}generatorType" minOccurs="0"/> * &lt;element name="icon" type="{http://www.w3.org/2005/Atom}iconType" minOccurs="0"/> * &lt;element name="id" type="{http://www.w3.org/2005/Atom}idType" minOccurs="0"/> * &lt;element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="logo" type="{http://www.w3.org/2005/Atom}logoType" minOccurs="0"/> * &lt;element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/> * &lt;element name="subtitle" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/> * &lt;element name="title" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/> * &lt;element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType" minOccurs="0"/> * &lt;any namespace='##other' maxOccurs="unbounded" minOccurs="0"/> * &lt;/choice> * &lt;attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/> * &lt;anyAttribute namespace='##other'/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sourceType", propOrder = { "authorOrCategoryOrContributor" }) public class SourceType { @XmlElementRefs({ @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false), @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false) }) @XmlAnyElement(lax = true) protected List<Object> authorOrCategoryOrContributor; @XmlAttribute(name = "base", namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the authorOrCategoryOrContributor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the authorOrCategoryOrContributor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAuthorOrCategoryOrContributor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link CategoryType }{@code >} * {@link JAXBElement }{@code <}{@link LogoType }{@code >} * {@link JAXBElement }{@code <}{@link TextType }{@code >} * {@link JAXBElement }{@code <}{@link PersonType }{@code >} * {@link JAXBElement }{@code <}{@link IconType }{@code >} * {@link JAXBElement }{@code <}{@link LinkType }{@code >} * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} * {@link Object } * {@link JAXBElement }{@code <}{@link PersonType }{@code >} * {@link JAXBElement }{@code <}{@link IdType }{@code >} * {@link JAXBElement }{@code <}{@link GeneratorType }{@code >} * {@link JAXBElement }{@code <}{@link TextType }{@code >} * {@link JAXBElement }{@code <}{@link TextType }{@code >} * * */ public List<Object> getAuthorOrCategoryOrContributor() { if (authorOrCategoryOrContributor == null) { authorOrCategoryOrContributor = new ArrayList<Object>(); } return this.authorOrCategoryOrContributor; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
package com.elytradev.correlated.inventory; import java.util.List; import com.elytradev.correlated.item.ItemDrive; import com.elytradev.correlated.item.ItemDrive.PartitioningMode; import com.elytradev.correlated.item.ItemDrive.Priority; import com.elytradev.correlated.storage.NetworkType; import com.google.common.collect.Lists; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ClickType; import net.minecraft.inventory.Container; import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerDrive extends Container { public class SlotFake extends Slot { public SlotFake(int index, int xPosition, int yPosition) { super(null, index, xPosition, yPosition); } private ItemStack stack = ItemStack.EMPTY; @Override public ItemStack getStack() { return stack; } @Override public void putStack(ItemStack stack) { this.stack = stack; onSlotChanged(); } @Override public ItemStack decrStackSize(int amount) { ItemStack split = stack.splitStack(amount); onSlotChanged(); return split; } @Override public int getItemStackLimit(ItemStack stack) { return 1; } @Override public boolean isHere(IInventory inv, int slotIn) { return false; } @Override public boolean isEnabled() { return true; } @Override public boolean canTakeStack(EntityPlayer playerIn) { return false; } @Override public boolean isItemValid(ItemStack stack) { for (ItemStack s : prototypes) { if (ItemStack.areItemsEqual(s, stack) && ItemStack.areItemStackTagsEqual(s, stack)) { return false; } } return getItemDrive().getKilobitsFree(getDrive()) >= getItemDrive().getTypeAllocationKilobits(getDrive(), stack.serializeNBT()); } @Override public void onSlotChanged() { getItemDrive().markDirty(getDrive()); } } private final EntityPlayer player; private List<ItemStack> prototypes; private ContainerTerminal ct; private int oldX; private int oldY; public ContainerDrive(ContainerTerminal ct, IInventory playerInventory, EntityPlayer player) { this.ct = ct; this.player = player; oldX = ct.maintenanceSlot.xPos; oldY = ct.maintenanceSlot.yPos; ct.maintenanceSlot.xPos = -2000; ct.maintenanceSlot.yPos = -2000; addSlotToContainer(ct.maintenanceSlot); for (int i = 0; i < 64; i++) { SlotFake slot = new SlotFake(i, (((i % 11)*18)+8)+(i > 54 ? 18 : 0), ((i/11)*18)+18); addSlotToContainer(slot); } updateSlots(); int x = 26; int y = 37; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { addSlotToContainer(new Slot(playerInventory, j + i * 9 + 8, x + j * 18, 103 + i * 18 + y)); } } for (int i = 0; i < 9; ++i) { addSlotToContainer(new Slot(playerInventory, i, x + i * 18, 161 + y)); } } public void updateSlots() { prototypes = getItemDrive().getPartitioningMode(getDrive()) == PartitioningMode.BLACKLIST ? getItemDrive().getBlacklistedTypes(getDrive()) : Lists.transform(getItemDrive().getPrototypes(getDrive()), NetworkType::getStack); for (int i = 1; i < 65; i++) { Slot slot = inventorySlots.get(i); if (slot instanceof SlotFake) { if (slot.getSlotIndex() < prototypes.size()) { ItemStack stack = prototypes.get(slot.getSlotIndex()); stack.setCount(1); slot.putStack(stack); } else { slot.putStack(ItemStack.EMPTY); } } } } @Override public boolean enchantItem(EntityPlayer playerIn, int id) { if (id == 0 || id == 1) { Priority[] values = Priority.values(); Priority cur = getItemDrive().getPriority(getDrive()); int idx = (cur.ordinal()+(id == 0 ? -1 : 1))%values.length; if (idx < 0) { idx = values.length+idx; } Priority nxt = values[idx]; getItemDrive().setPriority(getDrive(), nxt); } else if (id == 2) { PartitioningMode[] values = PartitioningMode.values(); PartitioningMode cur = getItemDrive().getPartitioningMode(getDrive()); int idx = (cur.ordinal()+1)%values.length; PartitioningMode nxt = values[idx]; getItemDrive().setPartitioningMode(getDrive(), nxt); updateSlots(); } else if (id == 3) { ct.maintenanceSlot.xPos = oldX; ct.maintenanceSlot.yPos = oldY; player.openContainer = ct; } return true; } @Override public void onContainerClosed(EntityPlayer playerIn) { super.onContainerClosed(playerIn); ct.maintenanceSlot.xPos = oldX; ct.maintenanceSlot.yPos = oldY; } @Override public void updateProgressBar(int id, int data) { } @Override public void addListener(IContainerListener listener) { super.addListener(listener); } @Override public ItemStack slotClick(int slotId, int dragType, ClickType clickTypeIn, EntityPlayer player) { if (clickTypeIn == ClickType.QUICK_CRAFT) return player.inventory.getItemStack(); if (slotId >= 1) { Slot slot = getSlot(slotId); if (slot instanceof SlotFake) { if (clickTypeIn == ClickType.PICKUP) { if (slot.getHasStack()) { int stored = getItemDrive().getAmountStored(getDrive(), slot.getStack()); if (stored <= 0) { getItemDrive().deallocateType(getDrive(), slot.getStack()); updateSlots(); } return ItemStack.EMPTY; } else { ItemStack cursor = player.inventory.getItemStack(); if (getItemDrive().getPartitioningMode(getDrive()) == PartitioningMode.NONE) return cursor; if (cursor != null) { if (slot.isItemValid(cursor)) { if (cursor != getDrive()) { if (getItemDrive().getPartitioningMode(getDrive()) == PartitioningMode.BLACKLIST) { int stored = getItemDrive().getAmountStored(getDrive(), cursor); if (stored <= 0) { getItemDrive().blacklistType(getDrive(), cursor); updateSlots(); } } else { getItemDrive().allocateType(getDrive(), cursor, 0); updateSlots(); } } } } return cursor; } } } else if (clickTypeIn == ClickType.QUICK_MOVE) { ItemStack stack = slot.getStack(); if (getItemDrive().getPartitioningMode(getDrive()) == PartitioningMode.NONE) return stack; if (getSlot(1).isItemValid(stack)) { if (stack != getDrive()) { if (getItemDrive().getPartitioningMode(getDrive()) == PartitioningMode.BLACKLIST) { int stored = getItemDrive().getAmountStored(getDrive(), stack); if (stored <= 0) { getItemDrive().blacklistType(getDrive(), stack); updateSlots(); } } else { getItemDrive().allocateType(getDrive(), stack, 0); updateSlots(); } } } return stack; } } return super.slotClick(slotId, dragType, clickTypeIn, player); } public ItemStack getDrive() { return ct.maintenanceSlot.getStack(); } public ItemDrive getItemDrive() { return (ItemDrive)getDrive().getItem(); } @Override public boolean canInteractWith(EntityPlayer playerIn) { return playerIn == player; } }
/* * Copyright (c) 2008-2014 MongoDB, 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.mongodb; import org.bson.util.annotations.ThreadSafe; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.String.format; import static java.util.concurrent.TimeUnit.MILLISECONDS; @ThreadSafe class ServerStateNotifier implements Runnable { private static final Logger LOGGER = Loggers.getLogger("cluster"); private ServerAddress serverAddress; private final ChangeListener<ServerDescription> serverStateListener; private final SocketSettings socketSettings; private final Mongo mongo; private int count; private long elapsedNanosSum; private volatile ServerDescription serverDescription; private volatile boolean isClosed; DBPort connection; ServerStateNotifier(final ServerAddress serverAddress, final ChangeListener<ServerDescription> serverStateListener, final SocketSettings socketSettings, final Mongo mongo) { this.serverAddress = serverAddress; this.serverStateListener = serverStateListener; this.socketSettings = socketSettings; this.mongo = mongo; serverDescription = getConnectingServerDescription(); } @Override @SuppressWarnings("unchecked") public synchronized void run() { if (isClosed) { return; } final ServerDescription currentServerDescription = serverDescription; Throwable throwable = null; try { if (connection == null) { connection = new DBPort(serverAddress, null, getOptions(), 0); } try { LOGGER.fine(format("Checking status of %s", serverAddress)); long startNanoTime = System.nanoTime(); final CommandResult isMasterResult = connection.runCommand(mongo.getDB("admin"), new BasicDBObject("ismaster", 1)); count++; elapsedNanosSum += System.nanoTime() - startNanoTime; final CommandResult buildInfoResult = connection.runCommand(mongo.getDB("admin"), new BasicDBObject("buildinfo", 1)); serverDescription = createDescription(isMasterResult, buildInfoResult, elapsedNanosSum / count); } catch (IOException e) { if (!isClosed) { connection.close(); connection = null; count = 0; elapsedNanosSum = 0; throw e; } } } catch (Throwable t) { throwable = t; serverDescription = getUnconnectedServerDescription(); } if (!isClosed) { try { // Note that the ServerDescription.equals method does not include the average ping time as part of the comparison, // so this will not spam the logs too hard. if (!currentServerDescription.equals(serverDescription)) { if (throwable != null) { LOGGER.log(Level.INFO, format("Exception in monitor thread while connecting to server %s", serverAddress), throwable); } else { LOGGER.info(format("Monitor thread successfully connected to server with description %s", serverDescription)); } } serverStateListener.stateChanged(new ChangeEvent<ServerDescription>(currentServerDescription, serverDescription)); } catch (Throwable t) { LOGGER.log(Level.WARNING, "Exception in monitor thread during notification of server description state change", t); } } } public void close() { isClosed = true; if (connection != null) { connection.close(); connection = null; } } private MongoOptions getOptions() { MongoOptions options = new MongoOptions(); options.setConnectTimeout(socketSettings.getConnectTimeout(MILLISECONDS)); options.setSocketTimeout(socketSettings.getReadTimeout(MILLISECONDS)); options.setSocketFactory(socketSettings.getSocketFactory()); return options; } @SuppressWarnings("unchecked") private ServerDescription createDescription(final CommandResult commandResult, final CommandResult buildInfoResult, final long averagePingTimeNanos) { return ServerDescription.builder() .state(ServerConnectionState.Connected) .version(getVersion(buildInfoResult)) .address(commandResult.getServerUsed()) .type(getServerType(commandResult)) .hosts(listToSet((List<String>) commandResult.get("hosts"))) .passives(listToSet((List<String>) commandResult.get("passives"))) .arbiters(listToSet((List<String>) commandResult.get("arbiters"))) .primary(commandResult.getString("primary")) .maxDocumentSize(commandResult.getInt("maxBsonObjectSize", ServerDescription.getDefaultMaxDocumentSize())) .maxMessageSize(commandResult.getInt("maxMessageSizeBytes", ServerDescription.getDefaultMaxMessageSize())) .maxWriteBatchSize(commandResult.getInt("maxWriteBatchSize", ServerDescription.getDefaultMaxWriteBatchSize())) .tags(getTagsFromDocument((DBObject) commandResult.get("tags"))) .setName(commandResult.getString("setName")) .setVersion((Integer) commandResult.get("setVersion")) .minWireVersion(commandResult.getInt("minWireVersion", ServerDescription.getDefaultMinWireVersion())) .maxWireVersion(commandResult.getInt("maxWireVersion", ServerDescription.getDefaultMaxWireVersion())) .averagePingTime(averagePingTimeNanos, TimeUnit.NANOSECONDS) .ok(commandResult.ok()).build(); } @SuppressWarnings("unchecked") private static ServerVersion getVersion(final CommandResult buildInfoResult) { return new ServerVersion(((List<Integer>) buildInfoResult.get("versionArray")).subList(0, 3)); } private Set<String> listToSet(final List<String> list) { if (list == null || list.isEmpty()) { return Collections.emptySet(); } else { return new HashSet<String>(list); } } private static ServerType getServerType(final BasicDBObject isMasterResult) { if (isReplicaSetMember(isMasterResult)) { if (isMasterResult.getBoolean("ismaster", false)) { return ServerType.ReplicaSetPrimary; } if (isMasterResult.getBoolean("secondary", false)) { return ServerType.ReplicaSetSecondary; } if (isMasterResult.getBoolean("arbiterOnly", false)) { return ServerType.ReplicaSetArbiter; } return ServerType.ReplicaSetOther; } if (isMasterResult.containsKey("msg") && isMasterResult.get("msg").equals("isdbgrid")) { return ServerType.ShardRouter; } return ServerType.StandAlone; } private static boolean isReplicaSetMember(final BasicDBObject isMasterResult) { return isMasterResult.containsKey("setName") || isMasterResult.getBoolean("isreplicaset", false); } private static Tags getTagsFromDocument(final DBObject tagsDocuments) { if (tagsDocuments == null) { return new Tags(); } final Tags tags = new Tags(); for (final String key : tagsDocuments.keySet()) { tags.put(key, tagsDocuments.get(key).toString()); } return tags; } private ServerDescription getConnectingServerDescription() { return ServerDescription.builder().type(ServerType.Unknown).state(ServerConnectionState.Connecting).address(serverAddress).build(); } private ServerDescription getUnconnectedServerDescription() { return ServerDescription.builder().type(ServerType.Unknown).state(ServerConnectionState.Unconnected).address(serverAddress).build(); } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.test.api.runtime; import java.util.List; import org.camunda.bpm.engine.ProcessEngineConfiguration; import org.camunda.bpm.engine.history.HistoricActivityInstance; import org.camunda.bpm.engine.history.HistoricDetail; import org.camunda.bpm.engine.history.HistoricProcessInstance; import org.camunda.bpm.engine.history.HistoricVariableInstance; import org.camunda.bpm.engine.history.HistoricVariableUpdate; import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; import org.camunda.bpm.engine.runtime.ActivityInstance; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.RequiredHistoryLevel; /** * @author Thorben Lindhauer * */ @RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_FULL) public class ProcessInstantiationAtActivitiesHistoryTest extends PluggableProcessEngineTestCase { protected static final String PARALLEL_GATEWAY_PROCESS = "org/camunda/bpm/engine/test/api/runtime/ProcessInstanceModificationTest.parallelGateway.bpmn20.xml"; protected static final String EXCLUSIVE_GATEWAY_PROCESS = "org/camunda/bpm/engine/test/api/runtime/ProcessInstanceModificationTest.exclusiveGateway.bpmn20.xml"; protected static final String SUBPROCESS_PROCESS = "org/camunda/bpm/engine/test/api/runtime/ProcessInstanceModificationTest.subprocess.bpmn20.xml"; protected static final String ASYNC_PROCESS = "org/camunda/bpm/engine/test/api/runtime/ProcessInstanceModificationTest.exclusiveGatewayAsyncTask.bpmn20.xml"; @Deployment(resources = EXCLUSIVE_GATEWAY_PROCESS) public void testHistoricProcessInstanceForSingleActivityInstantiation() { // when ProcessInstance instance = runtimeService .createProcessInstanceByKey("exclusiveGateway") .startBeforeActivity("task1") .execute(); // then HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery().singleResult(); assertNotNull(historicInstance); assertEquals(instance.getId(), historicInstance.getId()); assertNotNull(historicInstance.getStartTime()); assertNull(historicInstance.getEndTime()); // should be the first activity started assertEquals("task1", historicInstance.getStartActivityId()); HistoricActivityInstance historicActivityInstance = historyService.createHistoricActivityInstanceQuery().singleResult(); assertNotNull(historicActivityInstance); assertEquals("task1", historicActivityInstance.getActivityId()); assertNotNull(historicActivityInstance.getId()); assertFalse(instance.getId().equals(historicActivityInstance.getId())); assertNotNull(historicActivityInstance.getStartTime()); assertNull(historicActivityInstance.getEndTime()); } @Deployment(resources = SUBPROCESS_PROCESS) public void testHistoricActivityInstancesForSubprocess() { // when ProcessInstance instance = runtimeService .createProcessInstanceByKey("subprocess") .startBeforeActivity("innerTask") .startBeforeActivity("theSubProcessStart") .execute(); // then HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery().singleResult(); assertNotNull(historicInstance); assertEquals(instance.getId(), historicInstance.getId()); assertNotNull(historicInstance.getStartTime()); assertNull(historicInstance.getEndTime()); // should be the first activity started assertEquals("innerTask", historicInstance.getStartActivityId()); // subprocess, subprocess start event, two innerTasks assertEquals(4, historyService.createHistoricActivityInstanceQuery().count()); HistoricActivityInstance subProcessInstance = historyService.createHistoricActivityInstanceQuery() .activityId("subProcess").singleResult(); assertNotNull(subProcessInstance); assertEquals("subProcess", subProcessInstance.getActivityId()); assertNotNull(subProcessInstance.getId()); assertFalse(instance.getId().equals(subProcessInstance.getId())); assertNotNull(subProcessInstance.getStartTime()); assertNull(subProcessInstance.getEndTime()); HistoricActivityInstance startEventInstance = historyService.createHistoricActivityInstanceQuery() .activityId("theSubProcessStart").singleResult(); assertNotNull(startEventInstance); assertEquals("theSubProcessStart", startEventInstance.getActivityId()); assertNotNull(startEventInstance.getId()); assertFalse(instance.getId().equals(startEventInstance.getId())); assertNotNull(startEventInstance.getStartTime()); assertNotNull(startEventInstance.getEndTime()); List<HistoricActivityInstance> innerTaskInstances = historyService.createHistoricActivityInstanceQuery() .activityId("innerTask").list(); assertEquals(2, innerTaskInstances.size()); for (HistoricActivityInstance innerTaskInstance : innerTaskInstances) { assertNotNull(innerTaskInstance); assertEquals("innerTask", innerTaskInstance.getActivityId()); assertNotNull(innerTaskInstance.getId()); assertFalse(instance.getId().equals(innerTaskInstance.getId())); assertNotNull(innerTaskInstance.getStartTime()); assertNull(innerTaskInstance.getEndTime()); } } @Deployment(resources = ASYNC_PROCESS) public void testHistoricProcessInstanceAsyncStartEvent() { // when ProcessInstance instance = runtimeService .createProcessInstanceByKey("exclusiveGateway") .startBeforeActivity("task2") .setVariable("aVar", "aValue") .execute(); // then HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery().singleResult(); assertNotNull(historicInstance); assertEquals(instance.getId(), historicInstance.getId()); assertNotNull(historicInstance.getStartTime()); assertNull(historicInstance.getEndTime()); // should be the first activity started assertEquals("task2", historicInstance.getStartActivityId()); // task2 wasn't entered yet assertEquals(0, historyService.createHistoricActivityInstanceQuery().count()); // history events for variables exist already ActivityInstance activityInstance = runtimeService.getActivityInstance(instance.getId()); HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery() .variableName("aVar") .singleResult(); assertNotNull(historicVariable); assertEquals(instance.getId(), historicVariable.getProcessInstanceId()); assertEquals(activityInstance.getId(), historicVariable.getActivityInstanceId()); assertEquals("aVar", historicVariable.getName()); assertEquals("aValue", historicVariable.getValue()); HistoricDetail historicDetail = historyService.createHistoricDetailQuery() .variableInstanceId(historicVariable.getId()).singleResult(); assertEquals(instance.getId(), historicDetail.getProcessInstanceId()); assertNotNull(historicDetail); // TODO: fix if this is not ok due to CAM-3886 assertNull(historicDetail.getActivityInstanceId()); assertTrue(historicDetail instanceof HistoricVariableUpdate); assertEquals("aVar", ((HistoricVariableUpdate) historicDetail).getVariableName()); assertEquals("aValue", ((HistoricVariableUpdate) historicDetail).getValue()); } @Deployment(resources = EXCLUSIVE_GATEWAY_PROCESS) public void testHistoricVariableInstanceForSingleActivityInstantiation() { // when ProcessInstance instance = runtimeService .createProcessInstanceByKey("exclusiveGateway") .startBeforeActivity("task1") .setVariable("aVar", "aValue") .execute(); ActivityInstance activityInstance = runtimeService.getActivityInstance(instance.getId()); // then HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery() .variableName("aVar") .singleResult(); assertNotNull(historicVariable); assertEquals(instance.getId(), historicVariable.getProcessInstanceId()); assertEquals(activityInstance.getId(), historicVariable.getActivityInstanceId()); assertEquals("aVar", historicVariable.getName()); assertEquals("aValue", historicVariable.getValue()); HistoricDetail historicDetail = historyService.createHistoricDetailQuery() .variableInstanceId(historicVariable.getId()).singleResult(); assertEquals(instance.getId(), historicDetail.getProcessInstanceId()); assertNotNull(historicDetail); // TODO: fix if this is not ok due to CAM-3886 assertNull(historicDetail.getActivityInstanceId()); assertTrue(historicDetail instanceof HistoricVariableUpdate); assertEquals("aVar", ((HistoricVariableUpdate) historicDetail).getVariableName()); assertEquals("aValue", ((HistoricVariableUpdate) historicDetail).getValue()); } @Deployment(resources = EXCLUSIVE_GATEWAY_PROCESS) public void testHistoricVariableInstanceSetOnProcessInstance() { // when ProcessInstance instance = runtimeService .createProcessInstanceByKey("exclusiveGateway") // set the variables directly one the instance .setVariable("aVar", "aValue") .startBeforeActivity("task1") .execute(); ActivityInstance activityInstance = runtimeService.getActivityInstance(instance.getId()); // then HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery() .variableName("aVar") .singleResult(); assertNotNull(historicVariable); assertEquals(instance.getId(), historicVariable.getProcessInstanceId()); assertEquals(activityInstance.getId(), historicVariable.getActivityInstanceId()); assertEquals("aVar", historicVariable.getName()); assertEquals("aValue", historicVariable.getValue()); HistoricDetail historicDetail = historyService.createHistoricDetailQuery() .variableInstanceId(historicVariable.getId()).singleResult(); assertEquals(instance.getId(), historicDetail.getProcessInstanceId()); assertNotNull(historicDetail); // TODO: fix if this is not ok due to CAM-3886 assertEquals(instance.getId(), historicDetail.getActivityInstanceId()); assertTrue(historicDetail instanceof HistoricVariableUpdate); assertEquals("aVar", ((HistoricVariableUpdate) historicDetail).getVariableName()); assertEquals("aValue", ((HistoricVariableUpdate) historicDetail).getValue()); } @Deployment(resources = EXCLUSIVE_GATEWAY_PROCESS) public void testHistoricProcessInstanceForSynchronousCompletion() { // when the process instance ends immediately ProcessInstance instance = runtimeService .createProcessInstanceByKey("exclusiveGateway") .startAfterActivity("task1") .execute(); // then HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery().singleResult(); assertNotNull(historicInstance); assertEquals(instance.getId(), historicInstance.getId()); assertNotNull(historicInstance.getStartTime()); assertNotNull(historicInstance.getEndTime()); assertEquals("join", historicInstance.getStartActivityId()); } @Deployment(resources = EXCLUSIVE_GATEWAY_PROCESS) public void testSkipCustomListenerEnsureHistoryWritten() { // when creating the task skipping custom listeners runtimeService.createProcessInstanceByKey("exclusiveGateway") .startBeforeActivity("task2") .execute(true, false); // then the task assignment history (which uses a task listener) is written Task task = taskService.createTaskQuery().taskDefinitionKey("task2").singleResult(); HistoricActivityInstance instance = historyService .createHistoricActivityInstanceQuery() .activityId("task2") .singleResult(); assertNotNull(instance); assertEquals(task.getId(), instance.getTaskId()); assertEquals("kermit", instance.getAssignee()); } protected void completeTasksInOrder(String... taskNames) { for (String taskName : taskNames) { // complete any task with that name List<Task> tasks = taskService.createTaskQuery().taskDefinitionKey(taskName).listPage(0, 1); assertTrue("task for activity " + taskName + " does not exist", !tasks.isEmpty()); taskService.complete(tasks.get(0).getId()); } } }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.shield.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/ListAttacks" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListAttacksRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> */ private java.util.List<String> resourceArns; /** * <p> * The time period for the attacks. * </p> */ private TimeRange startTime; /** * <p> * The end of the time period for the attacks. * </p> */ private TimeRange endTime; /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> */ private String nextToken; /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> */ private Integer maxResults; /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * * @return The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. */ public java.util.List<String> getResourceArns() { return resourceArns; } /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * * @param resourceArns * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. */ public void setResourceArns(java.util.Collection<String> resourceArns) { if (resourceArns == null) { this.resourceArns = null; return; } this.resourceArns = new java.util.ArrayList<String>(resourceArns); } /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setResourceArns(java.util.Collection)} or {@link #withResourceArns(java.util.Collection)} if you want to * override the existing values. * </p> * * @param resourceArns * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withResourceArns(String... resourceArns) { if (this.resourceArns == null) { setResourceArns(new java.util.ArrayList<String>(resourceArns.length)); } for (String ele : resourceArns) { this.resourceArns.add(ele); } return this; } /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * * @param resourceArns * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withResourceArns(java.util.Collection<String> resourceArns) { setResourceArns(resourceArns); return this; } /** * <p> * The time period for the attacks. * </p> * * @param startTime * The time period for the attacks. */ public void setStartTime(TimeRange startTime) { this.startTime = startTime; } /** * <p> * The time period for the attacks. * </p> * * @return The time period for the attacks. */ public TimeRange getStartTime() { return this.startTime; } /** * <p> * The time period for the attacks. * </p> * * @param startTime * The time period for the attacks. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withStartTime(TimeRange startTime) { setStartTime(startTime); return this; } /** * <p> * The end of the time period for the attacks. * </p> * * @param endTime * The end of the time period for the attacks. */ public void setEndTime(TimeRange endTime) { this.endTime = endTime; } /** * <p> * The end of the time period for the attacks. * </p> * * @return The end of the time period for the attacks. */ public TimeRange getEndTime() { return this.endTime; } /** * <p> * The end of the time period for the attacks. * </p> * * @param endTime * The end of the time period for the attacks. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withEndTime(TimeRange endTime) { setEndTime(endTime); return this; } /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> * * @param nextToken * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to * <code>ListAttacksRequest</code>. Pass null if this is the first call. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> * * @return The <code>ListAttacksRequest.NextMarker</code> value from a previous call to * <code>ListAttacksRequest</code>. Pass null if this is the first call. */ public String getNextToken() { return this.nextToken; } /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> * * @param nextToken * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to * <code>ListAttacksRequest</code>. Pass null if this is the first call. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> * * @param maxResults * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 * results will be returned. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> * * @return The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 * results will be returned. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> * * @param maxResults * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 * results will be returned. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourceArns() != null) sb.append("ResourceArns: ").append(getResourceArns()).append(","); if (getStartTime() != null) sb.append("StartTime: ").append(getStartTime()).append(","); if (getEndTime() != null) sb.append("EndTime: ").append(getEndTime()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListAttacksRequest == false) return false; ListAttacksRequest other = (ListAttacksRequest) obj; if (other.getResourceArns() == null ^ this.getResourceArns() == null) return false; if (other.getResourceArns() != null && other.getResourceArns().equals(this.getResourceArns()) == false) return false; if (other.getStartTime() == null ^ this.getStartTime() == null) return false; if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false) return false; if (other.getEndTime() == null ^ this.getEndTime() == null) return false; if (other.getEndTime() != null && other.getEndTime().equals(this.getEndTime()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourceArns() == null) ? 0 : getResourceArns().hashCode()); hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode()); hashCode = prime * hashCode + ((getEndTime() == null) ? 0 : getEndTime().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); return hashCode; } @Override public ListAttacksRequest clone() { return (ListAttacksRequest) super.clone(); } }
/* * Copyright 2010 - 2012 Ed Venaglia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.venaglia.nondairy; import static net.venaglia.nondairy.soylang.lexer.SoyToken.WHITESPACE_TOKENS; import com.intellij.lang.LanguageParserDefinitions; import com.intellij.lang.PsiBuilder; import com.intellij.openapi.extensions.Extensions; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import net.venaglia.nondairy.mocks.MockTreeNavigator; import net.venaglia.nondairy.soylang.SoyElement; import net.venaglia.nondairy.soylang.SoyLanguage; import net.venaglia.nondairy.soylang.SoyParserDefinition; import net.venaglia.nondairy.soylang.elements.TreeBuildingTokenSource; import net.venaglia.nondairy.soylang.elements.TreeNavigator; import net.venaglia.nondairy.soylang.elements.factory.SoyPsiElementFactory; import net.venaglia.nondairy.soylang.elements.path.PsiElementPath; import net.venaglia.nondairy.soylang.lexer.SoyScannerTest; import net.venaglia.nondairy.soylang.lexer.SoySymbol; import net.venaglia.nondairy.soylang.lexer.TestableSoyScanner; import net.venaglia.nondairy.soylang.parser.SoyStructureParser; import net.venaglia.nondairy.util.SourceTuple; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; /** * Created by IntelliJ IDEA. * User: ed * Date: Jul 21, 2010 * Time: 7:25:22 PM */ @NonNls @SuppressWarnings({ "HardCodedStringLiteral" }) public class SoyTestUtil { private static AtomicBoolean INITILAIZED = new AtomicBoolean(); static { init(); } public static void init() { if (!INITILAIZED.getAndSet(true)) { Extensions.registerAreaClass("IDEA_PROJECT", null); System.setProperty(TreeNavigator.OVERRIDE_TREE_NAVIGATOR_PROPERTY, MockTreeNavigator.class.getName()); LanguageParserDefinitions.INSTANCE.addExplicitExtension(SoyLanguage.INSTANCE, new SoyParserDefinition()); if (System.getProperty(PsiElementPath.TRACE_PATH_PROPERTY_NAME) == null) { System.setProperty(PsiElementPath.TRACE_PATH_PROPERTY_NAME, PsiElementPath.TRACE_PATH_BY_THREAD); } } } public static String fromSource(String source) { if (source == null || "null".equals(source)) return null; if (source.length() < 2 || source.charAt(0) != source.charAt(source.length() - 1) || "\"\'".indexOf(source.charAt(0)) == -1) { throw new IllegalArgumentException("Unable to parse string literal: " + source); } StringBuilder buffer = new StringBuilder(source.length()); for (int i = 0, j = source.length(); i < j; ++i) { char c = source.charAt(i); if (c == '\\' && i < j - 1) { c = source.charAt(++i); switch (c) { case '\\': case '\"': case '\'': buffer.append(c); break; case 'r': buffer.append('\r'); break; case 'n': buffer.append('\n'); break; case 't': buffer.append('\t'); break; case 'f': buffer.append('\f'); break; } } else { buffer.append(c); } } return buffer.toString(); } public static String toSource(String text) { if (text == null) return "null"; StringBuilder buffer = new StringBuilder(text.length() + 10); buffer.append("\""); for (int i = 0, j = text.length(); i < j; ++i) { char c = text.charAt(i); if (c > 127) { buffer.append(String.format("\\u%04x", (int)c)); } else if (c < 8) { buffer.append("\\").append((int)c); } else { switch (c) { case '\t': buffer.append("\\t"); break; case '\f': buffer.append("\\f"); break; case '\b': buffer.append("\\b"); break; case '\n': buffer.append("\\n"); break; case '\r': buffer.append("\\r"); break; case '\'': case '\"': case '\\': buffer.append("\\").append(c); break; default: buffer.append(c); break; } } } buffer.append("\""); return buffer.toString(); } public static String getTestSourceBuffer(String name) throws IOException { Reader in = new InputStreamReader(SoyTestUtil.class.getResourceAsStream("/testSources/" + name)); StringWriter out = new StringWriter(16384); char[] buffer = new char[4096]; for (int i = 0; i > -1; i = in.read(buffer)) { out.write(buffer, 0, i); } in.close(); return out.getBuffer().toString(); } public static PsiElement getPsiTreeFor(@NotNull @NonNls String name) { SourceTuple tuple = new SourceTuple(name); return tuple.psi; } public static PsiElement getPsiTreeFor(@NotNull PsiFile fileNode, @NotNull @NonNls String name) { return getPsiTreeImpl(fileNode, name, null); } public static PsiElement getPsiTreeFor(@NotNull PsiFile fileNode, @NotNull @NonNls String name, @NotNull @NonNls CharSequence source) { return getPsiTreeImpl(fileNode, name, source); } private static PsiElement getPsiTreeImpl(@NotNull PsiFile fileNode, @NotNull @NonNls String name, @Nullable @NonNls CharSequence source) { try { source = source == null ? getTestSourceBuffer(name) : source; TestableSoyScanner scanner = SoyScannerTest.buildScanner(source, "YYINITIAL"); Iterator<SoySymbol> iterator = new WhitespaceFilteringIterator(scanner.iterator()); TreeBuildingTokenSource tokenSource = new TreeBuildingTokenSource(source, iterator); PsiBuilder.Marker file = tokenSource.mark("_file_"); new SoyStructureParser(tokenSource).parse(); assertTrue(tokenSource.eof()); file.done(SoyElement.soy_file); return tokenSource.buildNode(fileNode, SoyPsiElementFactory.getInstance()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } private static class WhitespaceFilteringIterator implements Iterator<SoySymbol> { private final Iterator<SoySymbol> delegate; private SoySymbol next; private WhitespaceFilteringIterator(Iterator<SoySymbol> delegate) { this.delegate = delegate; next = seek(); } private SoySymbol seek() { while (delegate.hasNext()) { SoySymbol symbol = delegate.next(); if (symbol != null && !WHITESPACE_TOKENS.contains(symbol.getToken())) { return symbol; } } return null; } @Override public boolean hasNext() { return next != null; } @Override public SoySymbol next() { if (this.next == null) { throw new NoSuchElementException(); } SoySymbol next = this.next; this.next = seek(); return next; } @Override public void remove() { throw new UnsupportedOperationException(); } } /** * Produces a human readable, multi-line string, that describes the passed * element and its children as a tree. * @param element The element to be described. * @return A multi-line indented string, representing a tree structure. */ public static String print(PsiElement element) { StringWriter buffer = new StringWriter(4096); print(element, "", new AtomicInteger(), new PrintWriter(buffer)); return buffer.toString(); } private static void print(PsiElement element, String indent, AtomicInteger count, PrintWriter out) { count.getAndIncrement(); out.print(indent); out.println(element); PsiElement[] children = element.getChildren(); if (children.length > 0) { String childIndent = indent + " "; for (PsiElement child : children) { print(child, childIndent, count, out); } } } public static void main(String[] args) { PsiElement element = getPsiTreeFor("minimal.soy"); System.out.println(print(element)); } }
/* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2015 Adobe * %% * 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% */ package com.adobe.acs.commons.workflow.bulk.removal.impl; import com.adobe.acs.commons.workflow.bulk.removal.*; import com.adobe.granite.workflow.WorkflowException; import com.adobe.granite.workflow.WorkflowSession; import com.adobe.granite.workflow.exec.WorkItem; import com.adobe.granite.workflow.exec.Workflow; import com.adobe.granite.workflow.exec.filter.WorkItemFilter; import com.day.cq.workflow.WorkflowService; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.*; import org.apache.jackrabbit.JcrConstants; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.event.jobs.JobManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.Node; import javax.jcr.RepositoryException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; /** * ACS AEM Commons - Workflow Instance Remover */ @Component @Service public final class WorkflowInstanceRemoverImpl implements WorkflowInstanceRemover { private static final Logger log = LoggerFactory.getLogger(WorkflowInstanceRemoverImpl.class); private static final String WORKFLOW_FOLDER_FORMAT = "YYYY-MM-dd"; private static final String PN_MODEL_ID = "modelId"; private static final String PN_STARTED_AT = "startedAt"; private static final String PN_STATUS = "status"; private static final String PAYLOAD_PATH = "data/payload/path"; private static final String NT_SLING_FOLDER = "sling:Folder"; private static final String NT_CQ_WORKFLOW = "cq:Workflow"; private static final String JOB_SEPARATOR = "_,_"; private static final Pattern NN_SERVER_FOLDER_PATTERN = Pattern.compile("server\\d+"); private static final Pattern NN_DATE_FOLDER_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}.*"); private static final int BATCH_SIZE = 1000; private static final int MAX_SAVE_RETRIES = 5; private static final long MS_IN_ONE_MINUTE = 60000; private final AtomicReference<WorkflowRemovalStatus> status = new AtomicReference<WorkflowRemovalStatus>(); private final AtomicBoolean forceQuit = new AtomicBoolean(false); @Reference private JobManager jobManager; @Reference private WorkflowService workflowService; /** * {@inheritDoc} */ @Override public WorkflowRemovalStatus getStatus() { return this.status.get(); } /** * {@inheritDoc} */ @Override public void forceQuit() { this.forceQuit.set(true); } /** * {@inheritDoc} */ public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds, final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan) throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException { return removeWorkflowInstances(resourceResolver, modelIds, statuses, payloads, olderThan, BATCH_SIZE); } /** * {@inheritDoc} */ public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds, final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan, final int batchSize) throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException { return removeWorkflowInstances(resourceResolver, modelIds, statuses, payloads, olderThan, batchSize, -1); } /** * {@inheritDoc} */ public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds, final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan, final int batchSize, final int maxDurationInMins) throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException { final long start = System.currentTimeMillis(); long end = -1; int count = 0; int checkedCount = 0; int workflowRemovedCount = 0; if (maxDurationInMins > 0) { // Max duration has been requested (greater than 0) // Convert minutes to milliseconds long maxDurationInMs = maxDurationInMins * MS_IN_ONE_MINUTE; // Compute the end time end = start + maxDurationInMs; } try { this.start(resourceResolver); final List<Resource> containerFolders = this.getWorkflowInstanceFolders(resourceResolver); for (Resource containerFolder : containerFolders) { log.debug("Checking [ {} ] for workflow instances to remove", containerFolder.getPath()); final Collection<Resource> sortedFolders = this.getSortedAndFilteredFolders(containerFolder); for (final Resource folder : sortedFolders) { int remaining = 0; for (final Resource instance : folder.getChildren()) { if (this.forceQuit.get()) { throw new WorkflowRemovalForceQuitException(); } else if (end > 0 && System.currentTimeMillis() >= end) { throw new WorkflowRemovalMaxDurationExceededException(); } final ValueMap properties = instance.getValueMap(); if (!StringUtils.equals(NT_CQ_WORKFLOW, properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) { // Only process cq:Workflow's remaining++; continue; } checkedCount++; final String status = getStatus(instance); final String model = properties.get(PN_MODEL_ID, String.class); final Calendar startTime = properties.get(PN_STARTED_AT, Calendar.class); final String payload = properties.get(PAYLOAD_PATH, String.class); if (StringUtils.isBlank(payload)) { log.warn("Unable to find payload for Workflow instance [ {} ]", instance.getPath()); remaining++; continue; } else if (CollectionUtils.isNotEmpty(statuses) && !statuses.contains(status)) { log.trace("Workflow instance [ {} ] has non-matching status of [ {} ]", instance.getPath(), status); remaining++; continue; } else if (CollectionUtils.isNotEmpty(modelIds) && !modelIds.contains(model)) { log.trace("Workflow instance [ {} ] has non-matching model of [ {} ]", instance.getPath(), model); remaining++; continue; } else if (olderThan != null && startTime != null && startTime.before(olderThan)) { log.trace("Workflow instance [ {} ] has non-matching start time of [ {} ]", instance.getPath(), startTime); remaining++; continue; } else { if (CollectionUtils.isNotEmpty(payloads)) { // Only evaluate payload patterns if they are provided boolean match = false; if (StringUtils.isNotEmpty(payload)) { for (final Pattern pattern : payloads) { if (payload.matches(pattern.pattern())) { // payload matches a pattern match = true; break; } } if (!match) { // Not a match; skip to next workflow instance log.trace("Workflow instance [ {} ] has non-matching payload path [ {} ]", instance.getPath(), payload); remaining++; continue; } } } // Only remove matching try { instance.adaptTo(Node.class).remove(); log.debug("Removed workflow instance at [ {} ]", instance.getPath()); workflowRemovedCount++; count++; } catch (RepositoryException e) { log.error("Could not remove workflow instance at [ {} ]. Continuing...", instance.getPath(), e); } if (count % batchSize == 0) { this.batchComplete(resourceResolver, checkedCount, workflowRemovedCount); log.info("Removed a running total of [ {} ] workflow instances", count); } } } if (remaining == 0 && isWorkflowDatedFolder(folder) && !StringUtils.startsWith(folder.getName(), new SimpleDateFormat(WORKFLOW_FOLDER_FORMAT).format(new Date()))) { // Dont remove folders w items and dont remove any of "today's" folders // MUST match the YYYY-MM-DD(.*) pattern; do not try to remove root folders try { folder.adaptTo(Node.class).remove(); log.debug("Removed empty workflow folder node [ {} ]", folder.getPath()); // Incrementing only count to trigger batch save and not total since is not a WF count++; } catch (RepositoryException e) { log.error("Could not remove workflow folder at [ {} ]", folder.getPath(), e); } } } // Save final batch if needed, and update tracking nodes this.complete(resourceResolver, checkedCount, workflowRemovedCount); } } catch (PersistenceException e) { this.forceQuit.set(false); log.error("Error persisting changes with Workflow Removal", e); this.error(resourceResolver); throw e; } catch (WorkflowRemovalException e) { this.forceQuit.set(false); log.error("Error with Workflow Removal", e); this.error(resourceResolver); throw e; } catch (InterruptedException e) { this.forceQuit.set(false); log.error("Errors in persistence retries during Workflow Removal", e); this.error(resourceResolver); throw e; } catch (WorkflowRemovalForceQuitException e) { this.forceQuit.set(false); // Uncommon instance of using Exception to control flow; Force quitting is an extreme condition. log.warn("Workflow removal was force quit. The removal state is unknown."); this.forceQuit(resourceResolver); throw e; } catch (WorkflowRemovalMaxDurationExceededException e) { // Uncommon instance of using Exception to control flow; Exceeding max duration extreme condition. log.warn("Workflow removal exceeded max duration of [ {} ] minutes. Final removal commit initiating...", maxDurationInMins); this.complete(resourceResolver, checkedCount, count); } if (log.isInfoEnabled()) { log.info("Workflow Removal Process Finished! " + "Removed a total of [ {} ] workflow instances in [ {} ] ms", count, System.currentTimeMillis() - start); } return count; } private Collection<Resource> getSortedAndFilteredFolders(Resource folderResource) { final Collection<Resource> sortedCollection = new TreeSet(new WorkflowInstanceFolderComparator()); for (Resource folder : folderResource.getChildren()) { // Only process sling:Folders; eg. skip rep:Policy, serverN folders if (folder.isResourceType(NT_SLING_FOLDER) && !isWorkflowServerFolder(folder)) { sortedCollection.add(folder); } } return sortedCollection; } private String getStatus(Resource workflowInstanceResource) { String status = workflowInstanceResource.getValueMap().get(PN_STATUS, "UNKNOWN"); if (!"RUNNING".equalsIgnoreCase(status)) { log.debug("Status of [ {} ] is not RUNNING, so we can take it at face value", status); return status; } // Else check if its RUNNING or STALE log.debug("Status is [ {} ] so we have to determine if its RUNNING or STALE", status); Resource metadataResource = workflowInstanceResource.getChild("data/metaData"); if (metadataResource == null) { log.debug("Workflow instance data/metaData does not exist for [ {} ]", workflowInstanceResource.getPath()); return status; } final ValueMap properties = metadataResource.getValueMap(); final String[] jobIds = StringUtils.splitByWholeSeparator(properties.get("currentJobs", ""), JOB_SEPARATOR); if (jobIds.length == 0) { log.debug("No jobs found for [ {} ] so assuming status as [ {} ]", workflowInstanceResource.getPath(), status); } // Make sure there are no JOBS that match to this jobs name for (final String jobId : jobIds) { if (jobManager.getJobById(jobId) != null) { // Found a job for this jobID; so this is a RUNNING job log.debug("JobManager found a job for jobId [ {} ] so marking workflow instances [ {} ] as RUNNING", jobId, workflowInstanceResource.getPath()); return "RUNNING"; } } log.debug("JobManager could not find any jobs for jobIds [ {} ] so workflow instance [ {} ] is potentially STALE", StringUtils.join(jobIds, ", "), workflowInstanceResource.getPath()); final WorkflowSession workflowSession = workflowInstanceResource.getResourceResolver().adaptTo(WorkflowSession.class); Workflow workflow = null; try { workflow = workflowSession.getWorkflow(workflowInstanceResource.getPath()); if (workflow == null) { throw new WorkflowException(String.format("Workflow instance object is null for [ %s]", workflowInstanceResource.getPath())); } } catch (WorkflowException e) { log.warn("Unable to locate Workflow Instance for [ {} ] So it cannot be RUNNING and must be STALE. ", workflowInstanceResource.getPath(), e); return "STALE"; } if (workflow != null) { final List<WorkItem> workItems = workflow.getWorkItems(new WorkItemFilter() { public boolean doInclude(WorkItem workItem) { // Only include active Workflow instances (ones without an End Time) in this list return workItem.getTimeEnded() == null; } }); if (!workItems.isEmpty()) { // If at least 1 work item exists that does not have an end time (meaning its still active), then its RUNNING return "RUNNING"; } } return "STALE"; } private void save(ResourceResolver resourceResolver) throws PersistenceException, InterruptedException { int count = 0; while (count++ <= MAX_SAVE_RETRIES) { try { if (resourceResolver.hasChanges()) { final long start = System.currentTimeMillis(); resourceResolver.commit(); log.debug("Saving batch workflow instance removal in [ {} ] ms", System.currentTimeMillis() - start); } // No changes or save did not error; return from loop return; } catch (PersistenceException ex) { if (count <= MAX_SAVE_RETRIES) { // If error occurred within bounds of retries, keep retrying resourceResolver.refresh(); log.warn("Could not persist Workflow Removal changes, trying again in {} ms", 1000 * count); Thread.sleep(1000 * count); } else { // If error occurred outside bounds of returns, throw the exception to exist this method throw ex; } } } } private void start(final ResourceResolver resourceResolver) throws PersistenceException, WorkflowRemovalException, InterruptedException { // Ensure forceQuit does not have a left-over value when starting a new run this.forceQuit.set(false); boolean running = false; WorkflowRemovalStatus localStatus = this.getStatus(); if(localStatus != null) { running = localStatus.isRunning(); } if (running) { log.warn("Unable to start workflow instance removal; Workflow removal already running."); throw new WorkflowRemovalException("Workflow removal already started by " + this.getStatus().getInitiatedBy()); } else { this.status.set(new WorkflowRemovalStatus(resourceResolver)); log.info("Starting workflow instance removal"); } } private void batchComplete(final ResourceResolver resourceResolver, final int checked, final int count) throws PersistenceException, InterruptedException { this.save(resourceResolver); WorkflowRemovalStatus status = this.status.get(); status.setChecked(checked); status.setRemoved(count); this.status.set(status); } private void complete(final ResourceResolver resourceResolver, final int checked, final int count) throws PersistenceException, InterruptedException { this.save(resourceResolver); WorkflowRemovalStatus status = this.status.get(); status.setRunning(false); status.setChecked(checked); status.setRemoved(count); status.setCompletedAt(Calendar.getInstance()); this.status.set(status); } private void error(final ResourceResolver resourceResolver) throws PersistenceException, InterruptedException { WorkflowRemovalStatus status = this.status.get(); status.setRunning(false); status.setErredAt(Calendar.getInstance()); this.status.set(status); } private void forceQuit(final ResourceResolver resourceResolver) { WorkflowRemovalStatus status = this.status.get(); status.setRunning(false); status.setForceQuitAt(Calendar.getInstance()); this.status.set(status); // Reset force quit flag this.forceQuit.set(false); } private List<Resource> getWorkflowInstanceFolders(final ResourceResolver resourceResolver) { final List<Resource> folders = new ArrayList<Resource>(); final Resource root = resourceResolver.getResource(WORKFLOW_INSTANCES_PATH); final Iterator<Resource> itr = root.listChildren(); boolean addedRoot = false; while (itr.hasNext()) { Resource resource = itr.next(); if (isWorkflowServerFolder(resource)) { folders.add(resource); } else if (!addedRoot && isWorkflowDatedFolder(resource)) { folders.add(root); addedRoot = true; } } if (folders.isEmpty()) { folders.add(root); } return folders; } private boolean isWorkflowDatedFolder(final Resource resource) { return NN_DATE_FOLDER_PATTERN.matcher(resource.getName()).matches(); } private boolean isWorkflowServerFolder(final Resource folder) { return NN_SERVER_FOLDER_PATTERN.matcher(folder.getName()).matches(); } @Activate @Deactivate protected void reset(Map<String, Object> config) { this.forceQuit.set(false); } }
package com.github.jreddit.retrieval; import static com.github.jreddit.utils.restclient.JsonUtils.safeJsonToString; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.LinkedList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.github.jreddit.entity.Kind; import com.github.jreddit.entity.Subreddit; import com.github.jreddit.entity.User; import com.github.jreddit.exception.RedditError; import com.github.jreddit.exception.RetrievalFailedException; import com.github.jreddit.retrieval.params.SubredditsView; import com.github.jreddit.utils.ApiEndpointUtils; import com.github.jreddit.utils.ParamFormatter; import com.github.jreddit.utils.restclient.RestClient; /** * This class offers the following functionality: * 1) Parsing the results of a request into Subreddit objects (see <code>Subreddits.parse()</code>). * 2) The ability to get listings of subreddits (see <code>Subreddits.get()</code>). * 3) The ability to search the subreddits (for subreddits) on Reddit (see <code>Subreddits.search()</code>). * * @author Benjamin Jakobus * @author Raul Rene Lepsa * @author Andrei Sfat * @author Simon Kassing */ public class Subreddits implements ActorDriven { /** * Handle to the REST client instance. */ private final RestClient restClient; private User user; /** * Constructor. * * @param restClient REST client instance */ public Subreddits(RestClient restClient) { this.restClient = restClient; } /** * Constructor. * @param restClient REST Client instance * @param actor User instance */ public Subreddits(RestClient restClient, User actor) { this.restClient = restClient; this.user = actor; } /** * Switch the current user for the new user who will * be used when invoking retrieval requests. * * @param new_actor New user */ public void switchActor(User new_actor) { this.user = new_actor; } /** * Parses a JSON feed from the Reddit (URL) into a nice list of Subreddit objects. * * @param user User * @param url URL * @return Listing of submissions */ public List<Subreddit> parse(String url) throws RetrievalFailedException, RedditError { // Determine cookie String cookie = (user == null) ? null : user.getCookie(); // List of subreddits List<Subreddit> subreddits = new LinkedList<Subreddit>(); // Send request to reddit server via REST client Object response = restClient.get(url, cookie).getResponseObject(); if (response instanceof JSONObject) { JSONObject object = (JSONObject) response; JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the subreddit results JSONObject data; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind.equals(Kind.SUBREDDIT.value())) { // Create and add subreddit data = ((JSONObject) data.get("data")); subreddits.add(new Subreddit(data)); } } } else { System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'"); } // Finally return list of subreddits return subreddits; } /** * Searches all subreddits with the given query using the given parameters. * The parameters here are in Strings instead of wrapper objects, which allows users * to manually adjust the parameters (if the API changes and jReddit is not updated * in time yet). * * @param query Search query * @param count Count at which the subreddits are started being numbered * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) * @param after The subreddit after which needs to be retrieved * @param before The subreddit after which needs to be retrieved * * @return List of subreddits that satisfy the given parameters. */ public List<Subreddit> search(String query, String count, String limit, String after, String before) throws RetrievalFailedException, RedditError { // Format parameters String params = ""; try { params = ParamFormatter.addParameter(params, "q", URLEncoder.encode(query, "ISO-8859-1")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } params = ParamFormatter.addParameter(params, "count", count); params = ParamFormatter.addParameter(params, "limit", limit); params = ParamFormatter.addParameter(params, "after", after); params = ParamFormatter.addParameter(params, "before", before); // Retrieve submissions from the given URL return parse(String.format(ApiEndpointUtils.SUBREDDITS_SEARCH, params)); } /** * Searches all subreddits with the given query using the given parameters. * * @param query Search query * @param count Count at which the subreddits are started being numbered * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) * @param after The subreddit after which needs to be retrieved * @param before The subreddit after which needs to be retrieved * * @return List of subreddits that satisfy the given parameters. */ public List<Subreddit> search(String query, int count, int limit, Subreddit after, Subreddit before) throws RetrievalFailedException, RedditError { if (query == null || query.isEmpty()) { throw new IllegalArgumentException("The query must be defined."); } return search( query, String.valueOf(count), String.valueOf(limit), (after != null) ? after.getFullName() : "", (before != null) ? before.getFullName() : "" ); } /** * Gets all subreddits using the given parameters. * The parameters here are in Strings instead of wrapper objects, which allows users * to manually adjust the parameters (if the API changes and jReddit is not updated * in time yet). * * @param type Type of subreddit, this determines the ordering (e.g. new or mine) * @param count Count at which the subreddits are started being numbered * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) * @param after The subreddit after which needs to be retrieved * @param before The subreddit after which needs to be retrieved * * @return List of subreddits that satisfy the given parameters. */ public List<Subreddit> get(String type, String count, String limit, String after, String before) throws RetrievalFailedException, RedditError { // Format parameters String params = ""; params = ParamFormatter.addParameter(params, "count", count); params = ParamFormatter.addParameter(params, "limit", limit); params = ParamFormatter.addParameter(params, "after", after); params = ParamFormatter.addParameter(params, "before", before); // Retrieve submissions from the given URL return parse(String.format(ApiEndpointUtils.SUBREDDITS_GET, type, params)); } /** * Gets all subreddits using the given parameters. * * @param type Type of subreddit, this determines the ordering (e.g. new or mine) * @param count Count at which the subreddits are started being numbered * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) * @param after The subreddit after which needs to be retrieved * @param before The subreddit after which needs to be retrieved * * @return List of subreddits that satisfy the given parameters. */ public List<Subreddit> get(SubredditsView type, int count, int limit, Subreddit after, Subreddit before) throws RetrievalFailedException, RedditError { return get( (type != null) ? type.value() : "", String.valueOf(count), String.valueOf(limit), (after != null) ? after.getFullName() : "", (before != null) ? before.getFullName() : "" ); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.pig; import java.io.IOException; import java.nio.charset.CharacterCodingException; import java.util.Iterator; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.thrift.AuthenticationException; import org.apache.cassandra.thrift.AuthorizationException; import org.apache.cassandra.thrift.InvalidRequestException; import org.apache.cassandra.thrift.NotFoundException; import org.apache.cassandra.thrift.SchemaDisagreementException; import org.apache.cassandra.thrift.TimedOutException; import org.apache.cassandra.thrift.UnavailableException; import org.apache.pig.data.DataBag; import org.apache.pig.data.Tuple; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransportException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class CqlTableTest extends PigTestBase { private static String[] statements = { "CREATE KEYSPACE cql3ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}", "USE cql3ks;", "CREATE TABLE cqltable (key1 text, key2 int, column1 int, column2 float, primary key(key1, key2))", "INSERT INTO cqltable (key1, key2, column1, column2) values ('key1', 111, 100, 10.1)", "CREATE TABLE compactcqltable (key1 text, column1 int, column2 float, primary key(key1)) WITH COMPACT STORAGE", "INSERT INTO compactcqltable (key1, column1, column2) values ('key1', 100, 10.1)", "CREATE TABLE test (a int PRIMARY KEY, b int);", "CREATE INDEX test_b on test (b);", "CREATE TABLE moredata (x int PRIMARY KEY, y int);", "INSERT INTO test (a,b) VALUES (1,1);", "INSERT INTO test (a,b) VALUES (2,2);", "INSERT INTO test (a,b) VALUES (3,3);", "INSERT INTO moredata (x, y) VALUES (4,4);", "INSERT INTO moredata (x, y) VALUES (5,5);", "INSERT INTO moredata (x, y) VALUES (6,6);", "CREATE TABLE compotable (a int, b int, c text, d text, PRIMARY KEY (a,b,c));", "INSERT INTO compotable (a, b , c , d ) VALUES ( 1,1,'One','match');", "INSERT INTO compotable (a, b , c , d ) VALUES ( 2,2,'Two','match');", "INSERT INTO compotable (a, b , c , d ) VALUES ( 3,3,'Three','match');", "INSERT INTO compotable (a, b , c , d ) VALUES ( 4,4,'Four','match');", "create table compmore (id int PRIMARY KEY, x int, y int, z text, data text);", "INSERT INTO compmore (id, x, y, z,data) VALUES (1,5,6,'Fix','nomatch');", "INSERT INTO compmore (id, x, y, z,data) VALUES (2,6,5,'Sive','nomatch');", "INSERT INTO compmore (id, x, y, z,data) VALUES (3,7,7,'Seven','match');", "INSERT INTO compmore (id, x, y, z,data) VALUES (4,8,8,'Eight','match');", "INSERT INTO compmore (id, x, y, z,data) VALUES (5,9,10,'Ninen','nomatch');", "CREATE TABLE collectiontable(m text PRIMARY KEY, n map<text, text>);", "UPDATE collectiontable SET n['key1'] = 'value1' WHERE m = 'book1';", "UPDATE collectiontable SET n['key2'] = 'value2' WHERE m = 'book2';", "UPDATE collectiontable SET n['key3'] = 'value3' WHERE m = 'book3';", "UPDATE collectiontable SET n['key4'] = 'value4' WHERE m = 'book4';", }; @BeforeClass public static void setup() throws TTransportException, IOException, InterruptedException, ConfigurationException, AuthenticationException, AuthorizationException, InvalidRequestException, UnavailableException, TimedOutException, TException, NotFoundException, CharacterCodingException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException { startCassandra(); setupDataByCql(statements); startHadoopCluster(); } @Test public void testCqlStorageSchema() throws AuthenticationException, AuthorizationException, InvalidRequestException, UnavailableException, TimedOutException, TException, NotFoundException, SchemaDisagreementException, IOException { pig.registerQuery("rows = LOAD 'cql://cql3ks/cqltable?" + defaultParameters + "' USING CqlStorage();"); Iterator<Tuple> it = pig.openIterator("rows"); if (it.hasNext()) { Tuple t = it.next(); Assert.assertEquals(t.get(0).toString(), "key1"); Assert.assertEquals(t.get(1), 111); Assert.assertEquals(t.get(2), 100); Assert.assertEquals(t.get(3), 10.1f); Assert.assertEquals(4, t.size()); } pig.registerQuery("rows = LOAD 'cql://cql3ks/compactcqltable?" + defaultParameters + "' USING CqlStorage();"); it = pig.openIterator("rows"); if (it.hasNext()) { Tuple t = it.next(); Assert.assertEquals(t.get(0).toString(), "key1"); Assert.assertEquals(t.get(1), 100); Assert.assertEquals(t.get(2), 10.1f); Assert.assertEquals(3, t.size()); } } @Test public void testCqlStorageSingleKeyTable() throws AuthenticationException, AuthorizationException, InvalidRequestException, UnavailableException, TimedOutException, TException, NotFoundException, SchemaDisagreementException, IOException { pig.setBatchOn(); pig.registerQuery("moretestvalues= LOAD 'cql://cql3ks/moredata?" + defaultParameters + "' USING CqlStorage();"); pig.registerQuery("insertformat= FOREACH moretestvalues GENERATE TOTUPLE(TOTUPLE('a',x)),TOTUPLE(y);"); pig.registerQuery("STORE insertformat INTO 'cql://cql3ks/test?" + defaultParameters + "&output_query=UPDATE+cql3ks.test+set+b+%3D+%3F' USING CqlStorage();"); pig.executeBatch(); //(5,5) //(6,6) //(4,4) //(2,2) //(3,3) //(1,1) pig.registerQuery("result= LOAD 'cql://cql3ks/test?" + defaultParameters + "' USING CqlStorage();"); Iterator<Tuple> it = pig.openIterator("result"); if (it.hasNext()) { Tuple t = it.next(); Assert.assertEquals(t.get(0), t.get(1)); } } @Test public void testCqlStorageCompositeKeyTable() throws AuthenticationException, AuthorizationException, InvalidRequestException, UnavailableException, TimedOutException, TException, NotFoundException, SchemaDisagreementException, IOException { pig.setBatchOn(); pig.registerQuery("moredata= LOAD 'cql://cql3ks/compmore?" + defaultParameters + "' USING CqlStorage();"); pig.registerQuery("insertformat = FOREACH moredata GENERATE TOTUPLE (TOTUPLE('a',x),TOTUPLE('b',y), TOTUPLE('c',z)),TOTUPLE(data);"); pig.registerQuery("STORE insertformat INTO 'cql://cql3ks/compotable?" + defaultParameters + "&output_query=UPDATE%20cql3ks.compotable%20SET%20d%20%3D%20%3F' USING CqlStorage();"); pig.executeBatch(); //(5,6,Fix,nomatch) //(3,3,Three,match) //(1,1,One,match) //(2,2,Two,match) //(7,7,Seven,match) //(8,8,Eight,match) //(6,5,Sive,nomatch) //(4,4,Four,match) //(9,10,Ninen,nomatch) pig.registerQuery("result= LOAD 'cql://cql3ks/compotable?" + defaultParameters + "' USING CqlStorage();"); Iterator<Tuple> it = pig.openIterator("result"); int count = 0; while (it.hasNext()) { it.next(); count ++; } Assert.assertEquals(count, 9); } @Test public void testCqlStorageCollectionColumnTable() throws AuthenticationException, AuthorizationException, InvalidRequestException, UnavailableException, TimedOutException, TException, NotFoundException, SchemaDisagreementException, IOException { pig.setBatchOn(); pig.registerQuery("collectiontable= LOAD 'cql://cql3ks/collectiontable?" + defaultParameters + "' USING CqlStorage();"); pig.registerQuery("recs= FOREACH collectiontable GENERATE TOTUPLE(TOTUPLE('m', m) ), TOTUPLE(TOTUPLE('map', TOTUPLE('m', 'mm'), TOTUPLE('n', 'nn')));"); pig.registerQuery("STORE recs INTO 'cql://cql3ks/collectiontable?" + defaultParameters + "&output_query=update+cql3ks.collectiontable+set+n+%3D+%3F' USING CqlStorage();"); pig.executeBatch(); //(book2,((key2, value2),(m,mm),(n,nn))) //(book3,((key3, value3),(m,mm),(n,nn))) //(book4,((key4, value4),(m,mm),(n,nn))) //(book1,((key1, value1),(m,mm),(n,nn))) pig.registerQuery("result= LOAD 'cql://cql3ks/collectiontable?" + defaultParameters + "' USING CqlStorage();"); Iterator<Tuple> it = pig.openIterator("result"); while (it.hasNext()) { Tuple t = it.next(); Tuple t1 = (Tuple) t.get(1); Assert.assertEquals(t1.size(), 3); Tuple element1 = (Tuple) t1.get(1); Tuple element2 = (Tuple) t1.get(2); Assert.assertEquals(element1.get(0), "m"); Assert.assertEquals(element1.get(1), "mm"); Assert.assertEquals(element2.get(0), "n"); Assert.assertEquals(element2.get(1), "nn"); } } @Test public void testCassandraStorageSchema() throws IOException, ClassNotFoundException, TException, TimedOutException, NotFoundException, InvalidRequestException, NoSuchFieldException, UnavailableException, IllegalAccessException, InstantiationException { //results: (key1,{((111,),),((111,column1),100),((111,column2),10.1)}) pig.registerQuery("rows = LOAD 'cassandra://cql3ks/cqltable?" + defaultParameters + "' USING CassandraStorage();"); //schema: {key: chararray,columns: {(name: (),value: bytearray)}} Iterator<Tuple> it = pig.openIterator("rows"); if (it.hasNext()) { Tuple t = it.next(); String rowKey = t.get(0).toString(); Assert.assertEquals(rowKey, "key1"); DataBag columns = (DataBag) t.get(1); Iterator<Tuple> iter = columns.iterator(); int i = 0; while(iter.hasNext()) { i++; Tuple column = (Tuple) iter.next(); if (i==1) { Assert.assertEquals(((Tuple) column.get(0)).get(0), 111); Assert.assertEquals(((Tuple) column.get(0)).get(1), ""); Assert.assertEquals(column.get(1).toString(), ""); } if (i==2) { Assert.assertEquals(((Tuple) column.get(0)).get(0), 111); Assert.assertEquals(((Tuple) column.get(0)).get(1), "column1"); Assert.assertEquals(column.get(1), 100); } if (i==3) { Assert.assertEquals(((Tuple) column.get(0)).get(0), 111); Assert.assertEquals(((Tuple) column.get(0)).get(1), "column2"); Assert.assertEquals(column.get(1), 10.1f); } } Assert.assertEquals(3, columns.size()); } //results: (key1,(column1,100),(column2,10.1)) pig.registerQuery("compact_rows = LOAD 'cassandra://cql3ks/compactcqltable?" + defaultParameters + "' USING CassandraStorage();"); //schema: {key: chararray,column1: (name: chararray,value: int),column2: (name: chararray,value: float)} it = pig.openIterator("compact_rows"); if (it.hasNext()) { Tuple t = it.next(); String rowKey = t.get(0).toString(); Assert.assertEquals(rowKey, "key1"); Tuple column = (Tuple) t.get(1); Assert.assertEquals(column.get(0), "column1"); Assert.assertEquals(column.get(1), 100); column = (Tuple) t.get(2); Assert.assertEquals(column.get(0), "column2"); Assert.assertEquals(column.get(1), 10.1f); } } }